test(micromate): an AST scan pins execute() as the only write grant; cover the last mutants

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-23 16:17:04 -04:00
1 parent a90b8158b6
commit 9ed9578d12
4 files changed
+90 -25

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ Read this first when picking the project back up.
the setup rewrite, reproduced byte for byte against THOR's captured frames.
`bridges/mm_dry_run.py` prints a write's planned frames from a live unit's
reads (run on UM20147: sizes equal UM12947's). `MicromateProtocol._send`
refuses every write opcode unless explicitly allowed, and `0xA2` always, so
refuses every write opcode except one start/stop plan at a time through `execute()`, on a connection with a fresh Micromate reply, and `0xA2` always, so
"no command has ever been originated against a unit" is still true and is now
enforced in `micromate/` (its `_send` gate); the Series-3 `minimateplus`
stack and raw-socket bench bridges are outside it. The reproduction's
+1 -1
View File
@@ -54,7 +54,7 @@ def main() -> int:
if not (a.port or a.host):
ap.error("give a serial port or --host")
transport = TcpTransport(a.host, port=a.tcp_port) if a.host else SerialTransport(a.port, a.baud)
mm = MicromateClient(transport) # no allowed_writes: the gate refuses every write
mm = MicromateClient(transport) # no execute(): nothing here can transmit a write
mm.open()
try:
info = mm.connect()
+5 -7
View File
@@ -55,7 +55,7 @@ from .framing import (
FLAGS_BLASTWARE, FLAGS_THOR, MicromateFrame, MicromateFrameParser,
build_request, request_sub,
)
from .opcodes import ENABLEABLE_WRITES, WRITE_SUBS, OpcodeRefused, check_transmit
from .opcodes import ENABLEABLE_WRITES, OpcodeRefused, check_transmit
if TYPE_CHECKING:
from .writes import WritePlan
@@ -513,11 +513,9 @@ class MicromateProtocol:
) -> MicromateFrame:
if offset is None:
offset = _OFFSETS.get(sub, READ_ALL)
# Start every exchange clean: drop any half-frame and any frame left
# stashed by the last one. This is a strict request/response protocol,
# 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.
# `_request` starts every exchange clean (drops any half-frame and any
# stashed frame): this is a strict request/response protocol, so anything
# already buffered when we send is stale.
return self._request(build_request(sub, offset, params), 0xFF - sub,
timeout=timeout)
@@ -561,7 +559,7 @@ class MicromateProtocol:
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.
# `permit` is passed only via _request, from execute(), for one step.
frame = bytes(frame)
# Trust means the most recent request got a validated Micromate reply.
self.last_flags = None
+83 -16
View File
@@ -2,8 +2,9 @@
from __future__ import annotations
import os
import ast
import pathlib
import re
import subprocess
import sys
from types import SimpleNamespace
@@ -98,11 +99,6 @@ def test_a_permit_beyond_the_ceiling_cannot_send():
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),))
@@ -166,15 +162,86 @@ def test_execute_works_right_after_a_valid_read():
assert len(t.written) == 1
# -- nothing outside protocol.py passes permit= to _send ---------------------------
def test_a_successful_two_step_plan_sends_both_in_order():
plan = WritePlan("start then stop",
(WriteStep(0x96, 0xFFFF), WriteStep(0x97, 0xFFFF)))
p, t = _ready([ACK_START, frame(0x68, bytes(ACK_DATA_LEN))])
acks = p.execute(plan)
assert t.written == [build_request(0x96, 0xFFFF), build_request(0x97, 0xFFFF)]
assert [a.sub for a in acks] == [0x69, 0x68]
def test_only_protocol_py_passes_permit():
def test_an_in_ceiling_frame_sub_mismatch_is_refused():
class Liar(WriteStep):
@property
def frame(self):
return build_request(0x97, 0xFFFF)
p, t = _ready([ACK_START])
plan = WritePlan("x", (Liar(0x96, 0xFFFF),))
with pytest.raises(OpcodeRefused):
p.execute(plan)
assert t.written == []
@pytest.mark.parametrize("bad", [
frame(0x99, bytes(48)), # Micromate flags, wrong SUB
frame(0xA4, bytes(48))[:-2] + b"\x00\x03", # Micromate flags, bad checksum
])
def test_a_flagged_reply_that_fails_validation_leaves_no_trust(bad):
p, t = _ready([bad])
with pytest.raises(Exception):
p.poll()
assert p.last_flags is None
t.written.clear()
with pytest.raises(OpcodeRefused):
p.execute(plan_start_monitoring())
assert t.written == []
# -- nothing outside protocol.py reaches the wire with permission -----------------
def scan_source(src: str, name: str = "<s>") -> list[str]:
"""Hits: a `permit=` keyword, `**kw` into _send/_request, any `._request` call."""
hits = []
for node in ast.walk(ast.parse(src)):
if not isinstance(node, ast.Call):
continue
fn = node.func
fname = fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", "")
if any(k.arg == "permit" for k in node.keywords):
hits.append(f"{name}:{node.lineno} permit=")
if fname in ("_send", "_request") and any(k.arg is None for k in node.keywords):
hits.append(f"{name}:{node.lineno} **kwargs into {fname}")
if isinstance(fn, ast.Attribute) and fn.attr == "_request":
hits.append(f"{name}:{node.lineno} ._request call")
return hits
@pytest.mark.parametrize("src", [
"p._send(build_request(0x96, 0xFFFF), permit=frozenset({0x96}))",
"p._send(frame, **kw)",
"p._request(frame, 0x69, permit=x)",
"p._request(frame, 0x69)",
])
def test_the_scanner_catches_each_shape(src):
assert scan_source(src)
def test_the_scanner_ignores_ordinary_calls():
assert scan_source("p._send(frame)\nf(a, b=1)") == []
def test_only_protocol_py_grants_write_permission():
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 == []
files = subprocess.run(["git", "ls-files", "*.py"], cwd=root, capture_output=True,
text=True, check=True).stdout.split()
hits = []
for rel in files:
if rel.startswith("tests/") or rel == "micromate/protocol.py":
continue
try:
src = (root / rel).read_text(errors="ignore")
hits += scan_source(src, rel)
except SyntaxError:
pass
assert hits == []