diff --git a/homewizard_energy/__init__.py b/homewizard_energy/__init__.py index a34344e..545e5c8 100644 --- a/homewizard_energy/__init__.py +++ b/homewizard_energy/__init__.py @@ -1,11 +1,16 @@ """HomeWizard Energy API library.""" -from aiohttp import ClientSession, ClientTimeout +import asyncio +from contextlib import suppress +from typing import Any +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 import HomeWizardEnergyV2, create_ssl_context __all__ = [ "DisabledError", @@ -17,28 +22,122 @@ "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 +) + +# 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 +TIMEOUT = 5 + + +def _get_certificate_product_id(certificate: dict[str, Any] | None) -> str | None: + """Get the product type identifier from a device certificate. + + The common name of the certificate is formatted as + `appliance//`, see `MODEL_TO_ID`. + """ + for rdn in (certificate or {}).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.""" - websession_provided = websession is not None - if websession is None: - websession = ClientSession() + +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: - # 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=ClientTimeout(total=5), + 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" ) - res.close() + 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 res.status == 401 - except Exception: # pylint: disable=broad-except - # all other status/exceptions means the device is not v2 or not reachable at this time + return product_id + + +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, 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. + 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. + """ + del websession # Kept for backwards compatibility + + if product_type is not None and product_type not in SUPPORTED_V2_MODELS: return False - finally: - if not websession_provided: - await websession.close() + + try: + 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 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: + return product_id == MODEL_TO_ID[product_type] + + return product_id in SUPPORTED_V2_CERTIFICATE_IDS diff --git a/homewizard_energy/const.py b/homewizard_energy/const.py index 8f4e92e..7bd344f 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/homewizard_energy/v2/__init__.py b/homewizard_energy/v2/__init__.py index 443b456..74485a2 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 079c5a0..4ee2e15 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1,68 +1,297 @@ """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 ( + _get_certificate_product_id, + _get_v2_product_id, + has_v2_api, +) +from homewizard_energy.v2 import create_ssl_context pytestmark = [pytest.mark.asyncio] -async def test_has_v2_api_true(aresponses): - """Test if has_v2_api returns True for a v2 device.""" - - aresponses.add( - "example.com", - "/api", - "GET", - aresponses.Response( - status=401, +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 of a device that serves the v2 API.""" + with patch( + "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", "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.""" + mock_product_id.return_value = product_id + + assert await has_v2_api("example.com") 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(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 + + assert await has_v2_api("example.com") is False + + +@pytest.mark.parametrize( + "exception", + [ + ssl.SSLCertVerificationError, + ssl.SSLError, + ConnectionRefusedError, + ConnectionResetError, + 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 + + 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) + + assert await has_v2_api("example.com", session) is True + assert not session.mock_calls + mock_product_id.assert_awaited_once_with("example.com") + + +@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"), + ("HWE-BAT", "generic"), + ("HWE-P1", "generic"), + ], +) +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") + + +@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() + + +@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 + + assert await has_v2_api("example.com", product_type="HWE-P1") is False + + +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( + ("peercert", "expected"), + [ + (_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), + ({}, None), + (None, None), + ], +) +def test_get_certificate_product_id(peercert, expected): + """Test reading the product type identifier from the device certificate.""" + assert _get_certificate_product_id(peercert) == 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 == ("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 with ClientSession() as session: - result = await has_v2_api("example.com", session) - assert result is True +async def test_get_v2_product_id_ipv6(mock_connection): + """Test the Host header for an IPv6 address.""" + _, _, writer = mock_connection -async def test_has_v2_api_false(aresponses): - """Test if has_v2_api returns False for a non-v2 device.""" - aresponses.add( - "example.com", - "/api", - "GET", - aresponses.Response( - status=404, - ), + 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" ) - async with ClientSession() as session: - result = await has_v2_api("example.com", session) - assert result is False +@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 -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) + assert await _get_v2_product_id("example.com") is None + writer.close.assert_called_once() - result = await has_v2_api("example.com", session) - assert result is False +@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 -async def test_has_v2_api_own_session(aresponses): - """Test if has_v2_api opens and closes its own session.""" - aresponses.add( - "example.com", - "/api", - "GET", - aresponses.Response( - status=401, - ), - ) + 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_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) - result = await has_v2_api("example.com") - assert result is 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()