fix(sfm): legacy Series-3 writes and erase refuse a unit that does not answer as Series 3

0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate, and the
legacy host/port routes had no identity check: only the MiniMate parser's
inability to read a Micromate's replies stood between Diagnostics' Erase and a
Micromate (phase 1c safeguard, agreed with Brian 2026-10-28).

_require_series3(unit_serial, expected) refuses (409, 'nothing sent') unless the
unit's own serial is Series 3 and, when ?serial= names one, that one:
- POST /device/config (+ /config/project) and /device/events/erase: the serial
  connect() already reads -- no extra request;
- /device/rescue (when it writes call-home or erases) and POST /device/call_home:
  one SUB 0x15 read (new MiniMateClient.read_serial).
Exempt, with the reason in a comment: legacy monitor start/stop, blind stop, slow
drip, spam -- 0x96/0x97 mean the same on both series (measured), and the rescue
tools must reach a unit too wedged to answer.

Tests: each guarded route refuses a unit answering UM20147 and a different BE
unit with no write call, proceeds for the named unit (normalised), reuses
connect()'s serial where it has one; the blind stop builds no client;
read_serial decodes BE9441's recorded 0x15 reply.

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-29 11:43:42 -04:00
1 parent c3746a6a01
commit 1cb11abcef
3 files changed
+232 -4

No files matched your search

+46 -4
View File
@@ -86,7 +86,7 @@ from sfm.event_ingest import backfill_series3_event, persist_download
import dataclasses
from sfm.device_access import DeviceAccess, DeviceError, UnitAddress
from sfm.device_access.errors import BadRequest
from sfm.device_access.series import normalise_serial
from sfm.device_access.series import normalise_serial, series_for_serial
from sfm.audit import DbAudit
logging.basicConfig(
@@ -443,6 +443,28 @@ async def _device_guard_middleware(request, call_next):
_SERIAL_DOC = "Unit serial -- UM... (Series 4) or BE.../BA... (Series 3). Returns the shared model."
_SERIAL_CHECK_DOC = ("Expected unit serial (BE.../BA...). The unit's own serial is read before "
"any write; a different unit, or one that is not Series 3, is refused (409).")
def _require_series3(unit_serial: Optional[str], expected: Optional[str]) -> None:
"""Refuse (409) a legacy Series-3 write or erase unless the unit at the address
answers as Series 3 -- and as `expected`, when one was named.
0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate, and
these routes had no identity check (phase 1c, 2026-10-29). The serial comes
from connect() where a route already makes it, else one SUB 0x15 read.
"""
try:
series = series_for_serial(unit_serial or "")
except BadRequest:
series = None
if series != 3:
raise HTTPException(status_code=409, detail=(
f"the unit at this address answers as {unit_serial!r}, not a Series-3 unit -- nothing sent"))
if expected and normalise_serial(expected) != normalise_serial(unit_serial):
raise HTTPException(status_code=409, detail=(
f"the unit at this address is {unit_serial}, not {expected} -- nothing sent"))
# ── Helpers ────────────────────────────────────────────────────────────────────
@@ -1111,6 +1133,7 @@ def device_config(
baud: int = Query(38400, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""
Read the current device config, apply any supplied changes to the compliance
@@ -1149,7 +1172,8 @@ def device_config(
try:
def _do():
with _build_client(port, baud, host, tcp_port) as client:
client.connect()
info = client.connect()
_require_series3(info.serial, serial)
client.apply_config(
recording_mode=body.recording_mode,
sample_rate=body.sample_rate,
@@ -1194,9 +1218,10 @@ def device_config_project(
baud: int = Query(38400, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""Deprecated alias for POST /device/config — use that instead."""
return device_config(body=body, port=port, baud=baud, host=host, tcp_port=tcp_port)
return device_config(body=body, port=port, baud=baud, host=host, tcp_port=tcp_port, serial=serial)
# ── Monitoring endpoints ───────────────────────────────────────────────────────
@@ -1430,6 +1455,7 @@ def device_events_erase(
baud: int = Query(38400, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""
Erase ALL stored events from the device memory.
@@ -1449,7 +1475,8 @@ def device_events_erase(
try:
def _do():
with _build_client(port, baud, host, tcp_port) as client:
client.connect()
info = client.connect()
_require_series3(info.serial, serial)
client.delete_all_events()
_run_with_retry(_do, is_tcp=_is_tcp(host))
except HTTPException:
@@ -1498,6 +1525,7 @@ def device_stop_monitoring_blind(
Returns the number of bytes sent. A 503 means the TCP connect failed
(device busy in another session — caller should retry).
"""
# Not identity-checked (phase 1c): it sends only 0x97/0x96, which mean the same on both series (measured 2026-10-25/27), and it must reach a unit too wedged to answer.
log.info(
"POST /device/stop_monitoring_blind host=%s tcp_port=%s connect_timeout=%.1fs repeat=%d",
host, tcp_port, connect_timeout, repeat,
@@ -1570,6 +1598,7 @@ def device_stop_monitoring_slow_drip(
Compared to spam mode: ~40× fewer bytes/sec on the wire, but each
byte has a much higher chance of actually being parsed.
"""
# Not identity-checked (phase 1c): it sends only 0x97/0x96, which mean the same on both series (measured 2026-10-25/27), and it must reach a unit too wedged to answer.
log.info(
"POST /device/stop_monitoring_slow_drip host=%s tcp_port=%s duration=%.1fs interval=%.2fs connect_timeout=%.1fs",
host, tcp_port, duration_s, interval_s, connect_timeout,
@@ -1699,6 +1728,7 @@ def device_stop_monitoring_spam(
when it finishes. No streaming; if you want live progress, watch
SFM logs.
"""
# Not identity-checked (phase 1c): it sends only 0x97/0x96, which mean the same on both series (measured 2026-10-25/27), and it must reach a unit too wedged to answer.
log.info(
"POST /device/stop_monitoring_spam host=%s tcp_port=%s duration=%.1fs connect_timeout=%.3fs repeat=%d",
host, tcp_port, duration_s, connect_timeout, repeat,
@@ -1770,6 +1800,7 @@ def device_rescue(
recv_timeout: float = Query(5.0, description="Per-frame S3 recv timeout in seconds (default 5)"),
disable_ach: bool = Query(True, description="Disable Auto Call Home on the device before erasing"),
erase: bool = Query(True, description="Erase all stored events after disabling ACH"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""
Rescue an uncooperative unit by squeezing all maintenance work into a
@@ -1820,6 +1851,11 @@ def device_rescue(
client.poll()
steps.append({"step": "poll", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
if disable_ach or erase:
# One SUB 0x15 read: this route writes call-home and erases.
_require_series3(client.read_serial(), serial)
steps.append({"step": "identify", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
if disable_ach:
client.set_call_home_config(auto_call_home_enabled=False)
steps.append({"step": "disable_ach", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
@@ -1828,6 +1864,8 @@ def device_rescue(
client.delete_all_events()
steps.append({"step": "erase", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2)})
except HTTPException:
raise
except ProtocolError as exc:
steps.append({"step": "error", "ok": False, "detail": f"protocol: {exc}"})
raise HTTPException(status_code=502, detail={"message": f"Protocol error: {exc}", "steps": steps}) from exc
@@ -1903,6 +1941,7 @@ def device_monitor_start(
even_if_already=even_if_already, caller=caller or "api"))
baud = 38400 if baud is None else baud
conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud)
# Legacy branch, not identity-checked: 0x96/0x97 mean the same on both series (measured).
with _build_client(port=port, baud=baud, host=host, tcp_port=tcp_port) as client:
try:
client.poll()
@@ -1968,6 +2007,7 @@ def device_monitor_stop(
even_if_already=even_if_already, caller=caller or "api"))
baud = 38400 if baud is None else baud
conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud)
# Legacy branch, not identity-checked: 0x96/0x97 mean the same on both series (measured).
with _build_client(port=port, baud=baud, host=host, tcp_port=tcp_port) as client:
try:
client.poll()
@@ -2070,6 +2110,7 @@ def device_call_home_set(
baud: int = Query(38400, description="Serial baud rate"),
host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"),
tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"),
serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC),
) -> dict:
"""
Read the current call home config, apply supplied changes, and write back.
@@ -2093,6 +2134,7 @@ def device_call_home_set(
def _do():
with _build_client(port, baud, host, tcp_port) as client:
client.poll()
_require_series3(client.read_serial(), serial) # one SUB 0x15 read
client.set_call_home_config(
auto_call_home_enabled=body.auto_call_home_enabled,
after_event_recorded=body.after_event_recorded,