fix(sfm): any request taking the legacy path is refused beside a held line

The /device guard let every non-UM serial through before its held-line
check.  FastAPI drops an undeclared `serial`, so `?serial=BE18193` on a
legacy route still ran Series-3 code at an address holding a Series-4
line -- the hole the guard exists to close.  Serial-aware routes go
straight to DeviceAccess, which refuses that case itself; everything
else is checked.  baud is no longer parsed (it is not in the address
key, and pydantic's coercion made "38400.0" a second way past).

Also, from the same review:
- RingWatchTransport clears its frame state on every write, so a stray
  STX on an idle line cannot hide the ring that answers the next request.
- Series4Session.is_open reads _client once; held_serial() calls it
  without the unit lock, and a concurrent hang-up between two reads was
  an AttributeError (a 500).

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:58:57 -04:00
1 parent 080e8f4704
commit 278921796a
6 files changed
+71 -11

No files matched your search

+2 -1
View File
@@ -1416,7 +1416,8 @@ POST /device/hangup?host=1.2.3.4&tcp_port=9034 ← release a held Serie
`serial=` (UM = Series 4, BE/BA = Series 3) on `/device/info`, `/connect`,
`/monitor/status`, `/settings` returns the shared model, uncached. A `UM` serial on any
other `/device/*` route is 501; serial-less requests at a held Series-4 address are 409.
other `/device/*` route is 501; any request taking the legacy Series-3 path at a held
Series-4 address is 409.
SFM must run a single uvicorn worker (locks and held lines are per process).
Server retries once on `ProtocolError` for TCP connections (handles cold-boot timing).
+4 -3
View File
@@ -188,9 +188,10 @@ force a fresh read from the device.
Micromate, `BE...`/`BA...` = Series 3 MiniMate Plus) and return one shared model
for either series. Serial-named requests are **not cached** and ignore `force`.
Without `serial` the legacy Series-3 behaviour is unchanged. Any other `/device/*`
route given a `UM` serial answers **501** ("not supported for Series 4 yet"), and a
serial-less request at an address holding a Series-4 line answers **409** (use
`POST /device/hangup` first). Series-4 lines are held open between requests, so
route given a `UM` serial answers **501** ("not supported for Series 4 yet"), and any
request that takes the legacy Series-3 path (no `serial`, or a `BE`/`BA` serial on a
route that does not take one) at an address holding a Series-4 line answers **409**
(use `POST /device/hangup` first). Series-4 lines are held open between requests, so
SFM must run a **single uvicorn worker**: locks and held lines are per process.
**Cache stats** — `GET /cache/stats` returns hit/miss counts and TTL info; `DELETE /cache/device`
+5 -1
View File
@@ -56,6 +56,9 @@ class RingWatchTransport(BaseTransport):
return self._inner.is_connected
def write(self, data: bytes) -> None:
# A request starts a new exchange (MicromateProtocol resets its parser
# here too), so a stray STX on an idle line cannot hide the next ring.
self._in_frame = self._escaped = False
self._inner.write(data)
def read(self, n: int) -> bytes:
@@ -121,7 +124,8 @@ class Series4Session:
@property
def is_open(self) -> bool:
return self._client is not None and self._client.is_open()
client = self._client # one read: held_serial() calls this without the unit lock
return client is not None and client.is_open()
def call_up(self):
client = self._factory(self.address)
+8 -6
View File
@@ -395,16 +395,18 @@ def _device_guard(path: str, query: Mapping[str, str]) -> Optional[tuple]:
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 serial and path in _SERIAL_AWARE_PATHS:
return None # DeviceAccess routes by series and checks held lines itself
if serial.startswith("UM"):
return 501, f"not supported for Series 4 yet: {path}"
# Everything else runs the legacy Series-3 handler -- whatever serial it
# carried, FastAPI drops it -- so it must not reach a held Series-4 line.
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)
# baud is not part of the address key, so it is not parsed here.
addr = _unit_address(query.get("port") or None, None, query.get("host") or None, tcp_port)
except (BadRequest, ValueError):
return None
held = _device_access().held_serial(addr)
+30
View File
@@ -290,3 +290,33 @@ def test_s4_settings_maps_the_decoded_setup():
assert s.detail["mic_type"] == "linear"
assert s.detail["mic_trigger_db"] == pytest.approx(131.0, abs=0.01)
assert s.detail["geo_trigger_ips_per_channel"] == pytest.approx([0.5, 0.5, 0.5], abs=1e-6)
def test_a_new_request_clears_frame_state_left_by_a_stray_stx():
# A stray STX on an idle line would otherwise hide the ring that answers the
# next request. MicromateProtocol resets its own parser at every request too.
t = RingWatchTransport(ScriptedInner([b"\x02stray", b"\r\nRADIO RING\r\n"]))
t.connect()
t.read(64)
t.write(b"x")
with pytest.raises(RingDetected):
t.read(64)
def test_is_open_survives_a_hang_up_between_its_two_reads():
# held_serial() calls is_open without the unit lock; a concurrent hang-up can
# clear _client between the None check and the method call.
class Racy(Series4Session):
_reads = 0
@property
def _client(self):
Racy._reads += 1
return object.__new__(type("C", (), {"is_open": lambda s: True})) if Racy._reads == 1 else None
@_client.setter
def _client(self, value):
pass
s = Racy(ADDR, "UM20147", client_factory=lambda a: None)
assert s.is_open in (True, False)
+22
View File
@@ -135,3 +135,25 @@ def test_guard_ignores_non_device_paths(da):
def test_guard_allows_an_unbuildable_address_through(da):
assert srv._device_guard("/device/monitor/stop", {}) is None
@pytest.mark.parametrize("serial", ["BE18193", "BA1", "nonsense"])
def test_guard_refuses_any_non_um_serial_on_a_legacy_route_at_a_held_address(da, serial):
# FastAPI drops the undeclared serial, so the legacy Series-3 handler would run
# at the held Series-4 address -- the same hole as a serial-less request.
da.status(ADDR, "UM20147")
out = srv._device_guard("/device/events/erase", {"serial": serial, **Q_TCP})
assert out is not None and out[0] == 409 and "UM20147" in out[1]
def test_guard_leaves_serial_aware_routes_to_device_access_at_a_held_address(da):
# DeviceAccess routes by series and refuses a Series-3 serial beside a held line itself.
da.status(ADDR, "UM20147")
assert srv._device_guard("/device/info", {"serial": "BE18193", **Q_TCP}) is None
def test_guard_ignores_an_unparseable_baud_when_checking_for_a_held_line(da):
# baud is not part of the address key; pydantic would coerce "38400.0" and run the handler.
da.status(ADDR, "UM20147")
out = srv._device_guard("/device/monitor/stop", {"baud": "38400.0", **Q_TCP})
assert out is not None and out[0] == 409