diff --git a/minimateplus/client.py b/minimateplus/client.py index 280e266..d595df8 100644 --- a/minimateplus/client.py +++ b/minimateplus/client.py @@ -1212,6 +1212,11 @@ class MiniMateClient: log.debug("poll: startup handshake") proto.startup() + def read_serial(self) -> str: + """The unit's own serial (SUB 0x15), on an open, polled session. The + cheap identity read the legacy write routes check before writing.""" + return _decode_serial_number(self._require_proto().read(SUB_SERIAL_NUMBER)).serial + def wake(self, attempt_s: float = 5.0, deadline_s: float = 60.0) -> None: """SESSION_RESET + POLL, re-sent until the unit answers (see MiniMateProtocol.wake) -- for a unit that may be busy, e.g. sensor-checking diff --git a/sfm/server.py b/sfm/server.py index e1d39d1..519789e 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -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, diff --git a/tests/test_server_series3_guard.py b/tests/test_server_series3_guard.py new file mode 100644 index 0000000..a52ef91 --- /dev/null +++ b/tests/test_server_series3_guard.py @@ -0,0 +1,181 @@ +"""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; the +legacy host/port routes had no identity check, so nothing but a MiniMate parser +that cannot read a Micromate's replies stood between Diagnostics' Erase and a +Micromate. Each guarded route now reads -- or reuses -- the unit's own serial and +refuses (409) before its first write unless that serial is Series 3 and, when one +was named, the named one. The stop-only tools are exempt: 0x96/0x97 mean the +same on both series, and they must reach a unit too wedged to answer. +""" +from __future__ import annotations + +import os +import sys +from types import SimpleNamespace + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from fastapi import HTTPException # noqa: E402 + +import sfm.server as srv # noqa: E402 + +WRITES = {"delete_all_events", "apply_config", "set_call_home_config", "stop_monitoring"} +ADDR = dict(port=None, baud=38400, host="10.0.0.9", tcp_port=9034) + + +class Unit: + """A unit that answers as `serial`; records every client call.""" + + def __init__(self, serial): + self.serial, self.calls = serial, [] + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def _rec(self, name): + self.calls.append(name) + + def connect(self): + self._rec("connect") + return SimpleNamespace(serial=self.serial) + + def poll(self): + self._rec("poll") + + def read_serial(self): + self._rec("read_serial") + return self.serial + + def delete_all_events(self): + self._rec("delete_all_events") + + def apply_config(self, **kw): + self._rec("apply_config") + + def set_call_home_config(self, **kw): + self._rec("set_call_home_config") + + +class Cache: + def clear_device(self, key): + return 0 + + def mark_config_dirty(self, key): + pass + + +def _call(route, serial): + if route == "config": + return srv.device_config(body=srv.DeviceConfigBody(), serial=serial, **ADDR) + if route == "erase": + return srv.device_events_erase(serial=serial, **ADDR) + if route == "rescue": + return srv.device_rescue(connect_timeout=5.0, recv_timeout=5.0, disable_ach=True, + erase=True, serial=serial, **ADDR) + if route == "call_home": + return srv.device_call_home_set(body=srv.CallHomeConfigBody(auto_call_home_enabled=False), + serial=serial, **ADDR) + raise AssertionError(route) + + +@pytest.fixture +def unit(monkeypatch): + holder = {} + + def make(serial): + u = Unit(serial) + holder["u"] = u + monkeypatch.setattr(srv, "_build_client", lambda *a, **kw: u) + monkeypatch.setattr(srv, "get_cache", lambda: Cache()) + return u + return make + + +ROUTES = ["config", "erase", "rescue", "call_home"] + + +@pytest.mark.parametrize("route", ROUTES) +def test_guarded_route_refuses_a_unit_that_answers_as_series4(unit, route): + u = unit("UM20147") + with pytest.raises(HTTPException) as e: + _call(route, None) + assert e.value.status_code == 409 + assert "not a Series-3 unit" in str(e.value.detail) + assert not WRITES & set(u.calls), u.calls + + +@pytest.mark.parametrize("route", ROUTES) +def test_guarded_route_refuses_a_different_series3_unit(unit, route): + u = unit("BE9441") + with pytest.raises(HTTPException) as e: + _call(route, "BE12599") + assert e.value.status_code == 409 + assert "not BE12599" in str(e.value.detail) + assert not WRITES & set(u.calls), u.calls + + +@pytest.mark.parametrize("route", ROUTES) +def test_guarded_route_proceeds_for_the_named_series3_unit(unit, route): + u = unit("BE9441") + _call(route, "be9441 ") + assert len(WRITES & set(u.calls)) >= 1 + assert u.calls.index(next(c for c in u.calls if c in WRITES)) > \ + max(i for i, c in enumerate(u.calls) if c in ("connect", "read_serial")) + + +def test_the_identity_check_reuses_connects_serial_where_there_is_one(unit): + # speed: config and erase already read the serial in connect(); no extra read + for route in ("config", "erase"): + u = unit("BE9441") + _call(route, None) + assert "read_serial" not in u.calls + + +def test_unguarded_stop_routes_send_without_an_identity_read(monkeypatch): + sent = [] + + class Transport: + def __init__(self, *a, **kw): + pass + + def connect(self): + pass + + def write(self, data): + sent.append(bytes(data)) + + def disconnect(self): + pass + + def no_client(*a, **kw): + raise AssertionError("the blind stop must not build a client") + monkeypatch.setattr(srv, "TcpTransport", Transport) + monkeypatch.setattr(srv, "_build_client", no_client) + monkeypatch.setattr(srv.time, "sleep", lambda s: None) + srv.device_stop_monitoring_blind(host="10.0.0.9", tcp_port=9034, connect_timeout=5.0, repeat=1) + assert sent and all(b"\x97" in s for s in sent) + + +def test_read_serial_decodes_the_units_own_reply(): + # BE9441's SUB 0x15 reply, recorded 2026-10-26 through the bridge + from pathlib import Path + from minimateplus.client import MiniMateClient + from minimateplus.framing import S3FrameParser + raw = (Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram" + / "unit_replies.bin").read_bytes() + reply = next(f for f in S3FrameParser().feed(raw) if f.sub == 0xEA and len(f.data) > 12) + + class Proto: + def read(self, sub): + assert sub == 0x15 + return reply.data + c = MiniMateClient(transport=object()) + c._proto = Proto() + assert c.read_serial() == "BE9441"