From 23de2e9644f708fa2d893020bcd28292ad1df9c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Sep 2026 02:42:33 +0000 Subject: [PATCH] Add origin.peek() so a listener can route a datagram to the right secret A listener that follows one board can verify every datagram with the one secret it holds. A listener that follows twenty cannot: it has to know which board is claiming to have sent a datagram before it can pick the secret to check it against. Identifying the sender by its source address is the obvious shortcut and the wrong one -- NAT between a board and the listener rewrites it, and the signature, not the address, is what establishes who sent the datagram. peek() decodes the body without verifying it, for routing only. Its docstring is blunt about what that means: nothing it returns is trustworthy until unpack() has been called with the secret it led you to. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01VmtVSp58rDkDBRPzL9hJkt --- docs/machine.md | 14 +++++++++++++ tests/test_origin.py | 29 +++++++++++++++++++++++++++ warpedpinball/__init__.py | 2 +- warpedpinball/origin.py | 41 +++++++++++++++++++++++++++++++++------ 4 files changed, 79 insertions(+), 7 deletions(-) diff --git a/docs/machine.md b/docs/machine.md index e02dd70..d34dfe0 100644 --- a/docs/machine.md +++ b/docs/machine.md @@ -151,6 +151,20 @@ Re-registering rotates the secret and resets the counter, so a listener that restarts just registers again. See [`warpedpinball.origin`](api-reference.md) for the frame layout. +Listening to several boards at once means choosing a secret before you can +check the signature. `peek()` reads the unverified body so you can route on +the `machine_id` it claims: + +```python +claimed = origin.peek(datagram).get("machine_id") +event = origin.unpack(secrets[claimed], datagram) # this is the trust step +``` + +Identify boards this way rather than by the datagram's source address: NAT +between a board and the listener rewrites the address, and the signature is +what actually establishes who sent it. Treat everything `peek()` returns as +attacker-controlled until `unpack()` has returned. + ## The raw escape hatch Every firmware route is reachable even without a wrapper: diff --git a/tests/test_origin.py b/tests/test_origin.py index b125e88..457048a 100644 --- a/tests/test_origin.py +++ b/tests/test_origin.py @@ -51,3 +51,32 @@ def test_non_json_and_non_object_bodies_are_rejected(): packet = origin._mac(secret, body).encode() + body with pytest.raises(origin.OriginAuthError): origin.unpack(secret, packet) + + +def test_peek_reads_the_body_without_a_secret(): + body = {"machine_id": "a1b2c3d4", "type": "game_state", "n": 3} + packet = origin.pack(origin.new_secret(), body) + + # Routing to a secret has to happen before the secret is known. + assert origin.peek(packet) == body + + +def test_peek_does_not_authenticate(): + # A forged datagram peeks fine -- that is the point of the warning in the + # docstring. unpack() is the step that establishes trust. + forged = origin.pack("not-the-real-secret", {"machine_id": "a1b2c3d4", "n": 1}) + + assert origin.peek(forged)["machine_id"] == "a1b2c3d4" + with pytest.raises(origin.OriginAuthError): + origin.unpack("the-real-secret", forged) + + +@pytest.mark.parametrize("packet", [b"", b"short", b"0" * origin.MAC_LEN]) +def test_peek_rejects_malformed_frames(packet): + with pytest.raises(origin.OriginAuthError): + origin.peek(packet) + + +def test_peek_rejects_a_body_that_is_not_a_json_object(): + with pytest.raises(origin.OriginAuthError): + origin.peek(b"0" * origin.MAC_LEN + b"[1, 2]") diff --git a/warpedpinball/__init__.py b/warpedpinball/__init__.py index ce16e6f..0102d4b 100644 --- a/warpedpinball/__init__.py +++ b/warpedpinball/__init__.py @@ -33,7 +33,7 @@ from .origin import OriginAuthError from .transports.http import HttpTransport -__version__ = "0.3.1" +__version__ = "0.4.0" __all__ = [ "connect", diff --git a/warpedpinball/origin.py b/warpedpinball/origin.py index 9701fad..1fa9083 100644 --- a/warpedpinball/origin.py +++ b/warpedpinball/origin.py @@ -73,14 +73,14 @@ def pack(secret: str, body: Dict[str, Any]) -> bytes: return _mac(secret, encoded).encode("ascii") + encoded -def unpack(secret: str, packet: bytes) -> Dict[str, Any]: - """Verify and decode a datagram; raises :class:`OriginAuthError` if it - was not signed with ``secret`` or is not a well-formed frame.""" +def _split(packet: bytes) -> tuple[bytes, bytes]: + """Signature and body halves of a frame, or raise on a malformed one.""" if len(packet) <= MAC_LEN: raise OriginAuthError("Origin datagram too short to carry a signature") - received, body = packet[:MAC_LEN], packet[MAC_LEN:] - if not hmac.compare_digest(received.decode("ascii", "replace"), _mac(secret, body)): - raise OriginAuthError("Origin datagram signature does not match") + return packet[:MAC_LEN], packet[MAC_LEN:] + + +def _decode(body: bytes) -> Dict[str, Any]: try: decoded = json.loads(body) except ValueError as exc: @@ -88,3 +88,32 @@ def unpack(secret: str, packet: bytes) -> Dict[str, Any]: if not isinstance(decoded, dict): raise OriginAuthError("Origin datagram body is not a JSON object") return decoded + + +def peek(packet: bytes) -> Dict[str, Any]: + """Decode a datagram's body **without verifying its signature**. + + A listener holding secrets for many boards has a chicken-and-egg problem: + it must know which board is claiming to have sent a datagram before it can + choose the secret to check it against. This answers that question, and + nothing else -- everything it returns is unverified and, on an open + network, attacker-controlled. + + Use it only to route:: + + machine_id = origin.peek(packet).get("machine_id") + body = origin.unpack(secrets[machine_id], packet) # now it's trusted + + Nothing from :func:`peek` should reach storage, a decision, or a log line + that implies it is true. + """ + return _decode(_split(packet)[1]) + + +def unpack(secret: str, packet: bytes) -> Dict[str, Any]: + """Verify and decode a datagram; raises :class:`OriginAuthError` if it + was not signed with ``secret`` or is not a well-formed frame.""" + received, body = _split(packet) + if not hmac.compare_digest(received.decode("ascii", "replace"), _mac(secret, body)): + raise OriginAuthError("Origin datagram signature does not match") + return _decode(body)