From 452ad9e5f4ac4891c3a1cb9fa93e640b07742a2f Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 20 Nov 2026 13:48:52 +0100 Subject: [PATCH 01/15] Add pyhap.client: move the benchmark HAP client into the package The mock controller in benchmarks/client.py was in a usable state - it speaks the real protocol (pair-verify, encrypted transport, characteristic reads/writes, subscriptions, EVENT push) - so it moves to pyhap.client as HAPClient, split into identity/protocol/controller modules. The benchmarks now import it from there. On top of the move, the client gains batch characteristic reads/writes, unsubscribe, raw event access (next_event) and a pair-verify error check, and reuses pyhap.const.RESPONSE_TIMEOUT. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 9 + benchmarks/__init__.py | 2 +- benchmarks/run.py | 10 +- docs/source/api/client.rst | 15 ++ pyhap/client/__init__.py | 36 +++ .../client.py => pyhap/client/controller.py | 215 +++++++----------- pyhap/client/identity.py | 44 ++++ pyhap/client/protocol.py | 59 +++++ 8 files changed, 249 insertions(+), 141 deletions(-) create mode 100644 docs/source/api/client.rst create mode 100644 pyhap/client/__init__.py rename benchmarks/client.py => pyhap/client/controller.py (68%) create mode 100644 pyhap/client/identity.py create mode 100644 pyhap/client/protocol.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d6c58c7e..53306ab2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,15 @@ Sections ## [Unreleased] +### Added + +- `pyhap.client`: a HAP client (controller) package speaking the real + protocol - pair-verify, encrypted transport, characteristic reads/writes, + event subscriptions and `EVENT` push frames. Moved out of + `benchmarks/client.py` (now `pyhap.client.HAPClient`) and extended with + batch reads/writes, unsubscribe and raw event access. Covered by the new + integration tests in `tests/integration/`. + ### Fixed - Drop the write response of a coroutine setter that answers only after its diff --git a/benchmarks/__init__.py b/benchmarks/__init__.py index 31defc4f..50042432 100644 --- a/benchmarks/__init__.py +++ b/benchmarks/__init__.py @@ -2,7 +2,7 @@ See ``benchmarks/README.md`` for usage. The modules are: -* ``benchmarks.client``: a mock HAP controller (client) speaking the real +* ``pyhap.client``: the mock HAP controller (client) speaking the real protocol: pair-verify, encrypted transport and EVENT push events. * ``benchmarks.server``: the benchmark accessory server, run as a child process by the orchestrator. diff --git a/benchmarks/run.py b/benchmarks/run.py index be72664a..f2934ed2 100644 --- a/benchmarks/run.py +++ b/benchmarks/run.py @@ -49,10 +49,10 @@ REPO_ROOT = Path(__file__).resolve().parent.parent try: - from benchmarks.client import BenchController, ClientIdentity -except ImportError: # running as a plain script, not ``-m benchmarks.run`` + from pyhap.client import ClientIdentity, HAPClient +except ImportError: # running as a plain script without the package installed sys.path.insert(0, str(REPO_ROOT)) - from benchmarks.client import BenchController, ClientIdentity + from pyhap.client import ClientIdentity, HAPClient try: import psutil @@ -489,10 +489,10 @@ async def run_scenario(scenario: Scenario, args: argparse.Namespace) -> dict[str # ### Connect and pair-verify ### sampler.mark("connect") - clients: list[BenchController] = [] + clients: list[HAPClient] = [] pair_verify_ms: list[float] = [] for identity in identities: - controller = BenchController(identity, ltpk) + controller = HAPClient(identity, ltpk) started = time.perf_counter() await controller.connect("127.0.0.1", port) pair_verify_ms.append((time.perf_counter() - started) * 1000) diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst new file mode 100644 index 00000000..436a1a64 --- /dev/null +++ b/docs/source/api/client.rst @@ -0,0 +1,15 @@ +.. _api-client: + +====== +Client +====== + +A HAP controller (client) that speaks the real protocol against a running +accessory: pair-verify, the encrypted transport, characteristic +reads/writes, event subscriptions and ``EVENT`` push frames. The benchmark +suite and the integration tests use it to drive an +:class:`pyhap.accessory_driver.AccessoryDriver` end to end; it is also handy +for testing your own accessory. + +.. automodule:: pyhap.client + :members: diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py new file mode 100644 index 00000000..16747c61 --- /dev/null +++ b/pyhap/client/__init__.py @@ -0,0 +1,36 @@ +"""A HAP client (controller) for driving a HAP accessory over the real protocol. + +The client speaks the same protocol as a real iOS controller: + +* ``POST /pair-verify`` with X25519/Ed25519/HKDF and TLV payloads, based on a + pre-paired long-term identity (:class:`ClientIdentity`). +* The encrypted transport (ChaCha20-Poly1305 in 1024 byte blocks) via + :class:`pyhap.hap_crypto.HAPCrypto` in ``client_side`` mode. +* Plain HTTP/1.1 requests for characteristic reads/writes, subscriptions and + ``GET /accessories``, plus parsing of interleaved ``EVENT/1.0`` push frames + on the same connection. + +It is used by the benchmark suite (``benchmarks/run.py``) and by the +integration tests in ``tests/integration/`` to exercise a running +:class:`pyhap.accessory_driver.AccessoryDriver` end to end:: + + identity = ClientIdentity.generate(0) + driver.pair(identity.uuid_bytes, identity.public_key_bytes, HAP_PERMISSIONS.ADMIN) + # ... start the driver, then: + client = HAPClient(identity, accessory_ltpk_raw_bytes) + await client.connect("127.0.0.1", port) + frame = await client.get_accessories() +""" + +from ..const import RESPONSE_TIMEOUT +from .controller import HAPClient +from .identity import ClientIdentity +from .protocol import Frame, parse_frame + +__all__ = [ + "RESPONSE_TIMEOUT", + "ClientIdentity", + "Frame", + "HAPClient", + "parse_frame", +] diff --git a/benchmarks/client.py b/pyhap/client/controller.py similarity index 68% rename from benchmarks/client.py rename to pyhap/client/controller.py index dcf5afc3..aa02a219 100644 --- a/benchmarks/client.py +++ b/pyhap/client/controller.py @@ -1,139 +1,50 @@ -"""A mock HAP controller (client) used to drive the benchmark server. - -This module speaks the real HAP protocol against the server: - -* ``POST /pair-verify`` with X25519/Ed25519/HKDF and TLV payloads, exactly - as a real iOS controller would, based on a pre-paired long-term identity. -* The encrypted transport (ChaCha20-Poly1305 in 1024 byte blocks) via - :class:`pyhap.hap_crypto.HAPCrypto` in ``client_side`` mode. -* Plain HTTP/1.1 requests for characteristic reads/writes, subscriptions - and ``GET /accessories``, plus parsing of interleaved ``EVENT/1.0`` push - frames on the same connection. +"""A HAP controller (client) connected to a HAP accessory server. The client deliberately avoids h11 so that interleaved ``EVENT`` frames can -be parsed without fighting a strict HTTP state machine, and to keep the -flamegraph of the *server* process clean of client machinery. +be parsed without fighting a strict HTTP state machine. Requests on a +connection are strictly sequential (like the real protocol on a single +socket) while ``EVENT`` frames may arrive at any time between responses. """ from __future__ import annotations import asyncio -from dataclasses import dataclass +from collections.abc import Iterable import json import logging -import time from typing import Any -import uuid as uuid_module from chacha20poly1305_reuseable import ChaCha20Poly1305Reusable as ChaCha20Poly1305 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519, x25519 -from pyhap import tlv -from pyhap.hap_crypto import HAPCrypto, hap_hkdf, pad_tls_nonce -from pyhap.hap_handler import HAP_TLV_STATES, HAP_TLV_TAGS +from .. import tlv +from ..characteristic import CharacteristicWrite +from ..const import RESPONSE_TIMEOUT +from ..hap_crypto import HAPCrypto, hap_hkdf, pad_tls_nonce +from ..hap_handler import HAP_TLV_STATES, HAP_TLV_TAGS +from .identity import ClientIdentity +from .protocol import HAP_CONTENT_TYPE, PAIRING_CONTENT_TYPE, Frame, parse_frame logger = logging.getLogger(__name__) -# The server closes connections that take longer than 10 seconds to -# respond, so never wait longer than that on the client side either. -RESPONSE_TIMEOUT = 9.0 - -_PAIRING_CONTENT_TYPE = b"application/pairing+tlv8" -_HAP_CONTENT_TYPE = b"application/hap+json" - -_HEADER_SEPARATOR = b"\r\n\r\n" - - -@dataclass(frozen=True) -class ClientIdentity: - """The long-term pairing identity of a mock controller. - - The server pre-pairs these identities at startup (bypassing the slow - SRP pair-setup), so each controller only needs a pair-verify to open - an encrypted session. - """ - - uuid: str - private_key: ed25519.Ed25519PrivateKey - - @classmethod - def generate(cls, index: int) -> ClientIdentity: - """Generate a deterministic identity for the given index.""" - pair_uuid = str( - uuid_module.uuid5(uuid_module.NAMESPACE_URL, f"hap-bench-client-{index}") - ) - return cls(pair_uuid, ed25519.Ed25519PrivateKey.generate()) - - @property - def uuid_bytes(self) -> bytes: - """The UUID in the wire format the server expects.""" - return self.uuid.encode("utf-8") - - @property - def public_key_bytes(self) -> bytes: - """The raw long-term public key bytes.""" - return self.private_key.public_key().public_bytes( - encoding=serialization.Encoding.Raw, - format=serialization.PublicFormat.Raw, - ) - +# RESPONSE_TIMEOUT is the server's own request timeout: it closes connections +# that take longer than 10 seconds to respond, so never wait longer than that +# on the client side either. -@dataclass(frozen=True) -class Frame: - """A parsed HTTP response or EVENT frame received from the server.""" - kind: str # "response" or "event" - status: int - body: bytes - received_ns: int +class HAPClient: + """A HAP controller connected to an accessory server. - -def _parse_frame(buffer: bytearray) -> Frame | None: - """Parse one frame from ``buffer``. - - Returns ``None`` if the buffer does not hold a complete frame yet, in - which case the buffer is left untouched. Otherwise the frame is - returned and its bytes are consumed from the buffer. - """ - header_end = buffer.find(_HEADER_SEPARATOR) - if header_end < 0: - return None - lines = bytes(buffer[:header_end]).split(b"\r\n") - start = lines[0] - if start.startswith(b"EVENT/"): - kind = "event" - elif start.startswith(b"HTTP/"): - kind = "response" - else: - raise RuntimeError(f"Client received unexpected data: {start!r}") - status = int(start.split(b" ", 2)[1]) - content_length = 0 - for header in lines[1:]: - name, _, value = header.partition(b":") - if name.strip().lower() == b"content-length": - content_length = int(value.strip()) - body_start = header_end + len(_HEADER_SEPARATOR) - total = body_start + content_length - if len(buffer) < total: - return None - body = bytes(buffer[body_start:total]) - del buffer[:total] - return Frame(kind, status, body, time.perf_counter_ns()) - - -class BenchController: - """A mock HAP controller connected to the benchmark server. - - Requests on a connection are strictly sequential (like the real - protocol on a single socket) while ``EVENT`` frames may arrive at any - time between responses. + Create one per :class:`ClientIdentity` that the accessory is paired + with, then :meth:`connect` to run the pair-verify handshake and switch + to the encrypted transport. """ def __init__(self, identity: ClientIdentity, accessory_ltpk: bytes) -> None: """Initialize the controller for a given pairing identity. - :param identity: The long-term identity the server pre-paired. + :param identity: The long-term identity the server is paired with. :param accessory_ltpk: Raw long-term public key of the accessory, used to verify the server during pair-verify. """ @@ -200,7 +111,9 @@ async def _pair_verify(self) -> None: HAP_TLV_TAGS.PUBLIC_KEY, ephemeral_public, ) - response = await self._request(b"POST", b"/pair-verify", body) + response = await self._request( + b"POST", b"/pair-verify", body, content_type=PAIRING_CONTENT_TYPE + ) answer = tlv.decode(response.body) if answer.get(HAP_TLV_TAGS.SEQUENCE_NUM) != HAP_TLV_STATES.M2: raise RuntimeError(f"Unexpected pair-verify response: {answer!r}") @@ -241,10 +154,17 @@ async def _pair_verify(self) -> None: HAP_TLV_TAGS.ENCRYPTED_DATA, aead_message, ) - response = await self._request(b"POST", b"/pair-verify", body) + response = await self._request( + b"POST", b"/pair-verify", body, content_type=PAIRING_CONTENT_TYPE + ) answer = tlv.decode(response.body) if answer.get(HAP_TLV_TAGS.SEQUENCE_NUM) != HAP_TLV_STATES.M4: raise RuntimeError(f"Unexpected pair-verify response: {answer!r}") + if HAP_TLV_TAGS.ERROR_CODE in answer: + raise RuntimeError( + f"{self.name}: pair-verify rejected by the accessory: " + f"{answer[HAP_TLV_TAGS.ERROR_CODE]!r}" + ) # The M4 response arrives in plaintext; everything after it is # encrypted with the session key. @@ -268,7 +188,7 @@ async def _read_loop(self) -> None: else: plaintext = data self._buffer += plaintext - while (frame := _parse_frame(self._buffer)) is not None: + while (frame := parse_frame(self._buffer)) is not None: self._dispatch(frame) except asyncio.CancelledError: raise @@ -299,7 +219,7 @@ async def _request( method: bytes, target: bytes, body: bytes, - content_type: bytes = _HAP_CONTENT_TYPE, + content_type: bytes = HAP_CONTENT_TYPE, ) -> Frame: """Send one HTTP request and await its response frame.""" if self._closed: @@ -336,44 +256,69 @@ async def get_accessories(self) -> Frame: """``GET /accessories`` - the full accessory list.""" return await self._request(b"GET", b"/accessories", b"") + async def read_characteristics(self, char_ids: Iterable[tuple[int, int]]) -> Frame: + """``GET /characteristics?id=aid.iid,...`` for one or more characteristics.""" + ids = ",".join(f"{aid}.{iid}" for aid, iid in char_ids) + target = b"/characteristics?id=" + ids.encode("ascii") + return await self._request(b"GET", target, b"") + async def read_characteristic(self, aid: int, iid: int) -> Frame: """``GET /characteristics?id=aid.iid``.""" - target = b"/characteristics?id=" + f"{aid}.{iid}".encode("ascii") - return await self._request(b"GET", target, b"") + return await self.read_characteristics([(aid, iid)]) - async def write_characteristic( - self, aid: int, iid: int, value: Any, write_response: bool = False + async def write_characteristics( + self, characteristics: Iterable[CharacteristicWrite] ) -> Frame: - """``PUT /characteristics`` with a single characteristic value.""" + """``PUT /characteristics`` with the given entries. + + Each entry is a :class:`pyhap.characteristic.CharacteristicWrite`: + ``aid``/``iid`` plus any of ``value`` (write), ``ev`` (subscribe or + unsubscribe) and ``r`` (write response). + """ query: dict[str, Any] = { - "characteristics": [ - {"aid": aid, "iid": iid, "value": value, "r": write_response} - ] + "characteristics": [dict(entry) for entry in characteristics] } response = await self._request( b"PUT", b"/characteristics", json.dumps(query).encode("utf-8") ) if response.status not in (200, 204, 207): raise RuntimeError( - f"{self.name}: write of {aid}.{iid} failed: " - f"{response.status} {response.body!r}" + f"{self.name}: write failed: {response.status} {response.body!r}" ) return response + async def write_characteristic( + self, aid: int, iid: int, value: Any, write_response: bool = False + ) -> Frame: + """``PUT /characteristics`` with a single characteristic value.""" + return await self.write_characteristics( + [{"aid": aid, "iid": iid, "value": value, "r": write_response}] + ) + + async def set_event_subscription( + self, aid: int, iid: int, subscribed: bool + ) -> Frame: + """Subscribe to (``subscribed=True``) or unsubscribe from events.""" + return await self.write_characteristics( + [{"aid": aid, "iid": iid, "ev": subscribed}] + ) + async def subscribe(self, aid: int, iid: int) -> Frame: """Subscribe to events for a characteristic (``ev: true``).""" - query: dict[str, Any] = { - "characteristics": [{"aid": aid, "iid": iid, "ev": True}] - } - response = await self._request( - b"PUT", b"/characteristics", json.dumps(query).encode("utf-8") + return await self.set_event_subscription(aid, iid, True) + + async def unsubscribe(self, aid: int, iid: int) -> Frame: + """Unsubscribe from events for a characteristic (``ev: false``).""" + return await self.set_event_subscription(aid, iid, False) + + async def next_event( + self, timeout: float = RESPONSE_TIMEOUT + ) -> tuple[int, int, Any]: + """Wait for the next EVENT frame and return ``(aid, iid, value)``.""" + event_aid, event_iid, event_value, _ = await asyncio.wait_for( + self._events.get(), timeout ) - if response.status not in (200, 204, 207): - raise RuntimeError( - f"{self.name}: subscribe to {aid}.{iid} failed: " - f"{response.status} {response.body!r}" - ) - return response + return event_aid, event_iid, event_value async def wait_event( self, diff --git a/pyhap/client/identity.py b/pyhap/client/identity.py new file mode 100644 index 00000000..d9c7c76e --- /dev/null +++ b/pyhap/client/identity.py @@ -0,0 +1,44 @@ +"""The long-term pairing identity of a HAP client (controller).""" + +from __future__ import annotations + +from dataclasses import dataclass +import uuid as uuid_module + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed25519 + + +@dataclass(frozen=True) +class ClientIdentity: + """The long-term pairing identity of a HAP controller. + + The accessory must be paired with this identity first (e.g. via + :meth:`pyhap.accessory_driver.AccessoryDriver.pair`, bypassing the slow + SRP pair-setup), so the client only needs a pair-verify to open an + encrypted session. + """ + + uuid: str + private_key: ed25519.Ed25519PrivateKey + + @classmethod + def generate(cls, index: int = 0) -> ClientIdentity: + """Generate a deterministic identity for the given index.""" + pair_uuid = str( + uuid_module.uuid5(uuid_module.NAMESPACE_URL, f"hap-client-{index}") + ) + return cls(pair_uuid, ed25519.Ed25519PrivateKey.generate()) + + @property + def uuid_bytes(self) -> bytes: + """The UUID in the wire format the server expects.""" + return self.uuid.encode("utf-8") + + @property + def public_key_bytes(self) -> bytes: + """The raw long-term public key bytes.""" + return self.private_key.public_key().public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) diff --git a/pyhap/client/protocol.py b/pyhap/client/protocol.py new file mode 100644 index 00000000..c676de49 --- /dev/null +++ b/pyhap/client/protocol.py @@ -0,0 +1,59 @@ +"""Frame parsing for a HAP client connection. + +A connection carries plain HTTP/1.1 responses and interleaved ``EVENT/1.0`` +push frames; :func:`parse_frame` splits one frame out of a byte buffer without +an HTTP state machine, so the two can be told apart as they arrive. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import time + +PAIRING_CONTENT_TYPE = b"application/pairing+tlv8" +HAP_CONTENT_TYPE = b"application/hap+json" + +_HEADER_SEPARATOR = b"\r\n\r\n" + + +@dataclass(frozen=True) +class Frame: + """A parsed HTTP response or EVENT frame received from the server.""" + + kind: str # "response" or "event" + status: int + body: bytes + received_ns: int + + +def parse_frame(buffer: bytearray) -> Frame | None: + """Parse one frame from ``buffer``. + + Returns ``None`` if the buffer does not hold a complete frame yet, in + which case the buffer is left untouched. Otherwise the frame is returned + and its bytes are consumed from the buffer. + """ + header_end = buffer.find(_HEADER_SEPARATOR) + if header_end < 0: + return None + lines = bytes(buffer[:header_end]).split(b"\r\n") + start = lines[0] + if start.startswith(b"EVENT/"): + kind = "event" + elif start.startswith(b"HTTP/"): + kind = "response" + else: + raise RuntimeError(f"Client received unexpected data: {start!r}") + status = int(start.split(b" ", 2)[1]) + content_length = 0 + for header in lines[1:]: + name, _, value = header.partition(b":") + if name.strip().lower() == b"content-length": + content_length = int(value.strip()) + body_start = header_end + len(_HEADER_SEPARATOR) + total = body_start + content_length + if len(buffer) < total: + return None + body = bytes(buffer[body_start:total]) + del buffer[:total] + return Frame(kind, status, body, time.perf_counter_ns()) From f6ad1fee220c41ae18adc9fcd9f85883d1e872f8 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 20 Nov 2026 13:48:52 +0100 Subject: [PATCH 02/15] Add integration tests driving a real AccessoryDriver with pyhap.client tests/integration/ runs an AccessoryDriver in-process on a loopback port, pre-pairs client identities and connects real HAPClient instances. Covered: standalone and bridged accessories (GET /accessories, reads/writes by aid/iid), setter callbacks at accessory/service/characteristic level plus the characteristic getter (including an async setter delaying the write response), and the notification paths: a write from one client is evented to another subscribed client (never back to the writer), unsubscribe stops delivery, and accessory-side set_value is pushed too. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- tests/integration/__init__.py | 8 + tests/integration/conftest.py | 127 ++++++++++++++++ tests/integration/helpers.py | 78 ++++++++++ tests/integration/test_bridged_accessory.py | 80 ++++++++++ tests/integration/test_callbacks.py | 138 ++++++++++++++++++ tests/integration/test_notifications.py | 101 +++++++++++++ .../integration/test_standalone_accessory.py | 84 +++++++++++ 7 files changed, 616 insertions(+) create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/conftest.py create mode 100644 tests/integration/helpers.py create mode 100644 tests/integration/test_bridged_accessory.py create mode 100644 tests/integration/test_callbacks.py create mode 100644 tests/integration/test_notifications.py create mode 100644 tests/integration/test_standalone_accessory.py diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 00000000..abf09a35 --- /dev/null +++ b/tests/integration/__init__.py @@ -0,0 +1,8 @@ +"""Integration tests: real HAP clients against a running AccessoryDriver. + +These tests start an ``AccessoryDriver`` in-process on a loopback port and +drive it with :class:`pyhap.client.HAPClient` instances that perform the +real pair-verify handshake and speak the encrypted HAP transport, covering +standalone and bridged accessories, the setter/getter callbacks and the +EVENT notification paths end to end. +""" diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 00000000..de0d7ed3 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,127 @@ +"""Fixtures that run a real AccessoryDriver in-process with real HAP clients.""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Awaitable, Callable +import pathlib +import socket + +from cryptography.hazmat.primitives import serialization +import pytest + +from pyhap.accessory import Accessory +from pyhap.accessory_driver import AccessoryDriver +from pyhap.client import ClientIdentity, HAPClient +from pyhap.const import HAP_PERMISSIONS + +AccessoryFactory = Callable[[AccessoryDriver], Accessory] + + +def reserve_port() -> int: + """Reserve a loopback port for the HAP server. + + ``AccessoryDriver`` cannot express "pick an ephemeral port" (``State`` + falls back to the default port for port 0), so a port is reserved and + immediately released here for the driver to bind. + """ + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +class HAPServerHarness: + """A running ``AccessoryDriver`` with pre-paired HAP clients. + + The identities are paired directly via ``AccessoryDriver.pair`` (which + bypasses the slow SRP pair-setup), so each :meth:`connect` only needs + the pair-verify handshake before it can speak the encrypted transport. + """ + + def __init__( + self, + driver: AccessoryDriver, + identities: list[ClientIdentity], + accessory_ltpk: bytes, + ) -> None: + """Store the driver, the paired identities and the accessory LTPK.""" + self.driver = driver + self.identities = identities + self.accessory_ltpk = accessory_ltpk + self.clients: list[HAPClient] = [] + + @classmethod + async def start( + cls, + accessory_factory: AccessoryFactory, + persist_file: pathlib.Path, + client_count: int = 1, + ) -> HAPServerHarness: + """Build the accessory, pair ``client_count`` clients and start the driver.""" + driver = AccessoryDriver( + loop=asyncio.get_running_loop(), + address="127.0.0.1", + listen_address="127.0.0.1", + port=reserve_port(), + persist_file=str(persist_file), + advertise=False, + ) + driver.add_accessory(accessory_factory(driver)) + identities = [ClientIdentity.generate(index) for index in range(client_count)] + for identity in identities: + driver.pair( + identity.uuid_bytes, identity.public_key_bytes, HAP_PERMISSIONS.ADMIN + ) + await driver.async_start() + ltpk = driver.state.public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + return cls(driver, identities, ltpk) + + @property + def port(self) -> int: + """The loopback port the HAP server listens on.""" + return self.driver.state.port + + async def connect(self, index: int = 0) -> HAPClient: + """Connect pre-paired client ``index`` (pair-verify included).""" + client = HAPClient(self.identities[index], self.accessory_ltpk) + self.clients.append(client) + await client.connect("127.0.0.1", self.port) + return client + + async def stop(self) -> None: + """Close all clients and stop the driver.""" + for client in self.clients: + await client.close() + self.clients.clear() + await self.driver.async_stop() + + +@pytest.fixture +async def make_hap_server( + tmp_path: pathlib.Path, +) -> AsyncIterator[Callable[..., Awaitable[HAPServerHarness]]]: + """Start a driver for the accessory built by the given factory. + + Usage: ``server = await make_hap_server(lambda driver: MyAccessory(driver))``. + Pass ``client_count=N`` to pre-pair N clients. Every started server is + stopped when the test ends. + """ + harnesses: list[HAPServerHarness] = [] + + async def _make( + accessory_factory: AccessoryFactory, client_count: int = 1 + ) -> HAPServerHarness: + state_file = tmp_path / f"accessory-{len(harnesses)}.state" + harness = await HAPServerHarness.start( + accessory_factory, state_file, client_count + ) + harnesses.append(harness) + return harness + + yield _make + + for harness in harnesses: + await harness.stop() diff --git a/tests/integration/helpers.py b/tests/integration/helpers.py new file mode 100644 index 00000000..ab827fae --- /dev/null +++ b/tests/integration/helpers.py @@ -0,0 +1,78 @@ +"""Shared accessories and response helpers for the integration tests.""" + +from __future__ import annotations + +import json +from typing import Any + +from pyhap.accessory import Accessory +from pyhap.accessory_driver import AccessoryDriver +from pyhap.characteristic import Characteristic +from pyhap.client import Frame +from pyhap.const import CATEGORY_LIGHTBULB, CATEGORY_SWITCH + +# Service / characteristic type UUIDs in the short HAP form used in JSON +# payloads. +SWITCH_SERVICE_TYPE = "49" +ON_CHARACTERISTIC_TYPE = "25" +ACCESSORY_INFORMATION_TYPE = "3E" +LIGHTBULB_SERVICE_TYPE = "43" + + +class SwitchAccessory(Accessory): + """A switch accessory with a single writable ``On`` characteristic.""" + + category = CATEGORY_SWITCH + + def __init__( + self, driver: AccessoryDriver, display_name: str, aid: int | None = None + ) -> None: + """Create the switch with the preloaded Switch service.""" + super().__init__(driver, display_name, aid=aid) + self.service = self.add_preload_service("Switch") + self.char_on = self.service.get_characteristic("On") + + +class LightbulbAccessory(Accessory): + """A lightbulb with writable ``On`` and ``Brightness`` characteristics.""" + + category = CATEGORY_LIGHTBULB + + def __init__( + self, driver: AccessoryDriver, display_name: str, aid: int | None = None + ) -> None: + """Create the lightbulb with the preloaded Lightbulb service.""" + super().__init__(driver, display_name, aid=aid) + self.service = self.add_preload_service("Lightbulb", chars=["Brightness"]) + self.char_on = self.service.get_characteristic("On") + self.char_brightness = self.service.get_characteristic("Brightness") + + +def build_switch(driver: AccessoryDriver) -> SwitchAccessory: + """The switch accessory the integration tests run against.""" + return SwitchAccessory(driver, "Test Switch") + + +def iid_of(accessory: Accessory, char: Characteristic) -> int: + """The IID the driver assigned to ``char`` within ``accessory``.""" + iid = accessory.iid_manager.get_iid(char) + assert iid is not None + return iid + + +def body_json(frame: Frame) -> Any: + """Parse the JSON body of a response frame.""" + return json.loads(frame.body) + + +def characteristic_entries(frame: Frame) -> dict[tuple[int, int], dict[str, Any]]: + """The ``characteristics`` list of a response, keyed by ``(aid, iid)``.""" + return { + (int(entry["aid"]), int(entry["iid"])): entry + for entry in body_json(frame)["characteristics"] + } + + +def characteristic_value(frame: Frame, aid: int, iid: int) -> Any: + """The ``value`` of one characteristic in a read response.""" + return characteristic_entries(frame)[(aid, iid)]["value"] diff --git a/tests/integration/test_bridged_accessory.py b/tests/integration/test_bridged_accessory.py new file mode 100644 index 00000000..399ada78 --- /dev/null +++ b/tests/integration/test_bridged_accessory.py @@ -0,0 +1,80 @@ +"""Integration tests for a Bridge with bridged accessories over real HAP.""" + +from __future__ import annotations + +from typing import Any, cast + +import pytest + +from pyhap.accessory import Bridge + +from .helpers import ( + SwitchAccessory, + body_json, + characteristic_value, + iid_of, +) + +# Real socket + crypto round trips; the CI default of --timeout=2 is too +# tight on shared runners. +pytestmark = pytest.mark.timeout(10) + + +def build_bridge(driver: Any) -> Bridge: + """A bridge with two switch accessories.""" + bridge = Bridge(driver, "Test Bridge") + bridge.add_accessory(SwitchAccessory(driver, "Switch One", aid=2)) + bridge.add_accessory(SwitchAccessory(driver, "Switch Two", aid=3)) + return bridge + + +async def test_bridge_serves_all_bridged_accessories(make_hap_server: Any) -> None: + """GET /accessories lists the bridge and every bridged accessory.""" + server = await make_hap_server(build_bridge) + client = await server.connect(0) + + frame = await client.get_accessories() + assert frame.status == 200 + accessories = body_json(frame)["accessories"] + assert [acc["aid"] for acc in accessories] == [1, 2, 3] + # The bridge's own accessory information carries the bridge name. + bridge = cast("Bridge", server.driver.accessory) + info = bridge.get_service("AccessoryInformation") + assert info is not None + name_iid = iid_of(bridge, info.get_characteristic("Name")) + frame = await client.read_characteristic(1, name_iid) + assert characteristic_value(frame, 1, name_iid) == "Test Bridge" + + +async def test_bridged_characteristics_are_addressed_by_aid( + make_hap_server: Any, +) -> None: + """Reads and writes on one bridged accessory leave the others alone.""" + server = await make_hap_server(build_bridge) + bridge = cast("Bridge", server.driver.accessory) + acc_one = cast("SwitchAccessory", bridge.accessories[2]) + acc_two = cast("SwitchAccessory", bridge.accessories[3]) + on_one = iid_of(acc_one, acc_one.char_on) + on_two = iid_of(acc_two, acc_two.char_on) + + client = await server.connect(0) + + # One request can read characteristics of several accessories. + frame = await client.read_characteristics([(2, on_one), (3, on_two)]) + assert frame.status == 200 + assert characteristic_value(frame, 2, on_one) is False + assert characteristic_value(frame, 3, on_two) is False + + # Writing aid 2 does not touch aid 3. + frame = await client.write_characteristic(2, on_one, True) + assert frame.status == 204 + frame = await client.read_characteristics([(2, on_one), (3, on_two)]) + assert characteristic_value(frame, 2, on_one) is True + assert characteristic_value(frame, 3, on_two) is False + + # And the other way around. + frame = await client.write_characteristic(3, on_two, True) + assert frame.status == 204 + frame = await client.read_characteristics([(2, on_one), (3, on_two)]) + assert characteristic_value(frame, 2, on_one) is True + assert characteristic_value(frame, 3, on_two) is True diff --git a/tests/integration/test_callbacks.py b/tests/integration/test_callbacks.py new file mode 100644 index 00000000..d46256c7 --- /dev/null +++ b/tests/integration/test_callbacks.py @@ -0,0 +1,138 @@ +"""Integration tests for the setter/getter callbacks at all levels. + +A single ``PUT /characteristics`` runs the characteristic-level setter for +each written characteristic, then the service-level setter with that +service's written characteristics (by display name), then the accessory-level +setter with ``{Service: {Characteristic: value}}``. Reads run the +characteristic-level getter. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, cast + +import pytest + +from .helpers import LightbulbAccessory, SwitchAccessory, characteristic_value, iid_of + +# Real socket + crypto round trips; the CI default of --timeout=2 is too +# tight on shared runners. +pytestmark = pytest.mark.timeout(10) + + +async def test_setter_and_getter_callbacks_on_all_levels(make_hap_server: Any) -> None: + """One write triggers the char, service and accessory setters; a read the getter.""" + acc_setter_calls: list[Any] = [] + service_setter_calls: list[dict[str, Any]] = [] + char_setter_calls: list[Any] = [] + getter_calls: list[None] = [] + + def build(driver: Any) -> LightbulbAccessory: + accessory = LightbulbAccessory(driver, "Test Bulb") + + def acc_setter(updates_by_service: Any) -> None: + acc_setter_calls.append(updates_by_service) + + def service_setter(chars: dict[str, Any]) -> None: + service_setter_calls.append(chars) + + def char_setter(value: Any) -> None: + char_setter_calls.append(value) + + def brightness_getter() -> int: + getter_calls.append(None) + return 42 + + accessory.setter_callback = acc_setter + accessory.service.setter_callback = service_setter + accessory.char_on.setter_callback = char_setter + accessory.char_brightness.getter_callback = brightness_getter + return accessory + + server = await make_hap_server(build) + accessory = cast("LightbulbAccessory", server.driver.accessory) + aid = accessory.aid + assert aid is not None + on_iid = iid_of(accessory, accessory.char_on) + brightness_iid = iid_of(accessory, accessory.char_brightness) + + client = await server.connect(0) + + # One PUT writing both characteristics triggers every setter level. + frame = await client.write_characteristics( + [ + {"aid": aid, "iid": on_iid, "value": True}, + {"aid": aid, "iid": brightness_iid, "value": 55}, + ] + ) + assert frame.status == 204 + + # Characteristic level: called with the raw value. + assert char_setter_calls == [True] + # Service level: called once with {display name: value} of its chars. + assert service_setter_calls == [{"On": True, "Brightness": 55}] + # Accessory level: called once with {Service: {Characteristic: value}}. + assert len(acc_setter_calls) == 1 + updates = acc_setter_calls[0] + assert list(updates) == [accessory.service] + assert updates[accessory.service] == { + accessory.char_on: True, + accessory.char_brightness: 55, + } + + # A read returns the getter's value for the characteristic that has one. + frame = await client.read_characteristics([(aid, on_iid), (aid, brightness_iid)]) + assert frame.status == 200 + assert characteristic_value(frame, aid, on_iid) is True + assert characteristic_value(frame, aid, brightness_iid) == 42 + assert len(getter_calls) == 1 + + # A write of a single characteristic only reaches the levels with that char. + char_setter_calls.clear() + service_setter_calls.clear() + acc_setter_calls.clear() + frame = await client.write_characteristic(aid, on_iid, False) + assert frame.status == 204 + assert char_setter_calls == [False] + assert service_setter_calls == [{"On": False}] + assert acc_setter_calls[0][accessory.service] == {accessory.char_on: False} + + +async def test_async_characteristic_setter_delays_the_write_response( + make_hap_server: Any, +) -> None: + """A coroutine characteristic setter is awaited before the write is answered.""" + setter_started = asyncio.Event() + release_setter = asyncio.Event() + seen: list[Any] = [] + + def build(driver: Any) -> SwitchAccessory: + accessory = SwitchAccessory(driver, "Async Switch") + + async def char_setter(value: Any) -> None: + seen.append(value) + setter_started.set() + await release_setter.wait() + + accessory.char_on.setter_callback = char_setter + return accessory + + server = await make_hap_server(build) + accessory = cast("SwitchAccessory", server.driver.accessory) + aid = accessory.aid + assert aid is not None + on_iid = iid_of(accessory, accessory.char_on) + client = await server.connect(0) + + write_task = asyncio.create_task(client.write_characteristic(aid, on_iid, True)) + await asyncio.wait_for(setter_started.wait(), timeout=5.0) + assert seen == [True] + # The setter is still running, so the write has not been answered yet. + assert not write_task.done() + release_setter.set() + frame = await asyncio.wait_for(write_task, timeout=5.0) + assert frame.status == 204 + + frame = await client.read_characteristic(aid, on_iid) + assert characteristic_value(frame, aid, on_iid) is True diff --git a/tests/integration/test_notifications.py b/tests/integration/test_notifications.py new file mode 100644 index 00000000..8eeea6bf --- /dev/null +++ b/tests/integration/test_notifications.py @@ -0,0 +1,101 @@ +"""Integration tests for the EVENT notification paths. + +A subscribed client receives an ``EVENT/1.0`` push when another client writes +the characteristic, and when the accessory changes the value itself. The +client that made the write is not sent its own update back. Events are +coalesced server-side within a 0.5 s window, so "no event" assertions wait +longer than that. +""" + +from __future__ import annotations + +from typing import Any, cast + +import pytest + +from pyhap.const import STANDALONE_AID + +from .helpers import SwitchAccessory, build_switch, characteristic_value, iid_of + +# Real socket + crypto round trips and the server-side 0.5 s event coalescing +# window; the CI default of --timeout=2 is too tight for these. +pytestmark = pytest.mark.timeout(10) + +EVENT_WAIT = 5.0 +NO_EVENT_WAIT = 1.5 + + +async def test_write_by_one_client_is_evented_to_the_other_subscribed_client( + make_hap_server: Any, +) -> None: + """A write from client A reaches subscribed client B, but not A itself.""" + server = await make_hap_server(build_switch, client_count=2) + accessory = cast("SwitchAccessory", server.driver.accessory) + on_iid = iid_of(accessory, accessory.char_on) + writer = await server.connect(0) + subscriber = await server.connect(1) + + assert (await writer.subscribe(STANDALONE_AID, on_iid)).status == 204 + assert (await subscriber.subscribe(STANDALONE_AID, on_iid)).status == 204 + writer.clear_events() + subscriber.clear_events() + + await writer.write_characteristic(STANDALONE_AID, on_iid, True) + + # The other subscribed client receives the update... + await subscriber.wait_event(STANDALONE_AID, on_iid, True, timeout=EVENT_WAIT) + # ...while the writer is not sent its own write back. + with pytest.raises(TimeoutError): + await writer.next_event(timeout=NO_EVENT_WAIT) + + # The reverse direction works the same way. + await subscriber.write_characteristic(STANDALONE_AID, on_iid, False) + await writer.wait_event(STANDALONE_AID, on_iid, False, timeout=EVENT_WAIT) + with pytest.raises(TimeoutError): + await subscriber.next_event(timeout=NO_EVENT_WAIT) + + +async def test_unsubscribed_client_receives_no_events(make_hap_server: Any) -> None: + """After ``ev: false`` the client gets no more events; others still do.""" + server = await make_hap_server(build_switch, client_count=3) + accessory = cast("SwitchAccessory", server.driver.accessory) + on_iid = iid_of(accessory, accessory.char_on) + leaver = await server.connect(0) + stayer = await server.connect(1) + writer = await server.connect(2) + + for client in (leaver, stayer, writer): + assert (await client.subscribe(STANDALONE_AID, on_iid)).status == 204 + assert (await leaver.unsubscribe(STANDALONE_AID, on_iid)).status == 204 + for client in (leaver, stayer, writer): + client.clear_events() + + await writer.write_characteristic(STANDALONE_AID, on_iid, True) + + # The still-subscribed client receives the event. + await stayer.wait_event(STANDALONE_AID, on_iid, True, timeout=EVENT_WAIT) + # The unsubscribed client does not, and neither does the writer itself. + with pytest.raises(TimeoutError): + await leaver.next_event(timeout=NO_EVENT_WAIT) + with pytest.raises(TimeoutError): + await writer.next_event(timeout=NO_EVENT_WAIT) + + +async def test_accessory_side_update_is_evented_to_subscribed_client( + make_hap_server: Any, +) -> None: + """A value change made by the accessory itself (no client write) is pushed.""" + server = await make_hap_server(build_switch, client_count=1) + accessory = cast("SwitchAccessory", server.driver.accessory) + on_iid = iid_of(accessory, accessory.char_on) + client = await server.connect(0) + + assert (await client.subscribe(STANDALONE_AID, on_iid)).status == 204 + client.clear_events() + + # E.g. a physical switch toggled: the accessory updates its own value. + accessory.char_on.set_value(True) + + await client.wait_event(STANDALONE_AID, on_iid, True, timeout=EVENT_WAIT) + frame = await client.read_characteristic(STANDALONE_AID, on_iid) + assert characteristic_value(frame, STANDALONE_AID, on_iid) is True diff --git a/tests/integration/test_standalone_accessory.py b/tests/integration/test_standalone_accessory.py new file mode 100644 index 00000000..37f10a3a --- /dev/null +++ b/tests/integration/test_standalone_accessory.py @@ -0,0 +1,84 @@ +"""Integration tests for a standalone (non-bridged) Accessory over real HAP.""" + +from __future__ import annotations + +from typing import Any, cast + +import pytest + +from pyhap.client import ClientIdentity, HAPClient +from pyhap.const import HAP_SERVER_STATUS, STANDALONE_AID + +from .helpers import ( + ACCESSORY_INFORMATION_TYPE, + SWITCH_SERVICE_TYPE, + SwitchAccessory, + body_json, + build_switch, + characteristic_entries, + characteristic_value, + iid_of, +) + +# Real socket + crypto round trips; the CI default of --timeout=2 is too +# tight on shared runners. +pytestmark = pytest.mark.timeout(10) + + +async def test_standalone_accessory_end_to_end(make_hap_server: Any) -> None: + """A paired client lists, reads and writes a standalone accessory.""" + server = await make_hap_server(build_switch) + accessory = cast("SwitchAccessory", server.driver.accessory) + assert accessory.aid == STANDALONE_AID + on_iid = iid_of(accessory, accessory.char_on) + info = accessory.get_service("AccessoryInformation") + assert info is not None + name_iid = iid_of(accessory, info.get_characteristic("Name")) + + client = await server.connect(0) + + # GET /accessories returns exactly the one standalone accessory, with the + # AccessoryInformation service first and the Switch service present. + frame = await client.get_accessories() + assert frame.status == 200 + accessories = body_json(frame)["accessories"] + assert [acc["aid"] for acc in accessories] == [STANDALONE_AID] + services = accessories[0]["services"] + assert services[0]["type"] == ACCESSORY_INFORMATION_TYPE + assert SWITCH_SERVICE_TYPE in {service["type"] for service in services} + + # Read several characteristics in one request. + frame = await client.read_characteristics([(1, name_iid), (1, on_iid)]) + assert frame.status == 200 + assert characteristic_value(frame, 1, name_iid) == "Test Switch" + assert characteristic_value(frame, 1, on_iid) is False + + # Write On and read it back. + frame = await client.write_characteristic(1, on_iid, True) + assert frame.status == 204 + frame = await client.read_characteristic(1, on_iid) + assert frame.status == 200 + assert characteristic_value(frame, 1, on_iid) is True + + +async def test_read_of_unknown_characteristic_fails_per_characteristic( + make_hap_server: Any, +) -> None: + """A read of an unknown IID answers 207 with a failure status for it.""" + server = await make_hap_server(build_switch) + client = await server.connect(0) + + frame = await client.read_characteristic(STANDALONE_AID, 9999) + assert frame.status == 207 + entry = characteristic_entries(frame)[(STANDALONE_AID, 9999)] + assert entry["status"] == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + assert "value" not in entry + + +async def test_unpaired_client_is_rejected_at_pair_verify(make_hap_server: Any) -> None: + """A client whose identity was never paired cannot open a session.""" + server = await make_hap_server(build_switch) + stranger = HAPClient(ClientIdentity.generate(99), server.accessory_ltpk) + server.clients.append(stranger) # closed by the harness + with pytest.raises(RuntimeError, match="pair-verify rejected"): + await stranger.connect("127.0.0.1", server.port) From d268ff508256dcf79693d4e9ead234dcbfce079a Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Sat, 21 Nov 2026 16:10:39 +0100 Subject: [PATCH 03/15] Add ClientIdentity persistence (save/load) to pyhap.client A lib user can now persist the controller identity themselves: save() writes uuid + raw private/public key as JSON through a 0600 tempfile that is os.replace()d into place (atomic, never world-readable, mirroring how AccessoryDriver persists its own key), and load()/from_dict() rebuild it with validation (uuid format, hex keys, public key must match the private key). Covered by unit tests in tests/test_client_identity.py and by an integration test that restarts the driver on the same state file and reconnects with the identity loaded from disk. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 6 +- pyhap/client/__init__.py | 6 + pyhap/client/identity.py | 109 ++++++++++++++++++- tests/integration/conftest.py | 24 +++- tests/integration/test_persisted_identity.py | 61 +++++++++++ tests/test_client_identity.py | 90 +++++++++++++++ 6 files changed, 287 insertions(+), 9 deletions(-) create mode 100644 tests/integration/test_persisted_identity.py create mode 100644 tests/test_client_identity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 53306ab2..94bf6081 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,8 +24,10 @@ Sections protocol - pair-verify, encrypted transport, characteristic reads/writes, event subscriptions and `EVENT` push frames. Moved out of `benchmarks/client.py` (now `pyhap.client.HAPClient`) and extended with - batch reads/writes, unsubscribe and raw event access. Covered by the new - integration tests in `tests/integration/`. + batch reads/writes, unsubscribe, raw event access and + `ClientIdentity.save`/`load` for persisting the controller identity (UUID + + private key, written atomically with 0600 permissions). Covered by the + new integration tests in `tests/integration/`. ### Fixed diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py index 16747c61..d9f6f661 100644 --- a/pyhap/client/__init__.py +++ b/pyhap/client/__init__.py @@ -20,6 +20,12 @@ client = HAPClient(identity, accessory_ltpk_raw_bytes) await client.connect("127.0.0.1", port) frame = await client.get_accessories() + +To reconnect as the same controller after a restart, persist the identity +yourself (UUID + private key, written 0600) and load it back:: + + identity.save("controller.key") + identity = ClientIdentity.load("controller.key") """ from ..const import RESPONSE_TIMEOUT diff --git a/pyhap/client/identity.py b/pyhap/client/identity.py index d9c7c76e..021ef377 100644 --- a/pyhap/client/identity.py +++ b/pyhap/client/identity.py @@ -2,8 +2,14 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass +import json +import os +import tempfile +from typing import Any import uuid as uuid_module +from uuid import UUID from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 @@ -17,6 +23,12 @@ class ClientIdentity: :meth:`pyhap.accessory_driver.AccessoryDriver.pair`, bypassing the slow SRP pair-setup), so the client only needs a pair-verify to open an encrypted session. + + The identity lives in memory only; :meth:`save` and :meth:`load` persist + it (UUID + private key) to a file, like a real controller keeps its + long-term key in a keychain. The accessory persists the pairing (the + public key) in its own state file, so a saved identity reconnects as the + same controller after a restart. """ uuid: str @@ -24,7 +36,12 @@ class ClientIdentity: @classmethod def generate(cls, index: int = 0) -> ClientIdentity: - """Generate a deterministic identity for the given index.""" + """Generate an identity for the given index. + + The UUID is deterministic per ``index``, but the private key is + generated fresh on every call, so persist it with :meth:`save` to + reuse the identity. + """ pair_uuid = str( uuid_module.uuid5(uuid_module.NAMESPACE_URL, f"hap-client-{index}") ) @@ -42,3 +59,93 @@ def public_key_bytes(self) -> bytes: encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw, ) + + def to_dict(self) -> dict[str, str]: + """Return the JSON-serializable form of the identity. + + Holds the UUID and the raw private key (hex), plus the raw public + key (hex), which :meth:`from_dict` checks against the private key. + """ + private_key_bytes = self.private_key.private_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PrivateFormat.Raw, + encryption_algorithm=serialization.NoEncryption(), + ) + return { + "uuid": self.uuid, + "private_key": private_key_bytes.hex(), + "public_key": self.public_key_bytes.hex(), + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> ClientIdentity: + """Rebuild an identity from :meth:`to_dict` output. + + :raise ValueError: If the data is malformed or the stored public key + does not match the private key. + """ + try: + uuid_str = data["uuid"] + private_key_hex = data["private_key"] + public_key_hex = data["public_key"] + except (KeyError, TypeError) as error: + raise ValueError( + "Not a client identity (expected 'uuid', 'private_key' and " + f"'public_key'): {data!r}" + ) from error + if not isinstance(uuid_str, str): + raise ValueError(f"Invalid client uuid: {uuid_str!r}") + try: + UUID(uuid_str) + except ValueError as error: + raise ValueError(f"Invalid client uuid: {uuid_str!r}") from error + try: + private_key_bytes = bytes.fromhex(private_key_hex) + public_key_bytes = bytes.fromhex(public_key_hex) + except (TypeError, ValueError) as error: + raise ValueError("Client identity keys must be hex encoded") from error + try: + private_key = ed25519.Ed25519PrivateKey.from_private_bytes( + private_key_bytes + ) + except ValueError as error: + raise ValueError("Invalid client private key") from error + identity = cls(uuid_str, private_key) + if identity.public_key_bytes != public_key_bytes: + raise ValueError("Client public key does not match the private key") + return identity + + def save(self, path: str | os.PathLike[str]) -> None: + """Persist the identity to ``path`` as JSON. + + The write is atomic: a tempfile created with 0600 permissions in the + same directory is ``os.replace``d into place, so a crash cannot leave + a half-written key behind and the key file is never world-readable. + ``~`` in ``path`` is expanded. + """ + target = os.path.expanduser(os.fspath(path)) + directory = os.path.dirname(target) or "." + tmp_filename = None + try: + with tempfile.NamedTemporaryFile( + mode="w", dir=directory, delete=False, encoding="utf-8" + ) as file_handle: + tmp_filename = file_handle.name + json.dump(self.to_dict(), file_handle, indent=2) + file_handle.write("\n") + os.replace(tmp_filename, target) + finally: + if tmp_filename is not None and os.path.exists(tmp_filename): + os.remove(tmp_filename) + + @classmethod + def load(cls, path: str | os.PathLike[str]) -> ClientIdentity: + """Load an identity saved with :meth:`save`. + + :raise ValueError: If the file does not hold a valid identity. + :raise OSError: If the file does not exist or cannot be read. + """ + target = os.path.expanduser(os.fspath(path)) + with open(target, encoding="utf-8") as file_handle: + data = json.load(file_handle) + return cls.from_dict(data) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index de0d7ed3..763f9d1a 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -49,6 +49,7 @@ def __init__( self.identities = identities self.accessory_ltpk = accessory_ltpk self.clients: list[HAPClient] = [] + self._stopped = False @classmethod async def start( @@ -86,13 +87,20 @@ def port(self) -> int: async def connect(self, index: int = 0) -> HAPClient: """Connect pre-paired client ``index`` (pair-verify included).""" - client = HAPClient(self.identities[index], self.accessory_ltpk) + return await self.connect_identity(self.identities[index]) + + async def connect_identity(self, identity: ClientIdentity) -> HAPClient: + """Connect an arbitrary identity, e.g. one loaded from disk.""" + client = HAPClient(identity, self.accessory_ltpk) self.clients.append(client) await client.connect("127.0.0.1", self.port) return client async def stop(self) -> None: - """Close all clients and stop the driver.""" + """Close all clients and stop the driver. Idempotent.""" + if self._stopped: + return + self._stopped = True for client in self.clients: await client.close() self.clients.clear() @@ -106,15 +114,19 @@ async def make_hap_server( """Start a driver for the accessory built by the given factory. Usage: ``server = await make_hap_server(lambda driver: MyAccessory(driver))``. - Pass ``client_count=N`` to pre-pair N clients. Every started server is - stopped when the test ends. + Pass ``client_count=N`` to pre-pair N clients, and ``state_file`` to run + on a specific driver state file (e.g. to restart on the same one). Every + started server is stopped when the test ends. """ harnesses: list[HAPServerHarness] = [] async def _make( - accessory_factory: AccessoryFactory, client_count: int = 1 + accessory_factory: AccessoryFactory, + client_count: int = 1, + state_file: pathlib.Path | None = None, ) -> HAPServerHarness: - state_file = tmp_path / f"accessory-{len(harnesses)}.state" + if state_file is None: + state_file = tmp_path / f"accessory-{len(harnesses)}.state" harness = await HAPServerHarness.start( accessory_factory, state_file, client_count ) diff --git a/tests/integration/test_persisted_identity.py b/tests/integration/test_persisted_identity.py new file mode 100644 index 00000000..df3963e9 --- /dev/null +++ b/tests/integration/test_persisted_identity.py @@ -0,0 +1,61 @@ +"""Integration test: a user-persisted client identity survives a server restart. + +The accessory persists the pairing (the client's public key) in the driver +state file; the client persists its own identity with +:meth:`pyhap.client.ClientIdentity.save`. After a "restart" (a new driver on +the same state file), the loaded identity still pair-verifies. +""" + +from __future__ import annotations + +import pathlib +from typing import Any, cast + +import pytest + +from pyhap.client import ClientIdentity +from pyhap.const import STANDALONE_AID + +from .helpers import SwitchAccessory, build_switch, iid_of + +# Real socket + crypto round trips plus two server starts; the CI default of +# --timeout=2 is too tight on shared runners. +pytestmark = pytest.mark.timeout(10) + + +async def test_persisted_identity_reconnects_after_server_restart( + make_hap_server: Any, tmp_path: pathlib.Path +) -> None: + """A saved identity pair-verifies against a restarted driver.""" + state_file = tmp_path / "accessory.state" + key_file = tmp_path / "controller.key" + + # First run: pair a fresh identity, persist it user-side, use it. + server = await make_hap_server(build_switch, client_count=1, state_file=state_file) + identity = server.identities[0] + identity.save(key_file) + accessory = cast("SwitchAccessory", server.driver.accessory) + on_iid = iid_of(accessory, accessory.char_on) + client = await server.connect(0) + frame = await client.write_characteristic(STANDALONE_AID, on_iid, True) + assert frame.status == 204 + # Flush the pairing to the state file before the "restart". + server.driver.persist() + await server.stop() + + # Restart: a new driver on the same state file, no new pairing, and the + # identity loaded back from the user's key file. + restarted = await make_hap_server( + build_switch, client_count=0, state_file=state_file + ) + loaded = ClientIdentity.load(key_file) + assert loaded.uuid == identity.uuid + assert loaded.public_key_bytes == identity.public_key_bytes + + accessory2 = cast("SwitchAccessory", restarted.driver.accessory) + on_iid2 = iid_of(accessory2, accessory2.char_on) + client2 = await restarted.connect_identity(loaded) + frame = await client2.read_characteristic(STANDALONE_AID, on_iid2) + assert frame.status == 200 + frame = await client2.write_characteristic(STANDALONE_AID, on_iid2, True) + assert frame.status == 204 diff --git a/tests/test_client_identity.py b/tests/test_client_identity.py new file mode 100644 index 00000000..4c7613e6 --- /dev/null +++ b/tests/test_client_identity.py @@ -0,0 +1,90 @@ +"""Unit tests for ClientIdentity generation and persistence.""" + +import json +import os +import pathlib +import stat +from typing import Any + +from cryptography.hazmat.primitives.asymmetric import ed25519 +import pytest + +from pyhap.client import ClientIdentity + + +def test_generate_deterministic_uuid_but_fresh_key() -> None: + """The same index yields the same UUID but a new private key each time.""" + first = ClientIdentity.generate(3) + second = ClientIdentity.generate(3) + assert first.uuid == second.uuid + assert first.public_key_bytes != second.public_key_bytes + + +def test_to_from_dict_round_trip() -> None: + """from_dict(to_dict()) rebuilds an identity whose key can sign.""" + identity = ClientIdentity.generate(0) + clone = ClientIdentity.from_dict(identity.to_dict()) + assert clone.uuid == identity.uuid + assert clone.public_key_bytes == identity.public_key_bytes + signature = clone.private_key.sign(b"material") + verifying_key = ed25519.Ed25519PublicKey.from_public_bytes( + identity.public_key_bytes + ) + verifying_key.verify(signature, b"material") + + +def test_save_load_round_trip(tmp_path: pathlib.Path) -> None: + """save() then load() returns the same identity.""" + identity = ClientIdentity.generate(1) + path = tmp_path / "controller.key" + identity.save(path) + loaded = ClientIdentity.load(path) + assert loaded.to_dict() == identity.to_dict() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX file permissions") +def test_saved_file_is_private(tmp_path: pathlib.Path) -> None: + """The key file is written with 0600 permissions.""" + path = tmp_path / "controller.key" + ClientIdentity.generate(0).save(path) + mode = stat.S_IMODE(os.stat(path).st_mode) + assert mode == 0o600 + + +def test_save_overwrites_existing_file(tmp_path: pathlib.Path) -> None: + """Saving onto an existing file replaces it atomically.""" + path = tmp_path / "controller.key" + path.write_text("old contents", encoding="utf-8") + identity = ClientIdentity.generate(2) + identity.save(path) + assert ClientIdentity.load(path).to_dict() == identity.to_dict() + + +def test_load_rejects_malformed_files(tmp_path: pathlib.Path) -> None: + """Corrupt or incomplete identity files raise ValueError.""" + path = tmp_path / "bad.key" + path.write_text("not json", encoding="utf-8") + with pytest.raises(ValueError): + ClientIdentity.load(path) + + good = ClientIdentity.generate(0).to_dict() + mutations = [ + lambda data: data.pop("private_key"), + lambda data: data.update(uuid="not-a-uuid"), + lambda data: data.update(private_key="zz"), + lambda data: data.update(private_key="00"), + lambda data: data.update(public_key="00" * 32), + ] + for mutate in mutations: + data = dict(good) + mutate(data) + path.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(ValueError): + ClientIdentity.load(path) + + +def test_from_dict_rejects_non_mapping() -> None: + """from_dict on something that is not a mapping raises ValueError.""" + not_a_mapping: Any = ["not", "a", "mapping"] + with pytest.raises(ValueError): + ClientIdentity.from_dict(not_a_mapping) From 153cf8cf6d92f17309128b75a1f1d1b1cc65ea48 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Sat, 21 Nov 2026 16:21:22 +0100 Subject: [PATCH 04/15] Add HAPClient.new_persistent, docs example and README mention new_persistent(*, filepath, accessory_ltpk) loads the controller identity from filepath if it exists, otherwise generates a new one and backs it up there (via ClientIdentity.save/load); HAPClient gains an identity property so the identity can be paired with the accessory. The restart integration test now uses it end to end, and tests/test_client.py covers both the create-and-back-up and the load-existing paths. The API page for pyhap.client gets a short example, and the README feature list mentions the client. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 6 ++- README.md | 1 + docs/source/api/client.rst | 31 +++++++++++++ pyhap/client/__init__.py | 19 ++++---- pyhap/client/controller.py | 27 +++++++++++ tests/integration/conftest.py | 5 ++- tests/integration/test_persisted_identity.py | 47 ++++++++++++-------- tests/test_client.py | 40 +++++++++++++++++ 8 files changed, 146 insertions(+), 30 deletions(-) create mode 100644 tests/test_client.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 94bf6081..7c735076 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,8 +26,10 @@ Sections `benchmarks/client.py` (now `pyhap.client.HAPClient`) and extended with batch reads/writes, unsubscribe, raw event access and `ClientIdentity.save`/`load` for persisting the controller identity (UUID - + private key, written atomically with 0600 permissions). Covered by the - new integration tests in `tests/integration/`. + + private key, written atomically with 0600 permissions), plus the + `HAPClient.new_persistent(filepath=...)` convenience that loads the + identity from a file or creates and backs it up there. Covered by the new + integration tests in `tests/integration/`. ### Fixed diff --git a/README.md b/README.md index 87f23870..7932125d 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Main features: * **asyncio support** — run various tasks or accessories in the event loop. * **Out of the box support for Apple-defined services** — see them in [the resources folder](pyhap/resources). * **Secure pairing** — just scan a QR code, no manual codes to type in. +* **HAP client included** — [pyhap/client](pyhap/client) is a controller that speaks the real protocol (pair-verify, encrypted transport, events) against a running accessory, handy for tests and benchmarks. * **Proven in production** — HAP-python powers the HomeKit integration of the home automation framework [Home Assistant](https://github.com/home-assistant/home-assistant). Full API documentation is available on [readthedocs](http://hap-python.readthedocs.io/). diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index 436a1a64..cf8b1482 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -11,5 +11,36 @@ suite and the integration tests use it to drive an :class:`pyhap.accessory_driver.AccessoryDriver` end to end; it is also handy for testing your own accessory. +Example +======= + +Drive a running accessory as a controller, with the identity persisted so the +controller is recognized again after a restart: + +.. code-block:: python + + from pyhap.client import HAPClient + from pyhap.const import HAP_PERMISSIONS + + # Loads controller.key if it exists, otherwise creates a new identity + # and saves it there. + client = HAPClient.new_persistent( + filepath="controller.key", accessory_ltpk=accessory_ltpk_raw_bytes + ) + # Pair the identity once (bypasses the slow SRP pair-setup); the pairing + # is stored in the accessory's own state file. + driver.pair( + client.identity.uuid_bytes, + client.identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) + + await client.connect("127.0.0.1", port) # pair-verify + encryption + await client.get_accessories() # GET /accessories + await client.subscribe(1, on_iid) # EVENT notifications on + await client.write_characteristic(1, on_iid, True) + await client.wait_event(1, on_iid, True) # an update arrives as EVENT + await client.close() + .. automodule:: pyhap.client :members: diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py index d9f6f661..1a4504f3 100644 --- a/pyhap/client/__init__.py +++ b/pyhap/client/__init__.py @@ -14,18 +14,19 @@ integration tests in ``tests/integration/`` to exercise a running :class:`pyhap.accessory_driver.AccessoryDriver` end to end:: - identity = ClientIdentity.generate(0) - driver.pair(identity.uuid_bytes, identity.public_key_bytes, HAP_PERMISSIONS.ADMIN) + # A controller whose identity is persisted at controller.key: loaded + # back on later runs, created and saved on the first. + client = HAPClient.new_persistent( + filepath="controller.key", accessory_ltpk=accessory_ltpk_raw_bytes + ) + driver.pair( + client.identity.uuid_bytes, + client.identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) # ... start the driver, then: - client = HAPClient(identity, accessory_ltpk_raw_bytes) await client.connect("127.0.0.1", port) frame = await client.get_accessories() - -To reconnect as the same controller after a restart, persist the identity -yourself (UUID + private key, written 0600) and load it back:: - - identity.save("controller.key") - identity = ClientIdentity.load("controller.key") """ from ..const import RESPONSE_TIMEOUT diff --git a/pyhap/client/controller.py b/pyhap/client/controller.py index aa02a219..b89de25a 100644 --- a/pyhap/client/controller.py +++ b/pyhap/client/controller.py @@ -12,6 +12,7 @@ from collections.abc import Iterable import json import logging +import os from typing import Any from chacha20poly1305_reuseable import ChaCha20Poly1305Reusable as ChaCha20Poly1305 @@ -62,6 +63,32 @@ def __init__(self, identity: ClientIdentity, accessory_ltpk: bytes) -> None: self._events: asyncio.Queue[tuple[int, int, Any, int]] = asyncio.Queue() self._closed = False + @classmethod + def new_persistent( + cls, *, filepath: str | os.PathLike[str], accessory_ltpk: bytes + ) -> HAPClient: + """Create a client whose identity is persisted at ``filepath``. + + If ``filepath`` exists, the identity is loaded from it; otherwise a + new one is generated and saved there. Pair the identity with the + accessory once (e.g. :meth:`pyhap.accessory_driver.AccessoryDriver.pair` + with ``client.identity`` - the pairing itself is persisted in the + accessory's state file); afterwards the client reconnects as the same + controller after restarts. + """ + path = os.path.expanduser(os.fspath(filepath)) + if os.path.exists(path): + identity = ClientIdentity.load(path) + else: + identity = ClientIdentity.generate() + identity.save(path) + return cls(identity, accessory_ltpk) + + @property + def identity(self) -> ClientIdentity: + """The long-term identity this client pair-verifies with.""" + return self._identity + @property def name(self) -> str: """A human readable name for logging.""" diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 763f9d1a..fa377fc2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -91,7 +91,10 @@ async def connect(self, index: int = 0) -> HAPClient: async def connect_identity(self, identity: ClientIdentity) -> HAPClient: """Connect an arbitrary identity, e.g. one loaded from disk.""" - client = HAPClient(identity, self.accessory_ltpk) + return await self.connect_client(HAPClient(identity, self.accessory_ltpk)) + + async def connect_client(self, client: HAPClient) -> HAPClient: + """Connect an already-built client, e.g. from ``HAPClient.new_persistent``.""" self.clients.append(client) await client.connect("127.0.0.1", self.port) return client diff --git a/tests/integration/test_persisted_identity.py b/tests/integration/test_persisted_identity.py index df3963e9..6237bd55 100644 --- a/tests/integration/test_persisted_identity.py +++ b/tests/integration/test_persisted_identity.py @@ -1,9 +1,9 @@ -"""Integration test: a user-persisted client identity survives a server restart. +"""Integration test: a persisted client identity survives a server restart. The accessory persists the pairing (the client's public key) in the driver -state file; the client persists its own identity with -:meth:`pyhap.client.ClientIdentity.save`. After a "restart" (a new driver on -the same state file), the loaded identity still pair-verifies. +state file; the client persists its own identity via +``HAPClient.new_persistent``. After a "restart" (a new driver on the same +state file), the same identity pair-verifies again. """ from __future__ import annotations @@ -13,8 +13,8 @@ import pytest -from pyhap.client import ClientIdentity -from pyhap.const import STANDALONE_AID +from pyhap.client import ClientIdentity, HAPClient +from pyhap.const import HAP_PERMISSIONS, STANDALONE_AID from .helpers import SwitchAccessory, build_switch, iid_of @@ -26,35 +26,46 @@ async def test_persisted_identity_reconnects_after_server_restart( make_hap_server: Any, tmp_path: pathlib.Path ) -> None: - """A saved identity pair-verifies against a restarted driver.""" + """new_persistent() backs up a new identity, then loads it after a restart.""" state_file = tmp_path / "accessory.state" key_file = tmp_path / "controller.key" - # First run: pair a fresh identity, persist it user-side, use it. - server = await make_hap_server(build_switch, client_count=1, state_file=state_file) - identity = server.identities[0] - identity.save(key_file) + # First run: create the identity (backed up to key_file), pair it, use it. + server = await make_hap_server(build_switch, client_count=0, state_file=state_file) + client = HAPClient.new_persistent( + filepath=key_file, accessory_ltpk=server.accessory_ltpk + ) + assert key_file.exists() + server.driver.pair( + client.identity.uuid_bytes, + client.identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) accessory = cast("SwitchAccessory", server.driver.accessory) on_iid = iid_of(accessory, accessory.char_on) - client = await server.connect(0) + await server.connect_client(client) frame = await client.write_characteristic(STANDALONE_AID, on_iid, True) assert frame.status == 204 # Flush the pairing to the state file before the "restart". server.driver.persist() await server.stop() - # Restart: a new driver on the same state file, no new pairing, and the - # identity loaded back from the user's key file. + # Restart: a new driver on the same state file, no new pairing. The same + # key file now yields the existing identity, which pair-verifies. restarted = await make_hap_server( build_switch, client_count=0, state_file=state_file ) - loaded = ClientIdentity.load(key_file) - assert loaded.uuid == identity.uuid - assert loaded.public_key_bytes == identity.public_key_bytes + client2 = HAPClient.new_persistent( + filepath=key_file, accessory_ltpk=restarted.accessory_ltpk + ) + assert client2.identity.uuid == client.identity.uuid + assert ClientIdentity.load(key_file).public_key_bytes == ( + client.identity.public_key_bytes + ) accessory2 = cast("SwitchAccessory", restarted.driver.accessory) on_iid2 = iid_of(accessory2, accessory2.char_on) - client2 = await restarted.connect_identity(loaded) + await restarted.connect_client(client2) frame = await client2.read_characteristic(STANDALONE_AID, on_iid2) assert frame.status == 200 frame = await client2.write_characteristic(STANDALONE_AID, on_iid2, True) diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 00000000..67c4b10e --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,40 @@ +"""Unit tests for HAPClient construction helpers.""" + +import pathlib + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed25519 + +from pyhap.client import ClientIdentity, HAPClient + + +def _ltpk() -> bytes: + """A raw accessory long-term public key to construct clients with.""" + key = ed25519.Ed25519PrivateKey.generate() + return key.public_key().public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + +def test_new_persistent_creates_and_backs_up_identity( + tmp_path: pathlib.Path, +) -> None: + """A missing file leads to a new identity that is saved there.""" + path = tmp_path / "controller.key" + assert not path.exists() + client = HAPClient.new_persistent(filepath=path, accessory_ltpk=_ltpk()) + assert path.exists() + saved = ClientIdentity.load(path) + assert saved.uuid == client.identity.uuid + assert saved.public_key_bytes == client.identity.public_key_bytes + + +def test_new_persistent_loads_existing_identity(tmp_path: pathlib.Path) -> None: + """An existing file is loaded instead of being overwritten.""" + path = tmp_path / "controller.key" + identity = ClientIdentity.generate(5) + identity.save(path) + client = HAPClient.new_persistent(filepath=path, accessory_ltpk=_ltpk()) + assert client.identity.uuid == identity.uuid + assert client.identity.public_key_bytes == identity.public_key_bytes From c13864233d36a9df111c7c822ab9a9751c85e78b Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Sat, 21 Nov 2026 16:30:30 +0100 Subject: [PATCH 05/15] Make the accessory LTPK optional in pyhap.client (trust on first use) HAPClient and HAPClient.new_persistent no longer require accessory_ltpk: without it the pair-verify session is still encrypted but the accessory's signature is not verified (a warning is logged). An LTPK passed once is pinned in the persisted identity file (ClientIdentity.accessory_ltpk), so later new_persistent(filepath=...) calls verify the accessory against it. The restart integration test now reconnects without passing the LTPK, and a new test covers a real connection with no pinned LTPK. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 4 +- docs/source/api/client.rst | 8 ++-- pyhap/client/__init__.py | 7 ++- pyhap/client/controller.py | 47 +++++++++++++++---- pyhap/client/identity.py | 20 +++++++- tests/integration/test_persisted_identity.py | 8 ++-- .../integration/test_standalone_accessory.py | 26 +++++++++- tests/test_client.py | 21 +++++++++ tests/test_client_identity.py | 27 +++++++++++ 9 files changed, 143 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c735076..c7accd3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,9 @@ Sections `ClientIdentity.save`/`load` for persisting the controller identity (UUID + private key, written atomically with 0600 permissions), plus the `HAPClient.new_persistent(filepath=...)` convenience that loads the - identity from a file or creates and backs it up there. Covered by the new + identity from a file or creates and backs it up there. The accessory LTPK + is optional: pass it once to pin it in the file (trust on first use), or + omit it for an encrypted but unauthenticated session. Covered by the new integration tests in `tests/integration/`. ### Fixed diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index cf8b1482..19e5f458 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -23,10 +23,10 @@ controller is recognized again after a restart: from pyhap.const import HAP_PERMISSIONS # Loads controller.key if it exists, otherwise creates a new identity - # and saves it there. - client = HAPClient.new_persistent( - filepath="controller.key", accessory_ltpk=accessory_ltpk_raw_bytes - ) + # and saves it there. Pass accessory_ltpk=... once to pin the + # accessory's long-term key; without it the session is still encrypted, + # but the accessory is not authenticated. + client = HAPClient.new_persistent(filepath="controller.key") # Pair the identity once (bypasses the slow SRP pair-setup); the pairing # is stored in the accessory's own state file. driver.pair( diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py index 1a4504f3..cfe2dd17 100644 --- a/pyhap/client/__init__.py +++ b/pyhap/client/__init__.py @@ -15,10 +15,9 @@ :class:`pyhap.accessory_driver.AccessoryDriver` end to end:: # A controller whose identity is persisted at controller.key: loaded - # back on later runs, created and saved on the first. - client = HAPClient.new_persistent( - filepath="controller.key", accessory_ltpk=accessory_ltpk_raw_bytes - ) + # back on later runs, created and saved on the first. Pass + # accessory_ltpk=... once to pin the accessory's key for verification. + client = HAPClient.new_persistent(filepath="controller.key") driver.pair( client.identity.uuid_bytes, client.identity.public_key_bytes, diff --git a/pyhap/client/controller.py b/pyhap/client/controller.py index b89de25a..8d6333be 100644 --- a/pyhap/client/controller.py +++ b/pyhap/client/controller.py @@ -10,6 +10,7 @@ import asyncio from collections.abc import Iterable +from dataclasses import replace import json import logging import os @@ -42,17 +43,21 @@ class HAPClient: to the encrypted transport. """ - def __init__(self, identity: ClientIdentity, accessory_ltpk: bytes) -> None: + def __init__( + self, identity: ClientIdentity, accessory_ltpk: bytes | None = None + ) -> None: """Initialize the controller for a given pairing identity. :param identity: The long-term identity the server is paired with. :param accessory_ltpk: Raw long-term public key of the accessory, - used to verify the server during pair-verify. + used to verify the server during pair-verify. Defaults to the + LTPK pinned in ``identity.accessory_ltpk``. When neither is + given, the accessory's signature is not verified: the session is + still encrypted, but the accessory is unauthenticated. """ self._identity = identity - self._accessory_ltpk = ed25519.Ed25519PublicKey.from_public_bytes( - accessory_ltpk - ) + ltpk = accessory_ltpk if accessory_ltpk is not None else identity.accessory_ltpk + self._accessory_ltpk = ltpk self._reader: asyncio.StreamReader | None = None self._writer: asyncio.StreamWriter | None = None self._read_task: asyncio.Task[None] | None = None @@ -65,7 +70,7 @@ def __init__(self, identity: ClientIdentity, accessory_ltpk: bytes) -> None: @classmethod def new_persistent( - cls, *, filepath: str | os.PathLike[str], accessory_ltpk: bytes + cls, *, filepath: str | os.PathLike[str], accessory_ltpk: bytes | None = None ) -> HAPClient: """Create a client whose identity is persisted at ``filepath``. @@ -75,12 +80,22 @@ def new_persistent( with ``client.identity`` - the pairing itself is persisted in the accessory's state file); afterwards the client reconnects as the same controller after restarts. + + An ``accessory_ltpk`` passed here is pinned in the file (trust on + first use): later calls without it verify the accessory against the + pinned key. Without any LTPK the session is encrypted but the + accessory is not authenticated. """ path = os.path.expanduser(os.fspath(filepath)) if os.path.exists(path): identity = ClientIdentity.load(path) + if accessory_ltpk is not None and identity.accessory_ltpk != accessory_ltpk: + identity = replace(identity, accessory_ltpk=accessory_ltpk) + identity.save(path) else: identity = ClientIdentity.generate() + if accessory_ltpk is not None: + identity = replace(identity, accessory_ltpk=accessory_ltpk) identity.save(path) return cls(identity, accessory_ltpk) @@ -89,6 +104,11 @@ def identity(self) -> ClientIdentity: """The long-term identity this client pair-verifies with.""" return self._identity + @property + def accessory_ltpk(self) -> bytes | None: + """The raw accessory LTPK verified during pair-verify, if pinned.""" + return self._accessory_ltpk + @property def name(self) -> str: """A human readable name for logging.""" @@ -159,10 +179,17 @@ async def _pair_verify(self) -> None: proof = tlv.decode(decrypted) accessory_mac = proof[HAP_TLV_TAGS.USERNAME] accessory_proof = proof[HAP_TLV_TAGS.PROOF] - self._accessory_ltpk.verify( - accessory_proof, - server_ephemeral_public + accessory_mac + ephemeral_public, - ) + if self._accessory_ltpk is None: + logger.warning( + "%s: no accessory LTPK pinned; the session is encrypted but the " + "accessory's identity is not verified", + self.name, + ) + else: + ed25519.Ed25519PublicKey.from_public_bytes(self._accessory_ltpk).verify( + accessory_proof, + server_ephemeral_public + accessory_mac + ephemeral_public, + ) # Step 3: prove our own identity with our long-term key. material = ( diff --git a/pyhap/client/identity.py b/pyhap/client/identity.py index 021ef377..2c680907 100644 --- a/pyhap/client/identity.py +++ b/pyhap/client/identity.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Mapping +import dataclasses from dataclasses import dataclass import json import os @@ -29,10 +30,15 @@ class ClientIdentity: long-term key in a keychain. The accessory persists the pairing (the public key) in its own state file, so a saved identity reconnects as the same controller after a restart. + + ``accessory_ltpk`` optionally pins the accessory's raw long-term public + key (trust on first use): a client with a pinned LTPK verifies the + accessory during pair-verify, one without does not. """ uuid: str private_key: ed25519.Ed25519PrivateKey + accessory_ltpk: bytes | None = None @classmethod def generate(cls, index: int = 0) -> ClientIdentity: @@ -65,17 +71,21 @@ def to_dict(self) -> dict[str, str]: Holds the UUID and the raw private key (hex), plus the raw public key (hex), which :meth:`from_dict` checks against the private key. + The pinned accessory LTPK (hex) is included when set. """ private_key_bytes = self.private_key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption(), ) - return { + data = { "uuid": self.uuid, "private_key": private_key_bytes.hex(), "public_key": self.public_key_bytes.hex(), } + if self.accessory_ltpk is not None: + data["accessory_ltpk"] = self.accessory_ltpk.hex() + return data @classmethod def from_dict(cls, data: Mapping[str, Any]) -> ClientIdentity: @@ -113,6 +123,14 @@ def from_dict(cls, data: Mapping[str, Any]) -> ClientIdentity: identity = cls(uuid_str, private_key) if identity.public_key_bytes != public_key_bytes: raise ValueError("Client public key does not match the private key") + ltpk_hex = data.get("accessory_ltpk") + if ltpk_hex is not None: + try: + ltpk_bytes = bytes.fromhex(ltpk_hex) + ed25519.Ed25519PublicKey.from_public_bytes(ltpk_bytes) + except (TypeError, ValueError) as error: + raise ValueError("Invalid pinned accessory_ltpk") from error + identity = dataclasses.replace(identity, accessory_ltpk=ltpk_bytes) return identity def save(self, path: str | os.PathLike[str]) -> None: diff --git a/tests/integration/test_persisted_identity.py b/tests/integration/test_persisted_identity.py index 6237bd55..c1930d32 100644 --- a/tests/integration/test_persisted_identity.py +++ b/tests/integration/test_persisted_identity.py @@ -51,14 +51,14 @@ async def test_persisted_identity_reconnects_after_server_restart( await server.stop() # Restart: a new driver on the same state file, no new pairing. The same - # key file now yields the existing identity, which pair-verifies. + # key file now yields the existing identity (and the pinned accessory + # LTPK from the first run), which pair-verifies. restarted = await make_hap_server( build_switch, client_count=0, state_file=state_file ) - client2 = HAPClient.new_persistent( - filepath=key_file, accessory_ltpk=restarted.accessory_ltpk - ) + client2 = HAPClient.new_persistent(filepath=key_file) assert client2.identity.uuid == client.identity.uuid + assert client2.accessory_ltpk == server.accessory_ltpk assert ClientIdentity.load(key_file).public_key_bytes == ( client.identity.public_key_bytes ) diff --git a/tests/integration/test_standalone_accessory.py b/tests/integration/test_standalone_accessory.py index 37f10a3a..6cf5bd9c 100644 --- a/tests/integration/test_standalone_accessory.py +++ b/tests/integration/test_standalone_accessory.py @@ -2,12 +2,13 @@ from __future__ import annotations +import pathlib from typing import Any, cast import pytest from pyhap.client import ClientIdentity, HAPClient -from pyhap.const import HAP_SERVER_STATUS, STANDALONE_AID +from pyhap.const import HAP_PERMISSIONS, HAP_SERVER_STATUS, STANDALONE_AID from .helpers import ( ACCESSORY_INFORMATION_TYPE, @@ -82,3 +83,26 @@ async def test_unpaired_client_is_rejected_at_pair_verify(make_hap_server: Any) server.clients.append(stranger) # closed by the harness with pytest.raises(RuntimeError, match="pair-verify rejected"): await stranger.connect("127.0.0.1", server.port) + + +async def test_client_connects_without_pinned_ltpk( + make_hap_server: Any, tmp_path: pathlib.Path +) -> None: + """No LTPK needed: the session is encrypted, the accessory unverified.""" + server = await make_hap_server(build_switch, client_count=0) + accessory = cast("SwitchAccessory", server.driver.accessory) + on_iid = iid_of(accessory, accessory.char_on) + + client = HAPClient.new_persistent(filepath=tmp_path / "controller.key") + assert client.accessory_ltpk is None + server.driver.pair( + client.identity.uuid_bytes, + client.identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) + await server.connect_client(client) + + frame = await client.write_characteristic(STANDALONE_AID, on_iid, True) + assert frame.status == 204 + frame = await client.read_characteristic(STANDALONE_AID, on_iid) + assert characteristic_value(frame, STANDALONE_AID, on_iid) is True diff --git a/tests/test_client.py b/tests/test_client.py index 67c4b10e..5a9f58f3 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -38,3 +38,24 @@ def test_new_persistent_loads_existing_identity(tmp_path: pathlib.Path) -> None: client = HAPClient.new_persistent(filepath=path, accessory_ltpk=_ltpk()) assert client.identity.uuid == identity.uuid assert client.identity.public_key_bytes == identity.public_key_bytes + + +def test_new_persistent_works_without_ltpk(tmp_path: pathlib.Path) -> None: + """No LTPK needed: the client is created and the session key still set up.""" + path = tmp_path / "controller.key" + client = HAPClient.new_persistent(filepath=path) + assert client.accessory_ltpk is None + assert ClientIdentity.load(path).accessory_ltpk is None + + +def test_new_persistent_pins_and_reuses_ltpk(tmp_path: pathlib.Path) -> None: + """A passed LTPK is pinned in the file; later calls pick it up from there.""" + path = tmp_path / "controller.key" + ltpk = _ltpk() + first = HAPClient.new_persistent(filepath=path, accessory_ltpk=ltpk) + assert first.accessory_ltpk == ltpk + assert ClientIdentity.load(path).accessory_ltpk == ltpk + + second = HAPClient.new_persistent(filepath=path) + assert second.accessory_ltpk == ltpk + assert second.identity.uuid == first.identity.uuid diff --git a/tests/test_client_identity.py b/tests/test_client_identity.py index 4c7613e6..7f48f257 100644 --- a/tests/test_client_identity.py +++ b/tests/test_client_identity.py @@ -1,11 +1,13 @@ """Unit tests for ClientIdentity generation and persistence.""" +import dataclasses import json import os import pathlib import stat from typing import Any +from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 import pytest @@ -88,3 +90,28 @@ def test_from_dict_rejects_non_mapping() -> None: not_a_mapping: Any = ["not", "a", "mapping"] with pytest.raises(ValueError): ClientIdentity.from_dict(not_a_mapping) + + +def test_accessory_ltpk_round_trip() -> None: + """A pinned accessory LTPK survives to_dict/from_dict and save/load.""" + ltpk = ( + ed25519.Ed25519PrivateKey.generate() + .public_key() + .public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + ) + identity = ClientIdentity.generate(0) + pinned = dataclasses.replace(identity, accessory_ltpk=ltpk) + assert ClientIdentity.from_dict(pinned.to_dict()).accessory_ltpk == ltpk + assert "accessory_ltpk" in pinned.to_dict() + assert "accessory_ltpk" not in identity.to_dict() + + +def test_from_dict_rejects_invalid_ltpk() -> None: + """A malformed pinned accessory LTPK raises ValueError.""" + data = ClientIdentity.generate(0).to_dict() + data["accessory_ltpk"] = "zz" + with pytest.raises(ValueError): + ClientIdentity.from_dict(data) + data["accessory_ltpk"] = "00" # valid hex, not a 32 byte key + with pytest.raises(ValueError): + ClientIdentity.from_dict(data) From 9a80f657c1dd881612bc2be2c42f3757e9a0c3d5 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Sat, 21 Nov 2026 20:43:07 +0100 Subject: [PATCH 06/15] Accept accessory_state= in pyhap.client; document pairing assumptions HAPClient and HAPClient.new_persistent now take an optional accessory_state path (the accessory's accessory.state file, e.g. copied from the accessory machine): its LTPK is read via the new pyhap.client.load_accessory_ltpk and pinned in the client file (trust on first use), alongside the existing accessory_ltpk= bytes parameter. load_accessory_ltpk also serves as the export path for moving just the accessory's public key to another machine - the state file contains the accessory's private key and should not be copied wholesale. The client API docs now spell out the assumptions: the client speaks pair-verify only, the identity must be paired first (with the driver.pair(...) snippet), the LTPK is optional, and the cross-machine steps are listed. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 10 +++- docs/source/api/client.rst | 58 ++++++++++++++++++- pyhap/client/__init__.py | 6 +- pyhap/client/controller.py | 57 ++++++++++++------ pyhap/client/state.py | 35 +++++++++++ .../integration/test_standalone_accessory.py | 22 +++++++ tests/test_client.py | 51 +++++++++++++++- 7 files changed, 213 insertions(+), 26 deletions(-) create mode 100644 pyhap/client/state.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c7accd3f..d6f18e55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,9 +29,13 @@ Sections + private key, written atomically with 0600 permissions), plus the `HAPClient.new_persistent(filepath=...)` convenience that loads the identity from a file or creates and backs it up there. The accessory LTPK - is optional: pass it once to pin it in the file (trust on first use), or - omit it for an encrypted but unauthenticated session. Covered by the new - integration tests in `tests/integration/`. + is optional: pass it once (raw bytes via `accessory_ltpk=`, or read from + the accessory's state file via `accessory_state=` / + `load_accessory_ltpk`) to pin it in the file (trust on first use), or + omit it for an encrypted but unauthenticated session. The API docs spell + out the pairing assumptions (pair-verify only; pair the identity with + `AccessoryDriver.pair` first) and the cross-machine steps. Covered by the + new integration tests in `tests/integration/`. ### Fixed diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index 19e5f458..6ef79ec0 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -11,6 +11,58 @@ suite and the integration tests use it to drive an :class:`pyhap.accessory_driver.AccessoryDriver` end to end; it is also handy for testing your own accessory. +Pairing and trust assumptions +============================= + +The client speaks **pair-verify only**. It never runs pair-setup — the SRP +handshake with the pincode that the Home app performs once when scanning the +QR code. Two things must therefore already exist when you connect: + +1. **The client identity must be paired with the accessory.** Pairings are + per controller identity: an existing iPhone pairing does not cover the + client. When you run the accessory yourself (the usual case for this + library), pair the identity in-process once, before connecting:: + + client = HAPClient.new_persistent(filepath="controller.key") + driver.pair( + client.identity.uuid_bytes, + client.identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) + await client.connect("127.0.0.1", port) + + Against a remote accessory you do not control, a pairing can only be + added by pair-setup (not implemented in the client) or by an + already-paired admin through the ``/pairings`` endpoint (also not + implemented) — otherwise pair-verify is rejected. + +2. **The accessory LTPK is optional, but recommended.** The LTPK is the + accessory's long-term public key, used to verify the accessory during + pair-verify; it cannot be learned from pair-verify itself (a real + controller learns it from pair-setup's M6 response). Pass it once — as + raw bytes (``accessory_ltpk=...``) or read from the accessory's state + file (``accessory_state="accessory.state"``) — and it is pinned in the + client file and verified on every later run. Without any LTPK the session + is still encrypted, but the accessory is not authenticated. + +Running the client on a different machine than the accessory +------------------------------------------------------------- + +1. On the accessory machine, pair the client identity once (``driver.pair`` + as above, or add it in the Home app). +2. Move only the accessory's *public* key to the client machine — do not + copy the whole ``accessory.state``, it contains the accessory's private + key. Read the public key out with :func:`pyhap.client.load_accessory_ltpk` + (or take the ``"public_key"`` hex field of the file), and pass the state + file's path once; the key is then pinned in the client file, so only + ``controller.key`` is needed afterwards:: + + client = HAPClient.new_persistent( + filepath="controller.key", + accessory_state="/path/to/accessory.state", # copied from the accessory machine + ) + await client.connect("192.168.1.50", 51826) + Example ======= @@ -23,9 +75,9 @@ controller is recognized again after a restart: from pyhap.const import HAP_PERMISSIONS # Loads controller.key if it exists, otherwise creates a new identity - # and saves it there. Pass accessory_ltpk=... once to pin the - # accessory's long-term key; without it the session is still encrypted, - # but the accessory is not authenticated. + # and saves it there. Pass accessory_ltpk=... or accessory_state=... once + # to pin the accessory's long-term key for verification; without it the + # session is still encrypted, but the accessory is not authenticated. client = HAPClient.new_persistent(filepath="controller.key") # Pair the identity once (bypasses the slow SRP pair-setup); the pairing # is stored in the accessory's own state file. diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py index cfe2dd17..fda7b2b2 100644 --- a/pyhap/client/__init__.py +++ b/pyhap/client/__init__.py @@ -16,7 +16,9 @@ # A controller whose identity is persisted at controller.key: loaded # back on later runs, created and saved on the first. Pass - # accessory_ltpk=... once to pin the accessory's key for verification. + # accessory_ltpk=... or accessory_state="accessory.state" once to pin + # the accessory's key for verification (on another machine, point + # accessory_state at a copy of the accessory's state file). client = HAPClient.new_persistent(filepath="controller.key") driver.pair( client.identity.uuid_bytes, @@ -32,11 +34,13 @@ from .controller import HAPClient from .identity import ClientIdentity from .protocol import Frame, parse_frame +from .state import load_accessory_ltpk __all__ = [ "RESPONSE_TIMEOUT", "ClientIdentity", "Frame", "HAPClient", + "load_accessory_ltpk", "parse_frame", ] diff --git a/pyhap/client/controller.py b/pyhap/client/controller.py index 8d6333be..b394363b 100644 --- a/pyhap/client/controller.py +++ b/pyhap/client/controller.py @@ -27,6 +27,7 @@ from ..hap_handler import HAP_TLV_STATES, HAP_TLV_TAGS from .identity import ClientIdentity from .protocol import HAP_CONTENT_TYPE, PAIRING_CONTENT_TYPE, Frame, parse_frame +from .state import load_accessory_ltpk logger = logging.getLogger(__name__) @@ -44,20 +45,31 @@ class HAPClient: """ def __init__( - self, identity: ClientIdentity, accessory_ltpk: bytes | None = None + self, + identity: ClientIdentity, + accessory_ltpk: bytes | None = None, + *, + accessory_state: str | os.PathLike[str] | None = None, ) -> None: """Initialize the controller for a given pairing identity. :param identity: The long-term identity the server is paired with. :param accessory_ltpk: Raw long-term public key of the accessory, - used to verify the server during pair-verify. Defaults to the - LTPK pinned in ``identity.accessory_ltpk``. When neither is - given, the accessory's signature is not verified: the session is - still encrypted, but the accessory is unauthenticated. + used to verify the server during pair-verify. + :param accessory_state: Path to the accessory's ``accessory.state`` + file (e.g. copied from the accessory machine); its LTPK is read + from there. Used when ``accessory_ltpk`` is not given. If neither + is given, the LTPK pinned in ``identity.accessory_ltpk`` is used; + when none is available at all, the accessory's signature is not + verified: the session is still encrypted, but the accessory is + unauthenticated. """ self._identity = identity - ltpk = accessory_ltpk if accessory_ltpk is not None else identity.accessory_ltpk - self._accessory_ltpk = ltpk + if accessory_ltpk is None and accessory_state is not None: + accessory_ltpk = load_accessory_ltpk(accessory_state) + if accessory_ltpk is None: + accessory_ltpk = identity.accessory_ltpk + self._accessory_ltpk = accessory_ltpk self._reader: asyncio.StreamReader | None = None self._writer: asyncio.StreamWriter | None = None self._read_task: asyncio.Task[None] | None = None @@ -70,7 +82,11 @@ def __init__( @classmethod def new_persistent( - cls, *, filepath: str | os.PathLike[str], accessory_ltpk: bytes | None = None + cls, + *, + filepath: str | os.PathLike[str], + accessory_ltpk: bytes | None = None, + accessory_state: str | os.PathLike[str] | None = None, ) -> HAPClient: """Create a client whose identity is persisted at ``filepath``. @@ -81,23 +97,28 @@ def new_persistent( accessory's state file); afterwards the client reconnects as the same controller after restarts. - An ``accessory_ltpk`` passed here is pinned in the file (trust on - first use): later calls without it verify the accessory against the - pinned key. Without any LTPK the session is encrypted but the - accessory is not authenticated. + The accessory LTPK is resolved from, in order: ``accessory_ltpk``, + ``accessory_state`` (an ``accessory.state`` file, e.g. copied from + the accessory machine), or the key pinned in ``filepath``. A resolved + LTPK is pinned into ``filepath`` (trust on first use), so later calls + verify the accessory against it. Without any LTPK the session is + encrypted but the accessory is not authenticated. """ path = os.path.expanduser(os.fspath(filepath)) if os.path.exists(path): identity = ClientIdentity.load(path) - if accessory_ltpk is not None and identity.accessory_ltpk != accessory_ltpk: - identity = replace(identity, accessory_ltpk=accessory_ltpk) - identity.save(path) else: identity = ClientIdentity.generate() - if accessory_ltpk is not None: - identity = replace(identity, accessory_ltpk=accessory_ltpk) identity.save(path) - return cls(identity, accessory_ltpk) + ltpk = accessory_ltpk + if ltpk is None and accessory_state is not None: + ltpk = load_accessory_ltpk(accessory_state) + if ltpk is None: + ltpk = identity.accessory_ltpk + if ltpk is not None and identity.accessory_ltpk != ltpk: + identity = replace(identity, accessory_ltpk=ltpk) + identity.save(path) + return cls(identity, ltpk) @property def identity(self) -> ClientIdentity: diff --git a/pyhap/client/state.py b/pyhap/client/state.py new file mode 100644 index 00000000..ef72400d --- /dev/null +++ b/pyhap/client/state.py @@ -0,0 +1,35 @@ +"""Reading the accessory's persisted state file (``accessory.state``).""" + +from __future__ import annotations + +import json +import os + +from cryptography.hazmat.primitives.asymmetric import ed25519 + + +def load_accessory_ltpk(path: str | os.PathLike[str]) -> bytes: + """Return the accessory's raw long-term public key (LTPK) from its state file. + + The state file is the ``AccessoryDriver``'s ``accessory.state``. + + Use this to move just the accessory's public key to another machine, e.g. + where a client runs: the state file also contains the accessory's + *private* key, so prefer exporting the public key alone (via this + function or the ``"public_key"`` hex field) over copying the whole file. + + :raise ValueError: If the file is not an accessory state file or the key + is malformed. + :raise OSError: If the file does not exist or cannot be read. + """ + target = os.path.expanduser(os.fspath(path)) + try: + with open(target, encoding="utf-8") as file_handle: + data = json.load(file_handle) + ltpk = bytes.fromhex(data["public_key"]) + ed25519.Ed25519PublicKey.from_public_bytes(ltpk) + except (KeyError, TypeError, ValueError) as error: + raise ValueError( + f"Not an accessory state file (no valid 'public_key'): {target}" + ) from error + return ltpk diff --git a/tests/integration/test_standalone_accessory.py b/tests/integration/test_standalone_accessory.py index 6cf5bd9c..2e6e97a4 100644 --- a/tests/integration/test_standalone_accessory.py +++ b/tests/integration/test_standalone_accessory.py @@ -106,3 +106,25 @@ async def test_client_connects_without_pinned_ltpk( assert frame.status == 204 frame = await client.read_characteristic(STANDALONE_AID, on_iid) assert characteristic_value(frame, STANDALONE_AID, on_iid) is True + + +async def test_client_pins_ltpk_from_accessory_state_file( + make_hap_server: Any, tmp_path: pathlib.Path +) -> None: + """accessory_state= reads the LTPK from the driver's state file and pins it.""" + state_file = tmp_path / "accessory.state" + server = await make_hap_server(build_switch, client_count=0, state_file=state_file) + + client = HAPClient.new_persistent( + filepath=tmp_path / "controller.key", accessory_state=state_file + ) + assert client.accessory_ltpk == server.accessory_ltpk + server.driver.pair( + client.identity.uuid_bytes, + client.identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) + await server.connect_client(client) + + frame = await client.get_accessories() + assert frame.status == 200 diff --git a/tests/test_client.py b/tests/test_client.py index 5a9f58f3..61e67ffc 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -4,8 +4,11 @@ from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 +import pytest -from pyhap.client import ClientIdentity, HAPClient +from pyhap.client import ClientIdentity, HAPClient, load_accessory_ltpk +from pyhap.encoder import AccessoryEncoder +from pyhap.state import State def _ltpk() -> bytes: @@ -59,3 +62,49 @@ def test_new_persistent_pins_and_reuses_ltpk(tmp_path: pathlib.Path) -> None: second = HAPClient.new_persistent(filepath=path) assert second.accessory_ltpk == ltpk assert second.identity.uuid == first.identity.uuid + + +def _write_state_file(path: pathlib.Path) -> bytes: + """Write a real accessory.state via the encoder; return its raw LTPK.""" + state = State(address="127.0.0.1") + with open(path, "w", encoding="utf-8") as file_handle: + AccessoryEncoder().persist(file_handle, state) + return state.public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + +def test_load_accessory_ltpk(tmp_path: pathlib.Path) -> None: + """The LTPK is read back from a real accessory.state file.""" + state_file = tmp_path / "accessory.state" + expected = _write_state_file(state_file) + assert load_accessory_ltpk(state_file) == expected + + +def test_load_accessory_ltpk_rejects_bad_file(tmp_path: pathlib.Path) -> None: + """Files without a valid public_key raise ValueError.""" + bad = tmp_path / "bad.state" + bad.write_text("{}", encoding="utf-8") + with pytest.raises(ValueError): + load_accessory_ltpk(bad) + bad.write_text("not json", encoding="utf-8") + with pytest.raises(ValueError): + load_accessory_ltpk(bad) + + +def test_new_persistent_pins_ltpk_from_accessory_state( + tmp_path: pathlib.Path, +) -> None: + """accessory_state= resolves and pins the LTPK; later calls reuse the pin.""" + state_file = tmp_path / "accessory.state" + expected = _write_state_file(state_file) + key_file = tmp_path / "controller.key" + + client = HAPClient.new_persistent(filepath=key_file, accessory_state=state_file) + assert client.accessory_ltpk == expected + assert ClientIdentity.load(key_file).accessory_ltpk == expected + + again = HAPClient.new_persistent(filepath=key_file) + assert again.accessory_ltpk == expected + assert again.identity.uuid == client.identity.uuid From e642752822789ccb26e91cec3f032bafed7f9b1b Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Sat, 21 Nov 2026 20:54:06 +0100 Subject: [PATCH 07/15] new_persistent: raise on conflicting pinned LTPK instead of re-pinning The persisted client file is now authoritative for the accessory LTPK: the first resolved LTPK is pinned (trust on first use), and passing a different accessory_ltpk/accessory_state afterwards raises ValueError. Migrating the client to another accessory is an explicit out-of-band edit of the client file, out of scope for new_persistent. Docs updated to say so. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 4 +++- docs/source/api/client.rst | 7 +++++-- pyhap/client/controller.py | 21 +++++++++++++++------ tests/test_client.py | 9 +++++++++ 4 files changed, 32 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6f18e55..43bfb48e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,9 @@ Sections identity from a file or creates and backs it up there. The accessory LTPK is optional: pass it once (raw bytes via `accessory_ltpk=`, or read from the accessory's state file via `accessory_state=` / - `load_accessory_ltpk`) to pin it in the file (trust on first use), or + `load_accessory_ltpk`) to pin it in the file (trust on first use; a + conflicting pinned LTPK raises `ValueError` — migrating to another + accessory means editing the client file), or omit it for an encrypted but unauthenticated session. The API docs spell out the pairing assumptions (pair-verify only; pair the identity with `AccessoryDriver.pair` first) and the cross-machine steps. Covered by the diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index 6ef79ec0..331a293c 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -42,8 +42,11 @@ QR code. Two things must therefore already exist when you connect: controller learns it from pair-setup's M6 response). Pass it once — as raw bytes (``accessory_ltpk=...``) or read from the accessory's state file (``accessory_state="accessory.state"``) — and it is pinned in the - client file and verified on every later run. Without any LTPK the session - is still encrypted, but the accessory is not authenticated. + client file and verified on every later run. If the client file already + pins a *different* LTPK, ``new_persistent`` raises ``ValueError``: + migrating the client to another accessory is done by updating (or + deleting) the client file yourself, not via the method. Without any LTPK + the session is still encrypted, but the accessory is not authenticated. Running the client on a different machine than the accessory ------------------------------------------------------------- diff --git a/pyhap/client/controller.py b/pyhap/client/controller.py index b394363b..520960fe 100644 --- a/pyhap/client/controller.py +++ b/pyhap/client/controller.py @@ -97,12 +97,15 @@ def new_persistent( accessory's state file); afterwards the client reconnects as the same controller after restarts. - The accessory LTPK is resolved from, in order: ``accessory_ltpk``, + The accessory LTPK is resolved from ``accessory_ltpk``, ``accessory_state`` (an ``accessory.state`` file, e.g. copied from - the accessory machine), or the key pinned in ``filepath``. A resolved - LTPK is pinned into ``filepath`` (trust on first use), so later calls - verify the accessory against it. Without any LTPK the session is - encrypted but the accessory is not authenticated. + the accessory machine), or the pin in ``filepath``. The first time a + LTPK is resolved it is pinned into ``filepath`` (trust on first use), + so later calls verify the accessory against it. If the file already + pins a *different* LTPK, :exc:`ValueError` is raised: migrating the + client to another accessory is out of scope here — update (or delete) + the file yourself. Without any LTPK the session is encrypted but the + accessory is not authenticated. """ path = os.path.expanduser(os.fspath(filepath)) if os.path.exists(path): @@ -115,7 +118,13 @@ def new_persistent( ltpk = load_accessory_ltpk(accessory_state) if ltpk is None: ltpk = identity.accessory_ltpk - if ltpk is not None and identity.accessory_ltpk != ltpk: + pinned = identity.accessory_ltpk + if pinned is not None and ltpk is not None and pinned != ltpk: + raise ValueError( + f"{path} pins a different accessory LTPK; to point the client " + "at another accessory, update (or delete) the file yourself" + ) + if pinned is None and ltpk is not None: identity = replace(identity, accessory_ltpk=ltpk) identity.save(path) return cls(identity, ltpk) diff --git a/tests/test_client.py b/tests/test_client.py index 61e67ffc..ba61abc1 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -108,3 +108,12 @@ def test_new_persistent_pins_ltpk_from_accessory_state( again = HAPClient.new_persistent(filepath=key_file) assert again.accessory_ltpk == expected assert again.identity.uuid == client.identity.uuid + + +def test_new_persistent_rejects_conflicting_ltpk(tmp_path: pathlib.Path) -> None: + """A pinned LTPK is authoritative; a different one raises, file untouched.""" + path = tmp_path / "controller.key" + first = HAPClient.new_persistent(filepath=path, accessory_ltpk=_ltpk()) + with pytest.raises(ValueError, match="different accessory LTPK"): + HAPClient.new_persistent(filepath=path, accessory_ltpk=_ltpk()) + assert ClientIdentity.load(path).accessory_ltpk == first.accessory_ltpk From 5dcc070f3af63563669dfcaf10d361dab26afff1 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 15:26:09 +0100 Subject: [PATCH 08/15] nit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7932125d..cd6fb947 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Main features: * **asyncio support** — run various tasks or accessories in the event loop. * **Out of the box support for Apple-defined services** — see them in [the resources folder](pyhap/resources). * **Secure pairing** — just scan a QR code, no manual codes to type in. -* **HAP client included** — [pyhap/client](pyhap/client) is a controller that speaks the real protocol (pair-verify, encrypted transport, events) against a running accessory, handy for tests and benchmarks. +* **HAP client included** — [pyhap/client](pyhap/client) is a controller that speaks the real protocol against a running accessory. * **Proven in production** — HAP-python powers the HomeKit integration of the home automation framework [Home Assistant](https://github.com/home-assistant/home-assistant). Full API documentation is available on [readthedocs](http://hap-python.readthedocs.io/). From 5e06bfef154165750087c71850d90f3d0f719ce1 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 15:42:18 +0100 Subject: [PATCH 09/15] polish doc section for client; add sphinx into testing skill --- .skills/pyhap-testing/SKILL.md | 8 ++++++++ docs/source/api/client.rst | 32 +++++++++++++++++++++----------- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/.skills/pyhap-testing/SKILL.md b/.skills/pyhap-testing/SKILL.md index 3e0a5743..558dfaad 100644 --- a/.skills/pyhap-testing/SKILL.md +++ b/.skills/pyhap-testing/SKILL.md @@ -67,6 +67,14 @@ carries a pre-existing baseline of diagnostics (mostly in `tests/`): capture it before your changes and ensure your edits add no new findings. Otherwise report the findings. +## sphinx (docs) + +Check the documentation compiles fine by running: + +```sh +python -m sphinx -W -b html source build/html +``` + ## Reporting When asked to "test everything", run **pytest, ruff check/format, and ty** in that diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index 331a293c..dc529a37 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -4,26 +4,36 @@ Client ====== -A HAP controller (client) that speaks the real protocol against a running -accessory: pair-verify, the encrypted transport, characteristic -reads/writes, event subscriptions and ``EVENT`` push frames. The benchmark -suite and the integration tests use it to drive an -:class:`pyhap.accessory_driver.AccessoryDriver` end to end; it is also handy -for testing your own accessory. +`pyhap` also ships a HAP controller (client) under `pyhap.client.HAPClient`. +The client uses the HAP protocol to control an accessory similarly to how you +can control it through the Home app on iOS. Event subscribtion is also supported. + +The client can be persistent, i.e. after it is started it can persist its +identity (what the accesory remembers and later verifies) into a file for +subsequent reuse. + +The main limitation of the client currently is that it does not support pairing up +from scratch (see below). + +The client is used in the integration tests and in the benchmark suite, in case +you are looking for examples. Pairing and trust assumptions ============================= -The client speaks **pair-verify only**. It never runs pair-setup — the SRP -handshake with the pincode that the Home app performs once when scanning the -QR code. Two things must therefore already exist when you connect: +The client assumes a pyhap accessory has already completed `pair-setup`. That is, +the client does not support pairing from scratch right now - this is mainly because of +a missing part of the server-side crypto protocol. + +Two things must therefore already exist when you connect: 1. **The client identity must be paired with the accessory.** Pairings are per controller identity: an existing iPhone pairing does not cover the client. When you run the accessory yourself (the usual case for this - library), pair the identity in-process once, before connecting:: + library), pair the identity before connecting:: client = HAPClient.new_persistent(filepath="controller.key") + # Safe to do multiple times, it's idempotent. driver.pair( client.identity.uuid_bytes, client.identity.public_key_bytes, @@ -38,7 +48,7 @@ QR code. Two things must therefore already exist when you connect: 2. **The accessory LTPK is optional, but recommended.** The LTPK is the accessory's long-term public key, used to verify the accessory during - pair-verify; it cannot be learned from pair-verify itself (a real + pair-verify. This is not available from pair-verify itself (a real controller learns it from pair-setup's M6 response). Pass it once — as raw bytes (``accessory_ltpk=...``) or read from the accessory's state file (``accessory_state="accessory.state"``) — and it is pinned in the From 154747635228f41a6d731e6d9fe37737c24e6710 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 15:53:13 +0100 Subject: [PATCH 10/15] Complete the pyhap.client docs example: driver setup, advertise=False The example now instantiates the AccessoryDriver with advertise=False (the API switch that runs the HAP server without mDNS advertising), pairs the persistent client identity, and shows the full start/connect/operate/stop flow, plus the driverless variant against a running accessory via accessory_state= (noting the state file does not store the port). Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- docs/source/api/client.rst | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index dc529a37..0486a26f 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -79,33 +79,49 @@ Running the client on a different machine than the accessory Example ======= -Drive a running accessory as a controller, with the identity persisted so the -controller is recognized again after a restart: +Host an accessory and drive it with a client in the same process. +``advertise=False`` runs the HAP server *without* the mDNS advertisement +(a real deployment advertises, so the Home app can discover it; tests and +local setups can skip it): .. code-block:: python + from pyhap.accessory_driver import AccessoryDriver from pyhap.client import HAPClient from pyhap.const import HAP_PERMISSIONS + driver = AccessoryDriver(port=51827, advertise=False) # HAP server only, no mDNS + driver.add_accessory(MyAccessory(driver, "My Accessory")) # your Accessory subclass + # Loads controller.key if it exists, otherwise creates a new identity - # and saves it there. Pass accessory_ltpk=... or accessory_state=... once - # to pin the accessory's long-term key for verification; without it the - # session is still encrypted, but the accessory is not authenticated. + # and saves it there. Pair the identity once (bypasses the slow SRP + # pair-setup); the pairing is stored in the accessory's own state file. client = HAPClient.new_persistent(filepath="controller.key") - # Pair the identity once (bypasses the slow SRP pair-setup); the pairing - # is stored in the accessory's own state file. driver.pair( client.identity.uuid_bytes, client.identity.public_key_bytes, HAP_PERMISSIONS.ADMIN, ) - await client.connect("127.0.0.1", port) # pair-verify + encryption + await driver.async_start() # start the HAP server + await client.connect("127.0.0.1", 51827) # pair-verify + encryption await client.get_accessories() # GET /accessories await client.subscribe(1, on_iid) # EVENT notifications on await client.write_characteristic(1, on_iid, True) await client.wait_event(1, on_iid, True) # an update arrives as EVENT await client.close() + await driver.async_stop() + +Against an already-running accessory (e.g. on another machine) there is no +driver to instantiate: pass the accessory's state file once to pin its LTPK +(see the section above), and connect to its host:port explicitly — the state +file stores the keys and pairings but not the port:: + + client = HAPClient.new_persistent( + filepath="controller.key", + accessory_state="accessory.state", # copied from the accessory machine + ) + await client.connect("192.168.1.50", 51827) .. automodule:: pyhap.client :members: From b0ee71fc1ca24c50733946400894b4ad8a501ab0 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 16:05:55 +0100 Subject: [PATCH 11/15] Add add_client_pairing for offline pairing via the accessory state file pyhap.client.state.add_client_pairing(path, identity, permissions=ADMIN) loads an accessory.state with AccessoryEncoder.load_into, registers the client identity via State.add_paired_client, and writes the file back atomically (0600 tempfile + os.replace) - no driver needed, so the client can live on a different machine than the accessory (edit with the accessory stopped; a running driver would overwrite the file on its next persist). The docs' cross-machine section now spells out the three steps, and an integration test runs the full flow: accessory creates its state file and stops, pairing is added offline, accessory restarts, client pair-verifies. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 6 ++- docs/source/api/client.rst | 38 ++++++++++---- pyhap/client/__init__.py | 3 +- pyhap/client/state.py | 52 +++++++++++++++++++- tests/integration/test_persisted_identity.py | 30 ++++++++++- tests/test_client.py | 45 ++++++++++++++++- 6 files changed, 158 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43bfb48e..09185570 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,7 +34,11 @@ Sections `load_accessory_ltpk`) to pin it in the file (trust on first use; a conflicting pinned LTPK raises `ValueError` — migrating to another accessory means editing the client file), or - omit it for an encrypted but unauthenticated session. The API docs spell + omit it for an encrypted but unauthenticated session. Also + `add_client_pairing(state_file, identity)` registers a client identity in + the accessory's `accessory.state` offline (atomic write, no driver + needed), for running the client on a different machine than the + accessory. The API docs spell out the pairing assumptions (pair-verify only; pair the identity with `AccessoryDriver.pair` first) and the cross-machine steps. Covered by the new integration tests in `tests/integration/`. diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index 0486a26f..66652fdf 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -61,20 +61,38 @@ Two things must therefore already exist when you connect: Running the client on a different machine than the accessory ------------------------------------------------------------- -1. On the accessory machine, pair the client identity once (``driver.pair`` - as above, or add it in the Home app). -2. Move only the accessory's *public* key to the client machine — do not - copy the whole ``accessory.state``, it contains the accessory's private - key. Read the public key out with :func:`pyhap.client.load_accessory_ltpk` - (or take the ``"public_key"`` hex field of the file), and pass the state - file's path once; the key is then pinned in the client file, so only - ``controller.key`` is needed afterwards:: +1. On the client machine, create the persistent identity once and copy + ``controller.key`` to the accessory machine (it holds the client's + private key — only copy it to machines you trust):: + + client = HAPClient.new_persistent(filepath="controller.key") + +2. On the accessory machine, with the accessory **stopped** (a running + driver keeps its state in memory and would overwrite the edit on its + next persist), register the identity in the state file offline — no + driver needed:: + + from pyhap.client import ClientIdentity, add_client_pairing + + add_client_pairing("accessory.state", ClientIdentity.load("controller.key")) + + Then start the accessory again; it loads the updated ``accessory.state``. + While the driver is running, ``driver.pair(...)`` (above) does the same + in-process; an already-paired admin can also add pairings remotely via + the ``/pairings`` endpoint, which this client does not implement. +3. On the client machine, move only the accessory's *public* key back — do + not copy the whole ``accessory.state``, it contains the accessory's + private key (read just the public key out with + :func:`pyhap.client.load_accessory_ltpk`, or copy the file and pass it + once). The key is then pinned in the client file, so only + ``controller.key`` is needed afterwards. The state file does not store + the port, so pass host:port explicitly:: client = HAPClient.new_persistent( filepath="controller.key", - accessory_state="/path/to/accessory.state", # copied from the accessory machine + accessory_state="accessory.state", # copied from the accessory machine ) - await client.connect("192.168.1.50", 51826) + await client.connect("192.168.1.50", 51827) Example ======= diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py index fda7b2b2..1febe63c 100644 --- a/pyhap/client/__init__.py +++ b/pyhap/client/__init__.py @@ -34,13 +34,14 @@ from .controller import HAPClient from .identity import ClientIdentity from .protocol import Frame, parse_frame -from .state import load_accessory_ltpk +from .state import add_client_pairing, load_accessory_ltpk __all__ = [ "RESPONSE_TIMEOUT", "ClientIdentity", "Frame", "HAPClient", + "add_client_pairing", "load_accessory_ltpk", "parse_frame", ] diff --git a/pyhap/client/state.py b/pyhap/client/state.py index ef72400d..131bd72c 100644 --- a/pyhap/client/state.py +++ b/pyhap/client/state.py @@ -1,12 +1,18 @@ -"""Reading the accessory's persisted state file (``accessory.state``).""" +"""Reading and updating the accessory's persisted state file (``accessory.state``).""" from __future__ import annotations import json import os +import tempfile from cryptography.hazmat.primitives.asymmetric import ed25519 +from ..const import HAP_PERMISSIONS +from ..encoder import AccessoryEncoder +from ..state import State +from .identity import ClientIdentity + def load_accessory_ltpk(path: str | os.PathLike[str]) -> bytes: """Return the accessory's raw long-term public key (LTPK) from its state file. @@ -33,3 +39,47 @@ def load_accessory_ltpk(path: str | os.PathLike[str]) -> bytes: f"Not an accessory state file (no valid 'public_key'): {target}" ) from error return ltpk + + +def add_client_pairing( + path: str | os.PathLike[str], + identity: ClientIdentity, + permissions: bytes = HAP_PERMISSIONS.ADMIN, +) -> None: + """Register ``identity`` as a paired client in an accessory state file, offline. + + Loads the ``AccessoryDriver`` state file at ``path`` with + :meth:`pyhap.encoder.AccessoryEncoder.load_into`, adds the client via + :meth:`pyhap.state.State.add_paired_client`, and writes the file back + atomically (a 0600 tempfile swapped in with ``os.replace``, like the + driver does). No driver needs to run. + + Do this with the accessory **stopped**: a running driver keeps its state + in memory and would overwrite this edit on its next persist. (While the + driver runs, ``AccessoryDriver.pair(...)`` does the same in-process.) + After the accessory restarts with the updated file, a client with this + identity can pair-verify against it. + + :param path: The accessory's ``accessory.state`` file. + :param identity: The client identity to pair (UUID + long-term public key). + :param permissions: The pairing's permissions, admin by default. + :raise OSError: If the file does not exist or cannot be read. + :raise ValueError: If the file is malformed or the UUID is invalid. + """ + target = os.path.expanduser(os.fspath(path)) + state = State(address="127.0.0.1") # placeholders; load_into overwrites them + with open(target, encoding="utf-8") as file_handle: + AccessoryEncoder().load_into(file_handle, state) + state.add_paired_client(identity.uuid_bytes, identity.public_key_bytes, permissions) + directory = os.path.dirname(target) or "." + tmp_filename = None + try: + with tempfile.NamedTemporaryFile( + mode="w", dir=directory, delete=False, encoding="utf-8" + ) as file_handle: + tmp_filename = file_handle.name + AccessoryEncoder().persist(file_handle, state) + os.replace(tmp_filename, target) + finally: + if tmp_filename is not None and os.path.exists(tmp_filename): + os.remove(tmp_filename) diff --git a/tests/integration/test_persisted_identity.py b/tests/integration/test_persisted_identity.py index c1930d32..7798b3a6 100644 --- a/tests/integration/test_persisted_identity.py +++ b/tests/integration/test_persisted_identity.py @@ -13,7 +13,7 @@ import pytest -from pyhap.client import ClientIdentity, HAPClient +from pyhap.client import ClientIdentity, HAPClient, add_client_pairing from pyhap.const import HAP_PERMISSIONS, STANDALONE_AID from .helpers import SwitchAccessory, build_switch, iid_of @@ -70,3 +70,31 @@ async def test_persisted_identity_reconnects_after_server_restart( assert frame.status == 200 frame = await client2.write_characteristic(STANDALONE_AID, on_iid2, True) assert frame.status == 204 + + +async def test_pairing_added_offline_via_state_file( + make_hap_server: Any, tmp_path: pathlib.Path +) -> None: + """Two-machine flow: pairing added to accessory.state, no driver running.""" + state_file = tmp_path / "accessory.state" + key_file = tmp_path / "controller.key" + + # The accessory runs once, creating its state file, then stops. + server = await make_hap_server(build_switch, client_count=0, state_file=state_file) + await server.stop() + + # "Client machine": create the persistent identity. + client = HAPClient.new_persistent(filepath=key_file) + # "Accessory machine", offline: register the identity in accessory.state. + add_client_pairing(state_file, client.identity) + # Back on the "client machine": pin the accessory LTPK from the state file. + client = HAPClient.new_persistent(filepath=key_file, accessory_state=state_file) + assert client.accessory_ltpk is not None + + # The accessory restarts with the updated state file; the client pair-verifies. + restarted = await make_hap_server( + build_switch, client_count=0, state_file=state_file + ) + await restarted.connect_client(client) + frame = await client.get_accessories() + assert frame.status == 200 diff --git a/tests/test_client.py b/tests/test_client.py index ba61abc1..3ed8e54a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,12 +1,20 @@ -"""Unit tests for HAPClient construction helpers.""" +"""Unit tests for HAPClient construction helpers and state-file tooling.""" +import os import pathlib +import stat +import uuid from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 import pytest -from pyhap.client import ClientIdentity, HAPClient, load_accessory_ltpk +from pyhap.client import ( + ClientIdentity, + HAPClient, + add_client_pairing, + load_accessory_ltpk, +) from pyhap.encoder import AccessoryEncoder from pyhap.state import State @@ -110,6 +118,39 @@ def test_new_persistent_pins_ltpk_from_accessory_state( assert again.identity.uuid == client.identity.uuid +def test_add_client_pairing(tmp_path: pathlib.Path) -> None: + """A client identity can be registered in accessory.state offline.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + identity = ClientIdentity.generate(9) + + add_client_pairing(state_file, identity) + add_client_pairing(state_file, identity) # idempotent + + state = State(address="127.0.0.1") + with open(state_file, encoding="utf-8") as file_handle: + AccessoryEncoder().load_into(file_handle, state) + client_uuid = uuid.UUID(identity.uuid) + assert len(state.paired_clients) == 1 + assert state.paired_clients[client_uuid] == identity.public_key_bytes + assert state.is_admin(client_uuid) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX file permissions") +def test_add_client_pairing_keeps_file_private(tmp_path: pathlib.Path) -> None: + """The rewritten state file stays 0600 (atomic tempfile write).""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + add_client_pairing(state_file, ClientIdentity.generate(9)) + assert stat.S_IMODE(os.stat(state_file).st_mode) == 0o600 + + +def test_add_client_pairing_missing_file(tmp_path: pathlib.Path) -> None: + """A missing state file raises OSError.""" + with pytest.raises(OSError): + add_client_pairing(tmp_path / "nope.state", ClientIdentity.generate(9)) + + def test_new_persistent_rejects_conflicting_ltpk(tmp_path: pathlib.Path) -> None: """A pinned LTPK is authoritative; a different one raises, file untouched.""" path = tmp_path / "controller.key" From 3e22b670857cbf1a151c6f45c41a2ace9fad830a Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 16:35:24 +0100 Subject: [PATCH 12/15] Add python -m pyhap.client CLI: new / register / list / deregister Offline controller management without a running driver, for running the client on a different machine than the accessory: - `new -f client.state` creates a persistent controller identity and prints the public JSON (uuid + public_key only) to hand to the accessory machine; refuses to overwrite without --force. - `register -f client.json -a accessory.state [-p admin|user]` adds the pairing to the accessory state file (atomic 0600 write) and warns to stop a running accessory first. - `list -a accessory.state` prints `: ` lines (never keys). - `deregister -a accessory.state [--yes]` removes a pairing; refuses without --yes when it is an admin or the last pairing, because removing the last admin wipes all pairings. Backed by new pyhap.client helpers load_accessory_state / save_accessory_state / remove_client_pairing, and add_client_pairing now also accepts a plain uuid + public key. The client also reports a clean "pair-verify rejected" when the accessory is completely unpaired (error TLV at M2). The API docs lead with the CLI workflow, and tests cover the CLI in-process plus an end-to-end integration test (new -> register -> restart -> connect -> deregister -> rejected). Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 9 ++ docs/source/api/client.rst | 86 ++++++---- pyhap/client/__init__.py | 11 +- pyhap/client/__main__.py | 8 + pyhap/client/cli.py | 226 +++++++++++++++++++++++++++ pyhap/client/controller.py | 6 + pyhap/client/state.py | 146 +++++++++++------ tests/integration/test_client_cli.py | 68 ++++++++ tests/test_client.py | 57 +++++++ 9 files changed, 537 insertions(+), 80 deletions(-) create mode 100644 pyhap/client/__main__.py create mode 100644 pyhap/client/cli.py create mode 100644 tests/integration/test_client_cli.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 09185570..557a5bbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,15 @@ Sections out the pairing assumptions (pair-verify only; pair the identity with `AccessoryDriver.pair` first) and the cross-machine steps. Covered by the new integration tests in `tests/integration/`. +- `python -m pyhap.client` CLI for offline controller management: + `new -f client.state` creates a persistent controller identity and prints + the public (uuid + public key) JSON to register elsewhere; `register -f + client.json -a accessory.state` adds the pairing to the accessory's state + file without a running driver; `list -a accessory.state` prints + `: `; `deregister -a accessory.state [--yes]` + removes a pairing (guarded, since removing the last admin wipes all + pairings). Also `load_accessory_state`/`save_accessory_state`/ + `remove_client_pairing` in `pyhap.client` for the programmatic equivalent. ### Fixed diff --git a/docs/source/api/client.rst b/docs/source/api/client.rst index 66652fdf..bf03f686 100644 --- a/docs/source/api/client.rst +++ b/docs/source/api/client.rst @@ -44,7 +44,10 @@ Two things must therefore already exist when you connect: Against a remote accessory you do not control, a pairing can only be added by pair-setup (not implemented in the client) or by an already-paired admin through the ``/pairings`` endpoint (also not - implemented) — otherwise pair-verify is rejected. + implemented) — otherwise pair-verify is rejected. To pair a client with + an accessory on another machine without a running driver, use the + command line interface (``python -m pyhap.client``, see the first + example below) or :func:`pyhap.client.add_client_pairing`. 2. **The accessory LTPK is optional, but recommended.** The LTPK is the accessory's long-term public key, used to verify the accessory during @@ -61,42 +64,55 @@ Two things must therefore already exist when you connect: Running the client on a different machine than the accessory ------------------------------------------------------------- -1. On the client machine, create the persistent identity once and copy - ``controller.key`` to the accessory machine (it holds the client's - private key — only copy it to machines you trust):: - - client = HAPClient.new_persistent(filepath="controller.key") - -2. On the accessory machine, with the accessory **stopped** (a running - driver keeps its state in memory and would overwrite the edit on its - next persist), register the identity in the state file offline — no - driver needed:: - - from pyhap.client import ClientIdentity, add_client_pairing - - add_client_pairing("accessory.state", ClientIdentity.load("controller.key")) - - Then start the accessory again; it loads the updated ``accessory.state``. - While the driver is running, ``driver.pair(...)`` (above) does the same - in-process; an already-paired admin can also add pairings remotely via - the ``/pairings`` endpoint, which this client does not implement. -3. On the client machine, move only the accessory's *public* key back — do - not copy the whole ``accessory.state``, it contains the accessory's - private key (read just the public key out with - :func:`pyhap.client.load_accessory_ltpk`, or copy the file and pass it - once). The key is then pinned in the client file, so only - ``controller.key`` is needed afterwards. The state file does not store - the port, so pass host:port explicitly:: - - client = HAPClient.new_persistent( - filepath="controller.key", - accessory_state="accessory.state", # copied from the accessory machine - ) - await client.connect("192.168.1.50", 51827) +Use the command line interface (see the first example below): on the client +machine ``python -m pyhap.client new -f client.state`` creates the identity +and prints a small JSON file (uuid + public key only — copy *that* to the +accessory machine, never ``client.state`` itself, it holds the private key); +on the accessory machine, with the accessory **stopped** (a running driver +would overwrite the edit on its next persist), run ``python -m pyhap.client +register -f client.json -a accessory.state``. Then start the accessory again +and connect from the client machine. The programmatic equivalent of +``register`` is :func:`pyhap.client.add_client_pairing`. Example ======= +Command line (recommended when the client runs on another machine) +------------------------------------------------------------------ + +Create a persistent controller identity on the client machine — the command +prints the JSON to hand to the accessory machine: + +.. code-block:: console + + $ python -m pyhap.client new -f client.state + Creating new HAP controller in file "client.state"... + Done! + + On the machine where your accessory is running create a file with the + following contents: + + { + "uuid": "...", + "public_key": "..." + } + + and run `python -m pyhap.client register -f -a `. + ... + +On the accessory machine (accessory stopped), register the controller, and +list or remove paired controllers: + +.. code-block:: console + + $ python -m pyhap.client register -f client.json -a accessory.state + $ python -m pyhap.client list -a accessory.state + 123e4567-e89b-12d3-a456-426614174000: admin + $ python -m pyhap.client deregister -a accessory.state 123e4567-e89b-12d3-a456-426614174000 --yes + +Programmatic (same machine, or full control) +-------------------------------------------- + Host an accessory and drive it with a client in the same process. ``advertise=False`` runs the HAP server *without* the mDNS advertisement (a real deployment advertises, so the Home app can discover it; tests and @@ -133,7 +149,9 @@ local setups can skip it): Against an already-running accessory (e.g. on another machine) there is no driver to instantiate: pass the accessory's state file once to pin its LTPK (see the section above), and connect to its host:port explicitly — the state -file stores the keys and pairings but not the port:: +file stores the keys and pairings but not the port: + +.. code-block:: python client = HAPClient.new_persistent( filepath="controller.key", diff --git a/pyhap/client/__init__.py b/pyhap/client/__init__.py index 1febe63c..4e7c7259 100644 --- a/pyhap/client/__init__.py +++ b/pyhap/client/__init__.py @@ -34,7 +34,13 @@ from .controller import HAPClient from .identity import ClientIdentity from .protocol import Frame, parse_frame -from .state import add_client_pairing, load_accessory_ltpk +from .state import ( + add_client_pairing, + load_accessory_ltpk, + load_accessory_state, + remove_client_pairing, + save_accessory_state, +) __all__ = [ "RESPONSE_TIMEOUT", @@ -43,5 +49,8 @@ "HAPClient", "add_client_pairing", "load_accessory_ltpk", + "load_accessory_state", "parse_frame", + "remove_client_pairing", + "save_accessory_state", ] diff --git a/pyhap/client/__main__.py b/pyhap/client/__main__.py new file mode 100644 index 00000000..33d260df --- /dev/null +++ b/pyhap/client/__main__.py @@ -0,0 +1,8 @@ +"""Entry point for ``python -m pyhap.client``.""" + +import sys + +from .cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pyhap/client/cli.py b/pyhap/client/cli.py new file mode 100644 index 00000000..d0474499 --- /dev/null +++ b/pyhap/client/cli.py @@ -0,0 +1,226 @@ +"""Command line interface for offline controller management. + +Run as ``python -m pyhap.client --help``. The subcommands create +persistent controller identities and register/deregister them in an +accessory's state file without a running driver, e.g. to run the client on a +different machine than the accessory. +""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable +import json +import os +import sys +from typing import Any +from uuid import UUID + +from ..const import CLIENT_PROP_PERMS, HAP_PERMISSIONS +from .identity import ClientIdentity +from .state import ( + add_client_pairing, + load_accessory_state, + remove_client_pairing, +) + +_RUNNING_ACCESSORY_WARNING = ( + "Note: if the accessory is currently running, stop it and start it again " + "so it loads the updated state file - a running driver may overwrite this " + "change on its next persist (while it runs, use AccessoryDriver.pair() / " + "AccessoryDriver.unpair() in-process instead)." +) + + +def _permissions_name(perms: int) -> str: + """The human-readable name of a pairing's permission byte.""" + return "admin" if perms & 0x01 else "user" + + +def _permissions_bytes(name: Any) -> bytes: + """The wire permission byte for an "admin"/"user" name.""" + if name == "admin": + return HAP_PERMISSIONS.ADMIN + if name == "user": + return HAP_PERMISSIONS.USER + raise ValueError(f"unknown permissions {name!r} (choose 'admin' or 'user')") + + +def _cmd_new(args: argparse.Namespace) -> int: + """Create a new persistent controller identity file.""" + path = os.path.expanduser(args.file) + if os.path.exists(path) and not args.force: + raise ValueError(f"{path} already exists (use --force to overwrite it)") + print(f'Creating new HAP controller in file "{path}"...') + identity = ClientIdentity.generate() + identity.save(path) + print("Done!") + print() + print( + "On the machine where your accessory is running create a file " + "(e.g. client.json) with the following contents:" + ) + print() + print( + json.dumps( + { + "uuid": identity.uuid, + "public_key": identity.public_key_bytes.hex(), + }, + indent=4, + ) + ) + print() + print( + "and run `python -m pyhap.client register -f client.json " + "-a `." + ) + print() + print( + "Alternatively, check the pyhap.client documentation on how to work " + "directly with the accessory state file instead." + ) + print() + print( + "Once the new HAP controller is registered, it will be able to " + "connect and control the accessory." + ) + return 0 + + +def _cmd_register(args: argparse.Namespace) -> int: + """Register a controller in an accessory state file.""" + register_path = os.path.expanduser(args.file) + with open(register_path, encoding="utf-8") as file_handle: + data = json.load(file_handle) + try: + client_uuid = data["uuid"] + public_key = bytes.fromhex(data["public_key"]) + except (KeyError, TypeError, ValueError) as error: + raise ValueError( + f"{register_path} is not a controller file (expected 'uuid' and " + f"'public_key'): {error}" + ) from error + permissions = _permissions_bytes( + args.permissions or data.get("permissions") or "admin" + ) + add_client_pairing( + args.accessory_state, client_uuid, public_key, permissions=permissions + ) + print( + f"Registered HAP controller {client_uuid} " + f'({_permissions_name(ord(permissions))}) in "{args.accessory_state}".' + ) + print(_RUNNING_ACCESSORY_WARNING) + return 0 + + +def _cmd_list(args: argparse.Namespace) -> int: + """List paired clients of an accessory state file as ``: ``.""" + state = load_accessory_state(args.accessory_state) + if not state.paired_clients: + print("No paired clients.") + return 0 + for client_uuid in sorted(state.paired_clients): + perms = state.client_properties.get(client_uuid, {}).get(CLIENT_PROP_PERMS, 0) + print(f"{client_uuid}: {_permissions_name(perms)}") + return 0 + + +def _cmd_deregister(args: argparse.Namespace) -> int: + """Remove a paired client from an accessory state file, guarded by --yes.""" + uuid_obj = UUID(args.uuid) + state = load_accessory_state(args.accessory_state) + if uuid_obj not in state.paired_clients: + raise ValueError(f"{uuid_obj} is not a paired client in {args.accessory_state}") + is_admin = state.is_admin(uuid_obj) + other_admins = any( + state.is_admin(other) for other in state.paired_clients if other != uuid_obj + ) + if (is_admin or len(state.paired_clients) == 1) and not args.yes: + reason = ( + "removing the last admin removes ALL pairings" + if is_admin and not other_admins + else "removing an admin pairing" + ) + raise ValueError(f"refusing to deregister {uuid_obj} without --yes ({reason})") + remove_client_pairing(args.accessory_state, uuid_obj) + print(f'Deregistered HAP controller {uuid_obj} from "{args.accessory_state}".') + print(_RUNNING_ACCESSORY_WARNING) + return 0 + + +def main(argv: list[str] | None = None) -> int: + """Run the CLI; returns the process exit code.""" + parser = argparse.ArgumentParser( + prog="python -m pyhap.client", + description=( + "Create HAP controller identities and manage accessory pairings " + "offline (no driver needed)." + ), + ) + subparsers = parser.add_subparsers(dest="command", required=True) + + new_parser = subparsers.add_parser( + "new", help="create a new persistent HAP controller identity file" + ) + new_parser.add_argument( + "-f", + "--file", + required=True, + help="controller file to create; stays on this machine (holds the private key)", + ) + new_parser.add_argument( + "--force", action="store_true", help="overwrite the file if it exists" + ) + new_parser.set_defaults(func=_cmd_new) + + register_parser = subparsers.add_parser( + "register", help="register a controller in an accessory state file" + ) + register_parser.add_argument( + "-f", + "--file", + required=True, + help="the JSON file printed by 'new', or a full client.state", + ) + register_parser.add_argument( + "-a", + "--accessory-state", + required=True, + help="the accessory's accessory.state file", + ) + register_parser.add_argument( + "-p", + "--permissions", + choices=["admin", "user"], + default=None, + help="pairing permissions (default: admin)", + ) + register_parser.set_defaults(func=_cmd_register) + + list_parser = subparsers.add_parser( + "list", help="list the paired clients of an accessory state file" + ) + list_parser.add_argument("-a", "--accessory-state", required=True) + list_parser.set_defaults(func=_cmd_list) + + deregister_parser = subparsers.add_parser( + "deregister", help="remove a paired client from an accessory state file" + ) + deregister_parser.add_argument("-a", "--accessory-state", required=True) + deregister_parser.add_argument("uuid", help="the client UUID to remove") + deregister_parser.add_argument( + "--yes", + action="store_true", + help="confirm removing an admin or the last remaining pairing", + ) + deregister_parser.set_defaults(func=_cmd_deregister) + + args = parser.parse_args(argv) + handler: Callable[[argparse.Namespace], int] = args.func + try: + return handler(args) + except (OSError, ValueError) as error: + print(f"error: {error}", file=sys.stderr) + return 1 diff --git a/pyhap/client/controller.py b/pyhap/client/controller.py index 520960fe..e2b92469 100644 --- a/pyhap/client/controller.py +++ b/pyhap/client/controller.py @@ -194,6 +194,12 @@ async def _pair_verify(self) -> None: answer = tlv.decode(response.body) if answer.get(HAP_TLV_TAGS.SEQUENCE_NUM) != HAP_TLV_STATES.M2: raise RuntimeError(f"Unexpected pair-verify response: {answer!r}") + if HAP_TLV_TAGS.ERROR_CODE in answer: + # A completely unpaired accessory rejects already at M2. + raise RuntimeError( + f"{self.name}: pair-verify rejected by the accessory: " + f"{answer[HAP_TLV_TAGS.ERROR_CODE]!r}" + ) server_ephemeral_public = answer[HAP_TLV_TAGS.PUBLIC_KEY] shared_key = ephemeral_private.exchange( diff --git a/pyhap/client/state.py b/pyhap/client/state.py index 131bd72c..ad318490 100644 --- a/pyhap/client/state.py +++ b/pyhap/client/state.py @@ -2,10 +2,11 @@ from __future__ import annotations -import json import os import tempfile +from uuid import UUID +from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 from ..const import HAP_PERMISSIONS @@ -14,63 +15,33 @@ from .identity import ClientIdentity -def load_accessory_ltpk(path: str | os.PathLike[str]) -> bytes: - """Return the accessory's raw long-term public key (LTPK) from its state file. +def load_accessory_state(path: str | os.PathLike[str]) -> State: + """Load an accessory state file into a :class:`pyhap.state.State`, without a driver. - The state file is the ``AccessoryDriver``'s ``accessory.state``. + The state file is the ``AccessoryDriver``'s ``accessory.state``. Note it + contains the accessory's *private* key — handle it accordingly. - Use this to move just the accessory's public key to another machine, e.g. - where a client runs: the state file also contains the accessory's - *private* key, so prefer exporting the public key alone (via this - function or the ``"public_key"`` hex field) over copying the whole file. - - :raise ValueError: If the file is not an accessory state file or the key - is malformed. :raise OSError: If the file does not exist or cannot be read. + :raise ValueError: If the file is malformed. """ target = os.path.expanduser(os.fspath(path)) + # Placeholder address; load_into overwrites all persisted fields. + state = State(address="127.0.0.1") try: with open(target, encoding="utf-8") as file_handle: - data = json.load(file_handle) - ltpk = bytes.fromhex(data["public_key"]) - ed25519.Ed25519PublicKey.from_public_bytes(ltpk) + AccessoryEncoder().load_into(file_handle, state) except (KeyError, TypeError, ValueError) as error: - raise ValueError( - f"Not an accessory state file (no valid 'public_key'): {target}" - ) from error - return ltpk + raise ValueError(f"Not an accessory state file: {target}") from error + return state -def add_client_pairing( - path: str | os.PathLike[str], - identity: ClientIdentity, - permissions: bytes = HAP_PERMISSIONS.ADMIN, -) -> None: - """Register ``identity`` as a paired client in an accessory state file, offline. - - Loads the ``AccessoryDriver`` state file at ``path`` with - :meth:`pyhap.encoder.AccessoryEncoder.load_into`, adds the client via - :meth:`pyhap.state.State.add_paired_client`, and writes the file back - atomically (a 0600 tempfile swapped in with ``os.replace``, like the - driver does). No driver needs to run. +def save_accessory_state(path: str | os.PathLike[str], state: State) -> None: + """Write ``state`` to its state file, atomically and 0600. - Do this with the accessory **stopped**: a running driver keeps its state - in memory and would overwrite this edit on its next persist. (While the - driver runs, ``AccessoryDriver.pair(...)`` does the same in-process.) - After the accessory restarts with the updated file, a client with this - identity can pair-verify against it. - - :param path: The accessory's ``accessory.state`` file. - :param identity: The client identity to pair (UUID + long-term public key). - :param permissions: The pairing's permissions, admin by default. - :raise OSError: If the file does not exist or cannot be read. - :raise ValueError: If the file is malformed or the UUID is invalid. + A tempfile created with 0600 permissions in the same directory is swapped + in with ``os.replace``, like the driver's own persist. """ target = os.path.expanduser(os.fspath(path)) - state = State(address="127.0.0.1") # placeholders; load_into overwrites them - with open(target, encoding="utf-8") as file_handle: - AccessoryEncoder().load_into(file_handle, state) - state.add_paired_client(identity.uuid_bytes, identity.public_key_bytes, permissions) directory = os.path.dirname(target) or "." tmp_filename = None try: @@ -83,3 +54,88 @@ def add_client_pairing( finally: if tmp_filename is not None and os.path.exists(tmp_filename): os.remove(tmp_filename) + + +def load_accessory_ltpk(path: str | os.PathLike[str]) -> bytes: + """Return the accessory's raw long-term public key (LTPK) from its state file. + + Use this to move just the accessory's public key to another machine, e.g. + where a client runs: the state file also contains the accessory's + *private* key, so prefer exporting the public key alone over copying the + whole file. + + :raise ValueError: If the file is not an accessory state file. + :raise OSError: If the file does not exist or cannot be read. + """ + state = load_accessory_state(path) + return state.public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + +def add_client_pairing( + path: str | os.PathLike[str], + client: ClientIdentity | str | UUID, + client_public_key: bytes | None = None, + *, + permissions: bytes = HAP_PERMISSIONS.ADMIN, +) -> None: + """Register a client as paired in an accessory state file, offline. + + Loads the state file with :meth:`pyhap.encoder.AccessoryEncoder.load_into`, + adds the client via :meth:`pyhap.state.State.add_paired_client`, and writes + the file back atomically (0600 tempfile swapped in with ``os.replace``). + No driver needs to run. + + Do this with the accessory **stopped**: a running driver keeps its state + in memory and would overwrite this edit on its next persist. (While the + driver runs, ``AccessoryDriver.pair(...)`` does the same in-process.) + After the accessory restarts with the updated file, the client can + pair-verify against it. + + :param path: The accessory's ``accessory.state`` file. + :param client: A :class:`ClientIdentity`, or a client UUID (str/UUID) which + then requires ``client_public_key``. + :param client_public_key: The client's raw long-term public key, when + ``client`` is a UUID. + :param permissions: The pairing's permissions, admin by default. + :raise OSError: If the file does not exist or cannot be read. + :raise ValueError: If the file is malformed, the UUID is invalid or the + public key is not a valid Ed25519 key. + """ + if isinstance(client, ClientIdentity): + client_uuid = UUID(client.uuid) + public_key = client.public_key_bytes + else: + client_uuid = UUID(str(client)) + if client_public_key is None: + raise ValueError( + "client_public_key is required when client is not a ClientIdentity" + ) + public_key = client_public_key + ed25519.Ed25519PublicKey.from_public_bytes(public_key) # validate the key + state = load_accessory_state(path) + state.add_paired_client(str(client_uuid).encode("utf-8"), public_key, permissions) + save_accessory_state(path, state) + + +def remove_client_pairing( + path: str | os.PathLike[str], client_uuid: str | UUID +) -> None: + """Remove a paired client from an accessory state file, offline. + + Same offline caveat as :func:`add_client_pairing`. Note that + :meth:`pyhap.state.State.remove_paired_client` removes *all* pairings when + the last admin is removed ("new home" semantics) — check the paired clients + first if that matters. + + :raise OSError: If the file does not exist or cannot be read. + :raise ValueError: If the UUID is invalid or not paired in the file. + """ + uuid_obj = UUID(str(client_uuid)) + state = load_accessory_state(path) + if uuid_obj not in state.paired_clients: + raise ValueError(f"{uuid_obj} is not a paired client in {path}") + state.remove_paired_client(uuid_obj) + save_accessory_state(path, state) diff --git a/tests/integration/test_client_cli.py b/tests/integration/test_client_cli.py new file mode 100644 index 00000000..97b1049d --- /dev/null +++ b/tests/integration/test_client_cli.py @@ -0,0 +1,68 @@ +"""Integration tests for the pyhap.client CLI (``python -m pyhap.client``). + +The full two-machine flow: ``new`` on the client side, ``register`` offline +into the accessory's state file, accessory restart, client connects; then +``deregister`` and the client is rejected at pair-verify. +""" + +from __future__ import annotations + +import json +import pathlib +from typing import Any + +import pytest + +from pyhap.client import ClientIdentity, HAPClient, cli + +from .helpers import build_switch + +# Real socket + crypto round trips plus several server starts; the CI default +# of --timeout=2 is too tight on shared runners. +pytestmark = pytest.mark.timeout(10) + + +async def test_cli_new_register_connect_deregister( + make_hap_server: Any, tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] +) -> None: + """The CLI drives the whole offline pairing flow end to end.""" + state_file = tmp_path / "accessory.state" + key_file = tmp_path / "client.state" + + # The accessory runs once, creating accessory.state, then stops. + server = await make_hap_server(build_switch, client_count=0, state_file=state_file) + await server.stop() + + # Client machine: create the persistent controller identity. + assert cli.main(["new", "-f", str(key_file)]) == 0 + assert "Creating new HAP controller" in capsys.readouterr().out + identity = ClientIdentity.load(key_file) + + # Accessory machine, offline: register the printed JSON in accessory.state. + register_file = tmp_path / "client.json" + register_file.write_text( + json.dumps( + {"uuid": identity.uuid, "public_key": identity.public_key_bytes.hex()} + ), + encoding="utf-8", + ) + assert cli.main(["register", "-f", str(register_file), "-a", str(state_file)]) == 0 + assert cli.main(["list", "-a", str(state_file)]) == 0 + assert f"{identity.uuid}: admin" in capsys.readouterr().out + + # Accessory restarts; the client pair-verifies and controls it. + restarted = await make_hap_server( + build_switch, client_count=0, state_file=state_file + ) + client = HAPClient.new_persistent(filepath=key_file, accessory_state=state_file) + await restarted.connect_client(client) + frame = await client.get_accessories() + assert frame.status == 200 + await restarted.stop() + + # Deregister offline; after another restart the client is rejected. + assert cli.main(["deregister", "-a", str(state_file), identity.uuid, "--yes"]) == 0 + final = await make_hap_server(build_switch, client_count=0, state_file=state_file) + rejected = HAPClient.new_persistent(filepath=key_file, accessory_state=state_file) + with pytest.raises(RuntimeError, match="pair-verify rejected"): + await final.connect_client(rejected) diff --git a/tests/test_client.py b/tests/test_client.py index 3ed8e54a..109fc7df 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,5 +1,6 @@ """Unit tests for HAPClient construction helpers and state-file tooling.""" +import json import os import pathlib import stat @@ -13,6 +14,7 @@ ClientIdentity, HAPClient, add_client_pairing, + cli, load_accessory_ltpk, ) from pyhap.encoder import AccessoryEncoder @@ -151,6 +153,61 @@ def test_add_client_pairing_missing_file(tmp_path: pathlib.Path) -> None: add_client_pairing(tmp_path / "nope.state", ClientIdentity.generate(9)) +def test_cli_new_register_list_deregister( + tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] +) -> None: + """The CLI manages controller identities and pairings in a state file.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + key_file = tmp_path / "client.state" + + # new: creates the identity file and prints the public register JSON. + assert cli.main(["new", "-f", str(key_file)]) == 0 + out = capsys.readouterr().out + assert "Creating new HAP controller" in out + assert str(key_file) in out + assert "register -f" in out + identity = ClientIdentity.load(key_file) + assert identity.uuid in out + assert identity.public_key_bytes.hex() in out + # Refuses to overwrite without --force, then succeeds with it. + assert cli.main(["new", "-f", str(key_file)]) == 1 + assert cli.main(["new", "-f", str(key_file), "--force"]) == 0 + capsys.readouterr() + identity = ClientIdentity.load(key_file) # regenerated by --force + + # register: adds the pairing from the printed JSON file. + register_file = tmp_path / "client.json" + register_file.write_text( + json.dumps( + {"uuid": identity.uuid, "public_key": identity.public_key_bytes.hex()} + ), + encoding="utf-8", + ) + assert cli.main(["register", "-f", str(register_file), "-a", str(state_file)]) == 0 + assert "Registered HAP controller" in capsys.readouterr().out + + # list: ": " lines. + assert cli.main(["list", "-a", str(state_file)]) == 0 + assert f"{identity.uuid}: admin" in capsys.readouterr().out + + # deregister: refused without --yes for an admin, works with it. + assert cli.main(["deregister", "-a", str(state_file), identity.uuid]) == 1 + assert cli.main(["list", "-a", str(state_file)]) == 0 + assert identity.uuid in capsys.readouterr().out + assert cli.main(["deregister", "-a", str(state_file), identity.uuid, "--yes"]) == 0 + assert cli.main(["list", "-a", str(state_file)]) == 0 + assert "No paired clients." in capsys.readouterr().out + + # Error paths exit 1: unknown uuid, malformed register file, missing file. + unknown = str(uuid.uuid4()) + assert cli.main(["deregister", "-a", str(state_file), unknown, "--yes"]) == 1 + bad = tmp_path / "bad.json" + bad.write_text("{}", encoding="utf-8") + assert cli.main(["register", "-f", str(bad), "-a", str(state_file)]) == 1 + assert cli.main(["list", "-a", str(tmp_path / "missing.state")]) == 1 + + def test_new_persistent_rejects_conflicting_ltpk(tmp_path: pathlib.Path) -> None: """A pinned LTPK is authoritative; a different one raises, file untouched.""" path = tmp_path / "controller.key" From db095ab1800b71080af8426bcac5bef225782776 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 17:33:10 +0100 Subject: [PATCH 13/15] Add examples/ showing a HAP client driving a Lightbulb accessory examples/lightbulb_accessory.py runs a small Lightbulb accessory (no mDNS, listening on loopback and the LAN address) that pairs the controller identity from examples/client.state on startup; examples/control_lightbulb.py uses HAPClient.new_persistent to pair-verify, subscribe, read and toggle the On characteristic over the real HAP protocol. examples/README.md documents the same-machine and two-machine (python -m pyhap.client register) workflows, and docs/source/intro/examples.rst points to the new directory. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .gitignore | 1 + docs/source/intro/examples.rst | 13 +++++- examples/README.md | 34 ++++++++++++++++ examples/control_lightbulb.py | 70 +++++++++++++++++++++++++++++++++ examples/lightbulb_accessory.py | 69 ++++++++++++++++++++++++++++++++ 5 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 examples/README.md create mode 100644 examples/control_lightbulb.py create mode 100644 examples/lightbulb_accessory.py diff --git a/.gitignore b/.gitignore index e663648d..d84683c3 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,4 @@ pip-selfcheck.json # HAP-python-generated files accessory.pickle /*.state +examples/*.state diff --git a/docs/source/intro/examples.rst b/docs/source/intro/examples.rst index de615ab9..efed034b 100644 --- a/docs/source/intro/examples.rst +++ b/docs/source/intro/examples.rst @@ -51,4 +51,15 @@ of the tutorial's sensor. For cameras, start from ``accessories/camera_main.py``: the options dict describes what the camera supports, and HAP-python negotiates the sessions -(see :doc:`/media/camera`). \ No newline at end of file +(see :doc:`/media/camera`). + +Driving an accessory from Python +-------------------------------- + +The ``examples`` directory of the repository shows the other direction: a +:doc:`HAP client ` (``pyhap.client.HAPClient``) connecting to an +accessory over the real HAP protocol. ``examples/lightbulb_accessory.py`` +runs a small Lightbulb accessory and ``examples/control_lightbulb.py`` +toggles its ``On`` characteristic from a controller with a persistent +identity — see ``examples/README.md`` for the same-machine and two-machine +workflows. \ No newline at end of file diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..c3408f83 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,34 @@ +# Examples + +## Driving an accessory with a HAP client (`pyhap.client`) + +`lightbulb_accessory.py` runs a small Lightbulb accessory; +`control_lightbulb.py` toggles its `On` characteristic over the real HAP +protocol (pair-verify, encrypted transport) using a persistent controller +identity. See the [pyhap.client API docs](../docs/source/api/client.rst) for +the pairing and trust details. + +Same machine: + +```sh +python -m pyhap.client new -f examples/client.state # once; prints client.json +python examples/lightbulb_accessory.py # pairs client.state automatically +python examples/control_lightbulb.py # toggles the light +``` + +Client on a different machine than the accessory: on the client machine run +`python -m pyhap.client new -f client.state` and copy only the printed JSON +(`client.json`, uuid + public key) to the accessory machine. With the +accessory stopped, run there: + +```sh +python -m pyhap.client register -f client.json -a examples/accessory.state +``` + +then start the accessory again and run `control_lightbulb.py` on the client +machine (adjust `HOST`/`PORT` in the script). Use +`python -m pyhap.client list -a accessory.state` and +`python -m pyhap.client deregister -a accessory.state --yes` to manage +pairings on the accessory machine. + +The `*.state` files created here are gitignored. diff --git a/examples/control_lightbulb.py b/examples/control_lightbulb.py new file mode 100644 index 00000000..f2a05876 --- /dev/null +++ b/examples/control_lightbulb.py @@ -0,0 +1,70 @@ +"""Toggle the example Lightbulb accessory with a pyhap HAP client. + +Start ``lightbulb_accessory.py`` first, then run this script. The controller +identity in ``client.state`` (created once with +``python -m pyhap.client new -f client.state``) is paired by the accessory on +startup; the accessory's LTPK is pinned from ``accessory.state`` on first use. +See README.md in this directory for the two-machine variant. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +import sys +from typing import Any + +from pyhap.client import HAPClient + +HERE = Path(__file__).resolve().parent +HOST, PORT = "127.0.0.1", 51827 + +LIGHTBULB_SERVICE_TYPE = "43" # 00000043-0000-1000-8000-0026BB765291, short HAP form +ON_CHARACTERISTIC_TYPE = "25" # 00000025-0000-1000-8000-0026BB765291, short HAP form + + +def find_on_characteristic(accessories: Any) -> tuple[int, int] | None: + """The (aid, iid) of the On characteristic of the first Lightbulb service.""" + for acc in accessories: + for service in acc["services"]: + if service["type"] != LIGHTBULB_SERVICE_TYPE: + continue + for char in service["characteristics"]: + if char["type"] == ON_CHARACTERISTIC_TYPE: + return acc["aid"], char["iid"] + return None + + +async def main() -> int: + """Connect, find the lightbulb's On characteristic, toggle it, read back.""" + client = HAPClient.new_persistent( + filepath=HERE / "client.state", + accessory_state=HERE / "accessory.state", # pins the accessory LTPK once + ) + await client.connect(HOST, PORT) + try: + frame = await client.get_accessories() + on = find_on_characteristic(json.loads(frame.body)["accessories"]) + if on is None: + print("no Lightbulb with an On characteristic found", file=sys.stderr) + return 1 + aid, iid = on + # EVENT pushes arrive here when the value changes from another + # controller or from the accessory itself (not for our own writes). + await client.subscribe(aid, iid) + + frame = await client.read_characteristic(aid, iid) + current = json.loads(frame.body)["characteristics"][0]["value"] + await client.write_characteristic(aid, iid, not current) + + frame = await client.read_characteristic(aid, iid) + value = json.loads(frame.body)["characteristics"][0]["value"] + print(f"Lightbulb On (aid={aid}, iid={iid}) is now {'on' if value else 'off'}") + finally: + await client.close() + return 0 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/examples/lightbulb_accessory.py b/examples/lightbulb_accessory.py new file mode 100644 index 00000000..a1b1afaf --- /dev/null +++ b/examples/lightbulb_accessory.py @@ -0,0 +1,69 @@ +"""Example accessory: a Lightbulb that can be toggled with a pyhap HAP client. + +Run this, then ``control_lightbulb.py``. If ``client.state`` exists next to +this file (create it once with ``python -m pyhap.client new -f client.state``), +its controller identity is paired automatically on every start (pairing is +idempotent). Set ``advertise=True`` to also show the accessory in the Home app. +""" + +from __future__ import annotations + +from pathlib import Path +import signal + +from pyhap.accessory import Accessory +from pyhap.accessory_driver import AccessoryDriver +from pyhap.client import ClientIdentity +from pyhap.const import CATEGORY_LIGHTBULB, HAP_PERMISSIONS +from pyhap.util import get_local_address + +HERE = Path(__file__).resolve().parent +CLIENT_STATE = HERE / "client.state" + + +class LightBulb(Accessory): + """A lightbulb whose On characteristic prints every change.""" + + category = CATEGORY_LIGHTBULB + + def __init__( + self, driver: AccessoryDriver, display_name: str, aid: int | None = None + ) -> None: + """Create the lightbulb with the preloaded Lightbulb service.""" + super().__init__(driver, display_name, aid=aid) + service = self.add_preload_service("Lightbulb") + self.char_on = service.configure_char("On", setter_callback=self.bulb_toggled) + + def bulb_toggled(self, value: bool) -> None: + """Called on every write to On from a controller.""" + print(f"The light is now {'on' if value else 'off'}", flush=True) + + async def run(self) -> None: + """Pair the client identity from client.state, if present (idempotent).""" + if CLIENT_STATE.exists(): + identity = ClientIdentity.load(CLIENT_STATE) + self.driver.pair( + identity.uuid_bytes, + identity.public_key_bytes, + HAP_PERMISSIONS.ADMIN, + ) + print(f"Paired HAP controller {identity.uuid}", flush=True) + + +def main() -> None: + """Run the accessory until Ctrl+C / SIGTERM.""" + driver = AccessoryDriver( + port=51827, + advertise=False, # no mDNS for this demo; True to appear in the Home app + # Listen on loopback (client on the same machine) and the LAN address + # (client on another machine, see README.md). + listen_address=["127.0.0.1", get_local_address()], + persist_file=str(HERE / "accessory.state"), + ) + driver.add_accessory(LightBulb(driver, "Example LightBulb")) + signal.signal(signal.SIGTERM, driver.signal_handler) + driver.start() + + +if __name__ == "__main__": + main() From 7703c74f6b9cef2b2833718a3656b16a856ca97c Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 17:35:13 +0100 Subject: [PATCH 14/15] Move the HAP client example into examples/client/ The example now lives in its own subdirectory; the state files are created next to the scripts there, .gitignore and the intro/examples docs pointer are updated accordingly. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .gitignore | 2 +- docs/source/intro/examples.rst | 13 +++++++------ examples/{ => client}/README.md | 18 ++++++++++-------- examples/{ => client}/control_lightbulb.py | 0 examples/{ => client}/lightbulb_accessory.py | 0 5 files changed, 18 insertions(+), 15 deletions(-) rename examples/{ => client}/README.md (62%) rename examples/{ => client}/control_lightbulb.py (100%) rename examples/{ => client}/lightbulb_accessory.py (100%) diff --git a/.gitignore b/.gitignore index d84683c3..927f1967 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,4 @@ pip-selfcheck.json # HAP-python-generated files accessory.pickle /*.state -examples/*.state +examples/client/*.state diff --git a/docs/source/intro/examples.rst b/docs/source/intro/examples.rst index efed034b..28c11d2e 100644 --- a/docs/source/intro/examples.rst +++ b/docs/source/intro/examples.rst @@ -56,10 +56,11 @@ describes what the camera supports, and HAP-python negotiates the sessions Driving an accessory from Python -------------------------------- -The ``examples`` directory of the repository shows the other direction: a -:doc:`HAP client ` (``pyhap.client.HAPClient``) connecting to an -accessory over the real HAP protocol. ``examples/lightbulb_accessory.py`` -runs a small Lightbulb accessory and ``examples/control_lightbulb.py`` -toggles its ``On`` characteristic from a controller with a persistent -identity — see ``examples/README.md`` for the same-machine and two-machine +The ``examples/client`` directory of the repository shows the other +direction: a :doc:`HAP client ` (``pyhap.client.HAPClient``) +connecting to an accessory over the real HAP protocol. +``examples/client/lightbulb_accessory.py`` runs a small Lightbulb accessory +and ``examples/client/control_lightbulb.py`` toggles its ``On`` +characteristic from a controller with a persistent identity — see +``examples/client/README.md`` for the same-machine and two-machine workflows. \ No newline at end of file diff --git a/examples/README.md b/examples/client/README.md similarity index 62% rename from examples/README.md rename to examples/client/README.md index c3408f83..da2012ce 100644 --- a/examples/README.md +++ b/examples/client/README.md @@ -1,19 +1,21 @@ -# Examples +# Client examples ## Driving an accessory with a HAP client (`pyhap.client`) `lightbulb_accessory.py` runs a small Lightbulb accessory; `control_lightbulb.py` toggles its `On` characteristic over the real HAP protocol (pair-verify, encrypted transport) using a persistent controller -identity. See the [pyhap.client API docs](../docs/source/api/client.rst) for -the pairing and trust details. +identity. See the [pyhap.client API docs](../../docs/source/api/client.rst) +for the pairing and trust details. -Same machine: +Same machine (paths below are relative to this directory; the state files +always land next to the scripts): ```sh -python -m pyhap.client new -f examples/client.state # once; prints client.json -python examples/lightbulb_accessory.py # pairs client.state automatically -python examples/control_lightbulb.py # toggles the light +cd examples/client +python -m pyhap.client new -f client.state # once; prints client.json +python lightbulb_accessory.py # pairs client.state automatically +python control_lightbulb.py # toggles the light ``` Client on a different machine than the accessory: on the client machine run @@ -22,7 +24,7 @@ Client on a different machine than the accessory: on the client machine run accessory stopped, run there: ```sh -python -m pyhap.client register -f client.json -a examples/accessory.state +python -m pyhap.client register -f client.json -a accessory.state ``` then start the accessory again and run `control_lightbulb.py` on the client diff --git a/examples/control_lightbulb.py b/examples/client/control_lightbulb.py similarity index 100% rename from examples/control_lightbulb.py rename to examples/client/control_lightbulb.py diff --git a/examples/lightbulb_accessory.py b/examples/client/lightbulb_accessory.py similarity index 100% rename from examples/lightbulb_accessory.py rename to examples/client/lightbulb_accessory.py From 6bc391a6e11d589f8b0561ef319606f22b30ae52 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 23 Nov 2026 19:16:25 +0100 Subject: [PATCH 15/15] coverage and tests --- tests/test_client.py | 130 +++++++++++++ tests/test_client_controller.py | 331 ++++++++++++++++++++++++++++++++ tests/test_client_identity.py | 18 ++ tests/test_client_protocol.py | 86 +++++++++ 4 files changed, 565 insertions(+) create mode 100644 tests/test_client_controller.py create mode 100644 tests/test_client_protocol.py diff --git a/tests/test_client.py b/tests/test_client.py index 109fc7df..00b90e42 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -16,7 +16,10 @@ add_client_pairing, cli, load_accessory_ltpk, + remove_client_pairing, + save_accessory_state, ) +from pyhap.const import HAP_PERMISSIONS from pyhap.encoder import AccessoryEncoder from pyhap.state import State @@ -153,6 +156,75 @@ def test_add_client_pairing_missing_file(tmp_path: pathlib.Path) -> None: add_client_pairing(tmp_path / "nope.state", ClientIdentity.generate(9)) +def test_add_client_pairing_uuid_requires_public_key(tmp_path: pathlib.Path) -> None: + """A bare UUID without a public key is rejected before touching the file.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + with pytest.raises(ValueError, match="client_public_key is required"): + add_client_pairing(state_file, str(uuid.uuid4())) + + +def test_add_client_pairing_rejects_invalid_uuid(tmp_path: pathlib.Path) -> None: + """A client string that is not a UUID raises ValueError.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + with pytest.raises(ValueError): + add_client_pairing(state_file, "not-a-uuid", b"\x00" * 32) + + +def test_add_client_pairing_rejects_invalid_public_key( + tmp_path: pathlib.Path, +) -> None: + """Public key bytes that are not a valid Ed25519 key raise ValueError.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + with pytest.raises(ValueError): + add_client_pairing(state_file, str(uuid.uuid4()), b"not-a-key") + + +def test_remove_client_pairing(tmp_path: pathlib.Path) -> None: + """A registered client can be removed again; removing twice raises.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + identity = ClientIdentity.generate(9) + add_client_pairing(state_file, identity) + + remove_client_pairing(state_file, identity.uuid) + + state = State(address="127.0.0.1") + with open(state_file, encoding="utf-8") as file_handle: + AccessoryEncoder().load_into(file_handle, state) + assert not state.paired_clients + with pytest.raises(ValueError, match="not a paired client"): + remove_client_pairing(state_file, identity.uuid) + + +def test_remove_client_pairing_unknown_uuid(tmp_path: pathlib.Path) -> None: + """Removing a client that is not paired raises ValueError.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + with pytest.raises(ValueError, match="not a paired client"): + remove_client_pairing(state_file, uuid.uuid4()) + + +def test_save_accessory_state_cleans_up_tempfile_on_failure( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """If the atomic rename fails, the tempfile is removed and the file kept.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + original = state_file.read_bytes() + + def fail_replace(src: str, dst: str) -> None: + raise OSError("simulated rename failure") + + monkeypatch.setattr(os, "replace", fail_replace) + with pytest.raises(OSError, match="simulated rename failure"): + save_accessory_state(state_file, State(address="127.0.0.1")) + assert [path.name for path in tmp_path.iterdir()] == ["accessory.state"] + assert state_file.read_bytes() == original + + def test_cli_new_register_list_deregister( tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] ) -> None: @@ -215,3 +287,61 @@ def test_new_persistent_rejects_conflicting_ltpk(tmp_path: pathlib.Path) -> None with pytest.raises(ValueError, match="different accessory LTPK"): HAPClient.new_persistent(filepath=path, accessory_ltpk=_ltpk()) assert ClientIdentity.load(path).accessory_ltpk == first.accessory_ltpk + + +def test_permissions_bytes_names() -> None: + """The permission names map to their wire bytes; anything else raises.""" + assert cli._permissions_bytes("admin") == HAP_PERMISSIONS.ADMIN + assert cli._permissions_bytes("user") == HAP_PERMISSIONS.USER + with pytest.raises(ValueError, match="unknown permissions"): + cli._permissions_bytes("bogus") + + +def _write_register_file( + tmp_path: pathlib.Path, identity: ClientIdentity +) -> pathlib.Path: + """Write the JSON file ``new`` prints, for ``register -f``.""" + register_file = tmp_path / "client.json" + register_file.write_text( + json.dumps( + {"uuid": identity.uuid, "public_key": identity.public_key_bytes.hex()} + ), + encoding="utf-8", + ) + return register_file + + +def test_cli_register_with_user_permissions( + tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] +) -> None: + """``register -p user`` stores a non-admin pairing, shown by ``list``.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + identity = ClientIdentity.generate(4) + register_file = _write_register_file(tmp_path, identity) + + assert ( + cli.main( + ["register", "-f", str(register_file), "-a", str(state_file), "-p", "user"] + ) + == 0 + ) + assert "(user)" in capsys.readouterr().out + assert cli.main(["list", "-a", str(state_file)]) == 0 + assert f"{identity.uuid}: user" in capsys.readouterr().out + + +def test_cli_register_rejects_unknown_permissions_in_file( + tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] +) -> None: + """A ``permissions`` field in the register file that is not admin/user exits 1.""" + state_file = tmp_path / "accessory.state" + _write_state_file(state_file) + identity = ClientIdentity.generate(4) + register_file = _write_register_file(tmp_path, identity) + data = json.loads(register_file.read_text(encoding="utf-8")) + data["permissions"] = "bogus" + register_file.write_text(json.dumps(data), encoding="utf-8") + + assert cli.main(["register", "-f", str(register_file), "-a", str(state_file)]) == 1 + assert "unknown permissions" in capsys.readouterr().err diff --git a/tests/test_client_controller.py b/tests/test_client_controller.py new file mode 100644 index 00000000..ffd8ecf2 --- /dev/null +++ b/tests/test_client_controller.py @@ -0,0 +1,331 @@ +"""Unit tests for HAPClient internals the integration tests don't reach. + +Covers connection teardown, the frame dispatch and read loop (with fake +streams), the pair-verify failure paths (with a stubbed HTTP layer) and the +write error path. +""" + +import asyncio +from collections.abc import Callable +import json +import logging +import pathlib +import time +from typing import Any, cast + +from chacha20poly1305_reuseable import ChaCha20Poly1305Reusable as ChaCha20Poly1305 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import x25519 +import pytest + +from pyhap import tlv +from pyhap.client import ClientIdentity, Frame, HAPClient +from pyhap.client.controller import ( + _PVERIFY_1_INFO, + _PVERIFY_1_NONCE, + _PVERIFY_1_SALT, + _raw_public, +) +from pyhap.client.protocol import HAP_CONTENT_TYPE +from pyhap.encoder import AccessoryEncoder +from pyhap.hap_crypto import HAPCrypto, hap_hkdf +from pyhap.hap_handler import HAP_TLV_STATES, HAP_TLV_TAGS +from pyhap.state import State + + +class _FakeReader: + """A stand-in for ``asyncio.StreamReader`` feeding canned chunks, then EOF.""" + + def __init__(self, chunks: list[bytes]) -> None: + self._chunks = list(chunks) + + async def read(self, size: int) -> bytes: + if not self._chunks: + return b"" + return self._chunks.pop(0) + + +class _FailingReader: + """A reader whose reads always fail, like a socket error mid-stream.""" + + async def read(self, size: int) -> bytes: + raise RuntimeError("socket exploded") + + +class _BrokenWriter: + """A writer whose ``wait_closed`` fails with the given error.""" + + def __init__(self, error: Exception) -> None: + self._error = error + + def close(self) -> None: + pass + + async def wait_closed(self) -> None: + raise self._error + + +class _StubbedClient(HAPClient): + """A HAPClient whose HTTP layer is answered by the given responder.""" + + def __init__( + self, responder: Callable[[bytes, bytes, bytes, bytes], Frame] + ) -> None: + super().__init__(ClientIdentity.generate(0)) + self._responder = responder + + async def _request( + self, + method: bytes, + target: bytes, + body: bytes, + content_type: bytes = HAP_CONTENT_TYPE, + ) -> Frame: + return self._responder(method, target, body, content_type) + + +def _write_state_file(path: pathlib.Path) -> bytes: + """Write a real accessory.state via the encoder; return its raw LTPK.""" + state = State(address="127.0.0.1") + with open(path, "w", encoding="utf-8") as file_handle: + AccessoryEncoder().persist(file_handle, state) + return state.public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + +def _event_frame(*chars: dict[str, Any]) -> Frame: + """An EVENT/1.0 frame carrying the given characteristic entries.""" + body = json.dumps({"characteristics": list(chars)}).encode("utf-8") + return Frame( + kind="event", status=200, body=body, received_ns=time.perf_counter_ns() + ) + + +def test_init_resolves_ltpk_from_accessory_state(tmp_path: pathlib.Path) -> None: + """accessory_state= reads the accessory LTPK from the state file.""" + state_file = tmp_path / "accessory.state" + expected = _write_state_file(state_file) + client = HAPClient(ClientIdentity.generate(0), accessory_state=state_file) + assert client.accessory_ltpk == expected + + +async def test_close_without_connect_is_a_noop() -> None: + """close() before connect() has neither a reader task nor a writer.""" + client = HAPClient(ClientIdentity.generate(0)) + await client.close() + assert client._closed + + +@pytest.mark.parametrize( + "error", [ConnectionResetError("reset"), BrokenPipeError("pipe")] +) +async def test_close_ignores_writer_shutdown_errors(error: Exception) -> None: + """A writer failing wait_closed() does not make close() raise.""" + client = HAPClient(ClientIdentity.generate(0)) + client._writer = cast("asyncio.StreamWriter", _BrokenWriter(error)) + await client.close() + + +async def test_request_on_closed_connection_raises() -> None: + """Requests on a closed connection fail immediately.""" + client = HAPClient(ClientIdentity.generate(0)) + client._closed = True + with pytest.raises(ConnectionError, match="connection is closed"): + await client._request(b"GET", b"/accessories", b"") + + +def test_dispatch_response_without_pending_request_raises() -> None: + """A response frame with no waiter is a protocol error.""" + client = HAPClient(ClientIdentity.generate(0)) + frame = Frame(kind="response", status=200, body=b"{}", received_ns=0) + with pytest.raises(RuntimeError, match="no pending request"): + client._dispatch(frame) + + +async def test_dispatch_event_queues_and_next_event_returns_it() -> None: + """Event frames land in the queue; next_event() returns (aid, iid, value).""" + client = HAPClient(ClientIdentity.generate(0)) + client._dispatch(_event_frame({"aid": 1, "iid": 2, "value": True})) + client._dispatch(_event_frame({"aid": 3, "iid": 4})) # no "value" key + assert await client.next_event(timeout=1) == (1, 2, True) + assert await client.next_event(timeout=1) == (3, 4, None) + + +async def test_clear_events_drains_the_queue() -> None: + """clear_events() drops queued events so next_event() times out.""" + client = HAPClient(ClientIdentity.generate(0)) + client._dispatch(_event_frame({"aid": 1, "iid": 2, "value": 1})) + client.clear_events() + assert client._events.empty() + with pytest.raises(TimeoutError): + await client.next_event(timeout=0.05) + + +async def test_wait_event_times_out_when_deadline_already_passed() -> None: + """A zero timeout raises before waiting on the queue.""" + client = HAPClient(ClientIdentity.generate(0)) + with pytest.raises(TimeoutError, match="no event for 1.2"): + await client.wait_event(1, 2, True, timeout=0) + + +async def test_wait_event_skips_events_that_do_not_match() -> None: + """Events for other characteristics or other values are discarded.""" + client = HAPClient(ClientIdentity.generate(0)) + client._dispatch(_event_frame({"aid": 1, "iid": 2, "value": False})) + client._dispatch(_event_frame({"aid": 9, "iid": 9, "value": True})) + client._dispatch(_event_frame({"aid": 1, "iid": 2, "value": True})) + received_ns = await client.wait_event(1, 2, True, timeout=1) + assert received_ns > 0 + + +async def test_read_loop_eof_fails_pending_request() -> None: + """Server-side EOF ends the loop and fails the pending request.""" + client = HAPClient(ClientIdentity.generate(0)) + client._reader = cast("asyncio.StreamReader", _FakeReader([])) + pending = asyncio.get_running_loop().create_future() + client._pending = pending + await client._read_loop() + assert client._closed + assert pending.done() + assert isinstance(pending.exception(), ConnectionError) + + +async def test_read_loop_reader_error_is_logged_and_fails_pending( + caplog: pytest.LogCaptureFixture, +) -> None: + """A socket error terminates the loop, logs it and fails the waiter.""" + client = HAPClient(ClientIdentity.generate(0)) + client._reader = cast("asyncio.StreamReader", _FailingReader()) + pending = asyncio.get_running_loop().create_future() + client._pending = pending + with caplog.at_level(logging.ERROR, logger="pyhap.client.controller"): + await client._read_loop() + assert client._closed + assert isinstance(pending.exception(), ConnectionError) + assert "reader loop terminated" in caplog.text + + +async def test_read_loop_buffers_partial_encrypted_block() -> None: + """A split encrypted record is buffered until the rest of it arrives.""" + shared_key = b"\x01" * 32 + payload = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}" + encrypted = b"".join(HAPCrypto(shared_key).encrypt(payload)) + client = HAPClient(ClientIdentity.generate(0)) + client._reader = cast( + "asyncio.StreamReader", _FakeReader([encrypted[:10], encrypted[10:]]) + ) + client._crypto = HAPCrypto(shared_key, client_side=True) + pending = asyncio.get_running_loop().create_future() + client._pending = pending + await client._read_loop() + frame = pending.result() + assert frame.kind == "response" + assert frame.body == b"{}" + + +def test_raw_public_accepts_private_and_public_keys() -> None: + """_raw_public handles both key types.""" + private = x25519.X25519PrivateKey.generate() + assert _raw_public(private) == _raw_public(private.public_key()) + + +async def test_pair_verify_rejects_wrong_m2_sequence() -> None: + """An M2 answer with the wrong sequence number aborts the handshake.""" + + def responder( + method: bytes, target: bytes, body: bytes, content_type: bytes + ) -> Frame: + answer = tlv.encode(HAP_TLV_TAGS.SEQUENCE_NUM, HAP_TLV_STATES.M1) + return Frame(kind="response", status=200, body=answer, received_ns=0) + + client = _StubbedClient(responder) + client._reader = cast("asyncio.StreamReader", _FakeReader([])) + with pytest.raises(RuntimeError, match="Unexpected pair-verify response"): + await client._pair_verify() + + +def _responder_with_valid_m2( + second_answer: bytes, +) -> Callable[[bytes, bytes, bytes, bytes], Frame]: + """Answer M1 with a cryptographically valid M2, then ``second_answer``. + + The client runs without a pinned LTPK, so the accessory signature is not + verified and any proof bytes do. + """ + server_ephemeral = x25519.X25519PrivateKey.generate() + calls = 0 + + def responder( + method: bytes, target: bytes, body: bytes, content_type: bytes + ) -> Frame: + nonlocal calls + calls += 1 + if calls == 1: + client_public = tlv.decode(body)[HAP_TLV_TAGS.PUBLIC_KEY] + shared_key = server_ephemeral.exchange( + x25519.X25519PublicKey.from_public_bytes(client_public) + ) + output_key = hap_hkdf(shared_key, _PVERIFY_1_SALT, _PVERIFY_1_INFO) + proof = tlv.encode( + HAP_TLV_TAGS.USERNAME, + b"Accessory", + HAP_TLV_TAGS.PROOF, + b"\x00" * 64, + ) + cipher = ChaCha20Poly1305(output_key) + encrypted = bytes(cipher.encrypt(_PVERIFY_1_NONCE, proof, b"")) + answer = tlv.encode( + HAP_TLV_TAGS.SEQUENCE_NUM, + HAP_TLV_STATES.M2, + HAP_TLV_TAGS.PUBLIC_KEY, + _raw_public(server_ephemeral), + HAP_TLV_TAGS.ENCRYPTED_DATA, + encrypted, + ) + else: + answer = second_answer + return Frame(kind="response", status=200, body=answer, received_ns=0) + + return responder + + +@pytest.mark.parametrize( + ("second_answer", "match"), + [ + ( + tlv.encode(HAP_TLV_TAGS.SEQUENCE_NUM, HAP_TLV_STATES.M2), + "Unexpected pair-verify response", + ), + ( + tlv.encode( + HAP_TLV_TAGS.SEQUENCE_NUM, + HAP_TLV_STATES.M4, + HAP_TLV_TAGS.ERROR_CODE, + b"\x02", + ), + "pair-verify rejected", + ), + ], +) +async def test_pair_verify_rejects_bad_m4(second_answer: bytes, match: str) -> None: + """After a valid M2, a wrong-sequence or error M4 aborts the handshake.""" + client = _StubbedClient(_responder_with_valid_m2(second_answer)) + client._reader = cast("asyncio.StreamReader", _FakeReader([])) + with pytest.raises(RuntimeError, match=match): + await client._pair_verify() + + +async def test_write_characteristics_raises_on_error_status() -> None: + """A write answered with an error status raises instead of returning.""" + + def responder( + method: bytes, target: bytes, body: bytes, content_type: bytes + ) -> Frame: + return Frame(kind="response", status=500, body=b"boom", received_ns=0) + + client = _StubbedClient(responder) + client._reader = cast("asyncio.StreamReader", _FakeReader([])) + with pytest.raises(RuntimeError, match="write failed: 500"): + await client.write_characteristics([{"aid": 1, "iid": 2, "value": True}]) diff --git a/tests/test_client_identity.py b/tests/test_client_identity.py index 7f48f257..f00adb70 100644 --- a/tests/test_client_identity.py +++ b/tests/test_client_identity.py @@ -62,6 +62,23 @@ def test_save_overwrites_existing_file(tmp_path: pathlib.Path) -> None: assert ClientIdentity.load(path).to_dict() == identity.to_dict() +def test_save_cleans_up_tempfile_on_failure( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """If the atomic rename fails, the tempfile is removed and the file kept.""" + path = tmp_path / "controller.key" + path.write_text("old contents", encoding="utf-8") + + def fail_replace(src: str, dst: str) -> None: + raise OSError("simulated rename failure") + + monkeypatch.setattr(os, "replace", fail_replace) + with pytest.raises(OSError, match="simulated rename failure"): + ClientIdentity.generate(0).save(path) + assert [entry.name for entry in tmp_path.iterdir()] == ["controller.key"] + assert path.read_text(encoding="utf-8") == "old contents" + + def test_load_rejects_malformed_files(tmp_path: pathlib.Path) -> None: """Corrupt or incomplete identity files raise ValueError.""" path = tmp_path / "bad.key" @@ -73,6 +90,7 @@ def test_load_rejects_malformed_files(tmp_path: pathlib.Path) -> None: mutations = [ lambda data: data.pop("private_key"), lambda data: data.update(uuid="not-a-uuid"), + lambda data: data.update(uuid=123), lambda data: data.update(private_key="zz"), lambda data: data.update(private_key="00"), lambda data: data.update(public_key="00" * 32), diff --git a/tests/test_client_protocol.py b/tests/test_client_protocol.py new file mode 100644 index 00000000..287ed3a9 --- /dev/null +++ b/tests/test_client_protocol.py @@ -0,0 +1,86 @@ +"""Unit tests for the HAP client frame parser (``pyhap.client.protocol``).""" + +import pytest + +from pyhap.client import parse_frame + + +def _response_frame(status: int, body: bytes) -> bytes: + """A serialized HTTP/1.1 response frame.""" + return ( + f"HTTP/1.1 {status} X\r\nContent-Length: {len(body)}\r\n\r\n".encode("ascii") + + body + ) + + +def test_incomplete_header_returns_none_and_keeps_buffer() -> None: + """A buffer without the header terminator holds no frame yet.""" + buffer = bytearray(b"HTTP/1.1 200 OK\r\nContent-Length: 2") + assert parse_frame(buffer) is None + assert buffer == b"HTTP/1.1 200 OK\r\nContent-Length: 2" + + +def test_incomplete_body_returns_none_then_completes() -> None: + """Headers may arrive before the full body; the buffer waits for it.""" + raw = _response_frame(200, b"{}") + buffer = bytearray(raw[:-1]) + assert parse_frame(buffer) is None + assert buffer == raw[:-1] + + buffer += raw[-1:] + frame = parse_frame(buffer) + assert frame is not None + assert frame.kind == "response" + assert frame.status == 200 + assert frame.body == b"{}" + assert frame.received_ns > 0 + assert not buffer # the frame bytes were consumed + + +def test_unexpected_start_line_raises() -> None: + """Data that is neither an HTTP response nor an EVENT frame is rejected.""" + buffer = bytearray(b"GARBAGE/1.0 200 OK\r\nContent-Length: 0\r\n\r\n") + with pytest.raises(RuntimeError, match="unexpected data"): + parse_frame(buffer) + + +def test_event_frame_is_parsed() -> None: + """An EVENT/1.0 push frame is recognized as an event frame.""" + body = b'{"characteristics": []}' + raw = ( + b"EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\n" + + f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") + + body + ) + frame = parse_frame(bytearray(raw)) + assert frame is not None + assert frame.kind == "event" + assert frame.status == 200 + assert frame.body == body + + +def test_multiple_frames_in_one_buffer() -> None: + """Several frames delivered in one read are split off one by one.""" + first = _response_frame(200, b"a") + second = _response_frame(204, b"") + buffer = bytearray(first + second) + frame_one = parse_frame(buffer) + frame_two = parse_frame(buffer) + assert frame_one is not None and frame_one.body == b"a" + assert frame_two is not None and frame_two.status == 204 and frame_two.body == b"" + assert not buffer + assert parse_frame(buffer) is None + + +def test_header_names_are_case_insensitive_and_optional() -> None: + """Content-Length matching is case/space insensitive; absent means 0.""" + raw = b"HTTP/1.1 200 OK\r\ncontent-LENGTH : 3\r\n\r\nabc" + frame = parse_frame(bytearray(raw)) + assert frame is not None + assert frame.body == b"abc" + + no_length = b"HTTP/1.1 204 No Content\r\nContent-Type: x\r\n\r\n" + frame = parse_frame(bytearray(no_length)) + assert frame is not None + assert frame.status == 204 + assert frame.body == b""