From a5f6381d89b7ee951d3231fe39ba48816009dfaf Mon Sep 17 00:00:00 2001 From: Lex Postma Date: Mon, 23 Nov 2026 21:47:49 +0100 Subject: [PATCH 1/4] Only report v2 API support for officially supported models has_v2_api returned True for any device that answers 401 on the unauthenticated https /api endpoint. Devices that enable the v2 API before it is officially supported (for example with beta firmware) were therefore treated as v2 devices, and Home Assistant offered to migrate them to the v2 API. The unauthenticated v2 endpoint does not tell which product it is, so read the product type from the device certificate instead. Its common name is `appliance//` and it is validated against the HomeWizard CA, without authorization. Only models in the new SUPPORTED_V2_MODELS allowlist are reported as v2 capable: P1 Meter, Energy Socket, kWh Meters and Plug-In Battery. Co-Authored-By: Claude Opus 5.5 --- homewizard_energy/__init__.py | 66 +++++++++++++- homewizard_energy/const.py | 16 ++++ tests/test_helpers.py | 156 +++++++++++++++++++++++++++++----- 3 files changed, 213 insertions(+), 25 deletions(-) diff --git a/homewizard_energy/__init__.py b/homewizard_energy/__init__.py index 5053bfbf..e7289917 100644 --- a/homewizard_energy/__init__.py +++ b/homewizard_energy/__init__.py @@ -1,11 +1,17 @@ """HomeWizard Energy API library.""" +import asyncio +import ssl +from functools import cache + from aiohttp import ClientSession +from .const import MODEL_TO_ID, SUPPORTED_V2_MODELS from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError from .homewizard_energy import HomeWizardEnergy from .v1 import HomeWizardEnergyV1 from .v2 import HomeWizardEnergyV2 +from .v2.cacert import CACERT __all__ = [ "DisabledError", @@ -17,9 +23,60 @@ "UnsupportedError", ] +# Product type identifiers as used in the device certificate, +# for the models that are supported via the v2 API +SUPPORTED_V2_CERTIFICATE_IDS = frozenset( + MODEL_TO_ID[model] for model in SUPPORTED_V2_MODELS +) + + +@cache +def _certificate_ssl_context() -> ssl.SSLContext: + """SSL context that validates the device certificate, but not the hostname.""" + context = ssl.create_default_context(cadata=CACERT) + context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member + context.check_hostname = False + context.verify_mode = ssl.CERT_REQUIRED + return context + + +async def _get_certificate_product_id(host: str) -> str | None: + """Get the product type identifier from the device certificate. + + The common name of the certificate of a v2 device is formatted as + `appliance//`, see `MODEL_TO_ID`. + This works without authorization. + """ + loop = asyncio.get_running_loop() + # Loading the CA certificate is blocking IO, so run it in the executor + context = await loop.run_in_executor(None, _certificate_ssl_context) + + _, writer = await asyncio.wait_for( + asyncio.open_connection(host, 443, ssl=context), timeout=5 + ) + try: + certificate = writer.get_extra_info("peercert") or {} + finally: + writer.close() + + for rdn in certificate.get("subject", ()): + for key, value in rdn: + if key != "commonName": + continue + parts = value.split("/") + if len(parts) == 3 and parts[0] == "appliance": + return parts[1] + + return None + async def has_v2_api(host: str, websession: ClientSession | None = None) -> bool: - """Check if the device has support for the v2 api.""" + """Check if the device has support for the v2 api. + + Only returns True for models that are supported via the v2 API by this + version of the library (see `SUPPORTED_V2_MODELS`), so devices that enable + the v2 API before it is officially supported keep using the v1 API. + """ websession_provided = websession is not None if websession is None: websession = ClientSession() @@ -30,7 +87,12 @@ async def has_v2_api(host: str, websession: ClientSession | None = None) -> bool res = await websession.get(url, ssl=False, raise_for_status=False, timeout=5) res.close() - return res.status == 401 + if res.status != 401: + return False + + # The unauthorized response does not tell which product this is, + # so get the product type from the device certificate instead + return await _get_certificate_product_id(host) in SUPPORTED_V2_CERTIFICATE_IDS except Exception: # pylint: disable=broad-except # all other status/exceptions means the device is not v2 or not reachable at this time return False diff --git a/homewizard_energy/const.py b/homewizard_energy/const.py index 8f4e92ef..7bd344ff 100644 --- a/homewizard_energy/const.py +++ b/homewizard_energy/const.py @@ -32,6 +32,22 @@ class Model(StrEnum): Model.BATTERY: "battery", } +# Models that are supported via the v2 API by this version of the library. +# Keep in sync with https://api-documentation.homewizard.com/docs/introduction#devices +# Devices of other models may enable the v2 API (e.g. with beta firmware), but are +# not reported as v2 capable by `has_v2_api` until they are added here. +SUPPORTED_V2_MODELS = frozenset( + { + Model.P1_METER, + Model.ENERGY_SOCKET, + Model.ENERGY_METER_1_PHASE, + Model.ENERGY_METER_3_PHASE, + Model.ENERGY_METER_EASTRON_SDM230, + Model.ENERGY_METER_EASTRON_SDM630, + Model.BATTERY, + } +) + MODEL_TO_NAME = { Model.P1_METER: "P1 Meter", Model.ENERGY_SOCKET: "Energy Socket", diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 079c5a02..98bc6219 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1,48 +1,106 @@ """Test the helper functions.""" import asyncio -from unittest.mock import AsyncMock +import ssl +from collections.abc import Generator +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch import pytest from aiohttp import ClientSession -from homewizard_energy import has_v2_api +from homewizard_energy import ( + _certificate_ssl_context, + _get_certificate_product_id, + has_v2_api, +) pytestmark = [pytest.mark.asyncio] -async def test_has_v2_api_true(aresponses): - """Test if has_v2_api returns True for a v2 device.""" +def _peercert(common_name: str) -> dict[str, Any]: + """Build a certificate as returned by `SSLSocket.getpeercert()`.""" + return { + "subject": ( + (("countryName", "NL"),), + (("organizationName", "HomeWizard"),), + (("commonName", common_name),), + ), + } + + +@pytest.fixture(name="mock_product_id") +def fixture_mock_product_id() -> Generator[AsyncMock]: + """Mock the product type identifier read from the device certificate.""" + with patch( + "homewizard_energy._get_certificate_product_id", + new=AsyncMock(return_value="p1dongle"), + ) as mock: + yield mock + +def _add_api_response(aresponses, status: int) -> None: + """Add a response for the unauthenticated v2 /api endpoint.""" aresponses.add( "example.com", "/api", "GET", aresponses.Response( - status=401, + status=status, ), ) + +@pytest.mark.parametrize( + "product_id", + ["p1dongle", "energysocket", "energymeter", "battery"], +) +async def test_has_v2_api_true(aresponses, mock_product_id, product_id): + """Test if has_v2_api returns True for a supported v2 device.""" + mock_product_id.return_value = product_id + _add_api_response(aresponses, 401) + async with ClientSession() as session: result = await has_v2_api("example.com", session) assert result is True + mock_product_id.assert_awaited_once_with("example.com") + + +@pytest.mark.parametrize( + "product_id", + ["watermeter", "display", "unknown", None], +) +async def test_has_v2_api_unsupported_model(aresponses, mock_product_id, product_id): + """Test if has_v2_api returns False for a v2 device that is not supported.""" + mock_product_id.return_value = product_id + _add_api_response(aresponses, 401) + + async with ClientSession() as session: + result = await has_v2_api("example.com", session) + assert result is False + + +async def test_has_v2_api_certificate_error(aresponses, mock_product_id): + """Test if has_v2_api returns False when the certificate can't be read.""" + mock_product_id.side_effect = ssl.SSLCertVerificationError + _add_api_response(aresponses, 401) + + async with ClientSession() as session: + result = await has_v2_api("example.com", session) + assert result is False -async def test_has_v2_api_false(aresponses): + +async def test_has_v2_api_false(aresponses, mock_product_id): """Test if has_v2_api returns False for a non-v2 device.""" - aresponses.add( - "example.com", - "/api", - "GET", - aresponses.Response( - status=404, - ), - ) + _add_api_response(aresponses, 404) async with ClientSession() as session: result = await has_v2_api("example.com", session) assert result is False + mock_product_id.assert_not_awaited() + async def test_has_v2_api_exception(): """Test if has_v2_api returns False when an exception occurs.""" @@ -53,16 +111,68 @@ async def test_has_v2_api_exception(): assert result is False -async def test_has_v2_api_own_session(aresponses): +async def test_has_v2_api_own_session(aresponses, mock_product_id): """Test if has_v2_api opens and closes its own session.""" - aresponses.add( - "example.com", - "/api", - "GET", - aresponses.Response( - status=401, - ), - ) + _add_api_response(aresponses, 401) result = await has_v2_api("example.com") assert result is True + + mock_product_id.assert_awaited_once_with("example.com") + + +@pytest.mark.parametrize( + ("peercert", "expected"), + [ + (_peercert("appliance/p1dongle/5c2fafaabbcc"), "p1dongle"), + (_peercert("appliance/energysocket/5c2fafaabbcc"), "energysocket"), + (_peercert("appliance/watermeter/5c2fafaabbcc"), "watermeter"), + (_peercert("something/else"), None), + (_peercert("device/p1dongle/5c2fafaabbcc"), None), + ({"subject": ((("organizationName", "HomeWizard"),),)}, None), + ({}, None), + (None, None), + ], +) +async def test_get_certificate_product_id(peercert, expected): + """Test reading the product type identifier from the device certificate.""" + writer = MagicMock() + writer.get_extra_info.return_value = peercert + + with patch( + "homewizard_energy.asyncio.open_connection", + new=AsyncMock(return_value=(MagicMock(), writer)), + ) as mock_open_connection: + assert await _get_certificate_product_id("example.com") == expected + + mock_open_connection.assert_awaited_once() + assert mock_open_connection.await_args.args == ("example.com", 443) + assert mock_open_connection.await_args.kwargs["ssl"] is _certificate_ssl_context() + writer.get_extra_info.assert_called_once_with("peercert") + writer.close.assert_called_once() + + +async def test_get_certificate_product_id_closes_on_error(): + """Test the connection is closed when reading the certificate fails.""" + writer = MagicMock() + writer.get_extra_info.side_effect = RuntimeError + + with ( + patch( + "homewizard_energy.asyncio.open_connection", + new=AsyncMock(return_value=(MagicMock(), writer)), + ), + pytest.raises(RuntimeError), + ): + await _get_certificate_product_id("example.com") + + writer.close.assert_called_once() + + +def test_certificate_ssl_context(): + """Test the SSL context validates the certificate but not the hostname.""" + context = _certificate_ssl_context() + + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname is False + assert context.get_ca_certs() From cc0c678f129ec6923bffd8a64e5146e5e7ed2d4b Mon Sep 17 00:00:00 2001 From: Lex Postma Date: Mon, 23 Nov 2026 22:09:51 +0100 Subject: [PATCH 2/4] Check v2 support with a single TLS handshake and optional product type Drop the separate unauthenticated `GET /api` request: only v2 devices serve HTTPS, so a certificate that validates against the HomeWizard CA is enough to know the device runs the v2 API. This halves the number of connections, which matters because devices have very few connection slots. The websession argument is no longer used and only kept for backwards compatibility. Add an optional product_type argument for callers that already know it (discovery or an existing configuration). Unsupported models return False without connecting to the device, and a device of another product type at this host returns False as well. Co-Authored-By: Claude Opus 5.5 --- homewizard_energy/__init__.py | 52 +++++++++-------- tests/test_helpers.py | 106 ++++++++++++++++++---------------- 2 files changed, 86 insertions(+), 72 deletions(-) diff --git a/homewizard_energy/__init__.py b/homewizard_energy/__init__.py index e7289917..124d6eff 100644 --- a/homewizard_energy/__init__.py +++ b/homewizard_energy/__init__.py @@ -43,9 +43,10 @@ def _certificate_ssl_context() -> ssl.SSLContext: async def _get_certificate_product_id(host: str) -> str | None: """Get the product type identifier from the device certificate. - The common name of the certificate of a v2 device is formatted as - `appliance//`, see `MODEL_TO_ID`. - This works without authorization. + Only devices with the v2 API serve HTTPS. The common name of their + certificate is formatted as `appliance//`, + see `MODEL_TO_ID`. This works without authorization, and only needs a single + TLS handshake, as devices have very few connection slots. """ loop = asyncio.get_running_loop() # Loading the CA certificate is blocking IO, so run it in the executor @@ -70,32 +71,37 @@ async def _get_certificate_product_id(host: str) -> str | None: return None -async def has_v2_api(host: str, websession: ClientSession | None = None) -> bool: +async def has_v2_api( + host: str, + websession: ClientSession | None = None, + product_type: str | None = None, +) -> bool: """Check if the device has support for the v2 api. Only returns True for models that are supported via the v2 API by this version of the library (see `SUPPORTED_V2_MODELS`), so devices that enable the v2 API before it is officially supported keep using the v1 API. + + The product type is read from the device certificate. Pass `product_type` + when it is already known (e.g. from discovery or an existing configuration): + unsupported models then return False without connecting to the device, and + a device of another product type at this host returns False as well. + + `websession` is no longer used and only kept for backwards compatibility. """ - websession_provided = websession is not None - if websession is None: - websession = ClientSession() + del websession # Kept for backwards compatibility + + if product_type is not None and product_type not in SUPPORTED_V2_MODELS: + return False + try: - # v2 api is https only and returns a 401 Unauthorized when no key provided, - # no connection can be made if the device is not v2 - url = f"https://{host}/api" - res = await websession.get(url, ssl=False, raise_for_status=False, timeout=5) - res.close() - - if res.status != 401: - return False - - # The unauthorized response does not tell which product this is, - # so get the product type from the device certificate instead - return await _get_certificate_product_id(host) in SUPPORTED_V2_CERTIFICATE_IDS + product_id = await _get_certificate_product_id(host) except Exception: # pylint: disable=broad-except - # all other status/exceptions means the device is not v2 or not reachable at this time + # No (valid) HTTPS connection means the device is not v2 + # or not reachable at this time return False - finally: - if not websession_provided: - await websession.close() + + if product_type is not None: + return product_id == MODEL_TO_ID[product_type] + + return product_id in SUPPORTED_V2_CERTIFICATE_IDS diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 98bc6219..c09a5e0f 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -39,31 +39,15 @@ def fixture_mock_product_id() -> Generator[AsyncMock]: yield mock -def _add_api_response(aresponses, status: int) -> None: - """Add a response for the unauthenticated v2 /api endpoint.""" - aresponses.add( - "example.com", - "/api", - "GET", - aresponses.Response( - status=status, - ), - ) - - @pytest.mark.parametrize( "product_id", ["p1dongle", "energysocket", "energymeter", "battery"], ) -async def test_has_v2_api_true(aresponses, mock_product_id, product_id): +async def test_has_v2_api_true(mock_product_id, product_id): """Test if has_v2_api returns True for a supported v2 device.""" mock_product_id.return_value = product_id - _add_api_response(aresponses, 401) - - async with ClientSession() as session: - result = await has_v2_api("example.com", session) - assert result is True + assert await has_v2_api("example.com") is True mock_product_id.assert_awaited_once_with("example.com") @@ -71,54 +55,78 @@ async def test_has_v2_api_true(aresponses, mock_product_id, product_id): "product_id", ["watermeter", "display", "unknown", None], ) -async def test_has_v2_api_unsupported_model(aresponses, mock_product_id, product_id): +async def test_has_v2_api_unsupported_model(mock_product_id, product_id): """Test if has_v2_api returns False for a v2 device that is not supported.""" mock_product_id.return_value = product_id - _add_api_response(aresponses, 401) - async with ClientSession() as session: - result = await has_v2_api("example.com", session) - assert result is False + assert await has_v2_api("example.com") is False -async def test_has_v2_api_certificate_error(aresponses, mock_product_id): - """Test if has_v2_api returns False when the certificate can't be read.""" - mock_product_id.side_effect = ssl.SSLCertVerificationError - _add_api_response(aresponses, 401) +@pytest.mark.parametrize( + "exception", + [ + ssl.SSLCertVerificationError, + ConnectionRefusedError, + asyncio.TimeoutError, + OSError, + ], +) +async def test_has_v2_api_no_https(mock_product_id, exception): + """Test if has_v2_api returns False without a valid HTTPS connection.""" + mock_product_id.side_effect = exception - async with ClientSession() as session: - result = await has_v2_api("example.com", session) - assert result is False + assert await has_v2_api("example.com") is False -async def test_has_v2_api_false(aresponses, mock_product_id): - """Test if has_v2_api returns False for a non-v2 device.""" - _add_api_response(aresponses, 404) +async def test_has_v2_api_websession_unused(mock_product_id): + """Test if has_v2_api still accepts, but doesn't use, a websession.""" + session = AsyncMock(spec=ClientSession) - async with ClientSession() as session: - result = await has_v2_api("example.com", session) - assert result is False + assert await has_v2_api("example.com", session) is True + assert not session.mock_calls + mock_product_id.assert_awaited_once_with("example.com") - mock_product_id.assert_not_awaited() +@pytest.mark.parametrize( + ("product_type", "product_id"), + [ + ("HWE-P1", "p1dongle"), + ("HWE-SKT", "energysocket"), + ("HWE-KWH1", "energymeter"), + ("HWE-KWH3", "energymeter"), + ("SDM230-wifi", "energymeter"), + ("SDM630-wifi", "energymeter"), + ("HWE-BAT", "battery"), + ], +) +async def test_has_v2_api_product_type(mock_product_id, product_type, product_id): + """Test if has_v2_api returns True for a known, supported product type.""" + mock_product_id.return_value = product_id + + assert await has_v2_api("example.com", product_type=product_type) is True + mock_product_id.assert_awaited_once_with("example.com") -async def test_has_v2_api_exception(): - """Test if has_v2_api returns False when an exception occurs.""" - session = AsyncMock() - session.get = AsyncMock(side_effect=asyncio.TimeoutError) - result = await has_v2_api("example.com", session) - assert result is False +@pytest.mark.parametrize("product_type", ["HWE-WTR", "HWE-DSP", "HWE-UNKNOWN"]) +async def test_has_v2_api_product_type_unsupported(mock_product_id, product_type): + """Test if has_v2_api skips the device for an unsupported product type.""" + assert await has_v2_api("example.com", product_type=product_type) is False + mock_product_id.assert_not_awaited() -async def test_has_v2_api_own_session(aresponses, mock_product_id): - """Test if has_v2_api opens and closes its own session.""" - _add_api_response(aresponses, 401) +@pytest.mark.parametrize("product_id", ["energysocket", "watermeter", None]) +async def test_has_v2_api_product_type_mismatch(mock_product_id, product_id): + """Test if has_v2_api returns False when the device has another product type.""" + mock_product_id.return_value = product_id - result = await has_v2_api("example.com") - assert result is True + assert await has_v2_api("example.com", product_type="HWE-P1") is False - mock_product_id.assert_awaited_once_with("example.com") + +async def test_has_v2_api_product_type_no_https(mock_product_id): + """Test if has_v2_api returns False for a known type without HTTPS.""" + mock_product_id.side_effect = ConnectionRefusedError + + assert await has_v2_api("example.com", product_type="HWE-SKT") is False @pytest.mark.parametrize( From 4a659bdb78dec4c93e698419194a8f437b2afb0e Mon Sep 17 00:00:00 2001 From: Lex Postma Date: Wed, 25 Nov 2026 09:11:21 +0100 Subject: [PATCH 3/4] Address review: check the v2 API response and accept generic certificates - Send GET /api over the same TLS connection and require 401 Unauthorized, as some firmware serves a valid certificate without the v2 API. - Accept certificates with `appliance/generic/`, as used by early batteries that do serve the v2 API, instead of reporting them as not v2. - Wait for the connection to close, ignoring errors while closing. - Only catch OSError (includes SSL errors and timeouts) instead of Exception. - Share the SSL context with HomeWizardEnergyV2 via create_ssl_context. Co-Authored-By: Claude Opus 5.5 --- homewizard_energy/__init__.py | 107 ++++++++++++------- homewizard_energy/v2/__init__.py | 31 ++++-- tests/test_helpers.py | 171 +++++++++++++++++++++++++------ 3 files changed, 232 insertions(+), 77 deletions(-) diff --git a/homewizard_energy/__init__.py b/homewizard_energy/__init__.py index 124d6eff..8f66903b 100644 --- a/homewizard_energy/__init__.py +++ b/homewizard_energy/__init__.py @@ -1,8 +1,8 @@ """HomeWizard Energy API library.""" import asyncio -import ssl -from functools import cache +from contextlib import suppress +from typing import Any from aiohttp import ClientSession @@ -10,8 +10,7 @@ from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError from .homewizard_energy import HomeWizardEnergy from .v1 import HomeWizardEnergyV1 -from .v2 import HomeWizardEnergyV2 -from .v2.cacert import CACERT +from .v2 import HomeWizardEnergyV2, create_ssl_context __all__ = [ "DisabledError", @@ -29,38 +28,21 @@ MODEL_TO_ID[model] for model in SUPPORTED_V2_MODELS ) +# Some devices have a certificate without product type, e.g. early batteries +# with `appliance/generic/` +GENERIC_CERTIFICATE_ID = "generic" -@cache -def _certificate_ssl_context() -> ssl.SSLContext: - """SSL context that validates the device certificate, but not the hostname.""" - context = ssl.create_default_context(cadata=CACERT) - context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member - context.check_hostname = False - context.verify_mode = ssl.CERT_REQUIRED - return context +# Timeout in seconds for connecting to the device and for its response +TIMEOUT = 5 -async def _get_certificate_product_id(host: str) -> str | None: - """Get the product type identifier from the device certificate. +def _get_certificate_product_id(certificate: dict[str, Any] | None) -> str | None: + """Get the product type identifier from a device certificate. - Only devices with the v2 API serve HTTPS. The common name of their - certificate is formatted as `appliance//`, - see `MODEL_TO_ID`. This works without authorization, and only needs a single - TLS handshake, as devices have very few connection slots. + The common name of the certificate is formatted as + `appliance//`, see `MODEL_TO_ID`. """ - loop = asyncio.get_running_loop() - # Loading the CA certificate is blocking IO, so run it in the executor - context = await loop.run_in_executor(None, _certificate_ssl_context) - - _, writer = await asyncio.wait_for( - asyncio.open_connection(host, 443, ssl=context), timeout=5 - ) - try: - certificate = writer.get_extra_info("peercert") or {} - finally: - writer.close() - - for rdn in certificate.get("subject", ()): + for rdn in (certificate or {}).get("subject", ()): for key, value in rdn: if key != "commonName": continue @@ -71,6 +53,50 @@ async def _get_certificate_product_id(host: str) -> str | None: return None +async def _get_v2_product_id(host: str) -> str | None: + """Get the product type identifier of a device that serves the v2 API. + + Only devices with the v2 API serve HTTPS with a valid device certificate, + which contains the product type identifier. Some firmware serves this + certificate without the v2 API, so also check that the API responds to a + request without a token with 401 Unauthorized. + + This works without authorization, and needs only a single connection, + as devices have very few connection slots. + """ + loop = asyncio.get_running_loop() + # Creating an SSL context has some blocking IO so need to run it in the executor + context = await loop.run_in_executor(None, create_ssl_context, False) + + reader, writer = await asyncio.wait_for( + asyncio.open_connection(host, 443, ssl=context), timeout=TIMEOUT + ) + try: + product_id = _get_certificate_product_id(writer.get_extra_info("peercert")) + if product_id is None: + return None + + host_header = f"[{host}]" if ":" in host else host + request = ( + f"GET /api HTTP/1.1\r\nHost: {host_header}\r\nConnection: close\r\n\r\n" + ) + writer.write(request.encode()) + await writer.drain() + status_line = await asyncio.wait_for(reader.readline(), timeout=TIMEOUT) + finally: + writer.close() + # Closing raises an SSL error when the rest of the response is not read yet + with suppress(OSError): + await asyncio.wait_for(writer.wait_closed(), timeout=TIMEOUT) + + # Status line is formatted as `HTTP/1.1 401 Unauthorized` + parts = status_line.split() + if len(parts) < 2 or parts[1] != b"401": + return None + + return product_id + + async def has_v2_api( host: str, websession: ClientSession | None = None, @@ -82,10 +108,14 @@ async def has_v2_api( version of the library (see `SUPPORTED_V2_MODELS`), so devices that enable the v2 API before it is officially supported keep using the v1 API. - The product type is read from the device certificate. Pass `product_type` + The product type is read from the device certificate, and the device must + respond to a request without a token with 401 Unauthorized. Pass `product_type` when it is already known (e.g. from discovery or an existing configuration): unsupported models then return False without connecting to the device, and a device of another product type at this host returns False as well. + Some devices have a generic certificate without product type; those are + reported as v2 capable when they serve the v2 API and `product_type`, when + passed, is supported. `websession` is no longer used and only kept for backwards compatibility. """ @@ -95,12 +125,17 @@ async def has_v2_api( return False try: - product_id = await _get_certificate_product_id(host) - except Exception: # pylint: disable=broad-except - # No (valid) HTTPS connection means the device is not v2 - # or not reachable at this time + product_id = await _get_v2_product_id(host) + except OSError: + # Includes SSL errors and timeouts. No (valid) HTTPS connection means + # the device is not v2 or not reachable at this time return False + if product_id == GENERIC_CERTIFICATE_ID: + # The certificate doesn't tell the product type, so rely on the + # `product_type` that passed the check above, or on the API response + return True + if product_type is not None: return product_id == MODEL_TO_ID[product_type] diff --git a/homewizard_energy/v2/__init__.py b/homewizard_energy/v2/__init__.py index 443b4567..74485a2e 100644 --- a/homewizard_energy/v2/__init__.py +++ b/homewizard_energy/v2/__init__.py @@ -39,6 +39,23 @@ T = TypeVar("T") +def create_ssl_context(validate_hostname: bool) -> ssl.SSLContext: + """Create an SSL context that validates the certificate of a device. + + The hostname is only validated when `validate_hostname` is set, as it is based + on the device identifier. Creating an SSL context has some blocking IO, so + call this in the executor. + """ + context = ssl.create_default_context(cadata=CACERT) + context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member + if validate_hostname: + context.hostname_checks_common_name = True + else: + context.check_hostname = False # Skip hostname validation + context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active + return context + + def authorized_method( func: Callable[..., Coroutine[Any, Any, T]], ) -> Callable[..., Coroutine[Any, Any, T]]: @@ -260,19 +277,11 @@ async def _get_ssl_context(self) -> ssl.SSLContext: Get a clientsession that is tuned for communication with the HomeWizard Energy Device """ - def _build_ssl_context() -> ssl.SSLContext: - context = ssl.create_default_context(cadata=CACERT) - context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member - if self._identifier is not None: - context.hostname_checks_common_name = True - else: - context.check_hostname = False # Skip hostname validation - context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active - return context - # Creating an SSL context has some blocking IO so need to run it in the executor loop = asyncio.get_running_loop() - return await loop.run_in_executor(None, _build_ssl_context) + return await loop.run_in_executor( + None, create_ssl_context, self._identifier is not None + ) @backoff.on_exception(backoff.expo, RequestError, max_tries=3, logger=None) async def _request( diff --git a/tests/test_helpers.py b/tests/test_helpers.py index c09a5e0f..4ee2e15f 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -10,10 +10,11 @@ from aiohttp import ClientSession from homewizard_energy import ( - _certificate_ssl_context, _get_certificate_product_id, + _get_v2_product_id, has_v2_api, ) +from homewizard_energy.v2 import create_ssl_context pytestmark = [pytest.mark.asyncio] @@ -31,17 +32,34 @@ def _peercert(common_name: str) -> dict[str, Any]: @pytest.fixture(name="mock_product_id") def fixture_mock_product_id() -> Generator[AsyncMock]: - """Mock the product type identifier read from the device certificate.""" + """Mock the product type identifier of a device that serves the v2 API.""" with patch( - "homewizard_energy._get_certificate_product_id", + "homewizard_energy._get_v2_product_id", new=AsyncMock(return_value="p1dongle"), ) as mock: yield mock +@pytest.fixture(name="mock_connection") +def fixture_mock_connection() -> Generator[tuple[AsyncMock, MagicMock, MagicMock]]: + """Mock the HTTPS connection to a P1 Meter that serves the v2 API.""" + reader = MagicMock() + reader.readline = AsyncMock(return_value=b"HTTP/1.1 401 Unauthorized\r\n") + writer = MagicMock() + writer.get_extra_info.return_value = _peercert("appliance/p1dongle/5c2fafaabbcc") + writer.drain = AsyncMock() + writer.wait_closed = AsyncMock() + + with patch( + "homewizard_energy.asyncio.open_connection", + new=AsyncMock(return_value=(reader, writer)), + ) as mock_open_connection: + yield mock_open_connection, reader, writer + + @pytest.mark.parametrize( "product_id", - ["p1dongle", "energysocket", "energymeter", "battery"], + ["p1dongle", "energysocket", "energymeter", "battery", "generic"], ) async def test_has_v2_api_true(mock_product_id, product_id): """Test if has_v2_api returns True for a supported v2 device.""" @@ -66,8 +84,10 @@ async def test_has_v2_api_unsupported_model(mock_product_id, product_id): "exception", [ ssl.SSLCertVerificationError, + ssl.SSLError, ConnectionRefusedError, - asyncio.TimeoutError, + ConnectionResetError, + TimeoutError, OSError, ], ) @@ -78,6 +98,14 @@ async def test_has_v2_api_no_https(mock_product_id, exception): assert await has_v2_api("example.com") is False +async def test_has_v2_api_unexpected_error(mock_product_id): + """Test if has_v2_api doesn't hide unexpected errors.""" + mock_product_id.side_effect = RuntimeError + + with pytest.raises(RuntimeError): + await has_v2_api("example.com") + + async def test_has_v2_api_websession_unused(mock_product_id): """Test if has_v2_api still accepts, but doesn't use, a websession.""" session = AsyncMock(spec=ClientSession) @@ -97,6 +125,8 @@ async def test_has_v2_api_websession_unused(mock_product_id): ("SDM230-wifi", "energymeter"), ("SDM630-wifi", "energymeter"), ("HWE-BAT", "battery"), + ("HWE-BAT", "generic"), + ("HWE-P1", "generic"), ], ) async def test_has_v2_api_product_type(mock_product_id, product_type, product_id): @@ -110,6 +140,8 @@ async def test_has_v2_api_product_type(mock_product_id, product_type, product_id @pytest.mark.parametrize("product_type", ["HWE-WTR", "HWE-DSP", "HWE-UNKNOWN"]) async def test_has_v2_api_product_type_unsupported(mock_product_id, product_type): """Test if has_v2_api skips the device for an unsupported product type.""" + mock_product_id.return_value = "generic" + assert await has_v2_api("example.com", product_type=product_type) is False mock_product_id.assert_not_awaited() @@ -135,6 +167,7 @@ async def test_has_v2_api_product_type_no_https(mock_product_id): (_peercert("appliance/p1dongle/5c2fafaabbcc"), "p1dongle"), (_peercert("appliance/energysocket/5c2fafaabbcc"), "energysocket"), (_peercert("appliance/watermeter/5c2fafaabbcc"), "watermeter"), + (_peercert("appliance/generic/3c39e7aabbcc"), "generic"), (_peercert("something/else"), None), (_peercert("device/p1dongle/5c2fafaabbcc"), None), ({"subject": ((("organizationName", "HomeWizard"),),)}, None), @@ -142,45 +175,123 @@ async def test_has_v2_api_product_type_no_https(mock_product_id): (None, None), ], ) -async def test_get_certificate_product_id(peercert, expected): +def test_get_certificate_product_id(peercert, expected): """Test reading the product type identifier from the device certificate.""" - writer = MagicMock() - writer.get_extra_info.return_value = peercert + assert _get_certificate_product_id(peercert) == expected - with patch( - "homewizard_energy.asyncio.open_connection", - new=AsyncMock(return_value=(MagicMock(), writer)), - ) as mock_open_connection: - assert await _get_certificate_product_id("example.com") == expected + +async def test_get_v2_product_id(mock_connection): + """Test the product type identifier of a device that serves the v2 API.""" + mock_open_connection, reader, writer = mock_connection + + assert await _get_v2_product_id("192.168.1.2") == "p1dongle" mock_open_connection.assert_awaited_once() - assert mock_open_connection.await_args.args == ("example.com", 443) - assert mock_open_connection.await_args.kwargs["ssl"] is _certificate_ssl_context() + assert mock_open_connection.await_args.args == ("192.168.1.2", 443) + context = mock_open_connection.await_args.kwargs["ssl"] + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname is False writer.get_extra_info.assert_called_once_with("peercert") + writer.write.assert_called_once_with( + b"GET /api HTTP/1.1\r\nHost: 192.168.1.2\r\nConnection: close\r\n\r\n" + ) + reader.readline.assert_awaited_once() writer.close.assert_called_once() + writer.wait_closed.assert_awaited_once() -async def test_get_certificate_product_id_closes_on_error(): - """Test the connection is closed when reading the certificate fails.""" - writer = MagicMock() - writer.get_extra_info.side_effect = RuntimeError +async def test_get_v2_product_id_ipv6(mock_connection): + """Test the Host header for an IPv6 address.""" + _, _, writer = mock_connection - with ( - patch( - "homewizard_energy.asyncio.open_connection", - new=AsyncMock(return_value=(MagicMock(), writer)), - ), - pytest.raises(RuntimeError), - ): - await _get_certificate_product_id("example.com") + assert await _get_v2_product_id("fe80::1") == "p1dongle" + + writer.write.assert_called_once_with( + b"GET /api HTTP/1.1\r\nHost: [fe80::1]\r\nConnection: close\r\n\r\n" + ) + + +@pytest.mark.parametrize( + "status_line", + [ + b"HTTP/1.1 404 Not Found\r\n", + b"HTTP/1.1 200 OK\r\n", + b"HTTP/1.1\r\n", + b"", + ], +) +async def test_get_v2_product_id_no_v2_api(mock_connection, status_line): + """Test a device with a valid certificate, but without the v2 API.""" + _, reader, writer = mock_connection + reader.readline.return_value = status_line + + assert await _get_v2_product_id("example.com") is None + writer.close.assert_called_once() + + +@pytest.mark.parametrize( + "peercert", + [_peercert("something/else"), {}, None], +) +async def test_get_v2_product_id_unknown_certificate(mock_connection, peercert): + """Test a certificate without product type identifier skips the request.""" + _, reader, writer = mock_connection + writer.get_extra_info.return_value = peercert + + assert await _get_v2_product_id("example.com") is None + writer.write.assert_not_called() + reader.readline.assert_not_awaited() + writer.close.assert_called_once() + + +@pytest.mark.parametrize( + "exception", + [ssl.SSLError, ConnectionResetError, asyncio.TimeoutError], +) +async def test_get_v2_product_id_close_error(mock_connection, exception): + """Test errors while closing the connection are ignored.""" + _, _, writer = mock_connection + writer.wait_closed.side_effect = exception + + assert await _get_v2_product_id("example.com") == "p1dongle" + + +@pytest.mark.parametrize( + ("mock_name", "exception"), + [ + ("readline", ConnectionResetError), + ("readline", asyncio.TimeoutError), + ("drain", ConnectionResetError), + ], +) +async def test_get_v2_product_id_closes_on_error(mock_connection, mock_name, exception): + """Test the connection is closed when the request fails.""" + _, reader, writer = mock_connection + getattr( + reader if mock_name == "readline" else writer, mock_name + ).side_effect = exception + + with pytest.raises(exception): + await _get_v2_product_id("example.com") writer.close.assert_called_once() + writer.wait_closed.assert_awaited_once() -def test_certificate_ssl_context(): - """Test the SSL context validates the certificate but not the hostname.""" - context = _certificate_ssl_context() +def test_create_ssl_context_without_hostname(): + """Test the SSL context validates the certificate, but not the hostname.""" + context = create_ssl_context(False) assert context.verify_mode == ssl.CERT_REQUIRED assert context.check_hostname is False assert context.get_ca_certs() + + +def test_create_ssl_context_with_hostname(): + """Test the SSL context validates the certificate and the hostname.""" + context = create_ssl_context(True) + + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname is True + assert context.hostname_checks_common_name is True + assert context.get_ca_certs() From 34a771a5c97ac317e83d2f9b85be2300fd569a16 Mon Sep 17 00:00:00 2001 From: Lex Postma Date: Wed, 25 Nov 2026 16:44:13 +0100 Subject: [PATCH 4/4] Describe generic certificates as used by development units Co-Authored-By: Claude Opus 5.5 --- homewizard_energy/__init__.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/homewizard_energy/__init__.py b/homewizard_energy/__init__.py index 8f66903b..545e5c8c 100644 --- a/homewizard_energy/__init__.py +++ b/homewizard_energy/__init__.py @@ -28,8 +28,8 @@ MODEL_TO_ID[model] for model in SUPPORTED_V2_MODELS ) -# Some devices have a certificate without product type, e.g. early batteries -# with `appliance/generic/` +# Development units have a certificate without product type, +# formatted as `appliance/generic/` GENERIC_CERTIFICATE_ID = "generic" # Timeout in seconds for connecting to the device and for its response @@ -113,9 +113,9 @@ async def has_v2_api( when it is already known (e.g. from discovery or an existing configuration): unsupported models then return False without connecting to the device, and a device of another product type at this host returns False as well. - Some devices have a generic certificate without product type; those are - reported as v2 capable when they serve the v2 API and `product_type`, when - passed, is supported. + Development units have a generic certificate without product type; those + are reported as v2 capable when they serve the v2 API and `product_type`, + when passed, is supported. `websession` is no longer used and only kept for backwards compatibility. """ @@ -132,8 +132,9 @@ async def has_v2_api( return False if product_id == GENERIC_CERTIFICATE_ID: - # The certificate doesn't tell the product type, so rely on the - # `product_type` that passed the check above, or on the API response + # The certificate of a development unit doesn't tell the product type, + # so rely on the `product_type` that passed the check above, or on the + # API response return True if product_type is not None: