fix(micromate): a plan step is immutable once validated; setup push checks each block's own header

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:47:49 -04:00
1 parent b7b054aee9
commit 137aa699c7
3 files changed
+81

No files matched your search

+7
View File
@@ -12,6 +12,13 @@ this connection, so nothing else can go out even by mistake.
The JSON carries a `reads` block (length of each block read, and for
setup-rewrite the blocks themselves in hex) so the plan can be checked against
what the unit actually said.
⚠ `0x1A` reads the keypad's edit buffer live. A setup read taken while someone
is in the unit's menu includes their unsaved edits, and pushing that plan would
commit them.
⚠ The setup-rewrite JSON embeds the unit's whole `0x1A` block (job number,
notes), so do not paste it anywhere public.
"""
from __future__ import annotations
+21
View File
@@ -36,6 +36,17 @@ class WriteStep:
params: bytes = field(default=bytes(10))
what: str = ""
def __post_init__(self) -> None:
# Freeze the bytes: a caller's bytearray must not change a validated step.
object.__setattr__(self, "data", bytes(self.data))
object.__setattr__(self, "params", bytes(self.params))
if len(self.params) != 10:
raise ValueError(f"params must be 10 bytes, got {len(self.params)}")
if not 0 <= self.offset <= 0xFFFF:
raise ValueError(f"offset 0x{self.offset:X} does not fit a uint16")
if not 0 <= self.sub <= 0xFF:
raise ValueError(f"SUB {self.sub!r} does not fit a byte")
@property
def ack_sub(self) -> int:
return 0xFF - self.sub
@@ -61,6 +72,8 @@ class WritePlan:
object.__setattr__(self, "steps", tuple(self.steps))
object.__setattr__(self, "warnings", tuple(self.warnings))
for s in self.steps:
if not isinstance(s, WriteStep):
raise TypeError(f"a plan holds WriteStep objects, got {type(s).__name__}")
if s.sub in CROSS_SERIES_COLLISIONS:
raise OpcodeRefused(
f"a plan cannot hold SUB 0x{s.sub:02X}: {CROSS_SERIES_COLLISIONS[s.sub]}")
@@ -121,6 +134,10 @@ def _checked(block: bytes, size: int, label: str) -> bytes:
if len(block) != size:
raise ValueError(f"{label} block size {len(block)} B is not the {size} B "
"THOR's offset was observed at -- refusing to guess")
if int.from_bytes(block[0:2], "big") != size - 2:
raise ValueError(f"{label} block's own header says "
f"{int.from_bytes(block[0:2], 'big')}, expected {size - 2} -- "
"not the block it claims to be")
if not crc_ok(block):
raise ValueError(f"{label} block failed its checksum -- refusing to write a "
"corrupt read back to the unit")
@@ -134,6 +151,10 @@ def plan_setup_push(prefs: bytes, trigger: bytes, setup: bytes, name: str) -> Wr
[0:3] zeroed; the unit recomputes the CRCs, so 0x68 and 0x71 drop the CRC
slot and 0x82 sends it zeroed -- exactly THOR's frames.
⚠ `0x1A` reads the keypad's edit buffer live. A setup read taken while
someone is in the unit's menu includes their unsaved edits, and pushing
this plan would commit them.
The name goes out exactly as given. `MicromateClient.get_active_setup()`
strips whitespace, so a setup name with leading or trailing spaces would
not round-trip through it; phase 5 decides whether to take the unstripped
+53
View File
@@ -212,3 +212,56 @@ def test_thors_own_call_home_writes_carry_no_unobserved_warning(read_idx, enable
assert not any("unobserved" in w for w in plan.warnings)
assert plan.warnings == ()
assert plan_stop_monitoring().describe()["warnings"] == []
# ── a step is immutable after validation ──────────────────────────────────────
def test_a_step_built_from_a_bytearray_cannot_change_afterwards():
data, params = bytearray(b"\x01\x02\x03"), bytearray(10)
step = WriteStep(0x7E, 0x007E, data, params)
plan = WritePlan("x", (step,))
frame, desc = step.frame, plan.describe()
data[0] = 0xFF
params[0] = 0xFF
assert isinstance(step.data, bytes) and isinstance(step.params, bytes)
assert step.frame == frame and plan.describe() == desc
@pytest.mark.parametrize("kw", [{"params": bytes(9)}, {"params": bytes(11)},
{"offset": 0x10000}, {"offset": -1},
{"sub": 0x100}, {"sub": -1}])
def test_a_malformed_step_is_refused_at_construction(kw):
args = {"sub": 0x96, "offset": 0xFFFF}
args.update(kw)
with pytest.raises(ValueError):
WriteStep(**args)
def test_a_plan_refuses_a_step_that_is_not_a_writestep():
with pytest.raises(TypeError, match="WriteStep"):
WritePlan("x", (object(),))
with pytest.raises(TypeError, match="WriteStep"):
WritePlan("x", ((0x96, 0xFFFF),))
def _multi_step_plans():
reads, _ = _first_push("setup-push-multiday")
return [plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], "x.mmb"),
plan_call_home_enabled(_call_home_reads()[0], True)]
@pytest.mark.parametrize("i", [0, 1])
def test_describe_frames_match_frames_for_every_step(i):
plan = _multi_step_plans()[i]
d, frames = plan.describe()["steps"], plan.frames()
assert len(d) == len(frames) > 1
for j, f in enumerate(frames):
assert d[j]["frame"] == f.hex()
def test_setup_push_refuses_a_block_whose_own_length_header_is_wrong():
reads, _ = _first_push("setup-push-multiday")
bad = bytearray(reads[0x1A])
bad[0:2] = (int.from_bytes(bad[0:2], "big") + 1).to_bytes(2, "big")
with pytest.raises(ValueError, match="header"):
plan_setup_push(reads[0x08], reads[0x2E], bytes(bad), "x.mmb")