fix(sfm): one guard in front of every /device route -- UM serials 501 off the serial-aware routes, held lines 409 serial-less requests

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-21 01:44:35 -04:00
1 parent 6dd34f8fd7
commit 82b91835fb
4 files changed
+109 -1

No files matched your search

+8
View File
@@ -56,6 +56,14 @@ class DeviceAccess:
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
return self._dispatch(address, serial, self._s3.settings, s4_settings)
def held_serial(self, address: UnitAddress) -> Optional[str]:
"""Serial of the OPEN held Series-4 line at this address, else None. No I/O."""
with self._sessions_guard:
session = self._sessions.get(address.key)
if session is not None and session.is_open:
return session.serial
return None
def hang_up(self, address: UnitAddress) -> bool:
with self._locks.hold(address.key):
with self._sessions_guard:
+46 -1
View File
@@ -50,7 +50,7 @@ import tempfile
import threading
import time
from pathlib import Path
from typing import Optional
from typing import Mapping, Optional
# FastAPI / Pydantic
try:
@@ -84,6 +84,8 @@ from sfm.waveform_store import WaveformStore
from sfm import db_snapshot
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
logging.basicConfig(
level=logging.INFO,
@@ -379,6 +381,49 @@ def _via_device_access(fn) -> dict:
return dataclasses.asdict(result) if dataclasses.is_dataclass(result) else result
_SERIAL_AWARE_PATHS = frozenset({
"/device/info", "/device/connect", "/device/monitor/status", "/device/settings",
})
def _device_guard(path: str, query: Mapping[str, str]) -> Optional[tuple]:
"""Refuse a /device/* request that would reach the wrong series' code.
FastAPI drops query params a route does not declare, so `?serial=UM...` on
a Series-3 route would silently run Series-3 bytes against a Micromate
(0xA2 is CONFIRM ERASE there). Returns (status, detail) to refuse, or None.
/device/hangup is always allowed: it must always be able to release a line.
"""
if not path.startswith("/device/") or path == "/device/hangup":
return None
serial = normalise_serial(query.get("serial") or "")
if serial:
if serial.startswith("UM") and path not in _SERIAL_AWARE_PATHS:
return 501, f"not supported for Series 4 yet: {path}"
return None
if not (query.get("host") or query.get("port")):
return None
try:
tcp_port = int(query.get("tcp_port") or DEFAULT_TCP_PORT)
baud = int(query["baud"]) if query.get("baud") else None
addr = _unit_address(query.get("port") or None, baud, query.get("host") or None, tcp_port)
except (BadRequest, ValueError):
return None
held = _device_access().held_serial(addr)
if held is not None:
return 409, (f"a Series-4 line to {held} is held at {addr.key}; "
"POST /device/hangup first")
return None
@app.middleware("http")
async def _device_guard_middleware(request, call_next):
refusal = _device_guard(request.url.path, request.query_params)
if refusal is not None:
return JSONResponse(status_code=refusal[0], content={"detail": refusal[1]})
return await call_next(request)
_SERIAL_DOC = "Unit serial -- UM... (Series 4) or BE.../BA... (Series 3). Returns the shared model."
+10
View File
@@ -221,3 +221,13 @@ def test_both_series_return_the_same_model_with_the_same_fields(op):
a, b = getattr(s3, name), getattr(s4, name)
if a is not None and b is not None and name != "detail":
assert type(a) is type(b) or {type(a), type(b)} <= {int, float}, name
def test_held_serial_reports_an_open_line_only():
fake = FakeMicromateClient()
da = access(s4=[fake])
assert da.held_serial(ADDR) is None
da.status(ADDR, "UM20147")
assert da.held_serial(ADDR) == "UM20147"
da.hang_up(ADDR)
assert da.held_serial(ADDR) is None
+45
View File
@@ -90,3 +90,48 @@ def test_without_a_serial_the_legacy_path_runs_unchanged(monkeypatch):
monkeypatch.setattr(srv, "get_cache", lambda: Cache())
out = srv.device_info(force=False, serial=None, **TCP)
assert out == {"serial": "BE18193", "firmware_version": "S338.17", "_cached": True}
# ── the /device/* guard ───────────────────────────────────────────────────────
from sfm.device_access.models import UnitAddress # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
Q_TCP = {"host": "10.0.0.5", "tcp_port": "9034"}
@pytest.mark.parametrize("path", ["/device/events/erase", "/device/monitor/stop", "/device/config"])
def test_guard_refuses_a_um_serial_on_unsupported_routes_with_501(path):
out = srv._device_guard(path, {"serial": "um20147", **Q_TCP})
assert out is not None and out[0] == 501 and path in out[1]
def test_guard_lets_a_series3_serial_through_on_legacy_routes():
assert srv._device_guard("/device/events/erase", {"serial": "BE18193", **Q_TCP}) is None
@pytest.mark.parametrize("path", ["/device/info", "/device/connect",
"/device/monitor/status", "/device/settings",
"/device/hangup"])
def test_guard_allows_um_serial_on_serial_aware_routes_and_hangup(path):
assert srv._device_guard(path, {"serial": "UM20147", **Q_TCP}) is None
def test_guard_refuses_serialless_requests_at_a_held_address_with_409(da):
da.status(ADDR, "UM20147")
out = srv._device_guard("/device/monitor/stop", dict(Q_TCP))
assert out is not None and out[0] == 409
assert "UM20147" in out[1] and "tcp:10.0.0.5:9034" in out[1] and "hangup" in out[1]
def test_guard_allows_serialless_requests_at_an_unheld_address(da):
assert srv._device_guard("/device/monitor/stop", dict(Q_TCP)) is None
assert srv._device_guard("/device/monitor/stop", {"host": "10.9.9.9"}) is None
def test_guard_ignores_non_device_paths(da):
assert srv._device_guard("/db/events", {"serial": "UM20147", **Q_TCP}) is None
def test_guard_allows_an_unbuildable_address_through(da):
assert srv._device_guard("/device/monitor/stop", {}) is None