diff --git a/src/commander/server.py b/src/commander/server.py index 9b1dd9ed..ed98e300 100644 --- a/src/commander/server.py +++ b/src/commander/server.py @@ -21,7 +21,7 @@ import time from urllib.parse import urlsplit from src.commander.assets import static_assets -from src.commander.web_auth import WebHostAuth +from src.commander.web_auth import FailureLimiter, WebHostAuth from src.core.config import SHIP_SPEED_MAX_KN from src.commander.missions import MissionLibraryServerMixin @@ -200,7 +200,12 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, self._running = False self._code_index = None self._rotate_code_locked() - self._pair_failures = deque() + # Wrong pairing codes per source address (one stranger never locks out + # the crew) and, on the LAN listener only, all of them together: five + # within 60 s rotate the code there. The web-host room never rotates + # on anonymous failures (its code is handed out by the host). + self._pair_failures = FailureLimiter() + self._pair_code_failures = deque() self._sessions_v2 = {} self._solo = False self._next_v2_ordinal = 0 @@ -264,6 +269,7 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, self._v2_states = {role: _json_bytes(unpublished) for role in (None, *ROLES)} self._v2_sonar_compact_state = self._v2_states["sonar"] + self._v2_state_heads = {role: ("unpublished", 0) for role in (None, *ROLES)} self._v2_charts = {role: _json_bytes(empty_chart) for role in (None, *ROLES)} supplied = {} if contact_analysis_assets is None else contact_analysis_assets @@ -439,6 +445,22 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, self._expire_locked() return self._running and bool(self._sessions_v2) + def _record_pair_failure_locked(self, source): + """Count a wrong pairing code against its source address. + + On the LAN listener five wrong codes in 60 s from anyone rotate the + code (brute-force guard, as before). The web-host room keeps its code: + rotating it on anonymous failures would let a stranger on the public + proxy invalidate the code the host has handed to the crew. + """ + self._pair_failures.record(source) + if self.web_auth is not None: + return + self._pair_code_failures.append(time.monotonic()) + if len(self._pair_code_failures) >= 5: + self._pair_code_failures.clear() + self._rotate_code_locked() + def _rotate_code_locked(self): # Draw uniformly from the entire format space except the predecessor, # skipping its index instead of retrying a possible collision. @@ -563,11 +585,16 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, if candidate.session is session), None) if peer is not None: self._voice_disconnect_locked(peer) - if "sonar" in (session["active_station"], station): + # The audio ring belongs to the lease holder of its station. Only that + # session switching to or from it restarts the stream; an observer (or + # any session without the lease) looking at the station must never cut + # the real operator's live audio. + switched = (session["active_station"], station) + if "sonar" in switched and "sonar" in session["leases"]: self._clear_sonar_audio_locked() - if "helicopter" in (session["active_station"], station): + if "helicopter" in switched and "helicopter" in session["leases"]: self._clear_helicopter_audio_locked() - if "uboot_sonar" in (session["active_station"], station): + if "uboot_sonar" in switched and "uboot_sonar" in session["leases"]: self._clear_uboot_audio_locked() session["active_station"] = station session["active_generation"] += 1 @@ -703,8 +730,8 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, def _expire_locked(self): now = time.monotonic() - while self._pair_failures and now - self._pair_failures[0] >= 60.0: - self._pair_failures.popleft() + while self._pair_code_failures and now - self._pair_code_failures[0] >= 60.0: + self._pair_code_failures.popleft() for digest, session in tuple(self._sessions_v2.items()): if now - session["last_get"] >= _V2_SESSION_IDLE_S: self._clear_session_authority_locked(session) @@ -980,6 +1007,7 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, with self._lock: self._revoke_locked(rotate_code=True) self._pair_failures.clear() + self._pair_code_failures.clear() @property def solo_mode(self) -> bool: @@ -1014,6 +1042,7 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, self._solo = enabled self._revoke_locked(rotate_code=True) self._pair_failures.clear() + self._pair_code_failures.clear() @staticmethod def _solo_grants(station): @@ -1258,7 +1287,24 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, def apply_command_v2(self, envelope, *, now, phase, world_session, world_epoch, resource_revision, apply): - """Revalidate and complete one command atomically on the caller's thread.""" + """Revalidate, apply and complete one command on the main thread. + + Three steps. (1) Under the lock: revalidate the exact origin (client, + role, lease and active generation, grants, age, phase, world session, + epoch, revision). The envelope is already detached by + ``drain_commands_v2``, so it is claimed by this call alone. (2) Without + the lock: ``apply`` (a host load/new game/save can take seconds; every + transport thread keeps serving meanwhile). Only the main thread + mutates the world, phase, epoch and revision, and this is the main + thread, so nothing checked in (1) about the world can change before + ``apply`` runs. Transport threads may revoke a lease or grant during + ``apply``; that revocation is ordered after this command, exactly as if + it had arrived a moment later under the old single lock section + (stale queued commands are still rejected by the revocation itself). + (3) Under the lock again: record the result once. ``_finish_v2_locked`` + refuses a second result for the same command id, so exactly-once + holds even if the session was revoked in between. + """ if threading.current_thread() is not threading.main_thread(): raise RuntimeError("v2 commands require the main thread") if type(envelope) is not V2CommandEnvelope or not callable(apply): @@ -1272,6 +1318,9 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, if (session is None or session.get("client_id") != envelope.client_id or session.get("ordinal") != envelope.client_ordinal): return False + entry = session["command_ids"].get(envelope.command_id) + if entry is None or entry[0] != envelope.body_bytes or entry[1] is not None: + return False # already completed (or never accepted): never twice is_host = envelope.role == HOST_ROLE if not _v2_command_valid(body) or spec is None: reason = "invalid_schema" @@ -1313,32 +1362,36 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, # Host controls are never revision-bound: they reference no resource. reason = "revision_conflict" else: - try: - applied = apply(body["action"], dict(body["params"])) - except Exception as exc: - # Never log params/credentials/client addresses; type + action name only. - _log.warning("command apply failed: %s (%s)", - body["action"], type(exc).__name__) - applied = False - reason = ("ok" if applied is True or applied == "ok" else applied - if type(applied) is str and applied in { - "bridge_down", "sonar_down", "opz_down", - "engine_down", "radio_down", "flightdeck_down", - "invalid_value", "phase_blocked", "unknown_ref", - "stale_ref", "source_owned", "fusion_rejected", - "ineligible_track", "proposal_pending", - "not_ready", "no_solution", "no_buoys", - "water_required", "tas_fault", "invalid_target", - "roe_blocked", "not_located", "not_classified", - "salvo_limit", "empty", "no_tube", - "weapons_down", "weapons_degraded", "out_of_range", - "opz_degraded", "active_limit", "no_fuel", - "weather_unsafe", "no_save", "save_failed", - "no_mission", "mission_rejected", - "lookout_not_confirmed", "no_consort", "consort_lost", - "no_link", "stale_fix", "busy", "no_weapon", "no_track", - *UBOOT_REASONS} - else "action_rejected") + reason = None # validated: apply below, outside the lock + if reason is not None: + return self._finish_v2_locked(session, envelope, "rejected", reason) + try: + applied = apply(body["action"], dict(body["params"])) + except Exception as exc: + # Never log params/credentials/client addresses; type + action name only. + _log.warning("command apply failed: %s (%s)", + body["action"], type(exc).__name__) + applied = False + reason = ("ok" if applied is True or applied == "ok" else applied + if type(applied) is str and applied in { + "bridge_down", "sonar_down", "opz_down", + "engine_down", "radio_down", "flightdeck_down", + "invalid_value", "phase_blocked", "unknown_ref", + "stale_ref", "source_owned", "fusion_rejected", + "ineligible_track", "proposal_pending", + "not_ready", "no_solution", "no_buoys", + "water_required", "tas_fault", "invalid_target", + "roe_blocked", "not_located", "not_classified", + "salvo_limit", "empty", "no_tube", + "weapons_down", "weapons_degraded", "out_of_range", + "opz_degraded", "active_limit", "no_fuel", + "weather_unsafe", "no_save", "save_failed", + "no_mission", "mission_rejected", + "lookout_not_confirmed", "no_consort", "consort_lost", + "no_link", "stale_fix", "busy", "no_weapon", "no_track", + *UBOOT_REASONS} + else "action_rejected") + with self._lock: return self._finish_v2_locked( session, envelope, "applied" if reason == "ok" else "rejected", reason) @@ -1355,6 +1408,9 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, or set(states) != expected or set(charts) != expected): raise ValueError("invalid v2 publication") encoded_states, encoded_charts = {}, {} + # (world session, epoch) per role, kept beside the encoded state so the + # proposal/event/SimLog polls never re-parse a state of up to 512 KiB. + heads = {} compact_sonar = None # Roles with identical visibility share one chart object, so it is # serialised once per publication instead of once per role. @@ -1383,6 +1439,7 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, if len(state_bytes) > STATE_MAX_BYTES or len(chart_bytes) > CHART_MAX_BYTES: raise ValueError("v2 publication size limit exceeded") encoded_states[role], encoded_charts[role] = state_bytes, chart_bytes + heads[role] = (state["session"], state["epoch"]) if (role == "sonar" and state.get("role") == "sonar" and isinstance(state.get("sonar"), dict) and isinstance(state["sonar"].get("visualization"), dict)): @@ -1399,6 +1456,7 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, dict(state, sonar=dict(state["sonar"], visualization=visual))) with self._lock: self._v2_states = encoded_states + self._v2_state_heads = heads self._v2_charts = encoded_charts self._v2_sonar_compact_state = compact_sonar or encoded_states["sonar"] self._sonar_stream_sequence += 1 @@ -1558,9 +1616,11 @@ class CommanderServer(AudioStreamServerMixin, StationLeaseServerMixin, role = session["active_station"] merged = sorted(events_by_role[role] + rows, key=lambda row: row["seq"])[-EVENTS_MAX:] - encoded_private[digest] = _json_bytes({ + # Stored with its role: the poll serves it only to that role + # without re-parsing the document. + encoded_private[digest] = (role, _json_bytes({ "protocol": 2, "session": world_session, "epoch": world_epoch, - "role": role, "latest_seq": latest_seq, "events": merged}) + "role": role, "latest_seq": latest_seq, "events": merged})) self._v2_events = base self._v2_private_events = encoded_private self._v2_events_fingerprint = fingerprint diff --git a/src/commander/v2/routes.py b/src/commander/v2/routes.py index 16a13e84..6342a28d 100644 --- a/src/commander/v2/routes.py +++ b/src/commander/v2/routes.py @@ -482,6 +482,26 @@ class _Handler(BaseHTTPRequestHandler): or self.headers.get("Origin") == owner.public_origin or self.headers.get("Host") in self.server.public_hosts) + def _source_address(self): + """The address failed logins and pairings are counted against. + + The socket peer, unless ``--public-origin`` names a reverse proxy: then + the rightmost ``X-Forwarded-For`` entry, the one that proxy appended + (entries further left are client-supplied). A missing or malformed + header falls back to the peer, never to a shared bucket. + """ + peer = str(self.client_address[0]) if self.client_address else "" + if self.server.owner.public_origin is None: + return peer + forwarded = self.headers.get("X-Forwarded-For") + if type(forwarded) is not str or len(forwarded) > 1024: + return peer + candidate = forwarded.rsplit(",", 1)[-1].strip() + try: + return "fwd:" + str(ipaddress.ip_address(candidate)) + except ValueError: + return peer + def _v2_cookie(self, token): # Secure only on the HTTPS path: a browser drops a Secure cookie that # arrives over the plain-HTTP LAN address. @@ -1046,22 +1066,23 @@ class _Handler(BaseHTTPRequestHandler): body = (owner._v2_proposals.get((digest, role)) if role is not None else None) if body is None and role is not None: - state = json.loads(owner._v2_states[role].decode("ascii")) + # The small head stored at publish time; the full + # role state (up to 512 KiB) is never re-parsed. + world, epoch = owner._v2_state_heads[role] body = _json_bytes({"protocol": 2, - "session": state["session"], "epoch": state["epoch"], + "session": world, "epoch": epoch, "role": role, "target": None, "navigation": None}) elif session is not None and self.path == "/api/v2/events": cached = (owner._v2_private_events.get(digest) if role is not None else None) - if cached is not None and json.loads( - cached.decode("ascii")).get("role") == role: - body = cached + if cached is not None and cached[0] == role: + body = cached[1] elif role is not None: body = owner._v2_events.get(role) if body is None and role is not None: - state = json.loads(owner._v2_states[role].decode("ascii")) + world, epoch = owner._v2_state_heads[role] body = _json_bytes({"protocol": 2, - "session": state["session"], "epoch": state["epoch"], + "session": world, "epoch": epoch, "role": role, "latest_seq": 0, "events": []}) elif session is not None and self.path == "/api/v2/debrief": # Only after the mission ends, and only the own side's. @@ -1075,9 +1096,9 @@ class _Handler(BaseHTTPRequestHandler): body = (owner._v2_simlogs.get(role) if role is not None and session["simlog"] else None) if body is None and role is not None and session["simlog"]: - state = json.loads(owner._v2_states[role].decode("ascii")) + world, epoch = owner._v2_state_heads[role] body = _json_bytes({"protocol": 2, - "session": state["session"], "epoch": state["epoch"], + "session": world, "epoch": epoch, "role": role, "entries": []}) except (UnicodeEncodeError, ValueError): self.send_error(400) @@ -1112,38 +1133,48 @@ class _Handler(BaseHTTPRequestHandler): owner = self.server.owner status, response = 404, {"error": "not_found"} audio_reply = None + # The web host's password check (scrypt, 16 MiB and noticeable CPU) + # runs before the global lock: a stranger's login attempt must never + # stall the main thread or any stream. WebHostAuth has its own lock + # and counts failures per source address. + if owner.web_auth is not None and self.path == "/api/v2/web/setup": + if (type(body) is not dict or set(body) != {"code", "password"} + or type(body["code"]) is not str + or type(body["password"]) is not str): + status, response = 400, {"error": "invalid_request"} + elif owner.web_auth.configured: + status, response = 409, {"error": "already_configured"} + elif owner.web_auth.setup(body["code"], body["password"], + self._source_address()): + status, response = 200, {"status": "configured"} + else: + status, response = 403, {"error": "setup_failed"} + self._reply(status, response) + return + if owner.web_auth is not None and self.path == "/api/v2/web/login": + if (type(body) is not dict or set(body) != {"password"} + or type(body["password"]) is not str): + self._reply(400, {"error": "invalid_request"}) + return + if not owner.web_auth.verify(body["password"], self._source_address()): + self._reply(403, {"error": "invalid_credentials"}) + return + with owner._lock: + owner._expire_locked() + old = owner._sessions_v2.pop(owner._web_host_digest, None) + if old is not None: + owner._clear_session_authority_locked(old) + owner._web_admin_queue.clear() + owner._web_admin_inflight.clear() + owner._web_admin_seen.clear() + owner._web_admin_results.clear() + token, session = owner._new_session_locked("Host", web_host=True) + reply = self._session_v2_body(session, owner._sessions_v2, owner) + self._reply(200, reply, set_cookie=self._v2_cookie(token)) + return with owner._lock: owner._expire_locked() - if owner.web_auth is not None and self.path == "/api/v2/web/setup": - if (type(body) is not dict or set(body) != {"code", "password"} - or type(body["code"]) is not str - or type(body["password"]) is not str): - status, response = 400, {"error": "invalid_request"} - elif owner.web_auth.configured: - status, response = 409, {"error": "already_configured"} - elif owner.web_auth.setup(body["code"], body["password"]): - status, response = 200, {"status": "configured"} - else: - status, response = 403, {"error": "setup_failed"} - elif owner.web_auth is not None and self.path == "/api/v2/web/login": - if (type(body) is not dict or set(body) != {"password"} - or type(body["password"]) is not str): - status, response = 400, {"error": "invalid_request"} - elif not owner.web_auth.verify(body["password"]): - status, response = 403, {"error": "invalid_credentials"} - else: - old = owner._sessions_v2.pop(owner._web_host_digest, None) - if old is not None: - owner._clear_session_authority_locked(old) - owner._web_admin_queue.clear() - owner._web_admin_inflight.clear() - owner._web_admin_seen.clear() - owner._web_admin_results.clear() - token, session = owner._new_session_locked("Host", web_host=True) - self._reply(200, self._session_v2_body(session, owner._sessions_v2, owner), - set_cookie=self._v2_cookie(token)) - return - elif owner.web_auth is not None and self.path == "/api/v2/web/admin": + if owner.web_auth is not None and self.path == "/api/v2/web/admin": try: session, digest, presented = self._authenticated_v2_locked(renew=True) except (UnicodeEncodeError, ValueError): @@ -1221,7 +1252,7 @@ class _Handler(BaseHTTPRequestHandler): elif self.path == "/api/v2/pair": if not owner._running: status, response = 503, {"error": "unavailable"} - elif len(owner._pair_failures) >= 5: + elif not owner._pair_failures.allowed(self._source_address()): status, response = 429, {"error": "pairing_rate_limited"} elif (not isinstance(body, dict) or body.keys() not in ({"code", "name"}, {"code", "name", "role"}) @@ -1239,9 +1270,7 @@ class _Handler(BaseHTTPRequestHandler): elif not secrets.compare_digest( body["code"].encode("utf-8", errors="surrogatepass"), owner._code.encode("ascii")): - owner._pair_failures.append(time.monotonic()) - if len(owner._pair_failures) == 5: - owner._rotate_code_locked() + owner._record_pair_failure_locked(self._source_address()) status, response = 403, {"error": "invalid_code"} else: token, session = owner._new_session_locked( diff --git a/src/commander/web_auth.py b/src/commander/web_auth.py index 9db17424..8c18a1f9 100644 --- a/src/commander/web_auth.py +++ b/src/commander/web_auth.py @@ -10,7 +10,63 @@ from pathlib import Path import secrets import stat import tempfile +import threading import time +from collections import deque + + +class FailureLimiter: + """Failed attempts per source address in a sliding window, bounded. + + One stranger's failures never lock out another address. The table holds at + most ``max_sources`` addresses; while it is full a source that is not in it + yet is refused (fail closed) until entries age out of the window, so many + addresses cannot wash out the record of one. Thread-safe on its own lock. + """ + + def __init__(self, limit=5, window_s=60.0, max_sources=256): + self.limit = limit + self.window_s = window_s + self.max_sources = max_sources + self._lock = threading.Lock() + self._failures: dict[str, deque] = {} + + def _prune(self, now): + for source in tuple(self._failures): + times = self._failures[source] + while times and now - times[0] >= self.window_s: + times.popleft() + if not times: + del self._failures[source] + + def allowed(self, source: str) -> bool: + with self._lock: + self._prune(time.monotonic()) + times = self._failures.get(source) + if times is None: + return len(self._failures) < self.max_sources + return len(times) < self.limit + + def record(self, source: str) -> int: + """Count one failure; returns that source's failures in the window.""" + with self._lock: + now = time.monotonic() + self._prune(now) + times = self._failures.get(source) + if times is None: + if len(self._failures) >= self.max_sources: + return self.limit + times = self._failures[source] = deque(maxlen=self.limit) + times.append(now) + return len(times) + + def clear(self): + with self._lock: + self._failures.clear() + + def __len__(self): + with self._lock: + return len(self._failures) class WebHostAuth: @@ -18,7 +74,11 @@ class WebHostAuth: self.path = Path(path) self.setup_code = secrets.token_urlsafe(24) self.setup_deadline = time.monotonic() + 900 - self.failures: list[float] = [] + # Failed setup/login attempts per source address (routes._source_address). + self.failures = FailureLimiter() + # Guards the record and the setup secret. A login's slow scrypt runs + # outside it and always outside the server's global lock. + self._lock = threading.Lock() self.record = self._read() def _read(self): @@ -44,44 +104,44 @@ class WebHostAuth: def configured(self): return self.record is not None - def _allowed(self): - now = time.monotonic() - self.failures = [value for value in self.failures if now - value < 60] - return len(self.failures) < 5 - - def _failure(self): - self.failures.append(time.monotonic()) - - def setup(self, code: str, password: str): - if self.configured or not self._allowed(): + def setup(self, code: str, password: str, source: str = ""): + if self.configured or not self.failures.allowed(source): return False - if (time.monotonic() > self.setup_deadline or type(code) is not str - or not hmac.compare_digest(code, self.setup_code)): - self._failure() - return False - if type(password) is not str or not 12 <= len(password) <= 256: - return False - salt = secrets.token_bytes(16) - digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, - n=2**14, r=8, p=1, dklen=64) - record = {"version": 1, "salt": salt.hex(), "hash": digest.hex()} - self._write(record) - self.record = record - self.setup_code = "" - return True + # One-time flow: the auth lock (never the server lock) makes the + # check-and-set atomic against a second concurrent setup. + with self._lock: + if self.record is not None: + return False + if (time.monotonic() > self.setup_deadline or type(code) is not str + or not self.setup_code + or not hmac.compare_digest(code, self.setup_code)): + self.failures.record(source) + return False + if type(password) is not str or not 12 <= len(password) <= 256: + return False + salt = secrets.token_bytes(16) + digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, + n=2**14, r=8, p=1, dklen=64) + record = {"version": 1, "salt": salt.hex(), "hash": digest.hex()} + self._write(record) + self.record = record + self.setup_code = "" + return True - def verify(self, password: str): - if not self.configured or not self._allowed(): + def verify(self, password: str, source: str = ""): + with self._lock: + record = self.record + if record is None or not self.failures.allowed(source): return False if type(password) is not str or len(password) > 256: - self._failure() + self.failures.record(source) return False digest = hashlib.scrypt(password.encode("utf-8"), - salt=bytes.fromhex(self.record["salt"]), + salt=bytes.fromhex(record["salt"]), n=2**14, r=8, p=1, dklen=64) - ok = hmac.compare_digest(digest, bytes.fromhex(self.record["hash"])) + ok = hmac.compare_digest(digest, bytes.fromhex(record["hash"])) if not ok: - self._failure() + self.failures.record(source) return ok def reset_local(self): @@ -92,9 +152,10 @@ class WebHostAuth: self.path.unlink() except FileNotFoundError: pass - self.record = None - self.setup_code = secrets.token_urlsafe(24) - self.setup_deadline = time.monotonic() + 900 + with self._lock: + self.record = None + self.setup_code = secrets.token_urlsafe(24) + self.setup_deadline = time.monotonic() + 900 self.failures.clear() def _write(self, record): diff --git a/tests/test_commander_lock_scope.py b/tests/test_commander_lock_scope.py new file mode 100644 index 00000000..8f31c7d2 --- /dev/null +++ b/tests/test_commander_lock_scope.py @@ -0,0 +1,250 @@ +"""Remote Crew lock scope and per-source rate limits (audit 2026-10-03, C8-C11). + +Slow work (host commands, scrypt) never runs under the server's global lock, +polls never re-parse the full role state, failed logins and pairings are +counted per source address, and an observer never cuts an operator's audio. +""" + +from contextlib import closing +import http.client +import json +import threading +import time + +from src.commander import web_auth as web_auth_module +from src.commander.server import CommanderServer +from src.commander.web_auth import FailureLimiter, WebHostAuth +from test_commander_commands_v2 import command, pair, post, results, server # noqa: F401 +from test_commander_sessions_v2 import pair_v2, request as session_request + +PASSWORD = "a long private password" + + +def _lock_free_from_another_thread(lock): + """True when a thread other than the caller can take ``lock`` now.""" + outcome = [] + + def probe(): + acquired = lock.acquire(timeout=1.0) + outcome.append(acquired) + if acquired: + lock.release() + + worker = threading.Thread(target=probe) + worker.start() + worker.join(2.0) + return outcome == [True] + + +# C8 ------------------------------------------------------------------------- + +def test_apply_runs_outside_the_global_lock_and_completes_exactly_once(server): + cookie, session = pair(server, "Sonar", "sonar") + assert post(server, cookie, session, command(session, command_id="slow"))[0] == 202 + envelope = server.drain_commands_v2()[0] + calls = [] + + def apply(action, params): + # A transport thread (poll, push, audio, pairing) can take the lock + # while the command runs, and may even revoke the station meanwhile. + calls.append(_lock_free_from_another_thread(server._lock)) + revoker = threading.Thread(target=server.revoke_station, args=("sonar",)) + revoker.start() + revoker.join(2.0) + return True + + assert server.apply_command_v2( + envelope, now=time.monotonic(), phase="live", world_session="world", + world_epoch=3, resource_revision=5, apply=apply) + assert calls == [True] + # Recorded once; a second application of the same envelope is refused + # without calling apply again. + assert not server.apply_command_v2( + envelope, now=time.monotonic(), phase="live", world_session="world", + world_epoch=3, resource_revision=5, apply=lambda *_: calls.append("again")) + assert calls == [True] + rows = [row for row in results(server, cookie) if row["id"] == "slow"] + assert [(row["status"], row["reasoncode"]) for row in rows] == [("applied", "ok")] + + +def test_rejected_command_never_reaches_apply(server): + cookie, session = pair(server, "Sonar", "sonar") + assert post(server, cookie, session, command(session, command_id="stale"))[0] == 202 + envelope = server.drain_commands_v2()[0] + calls = [] + assert server.apply_command_v2( + envelope, now=time.monotonic(), phase="live", world_session="world", + world_epoch=4, resource_revision=5, apply=lambda *_: calls.append(1)) + assert calls == [] + rows = [row for row in results(server, cookie) if row["id"] == "stale"] + assert [(row["status"], row["reasoncode"]) for row in rows] == [ + ("rejected", "stale_world_epoch")] + + +# C9 ------------------------------------------------------------------------- + +def test_polls_use_the_stored_head_and_never_parse_the_role_state(server): + _, cookie, _, paired = pair_v2(server, "Sonar") + assert server.grant_station(paired["client_id"], "sonar") + assert server.set_client_grant(paired["client_id"], "simlog", True) + with server._lock: + # Not JSON at all: a route that re-parsed it would fail with 400. + server._v2_states["sonar"] = b"\xff not json" + server._v2_state_heads["sonar"] = ("head-world", 7) + for path, extra in (("/api/v2/proposals", {"target": None, "navigation": None}), + ("/api/v2/events", {"latest_seq": 0, "events": []}), + ("/api/v2/simlog", {"entries": []})): + status, _, body = session_request(server, path, cookie=cookie) + assert status == 200, path + assert body == {"protocol": 2, "session": "head-world", "epoch": 7, + "role": "sonar", **extra} + + +def test_private_events_are_served_only_to_their_stored_role(server): + _, cookie, token, paired = pair_v2(server, "Sonar") + assert server.grant_station(paired["client_id"], "sonar") + import hashlib + digest = hashlib.sha256(token.encode("ascii")).digest() + with server._lock: + server._v2_state_heads["sonar"] = ("w", 1) + server._v2_private_events = {digest: ("bridge", b'{"private":true}')} + body = session_request(server, "/api/v2/events", cookie=cookie)[2] + assert body["role"] == "sonar" and body["events"] == [] + with server._lock: + server._v2_private_events = {digest: ("sonar", b'{"private":true}')} + assert session_request(server, "/api/v2/events", cookie=cookie)[2] == {"private": True} + + +# C10 / C6 ------------------------------------------------------------------- + +def _room(tmp_path): + auth = WebHostAuth(tmp_path / "web-host.json") + room = CommanderServer(web_auth=auth, public_origin="https://game.test") + room.start("127.0.0.1", 0) + return auth, room + + +def _post(room, path, body, forwarded=None, host="game.test", + origin="https://game.test"): + address, port = room.address + headers = {"Host": host, "Origin": origin, "Content-Type": "application/json"} + if forwarded is not None: + headers["X-Forwarded-For"] = forwarded + with closing(http.client.HTTPConnection(address, port, timeout=5)) as connection: + connection.request("POST", path, body=json.dumps(body), headers=headers) + response = connection.getresponse() + return response.status, json.loads(response.read() or b"null") + + +def test_failure_limiter_counts_per_source_and_is_bounded(): + limiter = FailureLimiter(limit=2, window_s=60.0, max_sources=3) + for _ in range(2): + limiter.record("a") + assert not limiter.allowed("a") and limiter.allowed("b") + limiter.record("b") + limiter.record("c") + assert len(limiter) == 3 + # Full table: an unknown source is refused (fail closed), never evicting + # the record of a known one, and the table never grows. + assert not limiter.allowed("d") + limiter.record("d") + assert len(limiter) == 3 and not limiter.allowed("a") + + +def test_scrypt_runs_outside_the_global_lock(tmp_path, monkeypatch): + auth, room = _room(tmp_path) + original = web_auth_module.hashlib.scrypt + free = [] + + def scrypt(*args, **kwargs): + free.append(_lock_free_from_another_thread(room._lock)) + return original(*args, **kwargs) + + monkeypatch.setattr(web_auth_module.hashlib, "scrypt", scrypt) + try: + assert _post(room, "/api/v2/web/setup", { + "code": auth.setup_code, "password": PASSWORD})[0] == 200 + assert _post(room, "/api/v2/web/login", {"password": "wrong password"})[0] == 403 + assert _post(room, "/api/v2/web/login", {"password": PASSWORD})[0] == 200 + finally: + room.stop() + assert free == [True, True, True] + + +def test_a_strangers_failed_logins_never_lock_out_the_host(tmp_path): + auth, room = _room(tmp_path) + try: + assert _post(room, "/api/v2/web/setup", { + "code": auth.setup_code, "password": PASSWORD})[0] == 200 + for _ in range(5): + assert _post(room, "/api/v2/web/login", {"password": "guess"}, + forwarded="198.51.100.7")[0] == 403 + # The stranger is limited (even the right password fails for it) ... + assert _post(room, "/api/v2/web/login", {"password": PASSWORD}, + forwarded="198.51.100.7")[0] == 403 + # ... the host behind the same proxy, from its own address, is not. + # The proxy appends the real peer last; a spoofed left entry is ignored. + assert _post(room, "/api/v2/web/login", {"password": PASSWORD}, + forwarded="198.51.100.7, 203.0.113.9")[0] == 200 + finally: + room.stop() + + +def test_room_pairing_failures_are_per_source_and_never_rotate_the_code(tmp_path): + _, room = _room(tmp_path) + try: + code = room.pairing_code + for _ in range(5): + assert _post(room, "/api/v2/pair", {"code": "000AAA", "name": "x"}, + forwarded="198.51.100.7") == (403, {"error": "invalid_code"}) + assert _post(room, "/api/v2/pair", {"code": code, "name": "x"}, + forwarded="198.51.100.7")[0] == 429 + assert room.pairing_code == code + assert _post(room, "/api/v2/pair", {"code": code, "name": "Crew"}, + forwarded="203.0.113.9")[0] == 200 + finally: + room.stop() + + +def test_lan_pairing_still_rotates_the_code_after_five_wrong_codes(server): + code = server.pairing_code + for _ in range(5): + assert session_request(server, "/api/v2/pair", "POST", + {"code": "000AAA", "name": "x"})[0] == 403 + assert server.pairing_code != code + assert session_request(server, "/api/v2/pair", "POST", + {"code": server.pairing_code, "name": "x"})[0] == 429 + + +# C11 ------------------------------------------------------------------------ + +def test_an_observer_switching_views_never_clears_the_operators_audio(server): + _, _, _, operator = pair_v2(server, "Operator") + assert server.grant_station(operator["client_id"], "sonar") + _, cookie, _, paired = pair_v2(server, "Observer") + assert server.set_client_grant(paired["client_id"], "observer", True) + with server._lock: + server._sonar_audio.append((41, b"pcm")) + server._sonar_audio_context = ("operator",) + server._helicopter_audio.append((5, b"pcm")) + server._helicopter_audio_context = ("pilot",) + generation = session_request(server, "/api/v2/session", cookie=cookie)[2][ + "active_generation"] + for station in ("sonar", "helicopter", "bridge"): + status, _, body = session_request( + server, "/api/v2/stations/activate", "POST", + {"station": station, "station_generation": 0, + "active_generation": generation}, cookie, paired["csrf"]) + assert status == 200 and body["station"] == station + generation = body["active_generation"] + with server._lock: + assert list(server._sonar_audio) == [(41, b"pcm")] + assert server._sonar_audio_context == ("operator",) + assert list(server._helicopter_audio) == [(5, b"pcm")] + assert server._helicopter_audio_context == ("pilot",) + # The lease holder leaving its station still restarts the stream. + assert server.grant_station(operator["client_id"], "opz") + with server._lock: + session = server._session_by_client_locked(operator["client_id"]) + assert server._set_active_station_locked(session, "opz") + assert not server._sonar_audio and server._sonar_audio_context is None