From 1b23b3281782b6ddd73df9ced3ca48eba2a526f4 Mon Sep 17 00:00:00 2001 From: Dennis de Greef Date: Sun, 5 Mar 2017 23:08:29 +0100 Subject: [PATCH] Use bundled certificates if port matches mqtts (#6429) * Use bundled certificates if port matches mqtts * Move import requests.certs to top, since it's used in more places * Add happy and non-happy path tests for default certificate bundle on mqtts port --- homeassistant/components/mqtt/__init__.py | 5 ++++ tests/components/mqtt/test_init.py | 34 +++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 331d32e83be..034d1154679 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -9,6 +9,7 @@ import logging import os import socket import time +import requests.certs import voluptuous as vol @@ -310,6 +311,10 @@ def async_setup(hass, config): certificate = os.path.join(os.path.dirname(__file__), 'addtrustexternalcaroot.crt') + # When the port indicates mqtts, use bundled certificates from requests + if certificate is None and port == 8883: + certificate = requests.certs.where() + will_message = conf.get(CONF_WILL_MESSAGE) birth_message = conf.get(CONF_BIRTH_MESSAGE) diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index f476ed4be09..f29ef15a37f 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -380,6 +380,40 @@ def test_setup_fails_if_no_connect_broker(hass): assert not result +@asyncio.coroutine +def test_setup_uses_certificate_on_mqtts_port(hass): + """Test setup uses bundled certificates when mqtts port is requested.""" + test_broker_cfg = {mqtt.DOMAIN: {mqtt.CONF_BROKER: 'test-broker', + 'port': 8883}} + + with mock.patch('homeassistant.components.mqtt.MQTT') as mock_MQTT: + yield from async_setup_component(hass, mqtt.DOMAIN, test_broker_cfg) + + assert mock_MQTT.called + assert mock_MQTT.mock_calls[0][1][2] == 8883 + + import requests.certs + expectedCertificate = requests.certs.where() + assert mock_MQTT.mock_calls[0][1][7] == expectedCertificate + + +@asyncio.coroutine +def test_setup_uses_certificate_not_on_mqtts_port(hass): + """Test setup doesn't use bundled certificates when not mqtts port.""" + test_broker_cfg = {mqtt.DOMAIN: {mqtt.CONF_BROKER: 'test-broker', + 'port': 1883}} + + with mock.patch('homeassistant.components.mqtt.MQTT') as mock_MQTT: + yield from async_setup_component(hass, mqtt.DOMAIN, test_broker_cfg) + + assert mock_MQTT.called + assert mock_MQTT.mock_calls[0][1][2] == 1883 + + import requests.certs + mqttsCertificateBundle = requests.certs.where() + assert mock_MQTT.mock_calls[0][1][7] != mqttsCertificateBundle + + @asyncio.coroutine def test_birth_message(hass): """Test sending birth message."""