From a3e4e85dfdc0c19eee9d1d68ea1de5cb7015d9ad Mon Sep 17 00:00:00 2001 From: serversdown Date: Thu, 22 Oct 2026 17:10:23 -0400 Subject: [PATCH] feat(micromate): one opcode table and a send-side gate -- writes refused unless allowed, 0xA2 always micromate/opcodes.py holds WRITE_SUBS and the cross-series collision 0xA2. MicromateProtocol._send reads the SUB of the bytes about to go out (framing.request_sub) and refuses any write SUB not in allowed_writes, and 0xA2 unconditionally. Docstrings now say the reads-only policy is enforced. request_sub also refuses any frame not in canonical form (stuff(unstuff(body)) == body): an interior unescaped 02/03/04, a 10 XX outside {02,03,04,10}, or a trailing lone DLE. What the gate checks is then exactly what the unit parses. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- micromate/client.py | 3 +- micromate/framing.py | 6 +++ micromate/opcodes.py | 58 +++++++++++++++++++++++++ micromate/protocol.py | 28 ++++++++---- tests/test_micromate_framing.py | 17 ++++++++ tests/test_micromate_opcodes.py | 75 +++++++++++++++++++++++++++++++++ 6 files changed, 178 insertions(+), 9 deletions(-) create mode 100644 micromate/opcodes.py create mode 100644 tests/test_micromate_opcodes.py diff --git a/micromate/client.py b/micromate/client.py index c29efe2..5b8cdf0 100644 --- a/micromate/client.py +++ b/micromate/client.py @@ -2,7 +2,8 @@ client.py — high-level API for a live Micromate (Series IV). Owns the transport, turns raw payloads into models. Read-only, like the layer -below it: nothing here writes, erases, or changes monitoring state. +below it: nothing here writes, erases, or changes monitoring state, and the +protocol's opcode gate (`micromate.opcodes`) enforces that in code. with MicromateClient(TcpTransport("63.45.161.30", 9034)) as mm: info = mm.connect() diff --git a/micromate/framing.py b/micromate/framing.py index b935fac..a676748 100644 --- a/micromate/framing.py +++ b/micromate/framing.py @@ -182,6 +182,12 @@ def request_sub(frame: bytes) -> int: body = unstuff(frame[2:-1]) if len(body) < 17 or body[0] != MM_CMD: raise ValueError(f"not a host->unit request frame: {bytes(frame[:8]).hex()}") + # Canonical form only: what this check reads must be exactly what the unit + # parses. An unescaped 02/03/04, a `10 XX` outside {02,03,04,10} or a + # trailing lone DLE would be read one way here and another by the unit. + if stuff(body) != frame[2:-1]: + raise ValueError( + f"not a canonical request frame (stuffing differs): {bytes(frame[:8]).hex()}") return body[2] diff --git a/micromate/opcodes.py b/micromate/opcodes.py new file mode 100644 index 0000000..c5f204c --- /dev/null +++ b/micromate/opcodes.py @@ -0,0 +1,58 @@ +"""Micromate (Series IV) opcode table: which SUBs write, and which collide. + +One place, as the parity spec requires. `MicromateProtocol._send` consults it +on every outgoing frame, so a write cannot reach a unit by a path nobody +thought about -- a scratch tool calling `protocol._send`, a hand-built frame, a +method added later. + +Every SUB here was seen as a host->unit request in THOR's captures +(`docs/micromate_protocol_reference.md`). The table classifies REQUESTS: a few +of these values are also ACK SUBs of other commands (0x71 acks 0x8E, 0x72 acks +0x8D), which is irrelevant to a send-side check. +""" +from __future__ import annotations + +from typing import Dict, FrozenSet + +WRITE_SUBS: Dict[int, str] = { + 0x47: "scheduler enable/disable", + 0x68: "setup push: preferences block (0x08)", + 0x71: "setup push: setup block (0x1A)", + 0x72: "setup push: setup confirm", + 0x73: "setup push: preferences confirm", + 0x7E: "call-home config write (0x2C)", + 0x7F: "call-home config confirm", + 0x82: "setup push: trigger block (0x2E)", + 0x83: "setup push: trigger confirm", + 0x8D: "file open for write", + 0x8E: "file body write", + 0x96: "start monitoring", + 0x97: "stop monitoring", + 0xA2: "end call-home", + 0xA8: "delete one event", + 0xAA: "delete-event confirm", + 0xDA: "setup push: file name", +} + +# Same bytes, opposite consequence on the other series. Never transmitted on +# Series IV, allowed or not: if a Series-III unit is at the address (a moved +# modem, a stale IP), it would execute the other meaning. Lifting an entry is +# a spec change, not a parameter. +CROSS_SERIES_COLLISIONS: Dict[int, str] = { + 0xA2: "CONFIRM ERASE on Series III -- erases every stored event; " + "'end call-home' on Series IV", +} + + +class OpcodeRefused(RuntimeError): + """A frame was stopped before it reached the wire.""" + + +def check_transmit(sub: int, allowed_writes: FrozenSet[int] = frozenset()) -> None: + if sub in CROSS_SERIES_COLLISIONS: + raise OpcodeRefused( + f"refused to transmit SUB 0x{sub:02X}: {CROSS_SERIES_COLLISIONS[sub]}") + if sub in WRITE_SUBS and sub not in allowed_writes: + raise OpcodeRefused( + f"refused to transmit SUB 0x{sub:02X} ({WRITE_SUBS[sub]}): writes are " + "not enabled on this connection") diff --git a/micromate/protocol.py b/micromate/protocol.py index 215b02b..4d9892f 100644 --- a/micromate/protocol.py +++ b/micromate/protocol.py @@ -4,13 +4,16 @@ protocol.py — one method per Micromate (Series IV) wire command. Returns raw payload bytes. Interpretation belongs in ``client.py``; this layer knows frames, offsets and sequencing, and nothing about what a field means. -Scope: **reads only.** Nothing here writes, erases, or changes monitoring -state. That is deliberate and worth keeping — no command has ever been -originated against a unit by this project; every write in -``docs/micromate_protocol_reference.md`` was performed by THOR while we -recorded. The first thing this codebase ever sends to a customer's instrument -should be a decision someone made on purpose, not a side effect of a client -that grew a method. +Scope: **reads only on the wire, enforced.** Every outgoing frame passes +`micromate.opcodes.check_transmit()` in `_send`: a write opcode is refused +unless this connection was constructed with it in `allowed_writes` (nothing in +the codebase does so yet), and `0xA2` -- CONFIRM ERASE on Series III -- is +refused always. No command has ever been originated against a unit by this +project; every write in ``docs/micromate_protocol_reference.md`` was performed +by THOR while we recorded. The first thing this codebase ever sends to a +customer's instrument should be a decision someone made on purpose, not a side +effect of a client that grew a method. Write frames are *built* in +``micromate.writes`` as reviewable plans; building one sends nothing. Every offset and params layout below was read off THOR's own frames in ``bridges/captures/9-24-26 - micromate2/`` rather than taken from the spec @@ -43,7 +46,8 @@ from typing import Optional from minimateplus.transport import BaseTransport -from .framing import MicromateFrame, MicromateFrameParser, build_request +from .framing import MicromateFrame, MicromateFrameParser, build_request, request_sub +from .opcodes import check_transmit log = logging.getLogger(__name__) @@ -243,9 +247,13 @@ class MicromateProtocol: transport: BaseTransport, recv_timeout: float = DEFAULT_RECV_TIMEOUT, strict_checksums: bool = True, + allowed_writes: frozenset = frozenset(), ) -> None: """ Args: + allowed_writes: write SUBs this connection may transmit. Empty by + default -- every write opcode in `micromate.opcodes` is refused + at `_send`, and `0xA2` is refused whatever this says. strict_checksums: raise on a bad checksum. **Defaults to True, unlike the Series III sibling**, which logs and continues because its parser cannot reliably tell an inner-frame @@ -262,6 +270,7 @@ class MicromateProtocol: self._transport = transport self._recv_timeout = recv_timeout self._strict = strict_checksums + self._allowed_writes = frozenset(allowed_writes) self._parser = MicromateFrameParser() self._pending: list[MicromateFrame] = [] @@ -509,6 +518,9 @@ class MicromateProtocol: reset_parser=False) def _send(self, frame: bytes) -> None: + # The gate sees the bytes that are about to go out, not the caller's + # intent: every transmit in this package passes through here. + check_transmit(request_sub(frame), self._allowed_writes) log.debug("TX %d bytes: %s", len(frame), frame.hex()) self._transport.write(frame) diff --git a/tests/test_micromate_framing.py b/tests/test_micromate_framing.py index 50d5f2c..7fcef89 100644 --- a/tests/test_micromate_framing.py +++ b/tests/test_micromate_framing.py @@ -468,6 +468,23 @@ def test_request_sub_refuses_anything_that_is_not_a_request_frame(junk): request_sub(junk) +def _noncanonical_frames(): + good = build_request(0x96, 0xFFFF) + return { + "interior raw 03": good[:5] + b"\x03" + good[5:], + "10 05 pair": good[:5] + b"\x10\x05" + good[5:], + "lone DLE before ETX": good[:-1] + b"\x10" + good[-1:], + "double 41 02 prefix": good[:2] + good, + "first byte not 0x10": good[:2] + bytes([0x11]) + good[3:], + } + + +@pytest.mark.parametrize("name", list(_noncanonical_frames())) +def test_request_sub_refuses_a_frame_that_is_not_in_canonical_form(name): + with pytest.raises(ValueError): + request_sub(_noncanonical_frames()[name]) + + @pytest.mark.skipif( not _CAPTURES.is_dir(), reason="capture directory is gitignored; present only on a dev box", diff --git a/tests/test_micromate_opcodes.py b/tests/test_micromate_opcodes.py new file mode 100644 index 0000000..7c8fd7a --- /dev/null +++ b/tests/test_micromate_opcodes.py @@ -0,0 +1,75 @@ +"""The send-side gate: no write opcode reaches the wire unless allowed, and 0xA2 never.""" +from __future__ import annotations + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import micromate.protocol as mm_proto # noqa: E402 +from micromate.framing import build_request # noqa: E402 +from micromate.opcodes import ( # noqa: E402 + CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused, check_transmit, +) +from test_micromate_protocol import frame, proto # noqa: E402 + +# THOR's captured end-call-home frame -- byte-identical to Series III's CONFIRM ERASE. +A2_WIRE = bytes.fromhex("4102101000a200ffff00000000000000000000b003") + + +def test_no_read_command_is_classed_as_a_write(): + reads = {v for k, v in vars(mm_proto).items() if k.startswith("SUB_")} + assert reads and not (reads & set(WRITE_SUBS)) + + +def test_0xa2_is_a_collision_and_a_write(): + assert 0xA2 in CROSS_SERIES_COLLISIONS and 0xA2 in WRITE_SUBS + + +def test_a_write_is_refused_unless_allowed(): + with pytest.raises(OpcodeRefused, match="0x96"): + check_transmit(0x96) + check_transmit(0x96, frozenset({0x96})) + check_transmit(0x5B) # a read needs no permission + + +def test_0xa2_is_refused_even_when_allowed(): + with pytest.raises(OpcodeRefused, match="ERASE"): + check_transmit(0xA2, frozenset({0xA2})) + + +def test_the_protocol_refuses_a_write_and_writes_nothing(): + p, t = proto([]) + with pytest.raises(OpcodeRefused): + p._exchange(0x96, offset=0xFFFF) + with pytest.raises(OpcodeRefused): + p._send(build_request(0x97, 0xFFFF)) # a direct _send is gated too + assert t.written == [] + + +def test_the_protocol_refuses_the_captured_0xa2_frame_byte_for_byte(): + p, t = proto([], allowed_writes=frozenset({0xA2})) + with pytest.raises(OpcodeRefused): + p._send(A2_WIRE) + assert t.written == [] + + +def test_an_explicitly_allowed_write_goes_out_on_a_scripted_transport(): + p, t = proto([frame(0x69, bytes(11))], allowed_writes=frozenset({0x96})) + p._exchange(0x96, offset=0xFFFF) + assert t.written == [build_request(0x96, 0xFFFF)] + + +def test_reads_are_unaffected_by_the_gate(): + p, t = proto([frame(0xA4, bytes(11))]) + p.poll() + assert len(t.written) == 1 + + +def test_a_frame_that_is_not_a_request_is_refused_not_sent(): + p, t = proto([]) + with pytest.raises(ValueError): + p._send(b"\x41\x03") + assert t.written == []