diff --git a/homeassistant/components/zeroconf/__init__.py b/homeassistant/components/zeroconf/__init__.py index 373df9e6384..6fd5d96a40c 100644 --- a/homeassistant/components/zeroconf/__init__.py +++ b/homeassistant/components/zeroconf/__init__.py @@ -157,7 +157,14 @@ def info_from_service(service): # See https://ietf.org/rfc/rfc6763.html#section-6.4 and # https://ietf.org/rfc/rfc6763.html#section-6.5 for expected encodings # for property keys and values - key = key.decode("ascii") + try: + key = key.decode("ascii") + except UnicodeDecodeError: + _LOGGER.debug( + "Ignoring invalid key provided by [%s]: %s", service.name, key + ) + continue + properties["_raw"][key] = value try: diff --git a/tests/components/zeroconf/test_init.py b/tests/components/zeroconf/test_init.py index 6a3dc1f5941..6efcd4e463e 100644 --- a/tests/components/zeroconf/test_init.py +++ b/tests/components/zeroconf/test_init.py @@ -8,6 +8,14 @@ from homeassistant.components import zeroconf from homeassistant.generated import zeroconf as zc_gen from homeassistant.setup import async_setup_component +NON_UTF8_VALUE = b"ABCDEF\x8a" +NON_ASCII_KEY = b"non-ascii-key\x8a" +PROPERTIES = { + b"macaddress": b"ABCDEF012345", + b"non-utf8-value": NON_UTF8_VALUE, + NON_ASCII_KEY: None, +} + @pytest.fixture def mock_zeroconf(): @@ -31,7 +39,7 @@ def get_service_info_mock(service_type, name): weight=0, priority=0, server="name.local.", - properties={b"macaddress": b"ABCDEF012345", b"non-utf8-value": b"ABCDEF\x8a"}, + properties=PROPERTIES, ) @@ -124,13 +132,15 @@ async def test_homekit_match_full(hass, mock_zeroconf): async def test_info_from_service_non_utf8(hass): - """Test info_from_service handles non UTF-8 property values correctly.""" + """Test info_from_service handles non UTF-8 property keys and values correctly.""" service_type = "_test._tcp.local." info = zeroconf.info_from_service( get_service_info_mock(service_type, f"test.{service_type}") ) raw_info = info["properties"].pop("_raw", False) assert raw_info + assert len(raw_info) == len(PROPERTIES) - 1 + assert NON_ASCII_KEY not in raw_info assert len(info["properties"]) <= len(raw_info) assert "non-utf8-value" not in info["properties"] - assert raw_info["non-utf8-value"] is not None + assert raw_info["non-utf8-value"] is NON_UTF8_VALUE