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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-22 17:10:23 -04:00
1 parent 151ba1546f
commit a3e4e85dfd
6 files changed
+178 -9

No files matched your search

+2 -1
View File
@@ -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()
+6
View File
@@ -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]
+58
View File
@@ -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")
+20 -8
View File
@@ -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)