From 2351f2d95efeb1a0af37080ae418ffe08bb70e9d Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Wed, 23 Jun 2021 15:53:17 +0200 Subject: [PATCH] Warn when receiving message on illegal MQTT discovery topic (#52106) * Warn when receiving message on illegal MQTT discovery topic * Fix test --- homeassistant/components/mqtt/discovery.py | 4 ++++ tests/components/mqtt/test_discovery.py | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/mqtt/discovery.py b/homeassistant/components/mqtt/discovery.py index e68b47abe02..e4f461324a9 100644 --- a/homeassistant/components/mqtt/discovery.py +++ b/homeassistant/components/mqtt/discovery.py @@ -95,6 +95,10 @@ async def async_start( # noqa: C901 match = TOPIC_MATCHER.match(topic_trimmed) if not match: + if topic_trimmed.endswith("config"): + _LOGGER.warning( + "Received message on illegal discovery topic '%s'", topic + ) return component, node_id, object_id = match.groups() diff --git a/tests/components/mqtt/test_discovery.py b/tests/components/mqtt/test_discovery.py index d55c8e0eccc..907c3d398b6 100644 --- a/tests/components/mqtt/test_discovery.py +++ b/tests/components/mqtt/test_discovery.py @@ -55,18 +55,30 @@ async def test_subscribing_config_topic(hass, mqtt_mock): assert discovery_topic + "/+/+/+/config" in topics -async def test_invalid_topic(hass, mqtt_mock): +@pytest.mark.parametrize( + "topic, log", + [ + ("homeassistant/binary_sensor/bla/not_config", False), + ("homeassistant/binary_sensor/rörkrökare/config", True), + ], +) +async def test_invalid_topic(hass, mqtt_mock, caplog, topic, log): """Test sending to invalid topic.""" with patch( "homeassistant.components.mqtt.discovery.async_dispatcher_send" ) as mock_dispatcher_send: mock_dispatcher_send = AsyncMock(return_value=None) - async_fire_mqtt_message( - hass, "homeassistant/binary_sensor/bla/not_config", "{}" - ) + async_fire_mqtt_message(hass, topic, "{}") await hass.async_block_till_done() assert not mock_dispatcher_send.called + if log: + assert ( + f"Received message on illegal discovery topic '{topic}'" in caplog.text + ) + else: + assert "Received message on illegal discovery topic'" not in caplog.text + caplog.clear() async def test_invalid_json(hass, mqtt_mock, caplog):