fix(micromate): the write ceiling is enforced at the wire; allowed_writes retired; execute takes only real plans
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
8daf413fe3
commit
a90b8158b6
5 files changed
+150
-40
No files matched your search
@@ -2,7 +2,8 @@
|
||||
|
||||
One place, as the parity spec requires. The gate is an ALLOWLIST: a SUB is
|
||||
transmitted only if it is a catalogued read (READ_SUBS) or a catalogued write
|
||||
this connection was explicitly allowed. An unknown SUB is refused -- clock-set
|
||||
that arrives through `MicromateProtocol.execute` (one call's permission, capped at
|
||||
ENABLEABLE_WRITES; the connection itself holds none). An unknown SUB is refused -- clock-set
|
||||
and delete-all have Series-IV opcodes nobody has catalogued yet, and "unknown
|
||||
means read" is the wrong default. `MicromateProtocol._send` consults it
|
||||
on every outgoing frame, so a write cannot reach a unit by a path nobody
|
||||
|
||||
+27
-23
@@ -7,8 +7,8 @@ knows frames, offsets and sequencing, and nothing about what a field means.
|
||||
Scope: **reads only on the wire, enforced** (in this package: the Series-3
|
||||
`minimateplus` stack and raw-socket bench bridges are outside the gate). 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
|
||||
unless it arrives through `execute()` (the connection itself holds no write
|
||||
permission), and `0xA2` -- CONFIRM ERASE on Series III -- is
|
||||
refused always. The gate is an allowlist: a SUB not catalogued in
|
||||
`opcodes` (read or write) is refused as unknown. No command has ever been originated against a unit by this
|
||||
project; every write in ``docs/micromate_protocol_reference.md`` was performed
|
||||
@@ -47,7 +47,7 @@ import logging
|
||||
import math
|
||||
import struct
|
||||
import time
|
||||
from typing import Optional
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
|
||||
from minimateplus.transport import BaseTransport
|
||||
|
||||
@@ -57,6 +57,9 @@ from .framing import (
|
||||
)
|
||||
from .opcodes import ENABLEABLE_WRITES, WRITE_SUBS, OpcodeRefused, check_transmit
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .writes import WritePlan
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_RECV_TIMEOUT = 10.0
|
||||
@@ -255,13 +258,9 @@ 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
|
||||
@@ -278,13 +277,6 @@ class MicromateProtocol:
|
||||
self._transport = transport
|
||||
self._recv_timeout = recv_timeout
|
||||
self._strict = strict_checksums
|
||||
self._allowed_writes = frozenset(allowed_writes)
|
||||
unknown = self._allowed_writes - set(WRITE_SUBS)
|
||||
if unknown:
|
||||
raise ValueError(
|
||||
"allowed_writes may only name catalogued write SUBs; not in "
|
||||
"micromate.opcodes.WRITE_SUBS: "
|
||||
+ ", ".join(f"0x{x:02X}" for x in sorted(unknown)))
|
||||
self._parser = MicromateFrameParser()
|
||||
self._pending: list[MicromateFrame] = []
|
||||
self.last_flags: Optional[int] = None
|
||||
@@ -526,13 +518,20 @@ class MicromateProtocol:
|
||||
# so anything already buffered when we send is by definition stale, and
|
||||
# `expected_sub` would reject it anyway — better to discard it here than
|
||||
# to raise a confusing UnexpectedResponse one command later.
|
||||
return self._request(build_request(sub, offset, params), 0xFF - sub,
|
||||
timeout=timeout)
|
||||
|
||||
def _request(self, frame: bytes, expected_sub: int, *, timeout: Optional[float] = None,
|
||||
permit: frozenset = frozenset()) -> MicromateFrame:
|
||||
"""Clean slate, send one frame, receive its reply. The one sequence
|
||||
every exchange -- read or execute -- goes through."""
|
||||
self._parser.reset()
|
||||
self._pending.clear()
|
||||
self._send(build_request(sub, offset, params))
|
||||
return self._recv_one(expected_sub=0xFF - sub, timeout=timeout,
|
||||
self._send(frame, permit=permit)
|
||||
return self._recv_one(expected_sub=expected_sub, timeout=timeout,
|
||||
reset_parser=False)
|
||||
|
||||
def execute(self, plan) -> list:
|
||||
def execute(self, plan: "WritePlan") -> list[MicromateFrame]:
|
||||
"""Transmit a `micromate.writes.WritePlan` -- the only write path.
|
||||
|
||||
Permission is granted for this call alone, one step at a time, and only
|
||||
@@ -541,7 +540,11 @@ class MicromateProtocol:
|
||||
is awaited before the next is sent. Never retries: a timeout raises,
|
||||
and what happened is the caller's to find out by reading the unit back.
|
||||
"""
|
||||
beyond = plan.subs - ENABLEABLE_WRITES
|
||||
# Deferred: writes -> setup_block -> protocol would be circular at import.
|
||||
from .writes import WritePlan
|
||||
if not isinstance(plan, WritePlan):
|
||||
raise TypeError(f"execute takes a WritePlan, got {type(plan).__name__}")
|
||||
beyond = {st.sub for st in plan.steps} - ENABLEABLE_WRITES
|
||||
if beyond:
|
||||
raise OpcodeRefused(
|
||||
"plan holds SUB(s) above the write ceiling: "
|
||||
@@ -552,17 +555,18 @@ class MicromateProtocol:
|
||||
"refusing to write")
|
||||
acks = []
|
||||
for step in plan.steps:
|
||||
self._parser.reset()
|
||||
self._pending.clear()
|
||||
self._send(step.frame, permit=frozenset({step.sub}))
|
||||
acks.append(self._recv_one(expected_sub=step.ack_sub, reset_parser=False))
|
||||
acks.append(self._request(step.frame, step.ack_sub,
|
||||
permit=frozenset({step.sub})))
|
||||
return acks
|
||||
|
||||
def _send(self, frame: bytes, *, permit: frozenset = frozenset()) -> None:
|
||||
# The gate sees the bytes about to go out, not the caller's intent.
|
||||
# `permit` is passed only by execute(), for exactly one step.
|
||||
frame = bytes(frame)
|
||||
check_transmit(request_sub(frame), self._allowed_writes | permit)
|
||||
# Trust means the most recent request got a validated Micromate reply.
|
||||
self.last_flags = None
|
||||
# The ceiling is enforced here, where frames leave, whatever was permitted.
|
||||
check_transmit(request_sub(frame), permit & ENABLEABLE_WRITES)
|
||||
log.debug("TX %d bytes: %s", len(frame), frame.hex())
|
||||
self._transport.write(frame)
|
||||
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
"""Write plans for a Micromate: the exact frames a write would send, in order.
|
||||
|
||||
A plan is what a dry run returns. Building one sends nothing; transmitting it
|
||||
also needs a protocol constructed with those SUBs in `allowed_writes`, which no
|
||||
code does yet (see `micromate.opcodes`).
|
||||
is `MicromateProtocol.execute(plan)` and nothing else: the connection holds no
|
||||
write permission of its own (see `micromate.opcodes`).
|
||||
|
||||
Every input is the unit's OWN read of the block being written (content, i.e.
|
||||
response data[11:]), and every plan sends back exactly what was read except
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -10,9 +13,10 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from micromate.framing import FLAGS_THOR, build_request # noqa: E402
|
||||
from micromate.opcodes import ENABLEABLE_WRITES, OpcodeRefused # noqa: E402
|
||||
from micromate.protocol import ACK_DATA_LEN, UnexpectedResponse # noqa: E402
|
||||
from micromate.protocol import ACK_DATA_LEN, TimeoutError as MmTimeout, UnexpectedResponse # noqa: E402
|
||||
from micromate.writes import ( # noqa: E402
|
||||
plan_call_home_enabled, plan_start_monitoring, plan_stop_monitoring,
|
||||
WritePlan, WriteStep, plan_call_home_enabled, plan_start_monitoring,
|
||||
plan_stop_monitoring,
|
||||
)
|
||||
from test_micromate_protocol import frame, proto # noqa: E402
|
||||
|
||||
@@ -63,7 +67,7 @@ def test_execute_refuses_before_any_micromate_reply_has_been_seen():
|
||||
|
||||
|
||||
def test_execute_refuses_after_a_non_micromate_flags_reply():
|
||||
p, t = proto([frame(0xA4, bytes(48), flags=0x10), ACK_START], strict_checksums=False)
|
||||
p, t = proto([frame(0xA4, bytes(48), flags=0x10), ACK_START])
|
||||
p.poll()
|
||||
t.written.clear()
|
||||
with pytest.raises(OpcodeRefused):
|
||||
@@ -83,3 +87,94 @@ def test_thor_flags_are_accepted_too():
|
||||
p.poll()
|
||||
p.execute(plan_stop_monitoring())
|
||||
assert t.written[-1] == build_request(0x97, 0xFFFF)
|
||||
|
||||
|
||||
# -- fix round 1: the ceiling is enforced where frames leave --------------------
|
||||
|
||||
def test_a_permit_beyond_the_ceiling_cannot_send():
|
||||
p, t = _ready([])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p._send(build_request(0x8E, 0), permit=frozenset({0x8E}))
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_the_constructor_no_longer_grants_anything():
|
||||
with pytest.raises(TypeError):
|
||||
proto([], allowed_writes={0xA8})
|
||||
|
||||
|
||||
def test_a_duck_typed_plan_is_refused():
|
||||
p, t = _ready([])
|
||||
fake = SimpleNamespace(subs=frozenset({0x96}), steps=(WriteStep(0x7E, 0),))
|
||||
with pytest.raises(TypeError):
|
||||
p.execute(fake)
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_a_forged_step_in_a_real_plan_is_refused_at_the_step():
|
||||
p, t = _ready([])
|
||||
plan = plan_start_monitoring()
|
||||
object.__setattr__(plan, "steps", (WriteStep(0x7E, 0),)) # subs now reads 0x7E too
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan)
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_a_forged_step_hidden_behind_a_good_plan_is_refused():
|
||||
class Lying(WritePlan):
|
||||
@property
|
||||
def subs(self):
|
||||
return frozenset({0x96})
|
||||
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0x7E, 0)))
|
||||
p, t = _ready([ACK_START])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan)
|
||||
assert t.written == []
|
||||
|
||||
|
||||
# -- a lost ack is never retried, inside the real execute ------------------------
|
||||
|
||||
def test_a_lost_ack_raises_after_exactly_one_send():
|
||||
p, t = _ready([])
|
||||
with pytest.raises(MmTimeout):
|
||||
p.execute(plan_start_monitoring())
|
||||
assert len(t.written) == 1
|
||||
|
||||
|
||||
def test_a_lost_first_ack_stops_a_two_step_plan():
|
||||
plan = WritePlan("start then stop",
|
||||
(WriteStep(0x96, 0xFFFF), WriteStep(0x97, 0xFFFF)))
|
||||
p, t = _ready([])
|
||||
with pytest.raises(MmTimeout):
|
||||
p.execute(plan)
|
||||
assert t.written == [build_request(0x96, 0xFFFF)]
|
||||
|
||||
|
||||
def test_trust_is_the_most_recent_request_not_an_earlier_one():
|
||||
p, t = _ready([])
|
||||
with pytest.raises(MmTimeout):
|
||||
p.poll() # sent, never answered
|
||||
t.written.clear()
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan_start_monitoring())
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_execute_works_right_after_a_valid_read():
|
||||
p, t = _ready([ACK_START])
|
||||
p.execute(plan_start_monitoring())
|
||||
assert len(t.written) == 1
|
||||
|
||||
|
||||
# -- nothing outside protocol.py passes permit= to _send ---------------------------
|
||||
|
||||
def test_only_protocol_py_passes_permit():
|
||||
root = pathlib.Path(__file__).resolve().parent.parent
|
||||
offenders = []
|
||||
for d in ("micromate", "sfm", "bridges", "scratch", "scripts"):
|
||||
for f in (root / d).rglob("*.py"):
|
||||
if f == root / "micromate" / "protocol.py":
|
||||
continue
|
||||
if re.search(r"_send\([^)]*permit\s*=", f.read_text(errors="ignore"), re.S):
|
||||
offenders.append(str(f))
|
||||
assert offenders == []
|
||||
@@ -13,6 +13,7 @@ from micromate.framing import build_request # noqa: E4
|
||||
from micromate.opcodes import ( # noqa: E402
|
||||
CROSS_SERIES_COLLISIONS, READ_SUBS, WRITE_SUBS, OpcodeRefused, check_transmit,
|
||||
)
|
||||
from micromate.writes import plan_start_monitoring # noqa: E402
|
||||
from test_micromate_protocol import frame, proto # noqa: E402
|
||||
|
||||
# THOR's captured end-call-home frame. Same SUB as Series III's CONFIRM ERASE, not the
|
||||
@@ -51,15 +52,17 @@ def test_the_protocol_refuses_a_write_and_writes_nothing():
|
||||
|
||||
|
||||
def test_the_protocol_refuses_the_captured_0xa2_frame_byte_for_byte():
|
||||
p, t = proto([], allowed_writes=frozenset({0xA2}))
|
||||
p, t = proto([])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p._send(A2_WIRE)
|
||||
p._send(A2_WIRE, permit=frozenset({0xA2}))
|
||||
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)
|
||||
def test_a_write_goes_out_only_through_execute_on_a_scripted_transport():
|
||||
p, t = proto([frame(0xA4, bytes(48)), frame(0x69, bytes(11))])
|
||||
p.poll()
|
||||
t.written.clear()
|
||||
p.execute(plan_start_monitoring())
|
||||
assert t.written == [build_request(0x96, 0xFFFF)]
|
||||
|
||||
|
||||
@@ -95,10 +98,17 @@ def test_an_unknown_opcode_is_refused_and_nothing_is_written(sub):
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_allowed_writes_may_only_name_catalogued_writes():
|
||||
for bad in (frozenset({0xEE}), frozenset({0x5B})):
|
||||
with pytest.raises(ValueError):
|
||||
proto([], allowed_writes=bad)
|
||||
@pytest.mark.parametrize("sub", [0xEE, 0x7E, 0xA8])
|
||||
def test_a_permit_beyond_the_ceiling_is_refused_at_the_wire(sub):
|
||||
p, t = proto([])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p._send(build_request(sub, 0), permit=frozenset({sub}))
|
||||
assert t.written == []
|
||||
|
||||
|
||||
def test_allowed_writes_is_retired():
|
||||
with pytest.raises(TypeError):
|
||||
proto([], allowed_writes=frozenset({0x96}))
|
||||
|
||||
|
||||
def test_the_tables_are_read_only():
|
||||
@@ -111,9 +121,9 @@ def test_the_tables_are_read_only():
|
||||
|
||||
@pytest.mark.parametrize("tail", [build_request(0x96, 0xFFFF), A2_WIRE])
|
||||
def test_a_read_followed_by_a_write_in_one_send_is_refused(tail):
|
||||
p, t = proto([], allowed_writes=frozenset({0x96}))
|
||||
p, t = proto([])
|
||||
with pytest.raises(ValueError):
|
||||
p._send(build_request(0x5B, 0x0030) + tail)
|
||||
p._send(build_request(0x5B, 0x0030) + tail, permit=frozenset({0x96}))
|
||||
assert t.written == []
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user