From 00040cbbc7d7eeb69802bf8189da7dbe735cf18a Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 12:23:48 +0200 Subject: [PATCH 01/19] fix(store): nest nets only as deep as Murmur allows A store may already hold nets deeper than 8. They are kept, but a plan that holds them, an export of such a store included, no longer imports or loads: move them up before upgrading. --- src/mumblermapi/channels.py | 16 +++++++++++----- src/mumblermapi/store.py | 33 ++++++++++++++++++++++++++------ tests/test_api.py | 21 ++++++++++++++++++++ tests/test_channels.py | 8 +++++--- tests/test_store.py | 38 +++++++++++++++++++++++++++++++++---- 5 files changed, 98 insertions(+), 18 deletions(-) diff --git a/src/mumblermapi/channels.py b/src/mumblermapi/channels.py index efde5b9..2c6c266 100644 --- a/src/mumblermapi/channels.py +++ b/src/mumblermapi/channels.py @@ -33,8 +33,10 @@ # A TAK mission of the same name is ignored rather than allowed to gate it. GUARD = "Guard" -# Murmur's default channelname pattern, so the agent never asks for a name Murmur would refuse. Use fullmatch: -# match() lets "$" pass a trailing newline. +# Murmur checks a name only when a client makes or renames a channel, never over Ice, so this is the only gate on +# a net's name: Murmur's default channelname pattern with its dash taken literally (in Murmur's " -=" it is a +# range that lets most punctuation through), capped at 100 characters. Use fullmatch: match() lets "$" pass a +# trailing newline. NAME_RE = re.compile(r"^[ \-=\w#\[\]{}()@|]{1,100}$") # Murmur holds 1000 channels by default. The cap also stops YAML aliases from expanding a small plan without end. @@ -42,9 +44,13 @@ # Members across a plan, a members list aliased into many nets counted in each: about what a 1 MiB plan holds # written out in full, so aliases cannot multiply them past that. MAX_MEMBERS = 100_000 -# Far deeper than any organisation. It stops a net whose channels alias a list above it before Python's -# recursion limit does. -MAX_DEPTH = 100 +# Murmur's channelnestinglimit, which the deployment leaves at its default. Server::canNest refuses a channel +# under a parent this many levels below the root, over Ice too. The root is level 0 and Units/ level 1, so a net +# d deep is at level d + 1. +MURMUR_NESTING_LIMIT = 10 +# Keeps the last level free for the temporary channels members may make in the deepest net. It also stops a net +# whose channels alias a list above it before Python's recursion limit does. +MAX_DEPTH = MURMUR_NESTING_LIMIT - 2 MAX_DESCRIPTION = 1000 # as long as the admin API lets a description be diff --git a/src/mumblermapi/store.py b/src/mumblermapi/store.py index 7208103..813522b 100644 --- a/src/mumblermapi/store.py +++ b/src/mumblermapi/store.py @@ -7,7 +7,7 @@ from dataclasses import dataclass, field from pathlib import Path -from .channels import ACCESS, GUARD, ChannelSpec +from .channels import ACCESS, GUARD, MAX_DEPTH, ChannelSpec SCHEMA = """ CREATE TABLE IF NOT EXISTS users ( @@ -57,6 +57,14 @@ class NoSuchChannel(StoreError): """The channel does not exist""" +class ChannelExists(StoreError): + """A channel of that name is already there""" + + +class TooDeep(StoreError): + """The channel would nest deeper than Murmur takes""" + + @dataclass(frozen=True) class User: """A Deploy App user as rmapi reported it""" @@ -123,6 +131,16 @@ def version(self) -> int: def _bump(self) -> None: self._db.execute("UPDATE meta SET value = value + 1 WHERE key = 'version'") + def _depth(self, channel_id: int) -> int: + """How deep a channel is: 1 at the top of Units/, counted no further than MAX_DEPTH""" + row = self._db.execute( + "WITH RECURSIVE up(id, depth) AS (SELECT ?, 0 UNION ALL" + " SELECT c.parent, up.depth + 1 FROM channels c JOIN up ON c.id = up.id WHERE up.depth < ?)" + " SELECT MAX(depth) FROM up", + (channel_id, MAX_DEPTH), + ).fetchone() + return int(row[0]) + # ---- users def upsert_user(self, callsign: str, uuid: str) -> None: """A user was created or updated in rmapi""" @@ -156,19 +174,22 @@ def user(self, callsign: str) -> User | None: # ---- channels def add_channel(self, name: str, description: str = "", parent: int = 0, access: str | None = None) -> int: - """Create a channel under Units/ (parent 0) or under another channel. By default a top-level net is open - and a sub-net follows its parent.""" + """Create a channel under Units/ (parent 0) or under another channel, at most MAX_DEPTH deep. By default + a top-level net is open and a sub-net follows its parent.""" access = self._access(access, parent) with self._lock, self._db: if parent and not self._db.execute("SELECT 1 FROM channels WHERE id = ?", (parent,)).fetchone(): raise NoSuchChannel(f"no channel {parent}") + # Murmur refuses a channel past its nesting limit, and the agent would leave the net out + if parent and self._depth(parent) >= MAX_DEPTH: + raise TooDeep(f"nets nest at most {MAX_DEPTH} deep") try: cur = self._db.execute( "INSERT INTO channels (parent, name, description, access) VALUES (?, ?, ?, ?)", (parent, name, description, access), ) except sqlite3.IntegrityError as exc: - raise StoreError(f"channel {name!r} already exists there") from exc + raise ChannelExists(f"channel {name!r} already exists there") from exc self._bump() return int(cur.lastrowid or 0) @@ -211,7 +232,7 @@ def update_channel( ), ) except sqlite3.IntegrityError as exc: - raise StoreError(f"channel {name!r} already exists there") from exc + raise ChannelExists(f"channel {name!r} already exists there") from exc self._bump() def clear(self) -> int: @@ -267,7 +288,7 @@ def import_plan(self, plan: tuple[ChannelSpec, ...], parent: int = 0) -> int: [(channel_id, callsign) for callsign in spec.members], ) self._bump() - except StoreError: + except ChannelExists: with self._lock: row = self._db.execute( "SELECT id FROM channels WHERE parent = ? AND name = ?", (parent, spec.name) diff --git a/tests/test_api.py b/tests/test_api.py index ffa6fed..2896fdc 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -5,10 +5,12 @@ from pathlib import Path import pytest +import yaml from fastapi.testclient import TestClient from mumblermapi import api from mumblermapi.api import Settings, create_app +from mumblermapi.channels import MAX_DEPTH from mumblermapi.tak import TakSettings RMAPI = "rmapi.opendefence-system.serviceaccount.identity.linkerd.cluster.local" @@ -127,6 +129,25 @@ def test_plan_export_and_import(client: TestClient) -> None: assert huge.status_code == 413 +def test_nets_nest_only_as_deep_as_murmur_takes(client: TestClient) -> None: + """A net deeper than MAX_DEPTH is refused with the reason, whether made on its own or imported""" + parent = 0 + for _ in range(MAX_DEPTH): + made = client.post("/api/v1/admin/channels", json={"name": "x", "parent": parent}, headers=as_("VOICE1")) + parent = made.json()["id"] + deeper = client.post("/api/v1/admin/channels", json={"name": "y", "parent": parent}, headers=as_("VOICE1")) + assert (deeper.status_code, deeper.json()["detail"]) == (400, f"nets nest at most {MAX_DEPTH} deep") + net: dict[str, object] = {"name": "y"} + for _ in range(MAX_DEPTH): + net = {"name": "y", "channels": [net]} + imported = client.post( + "/api/v1/admin/channels/import", + content=yaml.safe_dump({"channels": [net]}), + headers=as_("VOICE1") | {"Content-Type": "application/yaml"}, + ) + assert imported.status_code == 400 and f"at most {MAX_DEPTH} deep" in imported.json()["detail"] + + def test_voice_off_for_one_callsign(client: TestClient) -> None: """Disabling voice refuses the callsign without revoking it""" users = client.get("/api/v1/admin/users", headers=as_("VOICE1")).json() diff --git a/tests/test_channels.py b/tests/test_channels.py index 3a9277d..30c58eb 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -198,12 +198,14 @@ def test_parse_plan_members() -> None: def test_parse_plan_holds_at_most_max_nets() -> None: - """A small plan of nested aliases would expand to 2^40 nets; parsing stops at MAX_NETS""" + """A small plan of nested aliases, ten nets a level, would expand to millions of nets; parsing stops at MAX_NETS""" + top = MAX_DEPTH - 1 # within the depth limit, so that the net limit is what stops it levels = ["l0: &l0 [{name: x}]"] + [ - f"l{k}: &l{k} [{{name: a, channels: *l{k - 1}}}, {{name: b, channels: *l{k - 1}}}]" for k in range(1, 41) + f"l{k}: &l{k} [{', '.join(f'{{name: n{i}, channels: *l{k - 1}}}' for i in range(10))}]" + for k in range(1, top + 1) ] with pytest.raises(ChannelPlanError, match=f"at most {MAX_NETS} nets"): - parse_plan(yaml.safe_load("\n".join([*levels, "channels: *l40"]))) + parse_plan(yaml.safe_load("\n".join([*levels, f"channels: *l{top}"]))) assert len(parse_plan({"channels": [{"name": f"n{i}"} for i in range(MAX_NETS)]})) == MAX_NETS with pytest.raises(ChannelPlanError, match="at most"): parse_plan({"channels": [{"name": f"n{i}"} for i in range(MAX_NETS + 1)]}) diff --git a/tests/test_store.py b/tests/test_store.py index 7bf3f8b..5961eb7 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -5,8 +5,8 @@ import pytest -from mumblermapi.channels import ChannelSpec -from mumblermapi.store import Store, StoreError +from mumblermapi.channels import MAX_DEPTH, ChannelSpec +from mumblermapi.store import Channel, ChannelExists, Store, StoreError, TooDeep @pytest.fixture(name="store") @@ -45,7 +45,7 @@ def test_channel_tree_and_members(store: Store) -> None: assert [c.name for c in tree] == ["10", "20"] assert tree[0].children[0].name == "101" assert tree[0].children[0].members == ["ALPHA 1"] - with pytest.raises(StoreError): + with pytest.raises(ChannelExists): store.add_channel("10") with pytest.raises(StoreError): store.add_channel("x", parent=999) @@ -65,6 +65,36 @@ def test_import_plan_is_idempotent(store: Store) -> None: assert not store.is_empty() +def _chain(store: Store, depth: int) -> int: + """A net depth deep under nets of one each; returns its id""" + parent = 0 + for _ in range(depth): + parent = store.add_channel("x", parent=parent) + return parent + + +def _depth(channels: list[Channel]) -> int: + return 1 + max(_depth(c.children) for c in channels) if channels else 0 + + +def test_nets_nest_at_most_max_depth(store: Store) -> None: + """A net as deep as Murmur takes is stored; one level more is refused and changes nothing""" + deepest = _chain(store, MAX_DEPTH) + assert _depth(store.tree()) == MAX_DEPTH + before = store.version() + with pytest.raises(TooDeep, match=f"at most {MAX_DEPTH} deep"): + store.add_channel("y", parent=deepest) + assert store.version() == before + assert _depth(store.tree()) == MAX_DEPTH + + +def test_import_under_a_net_too_deep(store: Store) -> None: + """A plan under the deepest net is refused as too deep, not mistaken for a net that exists""" + deepest = _chain(store, MAX_DEPTH) + with pytest.raises(TooDeep): + store.import_plan((ChannelSpec("y"),), deepest) + + def test_persists(tmp_path: Path) -> None: """State survives a restart""" first = Store(tmp_path / "state.db") @@ -103,7 +133,7 @@ def test_update_channel(tmp_path: Path) -> None: store.update_channel(ten, name="11") assert [(c.name, c.description) for c in store.tree()] == [("11", "Alfa-joukkue"), ("20", "")] assert store.version() == before + 2 - with pytest.raises(StoreError): + with pytest.raises(ChannelExists): store.update_channel(ten, name="20") with pytest.raises(StoreError): store.update_channel(999, description="x") From 2dd0db533941d6897687794c2dda8d081fa752b8 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 12:26:20 +0200 Subject: [PATCH 02/19] fix(agent): skip a net Murmur refuses instead of stalling every net --- src/mumblermapi/agent.py | 49 +++++++++++++++++------- src/mumblermapi/channels.py | 23 ++++++++--- tests/fake_murmur.py | 24 ++++++++++++ tests/test_agent.py | 76 +++++++++++++++++++++++++++++++++++-- tests/test_channels.py | 27 ++++++++++--- 5 files changed, 171 insertions(+), 28 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index 2c88a42..f0f5863 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -20,7 +20,7 @@ from libpvarki.logging import add_trace_and_audit, init_logging from .authenticator import Authenticator -from .channels import ExistingChannel, desired_tree, load_plan, prune, reconcile +from .channels import ChannelRefused, ExistingChannel, desired_tree, load_plan, prune, reconcile from .config import AgentConfig from .enforce import Acl, Session, acl_of, combine, plan, refused, shadows, violations from .identity import CertVerifier @@ -86,8 +86,9 @@ def idToTexture(self, id: int, current: Any = None) -> bytes: class IceChannels: """The reconciler's view of a Murmur virtual server""" - def __init__(self, server: Any) -> None: + def __init__(self, server: Any, mumble: ModuleType) -> None: self._server = server + self._mumble = mumble def channels(self) -> list[ExistingChannel]: """Every channel on the server""" @@ -97,8 +98,12 @@ def channels(self) -> list[ExistingChannel]: ] def add_channel(self, name: str, parent: int, description: str) -> int: - """Create a channel, with its description""" - channel_id: int = self._server.addChannel(name, parent) + """Create a channel, with its description. Only Murmur's nesting limit is a refusal: any other error + means Murmur cannot be worked with, and ends the pass.""" + try: + channel_id: int = self._server.addChannel(name, parent) + except self._mumble.NestingLimitException as exc: + raise ChannelRefused(f"{name!r} would nest past Murmur's channel nesting limit") from exc if description: state = self._server.getChannelState(channel_id) state.description = description @@ -147,10 +152,12 @@ def _sessions(server: Any) -> list[Session]: return [Session(session, user.name, user.channel) for session, user in server.getUsers().items()] -def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, units: bool) -> None: - """Make Murmur match the policy. Until the policy is known, Units/ and Missions/ are left as they are. +def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, units: bool) -> list[str]: + """Make Murmur match the policy, and return the paths of nets Murmur refused to create. Until the policy is + known, Units/ and Missions/ are left as they are. - Refused callsigns go first, so that nothing later in the pass can hold their disconnection up. + Refused callsigns go first, so that nothing later in the pass can hold their disconnection up. A net Murmur + refuses is left out with the nets under it, as if it were not created yet, and the other nets go on. """ sessions = _sessions(server) kicked = refused(policy, sessions) @@ -159,12 +166,13 @@ def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, unit LOGGER.warning("Disconnecting session %d: refused by mumblermapi", session) server.kickUser(session, "revoked or voice disabled in Deploy App") - channels = IceChannels(server) - created = reconcile(channels, desired_tree(policy.specs(), policy.mission_specs()) if units else desired_tree(())) + channels = IceChannels(server, mumble) + desired = desired_tree(policy.specs(), policy.mission_specs()) if units else desired_tree(()) + created, left_out = reconcile(channels, desired) if created: LOGGER.info("Created channels: %s", ", ".join(created)) if not units: - return + return left_out existing = channels.channels() roots = {c.name: c.id for c in existing if c.parent == 0} removed = prune(channels, policy.specs(), roots["Units"], "/Units") @@ -210,11 +218,21 @@ def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, unit with _may_be_gone(mumble): LOGGER.info("Stopping session %d listening to channel %d", session, channel_id) server.stopListening(session, channel_id) + return left_out + + +def _warn_left_out(left_out: list[str], before: list[str]) -> list[str]: + """Warn about the nets Murmur refuses when they change, not every round; returns them for the next round""" + if left_out and set(left_out) != set(before): + LOGGER.warning( + "Murmur refused these nets, so they and the nets under them are left out: %s", ", ".join(left_out) + ) + return left_out -def _presence(server: Any) -> list[Entry]: +def _presence(mumble: ModuleType, server: Any) -> list[Entry]: """Who is connected, and in which net""" - return presence(_sessions(server), channel_paths(IceChannels(server).channels())) + return presence(_sessions(server), channel_paths(IceChannels(server, mumble).channels())) @contextmanager @@ -273,6 +291,7 @@ def policy() -> Policy: communicator.stringToProxy(f"Meta:tcp -h {config.ice_host} -p {config.ice_port}") ) next_sweep = 0.0 + left_out: list[str] = [] while not stop.is_set(): if source: source.refresh() @@ -280,9 +299,11 @@ def policy() -> Policy: server = _server(meta, config.server_id) # Re-registering every round re-attaches the authenticator after a Murmur restart. server.setAuthenticator(authenticator) - _enforce(mumble, server, policy(), ids, units=source is None or source.ready) + left_out = _warn_left_out( + _enforce(mumble, server, policy(), ids, units=source is None or source.ready), left_out + ) if reporter: - reporter.report(_presence(server), time.monotonic()) + reporter.report(_presence(mumble, server), time.monotonic()) if time.monotonic() >= next_sweep: _sweep(mumble, server, auth) next_sweep = time.monotonic() + config.sweep_seconds diff --git a/src/mumblermapi/channels.py b/src/mumblermapi/channels.py index 2c6c266..1142903 100644 --- a/src/mumblermapi/channels.py +++ b/src/mumblermapi/channels.py @@ -63,6 +63,10 @@ class ChannelPlanError(ValueError): """The channel plan is malformed""" +class ChannelRefused(Exception): + """Murmur will not create the channel there, as when it would nest past Murmur's limit""" + + @dataclass(frozen=True) class ChannelSpec: """A channel and its children; access is one of ACCESS, or "" for the default. members are callsigns, so @@ -208,7 +212,7 @@ def channels(self) -> list[ExistingChannel]: """Every channel on the server""" def add_channel(self, name: str, parent: int, description: str) -> int: - """Create a channel and return its id""" + """Create a channel and return its id; raises ChannelRefused when Murmur will not have it there""" def set_description(self, channel_id: int, description: str) -> None: """Change a channel's description""" @@ -217,16 +221,19 @@ def remove_channel(self, channel_id: int) -> None: """Remove a channel and everything under it""" -def reconcile(server: ChannelServer, desired: tuple[ChannelSpec, ...], root: int = 0) -> list[str]: - """Create the channels that are missing and return their paths; correct the descriptions of the others. +def reconcile(server: ChannelServer, desired: tuple[ChannelSpec, ...], root: int = 0) -> tuple[list[str], list[str]]: + """Create the channels that are missing and correct the descriptions of the others. Returns the paths + created and the paths Murmur refused. Channels are matched by name, so a renamed net is a new channel and the old one is pruned. A temporary - channel holding a net's name is replaced. + channel holding a net's name is replaced. A refused channel is left out with everything under it, and the + rest of the tree still goes in. """ # ponytail: rename = recreate, which moves anyone in the net to its parent; keep a store-id map if renames # of busy nets become common existing = {(channel.parent, channel.name): channel for channel in server.channels()} created: list[str] = [] + refused: list[str] = [] def walk(specs: tuple[ChannelSpec, ...], parent: int, prefix: str) -> None: for spec in specs: @@ -238,7 +245,11 @@ def walk(specs: tuple[ChannelSpec, ...], parent: int, prefix: str) -> None: server.remove_channel(channel.id) channel = None if channel is None: - channel_id = server.add_channel(spec.name, parent, spec.description) + try: + channel_id = server.add_channel(spec.name, parent, spec.description) + except ChannelRefused: + refused.append(path) + continue # the nets under it cannot exist without it created.append(path) else: channel_id = channel.id @@ -247,7 +258,7 @@ def walk(specs: tuple[ChannelSpec, ...], parent: int, prefix: str) -> None: walk(spec.children, channel_id, path) walk(desired, root, "") - return created + return created, refused def prune(server: ChannelServer, desired: tuple[ChannelSpec, ...], root: int, prefix: str = "") -> list[str]: diff --git a/tests/fake_murmur.py b/tests/fake_murmur.py index f9b3f31..d3bbd54 100644 --- a/tests/fake_murmur.py +++ b/tests/fake_murmur.py @@ -15,6 +15,14 @@ class InvalidChannelException(Exception): """Murmur's: the channel is gone""" +class NestingLimitException(Exception): + """Murmur's: the channel would nest past channelnestinglimit""" + + +class InvalidSecretException(Exception): + """Murmur's: the Ice secret is wrong""" + + class ServerAuthenticator: """Base class the agent's servant derives from""" @@ -48,6 +56,8 @@ def __init__( MUMBLE = ModuleType("MumbleServer") MUMBLE.InvalidSessionException = InvalidSessionException # type: ignore[attr-defined] MUMBLE.InvalidChannelException = InvalidChannelException # type: ignore[attr-defined] +MUMBLE.NestingLimitException = NestingLimitException # type: ignore[attr-defined] +MUMBLE.InvalidSecretException = InvalidSecretException # type: ignore[attr-defined] MUMBLE.ServerAuthenticator = ServerAuthenticator # type: ignore[attr-defined] MUMBLE.UserInfo = SimpleNamespace(UserName=0) # type: ignore[attr-defined] MUMBLE.ACL = ACL # type: ignore[attr-defined] @@ -64,6 +74,7 @@ class FakeServer: listeners: dict[int, list[int]] = field(default_factory=dict) certificates: dict[int, list[bytes]] = field(default_factory=dict) log: list[str] = field(default_factory=list) + nesting_limit: int = 10 # Murmur's default channelnestinglimit def __post_init__(self) -> None: self.channels.setdefault( @@ -81,6 +92,14 @@ def connect(self, session: int, name: str, channel: int = 0, userid: int = 1) -> """A user logs in""" self.users[session] = SimpleNamespace(session=session, name=name, channel=channel, userid=userid) + def level(self, channel_id: int) -> int: + """How far below the root a channel is; the root is level 0""" + level = 0 + while channel_id != 0: + channel_id = self.channels[channel_id].parent + level += 1 + return level + def id_of(self, path: str) -> int: """Channel id by path, e.g. "/Missions/RECON" """ channel_id = 0 @@ -93,6 +112,11 @@ def getChannels(self) -> dict[int, SimpleNamespace]: return dict(self.channels) def addChannel(self, name: str, parent: int) -> int: + if parent not in self.channels: + raise InvalidChannelException() + # Server::canNest, which Murmur checks over Ice as well as for clients + if self.level(parent) >= self.nesting_limit: + raise NestingLimitException() channel_id = max(self.channels) + 1 self.channel(channel_id, parent, name) return channel_id diff --git a/tests/test_agent.py b/tests/test_agent.py index 4926efa..7e9e2d9 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging from pathlib import Path from types import SimpleNamespace from typing import Any @@ -10,11 +11,12 @@ from mumblermapi import agent from mumblermapi.authenticator import Refusal +from mumblermapi.channels import MAX_DEPTH from mumblermapi.enforce import OPEN, acl_of, members_only from mumblermapi.policy import Policy, Unit from mumblermapi.userids import UserIds -from .fake_murmur import MUMBLE, FakeServer +from .fake_murmur import MUMBLE, FakeServer, InvalidSecretException, NestingLimitException POLICY = Policy( version=2, @@ -152,11 +154,79 @@ def test_enforce_before_policy(ids: UserIds) -> None: assert server.acls == {} +def chain(depth: int, name: str) -> Unit: + """A net depth deep, under nets of the same name""" + unit = Unit(100 + depth, name) + for level in range(depth - 1, 0, -1): + unit = Unit(100 + level, name, children=(unit,)) + return unit + + +def test_a_refused_net_stalls_no_other(ids: UserIds) -> None: + """A net past Murmur's nesting limit is left out with what is under it; every other net is enforced""" + server = murmur() + stale = server.id_of("/Units/20") + server.users[4].channel = stale # an outsider, inside the open net about to become invite-only + server.listeners[stale] = [4, 1] + policy = Policy( + version=2, + units=( + chain(server.nesting_limit + 1, "00"), # first in walk order + Unit(1, "10", access="invite", members=frozenset({"VOICE1"})), + Unit(2, "20", access="invite", members=frozenset({"VOICE1"})), + ), + ) + refused = "/Units" + "/00" * server.nesting_limit + assert agent._enforce(MUMBLE, server, policy, ids, units=True) == [refused] + + assert server.id_of("/Units" + "/00" * (server.nesting_limit - 1)) + assert acl_of(*server.getACL(server.id_of("/Units/10"))) == members_only([1]) + assert acl_of(*server.getACL(stale)) == members_only([1]) + assert server.id_of("/Missions/Guard") and server.id_of("/Teams/Red") and server.id_of("/Roles/Medic") + assert server.users[4].channel == 0 and server.listeners[stale] == [1] + + server.log.clear() + assert agent._enforce(MUMBLE, server, policy, ids, units=True) == [refused] + assert server.log == [] + + +def wrong_secret(*args: object, **kwargs: object) -> Any: + """What every Murmur call raises once the Ice secret no longer matches""" + raise InvalidSecretException() + + +def test_other_murmur_errors_end_the_pass(ids: UserIds) -> None: + """Only the nesting limit is a refusal: any other error from Murmur still ends the pass""" + server = murmur() + server.addChannel = wrong_secret # type: ignore[method-assign] + with pytest.raises(InvalidSecretException): + agent._enforce(MUMBLE, server, POLICY, ids, units=True) + + +def test_the_deepest_net_has_room_for_temporary_channels(ids: UserIds) -> None: + """Nets as deep as mumblermapi takes them fit in Murmur, with a level left for members' temporary channels""" + server = murmur() + assert agent._enforce(MUMBLE, server, Policy(version=2, units=(chain(MAX_DEPTH, "x"),)), ids, units=True) == [] + temporary = server.addChannel("huddle", server.id_of("/Units" + "/x" * MAX_DEPTH)) + with pytest.raises(NestingLimitException): + server.addChannel("deeper", temporary) + + +def test_refused_nets_are_warned_about_when_they_change(caplog: pytest.LogCaptureFixture) -> None: + """Not every round""" + with caplog.at_level(logging.WARNING, logger=agent.__name__): + before = agent._warn_left_out(["/Units/a"], []) + before = agent._warn_left_out(["/Units/a"], before) + before = agent._warn_left_out(["/Units/a", "/Units/b"], before) + agent._warn_left_out([], before) + assert [r.getMessage().rsplit(": ", 1)[1] for r in caplog.records] == ["/Units/a", "/Units/a, /Units/b"] + + def test_presence(ids: UserIds) -> None: """Who is where, by path""" server = murmur() agent._enforce(MUMBLE, server, POLICY, ids, units=True) - assert agent._presence(server) == [ + assert agent._presence(MUMBLE, server) == [ {"callsign": "OTHER", "channel": "/"}, {"callsign": "VOICE1", "channel": "/"}, {"callsign": "VOICE3", "channel": "/Missions/RECON"}, @@ -217,7 +287,7 @@ def test_servant() -> None: def test_channel_description() -> None: """New channels get their description""" server = FakeServer() - channel_id = agent.IceChannels(server).add_channel("10", 0, "Alfa") + channel_id = agent.IceChannels(server, MUMBLE).add_channel("10", 0, "Alfa") assert server.channels[channel_id].description == "Alfa" diff --git a/tests/test_channels.py b/tests/test_channels.py index 30c58eb..2739d4b 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -15,6 +15,7 @@ ROLES, TEAM_COLOURS, ChannelPlanError, + ChannelRefused, ChannelSpec, ExistingChannel, desired_tree, @@ -123,24 +124,40 @@ def test_reconcile_creates_tree_once() -> None: desired = desired_tree( parse_plan({"channels": [{"name": "10", "description": "A", "channels": [{"name": "101"}]}]}) ) - created = reconcile(server, desired) - assert created[:3] == ["/Units", "/Units/10", "/Units/10/101"] + created, refused = reconcile(server, desired) + assert created[:3] == ["/Units", "/Units/10", "/Units/10/101"] and refused == [] assert "/Teams/Dark Blue" in created and "/Roles/Medic" in created platoon = next(c for c in server.existing if c.name == "10") squad = next(c for c in server.existing if c.name == "101") assert squad.parent == platoon.id assert server.descriptions[platoon.id] == "A" - assert reconcile(server, desired) == [] + assert reconcile(server, desired) == ([], []) def test_reconcile_fills_gaps_only() -> None: """Existing channels are kept, and missing children land under them""" server = FakeServer([ExistingChannel(7, 0, "Units")]) - created = reconcile(server, (ChannelSpec("Units", children=(ChannelSpec("20"),)),)) + created, _ = reconcile(server, (ChannelSpec("Units", children=(ChannelSpec("20"),)),)) assert created == ["/Units/20"] assert server.existing[-1] == ExistingChannel(2, 7, "20") +def test_reconcile_skips_a_refused_channel() -> None: + """A channel Murmur refuses is left out with what is under it; its siblings and the other branches go in""" + + class Refusing(FakeServer): + def add_channel(self, name: str, parent: int, description: str) -> int: + if name == "deep": + raise ChannelRefused(name) + return super().add_channel(name, parent, description) + + server = Refusing() + units = (ChannelSpec("deep", children=(ChannelSpec("under"),)), ChannelSpec("10")) + desired = (ChannelSpec("Units", children=units), ChannelSpec("Teams", children=(ChannelSpec("Red"),))) + assert reconcile(server, desired) == (["/Units", "/Units/10", "/Teams", "/Teams/Red"], ["/Units/deep"]) + assert reconcile(server, desired) == ([], ["/Units/deep"]) + + def test_prune_removes_what_the_plan_dropped() -> None: """Dropped permanent channels go with their subtrees; kept ones and users' temporary channels stay""" server = FakeServer( @@ -165,7 +182,7 @@ def test_reconcile_corrects_descriptions() -> None: """An edited description reaches Murmur once; an unchanged one is left alone""" server = FakeServer([ExistingChannel(1, 0, "Units"), ExistingChannel(2, 1, "10", description="old")]) plan = (ChannelSpec("Units", children=(ChannelSpec("10", "Alfa-joukkue"),)),) - assert reconcile(server, plan) == [] + assert reconcile(server, plan) == ([], []) assert server.descriptions == {2: "Alfa-joukkue"} server.descriptions.clear() reconcile(server, plan) From 46b9a500579e1243274fe8c58712e663c79650e8 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 12:29:53 +0200 Subject: [PATCH 03/19] fix(agent): sweep certificates before enforcing the plan --- src/mumblermapi/agent.py | 52 ++++++++++++++++++++++++++++++-------- tests/fake_murmur.py | 16 ++++++++---- tests/test_agent.py | 54 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 106 insertions(+), 16 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index f0f5863..344ac08 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -13,6 +13,7 @@ import time from collections.abc import Iterator from contextlib import contextmanager +from dataclasses import dataclass, field from importlib.resources import files from types import ModuleType from typing import Any @@ -256,6 +257,44 @@ def _server(meta: Any, server_id: int | None) -> Any: return booted[0] +@dataclass +class Rounds: + """What murmur-agent does with Murmur each round, and what it carries from one round to the next""" + + ice: ModuleType + mumble: ModuleType + auth: Authenticator + ids: UserIds + reporter: PresenceReporter | None + sweep_seconds: float + next_sweep: float = field(default=0.0, init=False) + left_out: list[str] = field(default_factory=list, init=False) + + def round(self, server: Any, policy: Policy, units: bool) -> None: + """Sweep certificates when due, then make Murmur match the policy and report presence. + + The sweep goes first, on its own, so that no lasting failure to enforce the policy stops disconnecting + revoked certificates. Presence follows enforcement, so a pass that keeps failing stops the reports and + mumblermapi's health shows it. + """ + not_ready = (self.ice.Exception, RuntimeError) + if time.monotonic() >= self.next_sweep: + try: + _sweep(self.mumble, server, self.auth) + except not_ready as exc: + LOGGER.warning("Murmur not ready for the certificate sweep: %s", exc) + else: + self.next_sweep = time.monotonic() + self.sweep_seconds + try: + left_out = _enforce(self.mumble, server, policy, self.ids, units) + if self.reporter: + self.reporter.report(_presence(self.mumble, server), time.monotonic()) + except not_ready as exc: + LOGGER.warning("Murmur not ready: %s", exc) + else: + self.left_out = _warn_left_out(left_out, self.left_out) + + def run(config: AgentConfig, stop: threading.Event) -> None: # pragma: no cover # needs Ice and Murmur """Register with Murmur and keep it in shape until stopped""" ice, mumble = _load_ice() @@ -290,8 +329,7 @@ def policy() -> Policy: meta = mumble.MetaPrx.uncheckedCast( communicator.stringToProxy(f"Meta:tcp -h {config.ice_host} -p {config.ice_port}") ) - next_sweep = 0.0 - left_out: list[str] = [] + rounds = Rounds(ice, mumble, auth, ids, reporter, config.sweep_seconds) while not stop.is_set(): if source: source.refresh() @@ -299,16 +337,10 @@ def policy() -> Policy: server = _server(meta, config.server_id) # Re-registering every round re-attaches the authenticator after a Murmur restart. server.setAuthenticator(authenticator) - left_out = _warn_left_out( - _enforce(mumble, server, policy(), ids, units=source is None or source.ready), left_out - ) - if reporter: - reporter.report(_presence(mumble, server), time.monotonic()) - if time.monotonic() >= next_sweep: - _sweep(mumble, server, auth) - next_sweep = time.monotonic() + config.sweep_seconds except (ice.Exception, RuntimeError) as exc: LOGGER.warning("Murmur not ready: %s", exc) + else: + rounds.round(server, policy(), units=source is None or source.ready) stop.wait(config.poll_seconds) diff --git a/tests/fake_murmur.py b/tests/fake_murmur.py index d3bbd54..0ea968c 100644 --- a/tests/fake_murmur.py +++ b/tests/fake_murmur.py @@ -7,19 +7,23 @@ from typing import Any -class InvalidSessionException(Exception): +class IceException(Exception): + """Ice.Exception, which every error over Ice derives from""" + + +class InvalidSessionException(IceException): """Murmur's: the session is gone""" -class InvalidChannelException(Exception): +class InvalidChannelException(IceException): """Murmur's: the channel is gone""" -class NestingLimitException(Exception): +class NestingLimitException(IceException): """Murmur's: the channel would nest past channelnestinglimit""" -class InvalidSecretException(Exception): +class InvalidSecretException(IceException): """Murmur's: the Ice secret is wrong""" @@ -52,7 +56,9 @@ def __init__( ) # fmt: skip -# Stands in for the MumbleServer module that Ice generates from the slice +# Stand in for the Ice module and the MumbleServer module that Ice generates from the slice +ICE = ModuleType("Ice") +ICE.Exception = IceException # type: ignore[attr-defined] MUMBLE = ModuleType("MumbleServer") MUMBLE.InvalidSessionException = InvalidSessionException # type: ignore[attr-defined] MUMBLE.InvalidChannelException = InvalidChannelException # type: ignore[attr-defined] diff --git a/tests/test_agent.py b/tests/test_agent.py index 7e9e2d9..067a87f 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -14,9 +14,10 @@ from mumblermapi.channels import MAX_DEPTH from mumblermapi.enforce import OPEN, acl_of, members_only from mumblermapi.policy import Policy, Unit +from mumblermapi.presence import PresenceReporter from mumblermapi.userids import UserIds -from .fake_murmur import MUMBLE, FakeServer, InvalidSecretException, NestingLimitException +from .fake_murmur import ICE, MUMBLE, FakeServer, InvalidSecretException, NestingLimitException POLICY = Policy( version=2, @@ -273,6 +274,57 @@ def certificates(session: int) -> list[bytes]: assert server.log == ["kick 1"] +def rounds(ids: UserIds, reports: list[object] | None = None) -> agent.Rounds: + """The agent's rounds, with presence reports collected in reports, or none made""" + + def post(url: str, body: object, timeout: float) -> int: + assert reports is not None + reports.append(body) + return 200 + + reporter = None if reports is None else PresenceReporter("http://m/presence", post=post) + return agent.Rounds(ICE, MUMBLE, FakeAuth(), ids, reporter, sweep_seconds=60) # type: ignore[arg-type] + + +def test_a_round_sweeps_first(ids: UserIds) -> None: + """A revoked certificate is disconnected even while enforcing the policy keeps failing; presence then stays + unreported, so health shows the failure""" + server = murmur() + server.addChannel = wrong_secret # type: ignore[method-assign] + reports: list[object] = [] + loop = rounds(ids, reports) + policy = Policy(version=2, refused=frozenset({"OTHER"})) + loop.round(server, policy, units=True) + # BAD's certificate is revoked; OTHER is refused by mumblermapi, which enforcement sees to before it fails + assert server.log == ["kick 3", "kick 4"] and reports == [] and loop.next_sweep > 0 + + del server.addChannel + loop.round(server, policy, units=True) + assert server.id_of("/Missions/Guard") and len(reports) == 1 + + +def test_a_failed_sweep_holds_up_nothing(ids: UserIds) -> None: + """The policy is still enforced and presence reported, and the sweep is tried again next round""" + server = murmur() + server.getCertificateList = wrong_secret # type: ignore[method-assign] + reports: list[object] = [] + loop = rounds(ids, reports) + loop.round(server, POLICY, units=True) + assert server.id_of("/Units/10") and len(reports) == 1 and loop.next_sweep == 0 + + +def test_a_round_warns_about_refused_nets(ids: UserIds, caplog: pytest.LogCaptureFixture) -> None: + """Once, not every round""" + server = murmur() + policy = Policy(version=2, units=(chain(server.nesting_limit + 1, "00"),)) + loop = rounds(ids) + with caplog.at_level(logging.WARNING, logger=agent.__name__): + loop.round(server, policy, units=True) + loop.round(server, policy, units=True) + warned = [r for r in caplog.records if r.getMessage().startswith("Murmur refused")] + assert len(warned) == 1 and loop.left_out == ["/Units" + "/00" * server.nesting_limit] + + def test_servant() -> None: """Murmur's ServerAuthenticator calls reach the authenticator""" servant = agent._servant(MUMBLE, FakeAuth()) # type: ignore[arg-type] From cba3ac62b03ea31d8ae983074c1af04566e46c34 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 12:20:36 +0200 Subject: [PATCH 04/19] feat(store): assign web voice slots per browser --- src/mumblermapi/store.py | 43 +++++++++++++++++++++++++++++++++++++- src/mumblermapi/tickets.py | 1 + tests/test_store.py | 26 +++++++++++++++++++++++ tests/test_tickets.py | 4 ++-- 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/src/mumblermapi/store.py b/src/mumblermapi/store.py index 813522b..fc66a39 100644 --- a/src/mumblermapi/store.py +++ b/src/mumblermapi/store.py @@ -1,4 +1,5 @@ -"""mumblermapi's state: users from rmapi, the Units/ channel tree and its members, and TAK missions""" +"""mumblermapi's state: users from rmapi, the Units/ channel tree and its members, TAK missions and the web +voice slot each browser holds""" from __future__ import annotations @@ -8,6 +9,7 @@ from pathlib import Path from .channels import ACCESS, GUARD, MAX_DEPTH, ChannelSpec +from .tickets import WEB_SLOTS SCHEMA = """ CREATE TABLE IF NOT EXISTS users ( @@ -37,6 +39,15 @@ callsign TEXT NOT NULL, PRIMARY KEY (mission, callsign) ); +-- Which web slot each of a callsign's browsers logs in with, so two browsers never share one +CREATE TABLE IF NOT EXISTS web_slots ( + callsign TEXT NOT NULL, -- as in the Mumble username + browser TEXT NOT NULL, -- the id the browser keeps for itself + slot INTEGER NOT NULL, + used_at REAL NOT NULL, -- wall-clock seconds of the last ticket + PRIMARY KEY (callsign, browser), + UNIQUE (callsign, slot) +); CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL); INSERT OR IGNORE INTO meta (key, value) VALUES ('version', 1); """ @@ -326,3 +337,33 @@ def is_empty(self) -> bool: """No channels yet""" with self._lock: return bool(self._db.execute("SELECT COUNT(*) FROM channels").fetchone()[0] == 0) + + # ---- web voice slots + def web_slot(self, callsign: str, browser: str, now: float) -> int: + """The web slot this browser of the callsign logs in with: the one it had, else the lowest free one. + Murmur drops the older of two sessions with one name, so two browsers must not share a slot. No new + version: nothing murmur-agent enforces changes.""" + with self._lock, self._db: + row = self._db.execute( + "SELECT slot FROM web_slots WHERE callsign = ? AND browser = ?", (callsign, browser) + ).fetchone() + if row: + self._db.execute( + "UPDATE web_slots SET used_at = ? WHERE callsign = ? AND browser = ?", (now, callsign, browser) + ) + return int(row[0]) + taken = {r[0] for r in self._db.execute("SELECT slot FROM web_slots WHERE callsign = ?", (callsign,))} + slot = next((s for s in WEB_SLOTS if s not in taken), None) + if slot is None: + # ponytail: a new browser takes the slot minted longest ago even if that browser is still in voice, + # which drops it; skipping slots presence reports online would fix that + oldest = self._db.execute( + "SELECT slot FROM web_slots WHERE callsign = ? ORDER BY used_at, slot LIMIT 1", (callsign,) + ).fetchone() + slot = int(oldest[0]) + # REPLACE drops the row of the browser that held a taken-over slot + self._db.execute( + "INSERT OR REPLACE INTO web_slots (callsign, browser, slot, used_at) VALUES (?, ?, ?, ?)", + (callsign, browser, slot, now), + ) + return slot diff --git a/src/mumblermapi/tickets.py b/src/mumblermapi/tickets.py index de6c63e..93d3edd 100644 --- a/src/mumblermapi/tickets.py +++ b/src/mumblermapi/tickets.py @@ -24,6 +24,7 @@ # Phones never get these slots, and the gateway gets no others. Murmur compares names case-insensitively. WEB_SLOT_PREFIX = "web-" WEB_SLOT = re.compile(r"^web-[1-9]$") +WEB_SLOTS = range(1, 10) # one per browser of a callsign, web-1 to web-9 MAX_TICKET_BYTES = 8192 # libpvarki's AUDIT level, for refused security decisions AUDIT = logging.CRITICAL + 5 diff --git a/tests/test_store.py b/tests/test_store.py index 5961eb7..76651e2 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -7,6 +7,7 @@ from mumblermapi.channels import MAX_DEPTH, ChannelSpec from mumblermapi.store import Channel, ChannelExists, Store, StoreError, TooDeep +from mumblermapi.tickets import WEB_SLOTS @pytest.fixture(name="store") @@ -250,3 +251,28 @@ def test_migrates_implicit_access(tmp_path: Path) -> None: ["invite", "inherit"], "open", ) + + +def test_web_slots_per_browser(tmp_path: Path) -> None: + """Each browser of a callsign gets its own slot and keeps it, also across a restart; no new version""" + store = Store(tmp_path / "db.sqlite") + before = store.version() + assert store.web_slot("ALPHA_1", "laptop-browser-01", 100.0) == 1 + assert store.web_slot("ALPHA_1", "phone-browser-0002", 101.0) == 2 + assert store.web_slot("ALPHA_1", "laptop-browser-01", 102.0) == 1 + assert store.web_slot("BRAVO_2", "phone-browser-0002", 103.0) == 1 # callsigns do not share slots + assert store.version() == before + reopened = Store(tmp_path / "db.sqlite") + assert reopened.web_slot("ALPHA_1", "phone-browser-0002", 104.0) == 2 + assert reopened.web_slot("ALPHA_1", "tablet-browser-03", 105.0) == 3 + + +def test_tenth_browser_takes_the_oldest_slot(store: Store) -> None: + """With all slots held, a new browser takes the one whose last ticket is oldest; a ticket refreshes it""" + for slot in WEB_SLOTS: + assert store.web_slot("ALPHA_1", f"browser-number-{slot:02}", 100.0 + slot) == slot + store.web_slot("ALPHA_1", "browser-number-01", 200.0) # web-1 is used again, so web-2 is now the oldest + assert store.web_slot("ALPHA_1", "browser-number-10", 201.0) == 2 + assert store.web_slot("ALPHA_1", "browser-number-10", 202.0) == 2 + # The browser that lost its slot is a new browser now, and web-3 is the oldest + assert store.web_slot("ALPHA_1", "browser-number-02", 203.0) == 3 diff --git a/tests/test_tickets.py b/tests/test_tickets.py index 53242a6..f5f6dc7 100644 --- a/tests/test_tickets.py +++ b/tests/test_tickets.py @@ -6,7 +6,7 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from mumblermapi.identity import IdentityError -from mumblermapi.tickets import TTL_SECONDS, _b64, is_web_slot, mint, public_key, verify, web_username +from mumblermapi.tickets import TTL_SECONDS, WEB_SLOTS, _b64, is_web_slot, mint, public_key, verify, web_username NOW = 1_800_000_000.0 LEAF = b"\x30\x82leaf-der" @@ -84,7 +84,7 @@ def test_skips_malformed_keys(key: Ed25519PrivateKey) -> None: def test_web_slots() -> None: """web-1 to web-9 exist, whatever the case; nothing else is minted""" - assert web_username("ALPHA_1", 9) == "ALPHA_1---web-9" + assert [web_username("ALPHA_1", slot) for slot in WEB_SLOTS][-1] == "ALPHA_1---web-9" for bad in (0, 10, -1): with pytest.raises(ValueError): web_username("ALPHA_1", bad) From f4f183482f99eaeffc0a75ef0767c3769651f6bf Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 12:22:25 +0200 Subject: [PATCH 05/19] fix(voice): let mumblermapi pick each browser's slot --- README.md | 11 ++++--- src/mumblermapi/api.py | 16 ++++++---- tests/test_voice_api.py | 65 ++++++++++++++++++++++++++++++++--------- ui/src/voice/Talk.tsx | 21 +++++++++---- ui/src/voice/client.ts | 8 ++--- ui/src/voice/ptt.ts | 22 +++++++------- ui/test/ptt.test.mjs | 48 ++++++++++++++++++++---------- 7 files changed, 134 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 790c00c..0cbd6b1 100644 --- a/README.md +++ b/README.md @@ -38,10 +38,13 @@ Browsers join the same nets through the voice gateway (`pvarki/golang-mumble-voi with no extra login. The gateway reads the ticket's username and certificate (`tickets.py`), so the two share that format: -1. The talk panel POSTs `{"slot": n}` to `/ui/mumble/api/v1/voice/token`. mumblermapi takes the client - certificate Traefik verified, checks it against the platform CA and its own user record (known, not - revoked, voice on), and signs a 60-second Ed25519 ticket for `---web-` that carries that - certificate. The signing key lives in memory only; murmur-agent gets the public key with its state. +1. The talk panel POSTs `{"browser": id}` to `/ui/mumble/api/v1/voice/token`, where `id` is a random id the + browser keeps. mumblermapi takes the client certificate Traefik verified, checks it against the platform CA + and its own user record (known, not revoked, voice on), and signs a 60-second Ed25519 ticket for + `---web-` that carries that certificate. Each of the callsign's browsers keeps its own slot `n` + of 1 to 9, as Murmur drops the older of two sessions with one name; a tenth browser takes the slot used + longest ago. Tabs of one browser share its slot, so a new tab takes over. The signing key lives in memory + only; murmur-agent gets the public key with its state. 2. The panel opens `wss://mtls./ui/mumble/ws` and sends the ticket. The gateway checks it carries the connection's own certificate, then logs in to Murmur with its own certificate and the ticket as the password. diff --git a/src/mumblermapi/api.py b/src/mumblermapi/api.py index 36698ce..b99cbf5 100644 --- a/src/mumblermapi/api.py +++ b/src/mumblermapi/api.py @@ -132,11 +132,16 @@ class VoiceSetting(BaseModel): class TicketRequest(BaseModel): - """Which browser slot to log in. A JSON body, so a cross-site form cannot send it.""" + """Which browser is joining. A JSON body, so a cross-site form cannot send it.""" model_config = ConfigDict(extra="forbid") - slot: int = Field(ge=1, le=9, description="This browser's slot, web-1 to web-9; each browser keeps its own") + # Only a hint within the caller's own callsign, which comes from the certificate: a made-up id can only move + # that person's own browsers. + browser: str = Field( + pattern=r"^[A-Za-z0-9-]{16,64}$", + description="A random id this browser keeps, so each of the caller's browsers gets its own web slot", + ) class Ticket(BaseModel): @@ -145,7 +150,7 @@ class Ticket(BaseModel): model_config = ConfigDict(extra="forbid") ticket: str = Field(description="The gateway's Murmur password for this login; valid for 60 s") - username: str = Field(description="The Mumble username it logs in, ---web-") + username: str = Field(description="The Mumble username it logs in: ---web-") class PresenceEntry(BaseModel): @@ -531,10 +536,11 @@ def voice_ticket(choice: TicketRequest, request: Request, store: StoreDep) -> Ti raise _refuse(404, "voice does not know this callsign yet", identity.callsign) if record.revoked or record.voice_disabled: raise _refuse(403, "voice is not enabled for this callsign in Deploy App", identity.callsign) - username = web_username(normalize_callsign(identity.callsign), choice.slot) + callsign, now = normalize_callsign(identity.callsign), time.time() # wall-clock: slots outlive a restart + username = web_username(callsign, store.web_slot(callsign, choice.browser, now)) LOGGER.info("Voice ticket for %s", username) leaf = identity.leaf.public_bytes(Encoding.DER) - return Ticket(ticket=mint(request.app.state.ticket_key, username, leaf, time.time()), username=username) + return Ticket(ticket=mint(request.app.state.ticket_key, username, leaf, now), username=username) public = APIRouter() diff --git a/tests/test_voice_api.py b/tests/test_voice_api.py index 4fee16f..f995d87 100644 --- a/tests/test_voice_api.py +++ b/tests/test_voice_api.py @@ -51,20 +51,45 @@ def client_fixture(pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> return client +LAPTOP = {"browser": "laptop-browser-01"} +PHONE = {"browser": "phone-browser-0002"} + + def _keys(client: TestClient) -> frozenset[str]: return frozenset(client.get("/api/v1/agent/state", headers=as_(AGENT)).json()["ticket_keys"]) def test_ticket_binds_the_slot_to_the_verified_leaf(client: TestClient, pki: Pki) -> None: """The agent's published key verifies the ticket, which carries the caller's own leaf""" - response = client.post("/api/v1/voice/token", json={"slot": 3}, headers=edge(pki.alpha, pki.ca)) + response = client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(pki.alpha, pki.ca)) assert response.status_code == 200 body = response.json() - assert body["username"] == "ALPHA_1---web-3" - leaf = verify(body["ticket"], _keys(client), "ALPHA_1---web-3", time.time()) + assert body["username"] == "ALPHA_1---web-1" + leaf = verify(body["ticket"], _keys(client), "ALPHA_1---web-1", time.time()) assert leaf == pki.alpha.der +def _username(client: TestClient, cert: Issued, browser: dict[str, str]) -> str: + response = client.post("/api/v1/voice/token", json=browser, headers=edge(cert)) + assert response.status_code == 200 + return str(response.json()["username"]) + + +def test_each_browser_keeps_its_own_slot(client: TestClient, pki: Pki) -> None: + """Two browsers of one callsign never share a slot, and a browser that comes back keeps its own""" + assert _username(client, pki.alpha, LAPTOP) == "ALPHA_1---web-1" + assert _username(client, pki.alpha, PHONE) == "ALPHA_1---web-2" + assert _username(client, pki.alpha, LAPTOP) == "ALPHA_1---web-1" + + +def test_browser_id_counts_only_within_the_callsign(client: TestClient, pki: Pki) -> None: + """The callsign comes from the certificate, so another person's browser id moves nobody else""" + assert _username(client, pki.alpha, LAPTOP) == "ALPHA_1---web-1" + assert _username(client, pki.alpha, PHONE) == "ALPHA_1---web-2" + assert _username(client, issue("BRAVO 2", pki.ca), PHONE) == "BRAVO_2---web-1" + assert _username(client, pki.alpha, LAPTOP) == "ALPHA_1---web-1" + + @pytest.mark.parametrize( "headers", [ @@ -76,28 +101,28 @@ def test_ticket_binds_the_slot_to_the_verified_leaf(client: TestClient, pki: Pki ) def test_refuses_without_the_edge_and_a_certificate(client: TestClient, headers: dict[str, str]) -> None: """Only Traefik's forwarded certificate counts""" - assert client.post("/api/v1/voice/token", json={"slot": 1}, headers=headers).status_code == 403 + assert client.post("/api/v1/voice/token", json=LAPTOP, headers=headers).status_code == 403 def test_refuses_a_certificate_from_another_ca(client: TestClient) -> None: """A self-made CA's certificate for a known callsign is refused""" rogue = issue("Rogue CA", ca=True) - response = client.post("/api/v1/voice/token", json={"slot": 1}, headers=edge(issue("ALPHA 1", rogue))) + response = client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(issue("ALPHA 1", rogue))) assert response.status_code == 403 def test_refuses_unknown_revoked_and_disabled(client: TestClient, pki: Pki) -> None: """Tickets fail closed: the callsign must be known (404 tells the UI to say so), unrevoked and have voice on""" stranger = issue("CHARLIE 3", pki.ca) - assert client.post("/api/v1/voice/token", json={"slot": 1}, headers=edge(stranger)).status_code == 404 + assert client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(stranger)).status_code == 404 bravo = issue("BRAVO 2", pki.ca) - assert client.post("/api/v1/voice/token", json={"slot": 1}, headers=edge(bravo)).status_code == 200 + assert client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(bravo)).status_code == 200 client.post("/api/v1/users/promoted", json=user("ALPHA 1"), headers=as_(RMAPI)) voice_off = client.put("/api/v1/admin/users/BRAVO 2/voice", json={"enabled": False}, headers=as_("ALPHA 1")) assert voice_off.status_code == 200 - assert client.post("/api/v1/voice/token", json={"slot": 1}, headers=edge(bravo)).status_code == 403 + assert client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(bravo)).status_code == 403 client.post("/api/v1/users/revoked", json=user("ALPHA 1"), headers=as_(RMAPI)) - assert client.post("/api/v1/voice/token", json={"slot": 1}, headers=edge(pki.alpha)).status_code == 403 + assert client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(pki.alpha)).status_code == 403 @pytest.mark.parametrize("content_type", ["text/plain", None]) @@ -106,13 +131,25 @@ def test_refuses_what_a_cross_site_page_can_send(client: TestClient, pki: Pki, c headers = {k: v for k, v in edge(pki.alpha).items() if k != "Content-Type"} if content_type: headers["Content-Type"] = content_type - response = client.post("/api/v1/voice/token", content=b'{"slot": 1}', headers=headers) + response = client.post("/api/v1/voice/token", content=b'{"browser": "laptop-browser-01"}', headers=headers) assert response.status_code == 422 -@pytest.mark.parametrize("body", [{"slot": 0}, {"slot": 10}, {"slot": 1, "username": "BRAVO_2---web-1"}, {}]) -def test_refuses_other_slots_and_fields(client: TestClient, pki: Pki, body: dict[str, object]) -> None: - """Only web-1 to web-9, and the caller cannot name anyone""" +@pytest.mark.parametrize( + "body", + [ + {"browser": "a" * 15}, + {"browser": "a" * 65}, + {"browser": "laptop_browser_01"}, + {"browser": "laptop-browser-01\n"}, + {"browser": 1234567890123456}, + {}, + {"slot": 3}, # the old request, when each browser picked its own slot + LAPTOP | {"username": "BRAVO_2---web-1"}, + ], +) +def test_refuses_bad_browser_ids_and_other_fields(client: TestClient, pki: Pki, body: dict[str, object]) -> None: + """A browser id is 16 to 64 letters, digits and dashes, and the caller cannot name a slot or anyone""" assert client.post("/api/v1/voice/token", json=body, headers=edge(pki.alpha)).status_code == 422 @@ -120,7 +157,7 @@ def test_no_bundle_no_tickets(tmp_path: Path, pki: Pki) -> None: """Without the CA bundle nothing can be checked, so nothing is minted""" settings = Settings(database=tmp_path / "db.sqlite", ca_bundle=tmp_path / "missing.pem", ui_dir=tmp_path / "x") client = TestClient(create_app(settings)) - assert client.post("/api/v1/voice/token", json={"slot": 1}, headers=edge(pki.alpha)).status_code == 503 + assert client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(pki.alpha)).status_code == 503 def test_restart_changes_the_etag(client: TestClient, tmp_path: Path, pki: Pki) -> None: diff --git a/ui/src/voice/Talk.tsx b/ui/src/voice/Talk.tsx index 16a65f7..8bb4924 100644 --- a/ui/src/voice/Talk.tsx +++ b/ui/src/voice/Talk.tsx @@ -1,7 +1,13 @@ // Voice in the browser: join a net and talk with push-to-talk, on a laptop or a phone (VOICE-PLAN ยง4.10). // Push-to-talk is the big button or a key or mouse button the user picks; it works only while this tab has // focus, and losing focus lets go. -import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; +import { + useCallback, + useEffect, + useRef, + useState, + useSyncExternalStore, +} from "react"; import type { CSSProperties } from "react"; import { useTranslation } from "react-i18next"; @@ -17,7 +23,7 @@ import { isButton, isKey, loadBinding, - loadSlot, + loadBrowser, saveBinding, talksOn, } from "./ptt"; @@ -331,6 +337,13 @@ export function Talk() { const s = useSyncExternalStore(client.subscribe, client.getSnapshot); const [binding, setBinding] = useState(() => loadBinding(storage())); const [choosing, setChoosing] = useState(false); + // This browser's id, read on the first click (not while rendering) and kept for the page even where storage + // throws, so every join from this page logs in the same slot + const browser = useRef(null); + const connect = () => { + browser.current ??= loadBrowser(storage(), () => crypto.randomUUID()); + void client.connect(browser.current); + }; const chosen = useCallback((next: Binding | null) => { if (next) { saveBinding(storage(), next); @@ -363,9 +376,7 @@ export function Talk() { type="button" aria-disabled={s.phase === "connecting"} className={ui.cx(ui.BTN, ui.BTN_PRIMARY_V)} - onClick={() => - void client.connect(loadSlot(storage(), Math.random)) - } + onClick={connect} > {s.phase === "connecting" ? ( diff --git a/ui/src/voice/client.ts b/ui/src/voice/client.ts index a31ae41..0751bd0 100644 --- a/ui/src/voice/client.ts +++ b/ui/src/voice/client.ts @@ -69,12 +69,12 @@ class Stop extends Error { } } -async function fetchTicket(slot: number): Promise { +async function fetchTicket(browser: string): Promise { const response = await fetch(TOKEN_URL, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ slot }), + body: JSON.stringify({ browser }), }); if (response.status === 404) throw new Stop("unknown"); if (response.status === 403) throw new Stop("refused"); @@ -111,7 +111,7 @@ export class VoiceClient { } // Must be called from a click: browsers unlock audio only inside a user gesture. - async connect(slot: number): Promise { + async connect(browser: string): Promise { if (this.snapshot.phase !== "idle") return; const generation = ++this.generation; this.set({ ...IDLE, phase: "connecting" }); @@ -133,7 +133,7 @@ export class VoiceClient { } this.mic = mic; this.speakers = new Speakers(ctx); - const ticket = await fetchTicket(slot); + const ticket = await fetchTicket(browser); if (generation !== this.generation) return; this.open(ticket, generation); } catch (e) { diff --git a/ui/src/voice/ptt.ts b/ui/src/voice/ptt.ts index f04622f..1ee527b 100644 --- a/ui/src/voice/ptt.ts +++ b/ui/src/voice/ptt.ts @@ -1,4 +1,4 @@ -// The push-to-talk binding and this browser's slot, both remembered per browser. No imports, so +// The push-to-talk binding and this browser's id, both remembered per browser. No imports, so // `node --test` can load this file directly. // A key by its physical position (KeyboardEvent.code), so the layout does not matter, or an extra mouse @@ -11,7 +11,9 @@ export const DEFAULT_BINDING: Binding = { kind: "key", code: "Tab" }; // Middle and the two side buttons; the primary and context buttons stay with the page export const MOUSE_BUTTONS = [1, 3, 4]; const BINDING_KEY = "mumble.ptt"; -const SLOT_KEY = "mumble.webSlot"; +const BROWSER_KEY = "mumble.browser"; +// As mumblermapi's TicketRequest.browser accepts it +const BROWSER_ID = /^[A-Za-z0-9-]{16,64}$/; // Storage can be missing or throw (private windows, blocked site data); the defaults then apply. type Store = Pick; @@ -96,12 +98,12 @@ export const talksOn = (binding: Binding, e: KeyLike): boolean => export const isButton = (binding: Binding, button: number): boolean => binding.kind === "mouse" && binding.button === button; -// Which of web-1 to web-9 this browser uses. Each browser keeps its own, so a laptop and a phone can be in -// voice at once; a second tab in the same browser takes over from the first. -export function loadSlot(store: Store | null, random: () => number): number { - const slot = Number(read(store, SLOT_KEY)); - if (Number.isInteger(slot) && slot >= 1 && slot <= 9) return slot; - const fresh = 1 + Math.floor(random() * 9); - write(store, SLOT_KEY, String(fresh)); - return fresh; +// A random id this browser keeps. mumblermapi gives each of a person's browsers its own web slot by it, so a +// laptop and a phone can be in voice at once; a second tab in the same browser takes over from the first. +export function loadBrowser(store: Store | null, fresh: () => string): string { + const stored = read(store, BROWSER_KEY); + if (stored !== null && BROWSER_ID.test(stored)) return stored; + const id = fresh(); + write(store, BROWSER_KEY, id); + return id; } diff --git a/ui/test/ptt.test.mjs b/ui/test/ptt.test.mjs index 609d7a4..7d969de 100644 --- a/ui/test/ptt.test.mjs +++ b/ui/test/ptt.test.mjs @@ -1,4 +1,4 @@ -// Unit tests for the push-to-talk binding and the browser slot: `pnpm test`. +// Unit tests for the push-to-talk binding and the browser id: `pnpm test`. import assert from "node:assert/strict"; import { describe, it } from "node:test"; @@ -8,7 +8,7 @@ import { isButton, isKey, loadBinding, - loadSlot, + loadBrowser, parseBinding, saveBinding, talksOn, @@ -112,25 +112,43 @@ describe("talksOn", () => { }); }); -describe("slot", () => { - it("picks one of web-1 to web-9 once and keeps it", () => { +describe("browser", () => { + const id = "laptop-browser-01"; + it("keeps a valid stored id", () => { const store = memory(); + store.setItem("mumble.browser", id); assert.equal( - loadSlot(store, () => 0.999), - 9, + loadBrowser(store, () => assert.fail("fresh")), + id, ); + }); + it("replaces a missing or malformed id and stores the new one", () => { + for (const bad of [ + null, + "", + "a".repeat(15), + "a".repeat(65), + "laptop_browser_01", + "laptop-browser-01\n", + ]) { + const store = memory(); + if (bad !== null) store.setItem("mumble.browser", bad); + assert.equal( + loadBrowser(store, () => id), + id, + String(bad), + ); + assert.equal(store.data.get("mumble.browser"), id); + } + }); + it("gives a fresh id without storage", () => { assert.equal( - loadSlot(store, () => 0), - 9, - ); - store.setItem("mumble.webSlot", "12"); - assert.equal( - loadSlot(store, () => 0), - 1, + loadBrowser(broken, () => id), + id, ); assert.equal( - loadSlot(broken, () => 0.5), - 5, + loadBrowser(null, () => id), + id, ); }); }); From fa2226b6406f133327a69e3227d32e6cc7101c84 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 14:10:26 +0200 Subject: [PATCH 06/19] chore: bump version to 1.0.4+261119 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/mumblermapi/__init__.py | 2 +- uv.lock | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index c4f440f..55510d4 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.0.3+261117" +current_version = "1.0.4+261119" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index 743b845..d6f8c1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mumblermapi" -version = "1.0.3+261117" +version = "1.0.4+261119" description = "Murmur (Mumble server) integration for the OpenDefence platform" license = { text = "GPL-2.0-only" } readme = "README.md" diff --git a/src/mumblermapi/__init__.py b/src/mumblermapi/__init__.py index 9c0d10b..7eb5b21 100644 --- a/src/mumblermapi/__init__.py +++ b/src/mumblermapi/__init__.py @@ -1,3 +1,3 @@ """Murmur integration for the OpenDefence platform""" -__version__ = "1.0.3+261117" +__version__ = "1.0.4+261119" diff --git a/uv.lock b/uv.lock index 4a2696d..8c366ce 100644 --- a/uv.lock +++ b/uv.lock @@ -964,7 +964,7 @@ wheels = [ [[package]] name = "mumblermapi" -version = "1.0.3+261117" +version = "1.0.4+261119" source = { editable = "." } dependencies = [ { name = "aiohttp" }, From f8f8f533da9fc58f979e9269687f67451fd3dc27 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:49:39 +0200 Subject: [PATCH 07/19] fix(agent): answer Murmur even when a login check fails Murmur drops an authenticator whose call raises, and every login then fails until the agent registers it again. --- src/mumblermapi/agent.py | 23 +++++++++++++++++------ tests/test_agent.py | 27 ++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index 344ac08..103b192 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -11,7 +11,7 @@ import signal import threading import time -from collections.abc import Iterator +from collections.abc import Callable, Iterator from contextlib import contextmanager from dataclasses import dataclass, field from importlib.resources import files @@ -20,7 +20,7 @@ from libpvarki.logging import add_trace_and_audit, init_logging -from .authenticator import Authenticator +from .authenticator import TRY_LATER, UNKNOWN, Authenticator from .channels import ChannelRefused, ExistingChannel, desired_tree, load_plan, prune, reconcile from .config import AgentConfig from .enforce import Acl, Session, acl_of, combine, plan, refused, shadows, violations @@ -44,6 +44,16 @@ def _load_ice() -> tuple[ModuleType, ModuleType]: # pragma: no cover # needs t return Ice, MumbleServer +def _answer[T](call: Callable[[], T], fallback: T) -> T: + """call's answer, or fallback when it raises. Murmur removes an authenticator that fails a call, and every + login then needs the server password, which nobody is given.""" + try: + return call() + except Exception: + LOGGER.exception("A check for Murmur failed, so it is answered %r", fallback) + return fallback + + def _servant(mumble: ModuleType, auth: Authenticator) -> Any: """A ServerAuthenticator that delegates to the Ice-free Authenticator""" @@ -62,20 +72,21 @@ def authenticate( # The password is a credential only from the voice gateway, where it is a mumblermapi ticket. certstrong # is Murmur's notion of trust, not ours. del certhash, certstrong, current - return auth.authenticate(name, [bytes(cert) for cert in certificates], pw), "", [] + user_id = _answer(lambda: auth.authenticate(name, [bytes(cert) for cert in certificates], pw), TRY_LATER) + return user_id, "", [] def getInfo(self, id: int, current: Any = None) -> tuple[bool, dict[Any, str]]: del current - name = auth.id_to_name(id) + name = _answer(lambda: auth.id_to_name(id), "") return (True, {mumble.UserInfo.UserName: name}) if name else (False, {}) def nameToId(self, name: str, current: Any = None) -> int: del current - return auth.name_to_id(name) + return _answer(lambda: auth.name_to_id(name), UNKNOWN) def idToName(self, id: int, current: Any = None) -> str: del current - return auth.id_to_name(id) + return _answer(lambda: auth.id_to_name(id), "") def idToTexture(self, id: int, current: Any = None) -> bytes: del id, current diff --git a/tests/test_agent.py b/tests/test_agent.py index 067a87f..0445b3e 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -10,7 +10,7 @@ import pytest from mumblermapi import agent -from mumblermapi.authenticator import Refusal +from mumblermapi.authenticator import TRY_LATER, UNKNOWN, Refusal from mumblermapi.channels import MAX_DEPTH from mumblermapi.enforce import OPEN, acl_of, members_only from mumblermapi.policy import Policy, Unit @@ -336,6 +336,31 @@ def test_servant() -> None: assert servant.idToTexture(7) == b"" +class BrokenAuth: + """Every check fails, as with a full disk, a responder answering garbage, or a bug""" + + def __init__(self, error: Exception) -> None: + self.error = error + + def __getattr__(self, name: str) -> Any: + def broken(*args: object) -> Any: + raise self.error + + return broken + + +@pytest.mark.parametrize("error", [OSError("no space left on device"), ValueError("garbage"), KeyError("a bug")]) +def test_servant_answers_when_a_check_fails(caplog: pytest.LogCaptureFixture, error: Exception) -> None: + """A failing check is a "try later" or "unknown" answer, never an error, which would make Murmur drop the + authenticator and refuse every login""" + servant = agent._servant(MUMBLE, BrokenAuth(error)) # type: ignore[arg-type] + with caplog.at_level(logging.ERROR, logger=agent.__name__): + assert servant.authenticate("VOICE1---a", "", [b"cert"], "hash", True) == (TRY_LATER, "", []) + assert servant.getInfo(7) == (False, {}) + assert servant.nameToId("VOICE1---a") == UNKNOWN and servant.idToName(7) == "" + assert len(caplog.records) == 4 and all(r.exc_info for r in caplog.records) + + def test_channel_description() -> None: """New channels get their description""" server = FakeServer() From 7f046ced9b6941558129fb5294210475c8673a02 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:50:24 +0200 Subject: [PATCH 08/19] fix(authenticator): refuse overlong usernames before reading them Murmur checks its 512-character limit only after asking us, so anyone could have a megabyte name parsed and logged. --- src/mumblermapi/authenticator.py | 7 ++++++- tests/test_authenticator.py | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/mumblermapi/authenticator.py b/src/mumblermapi/authenticator.py index f7e854d..5787464 100644 --- a/src/mumblermapi/authenticator.py +++ b/src/mumblermapi/authenticator.py @@ -21,6 +21,9 @@ REJECT = -1 UNKNOWN = -2 TRY_LATER = -3 +# Murmur's own limit, which it applies only to logins the authenticator leaves to it. It hands the authenticator +# any name, of up to 8 MiB and before any certificate, so this is the only length check on a login. +MAX_NAME_LENGTH = 512 class RevocationCheck(Protocol): @@ -100,6 +103,8 @@ def _chain(self, name: str, username: Username, certificates: list[bytes], ticke def refusal(self, name: str, certificates: list[bytes], ticket: str | None = None) -> Refusal | None: """Why this connection must not be in, or None when it may. ticket is the login password; the sweep leaves it out.""" + if len(name) > MAX_NAME_LENGTH: + return Refusal(f"username over {MAX_NAME_LENGTH} characters") now = self._clock() try: username = parse_username(name) @@ -123,7 +128,7 @@ def authenticate(self, name: str, certificates: list[bytes], ticket: str = "") - the login's password, which matters only from the voice gateway.""" refusal = self.refusal(name, certificates, ticket) if refusal is not None: - LOGGER.log(AUDIT, "Refused %r: %s", name, refusal.reason) + LOGGER.log(AUDIT, "Refused %r: %s", name[:MAX_NAME_LENGTH], refusal.reason) return TRY_LATER if refusal.transient else REJECT user_id = self._ids.get_or_assign(name) LOGGER.info("Accepted %r as user %d", name, user_id) diff --git a/tests/test_authenticator.py b/tests/test_authenticator.py index 79372e6..14e75dd 100644 --- a/tests/test_authenticator.py +++ b/tests/test_authenticator.py @@ -2,12 +2,13 @@ from __future__ import annotations +import logging from datetime import datetime from pathlib import Path import pytest -from mumblermapi.authenticator import REJECT, TRY_LATER, UNKNOWN, Authenticator, Refusal +from mumblermapi.authenticator import MAX_NAME_LENGTH, REJECT, TRY_LATER, UNKNOWN, Authenticator, Refusal from mumblermapi.identity import CertVerifier, Identity from mumblermapi.ocsp import OcspUnavailable from mumblermapi.policy import Policy @@ -84,6 +85,18 @@ def test_refusal_explains(pki: Pki, tmp_path: Path) -> None: assert auth.refusal("ALPHA_1---vs1", [pki.alpha.der]) == Refusal("down", transient=True) +def test_overlong_names_are_refused_unread(pki: Pki, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + """Murmur asks before checking the length itself; neither the check nor the log takes the whole name""" + auth = _auth(pki, tmp_path) + with caplog.at_level(logging.DEBUG): + assert auth.authenticate("A" * (MAX_NAME_LENGTH + 1) + "---" + "x" * 1_000_000, [pki.alpha.der]) == REJECT + assert caplog.records[-1].getMessage().endswith(f"username over {MAX_NAME_LENGTH} characters") + assert all(len(r.getMessage()) < 2 * MAX_NAME_LENGTH for r in caplog.records) + # Murmur's own limit, 512, still gets as far as the other checks + longest = auth.refusal("A" * MAX_NAME_LENGTH, [pki.alpha.der]) + assert MAX_NAME_LENGTH == 512 and longest is not None and "characters" not in longest.reason + + def test_unknown_names_and_ids(pki: Pki, tmp_path: Path) -> None: """Names and ids the agent never assigned fall through to Murmur""" auth = _auth(pki, tmp_path) From 65437eea79110254fb3be3270ba0ecf34b2c57b0 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:51:06 +0200 Subject: [PATCH 09/19] fix(agent): take every login Murmur can forward Murmur forwards names and passwords from a message of up to 8 MiB, with each invalid UTF-8 byte re-encoded as three, and a call over Ice's 1 MiB default made it drop the authenticator. Answers over the limit are now logged as such, not as Murmur not being ready. --- src/mumblermapi/agent.py | 36 ++++++++++++++++++++++++++++++------ tests/fake_murmur.py | 5 +++++ tests/test_agent.py | 36 +++++++++++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 7 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index 103b192..662fd51 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -32,6 +32,17 @@ LOGGER = logging.getLogger(__name__) _SLICE_FALLBACK_DIR = "/usr/share/ice/slice" +# Murmur forwards a login's name and password, before checking either, from a message of up to 8 MiB. It decodes +# them as UTF-8 and encodes them again for Ice, which makes each invalid byte three, and it drops the authenticator +# when the call fails. Anything smaller on the agent's adapter lets anyone stop every login; the certificate chain +# needs room on top. +MURMUR_MESSAGE_BYTES = 0x7FFFFF +ADAPTER = "Agent" +ADAPTER_MESSAGE_KIB = 3 * MURMUR_MESSAGE_BYTES // 1024 + 1024 +# Murmur's answers list every user or channel at once and have no such bound: comments stay under 5000 characters +# with HTML off, so this holds several hundred users' worth, but nothing in Murmur caps the plugin data a client +# sends. +ICE_MESSAGE_KIB = 10 * 1024 def _load_ice() -> tuple[ModuleType, ModuleType]: # pragma: no cover # needs the image's Ice @@ -54,6 +65,15 @@ def _answer[T](call: Callable[[], T], fallback: T) -> T: return fallback +def _properties(ice: ModuleType) -> Any: + """The secret goes with every call, and messages may be as large as Murmur makes them""" + properties = ice.createProperties() + properties.setProperty("Ice.ImplicitContext", "Shared") + properties.setProperty("Ice.MessageSizeMax", str(ICE_MESSAGE_KIB)) + properties.setProperty(f"{ADAPTER}.MessageSizeMax", str(ADAPTER_MESSAGE_KIB)) + return properties + + def _servant(mumble: ModuleType, auth: Authenticator) -> Any: """A ServerAuthenticator that delegates to the Ice-free Authenticator""" @@ -293,7 +313,7 @@ def round(self, server: Any, policy: Policy, units: bool) -> None: try: _sweep(self.mumble, server, self.auth) except not_ready as exc: - LOGGER.warning("Murmur not ready for the certificate sweep: %s", exc) + self._failed("the certificate sweep", exc) else: self.next_sweep = time.monotonic() + self.sweep_seconds try: @@ -301,10 +321,16 @@ def round(self, server: Any, policy: Policy, units: bool) -> None: if self.reporter: self.reporter.report(_presence(self.mumble, server), time.monotonic()) except not_ready as exc: - LOGGER.warning("Murmur not ready: %s", exc) + self._failed("the plan", exc) else: self.left_out = _warn_left_out(left_out, self.left_out) + def _failed(self, what: str, exc: Exception) -> None: + if isinstance(exc, self.ice.MemoryLimitException): + LOGGER.error("Murmur's answer for %s is over the agent's %d KiB limit: %s", what, ICE_MESSAGE_KIB, exc) + else: + LOGGER.warning("Murmur not ready for %s: %s", what, exc) + def run(config: AgentConfig, stop: threading.Event) -> None: # pragma: no cover # needs Ice and Murmur """Register with Murmur and keep it in shape until stopped""" @@ -328,13 +354,11 @@ def policy() -> Policy: gateway=CertVerifier.from_pem_file(config.gateway_ca) if config.gateway_ca else None, ) - properties = ice.createProperties() - properties.setProperty("Ice.ImplicitContext", "Shared") init_data = ice.InitializationData() - init_data.properties = properties + init_data.properties = _properties(ice) with ice.initialize(init_data) as communicator: communicator.getImplicitContext().put("secret", config.ice_secret) - adapter = communicator.createObjectAdapterWithEndpoints("Agent", f"tcp -h 127.0.0.1 -p {config.callback_port}") + adapter = communicator.createObjectAdapterWithEndpoints(ADAPTER, f"tcp -h 127.0.0.1 -p {config.callback_port}") adapter.activate() authenticator = mumble.ServerAuthenticatorPrx.uncheckedCast(adapter.addWithUUID(_servant(mumble, auth))) meta = mumble.MetaPrx.uncheckedCast( diff --git a/tests/fake_murmur.py b/tests/fake_murmur.py index 0ea968c..c89f9ec 100644 --- a/tests/fake_murmur.py +++ b/tests/fake_murmur.py @@ -11,6 +11,10 @@ class IceException(Exception): """Ice.Exception, which every error over Ice derives from""" +class MemoryLimitException(IceException): + """Ice's: a message is over Ice.MessageSizeMax""" + + class InvalidSessionException(IceException): """Murmur's: the session is gone""" @@ -59,6 +63,7 @@ def __init__( # Stand in for the Ice module and the MumbleServer module that Ice generates from the slice ICE = ModuleType("Ice") ICE.Exception = IceException # type: ignore[attr-defined] +ICE.MemoryLimitException = MemoryLimitException # type: ignore[attr-defined] MUMBLE = ModuleType("MumbleServer") MUMBLE.InvalidSessionException = InvalidSessionException # type: ignore[attr-defined] MUMBLE.InvalidChannelException = InvalidChannelException # type: ignore[attr-defined] diff --git a/tests/test_agent.py b/tests/test_agent.py index 0445b3e..3d4851a 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -17,7 +17,14 @@ from mumblermapi.presence import PresenceReporter from mumblermapi.userids import UserIds -from .fake_murmur import ICE, MUMBLE, FakeServer, InvalidSecretException, NestingLimitException +from .fake_murmur import ( + ICE, + MUMBLE, + FakeServer, + InvalidSecretException, + MemoryLimitException, + NestingLimitException, +) POLICY = Policy( version=2, @@ -313,6 +320,22 @@ def test_a_failed_sweep_holds_up_nothing(ids: UserIds) -> None: assert server.id_of("/Units/10") and len(reports) == 1 and loop.next_sweep == 0 +def test_a_round_names_oversized_answers(ids: UserIds, caplog: pytest.LogCaptureFixture) -> None: + """An answer over Ice's limit is no outage: the log says what it is""" + + def oversized(*args: object) -> Any: + raise MemoryLimitException() + + server = murmur() + server.getUsers = oversized # type: ignore[method-assign] + with caplog.at_level(logging.WARNING, logger=agent.__name__): + rounds(ids).round(server, POLICY, units=True) + assert [(r.levelname, r.getMessage().split(" is over")[0]) for r in caplog.records] == [ + ("ERROR", "Murmur's answer for the certificate sweep"), + ("ERROR", "Murmur's answer for the plan"), + ] + + def test_a_round_warns_about_refused_nets(ids: UserIds, caplog: pytest.LogCaptureFixture) -> None: """Once, not every round""" server = murmur() @@ -361,6 +384,17 @@ def test_servant_answers_when_a_check_fails(caplog: pytest.LogCaptureFixture, er assert len(caplog.records) == 4 and all(r.exc_info for r in caplog.records) +def test_ice_takes_what_murmur_sends() -> None: + """Murmur's largest login, with every invalid UTF-8 byte re-encoded as three, fits the agent's adapter with + room for a certificate chain; Murmur's answers to the agent get their own limit""" + properties: dict[str, str] = {} + ice: Any = SimpleNamespace(createProperties=lambda: SimpleNamespace(setProperty=properties.__setitem__)) + agent._properties(ice) + assert int(properties[f"{agent.ADAPTER}.MessageSizeMax"]) * 1024 >= 3 * 0x7FFFFF + 512 * 1024 + assert properties["Ice.MessageSizeMax"] == str(agent.ICE_MESSAGE_KIB) + assert properties["Ice.ImplicitContext"] == "Shared" + + def test_channel_description() -> None: """New channels get their description""" server = FakeServer() From b2fbc0f18eaaeb0f0e851f15ec5da0dbeef56aea Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:51:28 +0200 Subject: [PATCH 10/19] fix(userids): hand out an id only once it is saved A failed save left the id in memory, and after a restart it could go to another name. --- src/mumblermapi/userids.py | 9 +++++---- tests/test_userids.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/mumblermapi/userids.py b/src/mumblermapi/userids.py index c97f411..7172d9e 100644 --- a/src/mumblermapi/userids.py +++ b/src/mumblermapi/userids.py @@ -34,20 +34,21 @@ def _load(self) -> dict[str, int]: raise ValueError(f"{self._path} gives one id to several names") return data - def _save(self) -> None: + def _save(self, by_name: dict[str, int]) -> None: tmp = self._path.with_suffix(".tmp") - tmp.write_text(json.dumps(self._by_name, indent=1, sort_keys=True), encoding="utf-8") + tmp.write_text(json.dumps(by_name, indent=1, sort_keys=True), encoding="utf-8") os.replace(tmp, self._path) def get_or_assign(self, name: str) -> int: - """The name's id, assigning the next free one the first time""" + """The name's id, assigning the next free one the first time. The id is handed out only once saved, so a + failed save cannot give it to another name after a restart.""" with self._lock: user_id = self._by_name.get(name) if user_id is None: user_id = max(self._by_id, default=0) + 1 + self._save({**self._by_name, name: user_id}) self._by_name[name] = user_id self._by_id[user_id] = name - self._save() return user_id def id_for(self, name: str) -> int | None: diff --git a/tests/test_userids.py b/tests/test_userids.py index 1abbc62..9591cfe 100644 --- a/tests/test_userids.py +++ b/tests/test_userids.py @@ -41,3 +41,20 @@ def test_names(tmp_path: Path) -> None: names = ids.names() names["B"] = 9 assert ids.names() == {"A---vs1": 1} + + +def test_unsaved_ids_are_not_handed_out(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A full disk refuses the login; the id is not remembered for a name the file does not have""" + path = tmp_path / "ids.json" + ids = UserIds(path) + ids.get_or_assign("A---a") + + def full(*args: object) -> None: + raise OSError("no space left on device") + + with monkeypatch.context() as patch: + patch.setattr(ids, "_save", full) + with pytest.raises(OSError): + ids.get_or_assign("B---b") + assert ids.id_for("B---b") is None and ids.name_for(2) is None + assert ids.get_or_assign("C---c") == 2 == UserIds(path).id_for("C---c") From fdbbffc7e035fe6af6d6d545c68e77875ee01072 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:52:24 +0200 Subject: [PATCH 11/19] fix: treat malformed HTTP answers as unavailable http.client errors are no OSError, so they escaped the policy poll, presence reports and OCSP checks. A state over the size limit is now named as such instead of being cut short and read as garbage. --- src/mumblermapi/ocsp.py | 5 +++-- src/mumblermapi/policy.py | 9 ++++++--- src/mumblermapi/presence.py | 3 ++- tests/test_ocsp.py | 8 ++++++++ tests/test_policy.py | 22 +++++++++++++++++++--- tests/test_presence.py | 10 ++++++---- 6 files changed, 44 insertions(+), 13 deletions(-) diff --git a/src/mumblermapi/ocsp.py b/src/mumblermapi/ocsp.py index acd65ca..14472cb 100644 --- a/src/mumblermapi/ocsp.py +++ b/src/mumblermapi/ocsp.py @@ -2,6 +2,7 @@ from __future__ import annotations +import http.client import logging import threading import time @@ -47,8 +48,8 @@ def http_post(url: str, body: bytes, timeout: float) -> bytes: raise OcspUnavailable(f"OCSP responder answered HTTP {response.status}") data: bytes = response.read(MAX_RESPONSE_BYTES) return data - except OSError as exc: - raise OcspUnavailable(f"OCSP responder unreachable: {exc}") from exc + except (OSError, http.client.HTTPException) as exc: + raise OcspUnavailable(f"OCSP responder unreachable: {exc!r}") from exc def responder_url(cert: x509.Certificate) -> str | None: diff --git a/src/mumblermapi/policy.py b/src/mumblermapi/policy.py index e5c0628..b35d2fa 100644 --- a/src/mumblermapi/policy.py +++ b/src/mumblermapi/policy.py @@ -2,6 +2,7 @@ from __future__ import annotations +import http.client import json import logging import urllib.request @@ -117,7 +118,9 @@ def http_get(url: str, headers: dict[str, str], timeout: float) -> tuple[int, by try: # The scheme is checked above, so urlopen cannot be steered to file:// or similar. with urllib.request.urlopen(request, timeout=timeout) as response: # nosec B310 - body: bytes = response.read(MAX_STATE_BYTES) + body: bytes = response.read(MAX_STATE_BYTES + 1) + if len(body) > MAX_STATE_BYTES: + raise ValueError(f"the state is over {MAX_STATE_BYTES} bytes") return response.status, body except urllib.error.HTTPError as exc: return exc.code, b"" @@ -145,8 +148,8 @@ def refresh(self) -> bool: raise ValueError(f"HTTP {status}") data = json.loads(body) policy = parse_state(data) - except (OSError, ValueError, TypeError, KeyError) as exc: - LOGGER.warning("Keeping policy version %d, mumblermapi unavailable: %s", self.policy.version, exc) + except (OSError, http.client.HTTPException, ValueError, TypeError, KeyError) as exc: + LOGGER.warning("Keeping policy version %d, none newer from mumblermapi: %s", self.policy.version, exc) return False # The ETag also follows mumblermapi's ticket key; older mumblermapis send the version alone self._etag = str(data.get("etag", policy.version)) diff --git a/src/mumblermapi/presence.py b/src/mumblermapi/presence.py index 0b815dd..131a30b 100644 --- a/src/mumblermapi/presence.py +++ b/src/mumblermapi/presence.py @@ -2,6 +2,7 @@ from __future__ import annotations +import http.client import json import logging import urllib.error @@ -79,7 +80,7 @@ def report(self, entries: list[Entry], now: float) -> None: return try: status = self.post(self.url, {"sessions": entries}, self.timeout) - except (OSError, ValueError) as exc: + except (OSError, http.client.HTTPException, ValueError) as exc: LOGGER.warning("Could not report presence: %s", exc) return if status != 200: diff --git a/tests/test_ocsp.py b/tests/test_ocsp.py index d140cf2..7bc0c8c 100644 --- a/tests/test_ocsp.py +++ b/tests/test_ocsp.py @@ -2,6 +2,7 @@ from __future__ import annotations +import http.client import io import urllib.request from datetime import timedelta @@ -297,5 +298,12 @@ def refuse(request: urllib.request.Request, timeout: float) -> _FakeHttpResponse with pytest.raises(OcspUnavailable, match="unreachable"): http_post(URL, b"q", 1.0) + def garble(request: urllib.request.Request, timeout: float) -> _FakeHttpResponse: + raise http.client.BadStatusLine("junk") + + monkeypatch.setattr(urllib.request, "urlopen", garble) + with pytest.raises(OcspUnavailable, match="BadStatusLine"): + http_post(URL, b"q", 1.0) + with pytest.raises(OcspUnavailable, match="refusing"): http_post("file:///etc/passwd", b"q", 1.0) diff --git a/tests/test_policy.py b/tests/test_policy.py index 921cf67..fe078bd 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -2,6 +2,7 @@ from __future__ import annotations +import http.client import io import json import urllib.error @@ -10,7 +11,7 @@ import pytest from mumblermapi.channels import GUARD, ChannelSpec -from mumblermapi.policy import Policy, PolicySource, Unit, from_plan, http_get, parse_state +from mumblermapi.policy import MAX_STATE_BYTES, Policy, PolicySource, Unit, from_plan, http_get, parse_state STATE = { "version": 7, @@ -95,14 +96,23 @@ def __call__(self, url: str, headers: dict[str, str], timeout: float) -> tuple[i def test_source_polls_with_etag_and_survives_outages() -> None: """A change is reported once; 304s, errors and garbage keep the last good policy""" body = json.dumps(STATE).encode() - get = FakeGet((200, body), (304, b""), OSError("down"), (500, b""), (200, b"junk"), (200, b"{}"), (200, body)) + get = FakeGet( + (200, body), + (304, b""), + OSError("down"), + http.client.IncompleteRead(b"{"), + (500, b""), + (200, b"junk"), + (200, b"{}"), + (200, body), + ) source = PolicySource(url="http://mumblermapi/api/v1/agent/state", policy=Policy(), get=get) assert not source.ready assert source.refresh() is True assert source.ready assert source.policy.version == 7 assert get.headers[0] == {} - for _ in range(5): + for _ in range(6): assert source.refresh() is False assert get.headers[1] == {"If-None-Match": "7"} assert source.refresh() is False # same document again @@ -125,6 +135,12 @@ def not_modified(request: urllib.request.Request, timeout: float) -> _Resp: assert http_get("http://x/state", {"If-None-Match": "7"}, 1.0) == (304, b"") with pytest.raises(ValueError): http_get("file:///etc/passwd", {}, 1.0) + # Cut short, it would be read as garbage; the log says what it is + monkeypatch.setattr(urllib.request, "urlopen", lambda request, timeout: _Resp(b" " * (MAX_STATE_BYTES + 1))) + with pytest.raises(ValueError, match="over"): + http_get("http://x/state", {}, 1.0) + monkeypatch.setattr(urllib.request, "urlopen", lambda request, timeout: _Resp(b" " * MAX_STATE_BYTES)) + assert len(http_get("http://x/state", {}, 1.0)[1]) == MAX_STATE_BYTES def test_unit_defaults() -> None: diff --git a/tests/test_presence.py b/tests/test_presence.py index 0dfc86e..3d3c916 100644 --- a/tests/test_presence.py +++ b/tests/test_presence.py @@ -2,6 +2,7 @@ from __future__ import annotations +import http.client import io import urllib.error import urllib.request @@ -57,17 +58,18 @@ def __call__(self, url: str, body: object, timeout: float) -> int: def test_reports_changes_and_heartbeats() -> None: """Unchanged presence is resent only after the heartbeat; failures are retried at once""" - post = FakePost(200, OSError("down"), 500, 200, 200) + post = FakePost(200, OSError("down"), http.client.BadStatusLine("junk"), 500, 200, 200) reporter = PresenceReporter(url="http://m/api/v1/agent/presence", post=post, heartbeat=30) one = [{"callsign": "VOICE1", "channel": "/"}] two = [*one, {"callsign": "VOICE3", "channel": "/"}] reporter.report(one, now=0) reporter.report(one, now=10) # unchanged, not due reporter.report(two, now=11) # changed: fails - reporter.report(two, now=12) # retried: refused - reporter.report(two, now=13) # retried: sent + reporter.report(two, now=12) # retried: garbled + reporter.report(two, now=13) # retried: refused + reporter.report(two, now=14) # retried: sent reporter.report(two, now=50) # heartbeat - assert post.bodies == [{"sessions": one}] + [{"sessions": two}] * 4 + assert post.bodies == [{"sessions": one}] + [{"sessions": two}] * 5 class _Resp(io.BytesIO): From 1cbf69eeba276eb23a591af40bb66c7114ab4025 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:53:06 +0200 Subject: [PATCH 12/19] fix(ocsp): leave a failed responder alone for a while During an outage every login and every connected user in the sweep waited out its own timeout, holding up the agent's whole round. --- src/mumblermapi/ocsp.py | 15 +++++++++++++-- tests/test_ocsp.py | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/mumblermapi/ocsp.py b/src/mumblermapi/ocsp.py index 14472cb..673c18c 100644 --- a/src/mumblermapi/ocsp.py +++ b/src/mumblermapi/ocsp.py @@ -102,7 +102,9 @@ class OcspChecker: """Asks the responder whether a certificate is revoked, caching answers. Revocations are issued only in rmapi. While the responder is unreachable nobody can revoke anything, so a - certificate that was answered "good" before stays good; one never seen before is refused. + certificate that was answered "good" before stays good; one never seen before is refused. A responder that + failed is left alone for retry_seconds, so that an outage costs one timeout, not one per login and per + connected user in the sweep. """ def __init__( @@ -111,14 +113,17 @@ def __init__( url_override: str | None = None, cache_seconds: float = 300.0, timeout: float = 3.0, + retry_seconds: float = 10.0, fetch: Fetch = http_post, clock: Callable[[], float] = time.monotonic, ) -> None: self._url_override = url_override self._cache_seconds = cache_seconds self._timeout = timeout + self._retry_seconds = retry_seconds self._fetch = fetch self._clock = clock + self._down_until: dict[str, float] = {} # by responder URL self._good: dict[int, float] = {} self._revoked: set[int] = set() self._lock = threading.Lock() @@ -152,8 +157,14 @@ def _query(self, identity: Identity, now: datetime) -> ocsp.OCSPCertStatus: url = self._url_override or responder_url(identity.leaf) if not url: raise OcspUnavailable("certificate names no OCSP responder") + if self._clock() < self._down_until.get(url, float("-inf")): + raise OcspUnavailable("OCSP responder failed moments ago") request = ocsp.OCSPRequestBuilder().add_certificate(identity.leaf, identity.issuer, hashes.SHA256()).build() - body = self._fetch(url, request.public_bytes(Encoding.DER), self._timeout) + try: + body = self._fetch(url, request.public_bytes(Encoding.DER), self._timeout) + except OcspUnavailable: + self._down_until[url] = self._clock() + self._retry_seconds + raise try: response = ocsp.load_der_ocsp_response(body) except ValueError as exc: diff --git a/tests/test_ocsp.py b/tests/test_ocsp.py index 7bc0c8c..2f5935a 100644 --- a/tests/test_ocsp.py +++ b/tests/test_ocsp.py @@ -140,6 +140,24 @@ def test_unreachable_keeps_known_good(pki: Pki) -> None: assert len(fetch.requests) == 2 +def test_a_failed_responder_is_left_alone_a_while(pki: Pki) -> None: + """During an outage, one timeout per retry period, not one per certificate; known-good stays good meanwhile""" + bravo = issue("BRAVO 2", pki.ca) + fetch = FakeFetch(_response(pki), OcspUnavailable("down"), _response(pki, leaf=bravo)) + clock = FakeClock() + checker = _checker(fetch, clock) + assert checker.is_revoked(_identity(pki), NOW) is False + clock.now += 301 + assert checker.is_revoked(_identity(pki), NOW) is False # asks, fails + assert checker.is_revoked(_identity(pki), NOW) is False # does not ask + with pytest.raises(OcspUnavailable, match="moments ago"): + checker.is_revoked(_identity(pki, bravo), NOW) + assert len(fetch.requests) == 2 + clock.now += 10 + assert checker.is_revoked(_identity(pki, bravo), NOW) is False + assert len(fetch.requests) == 3 + + def test_delegated_responder(pki: Pki) -> None: """A responder certificate issued by the CA for OCSP signing is accepted""" delegate = issue("OCSP", pki.ca, eku=[ExtendedKeyUsageOID.OCSP_SIGNING]) From fbfb8e7a9d56374a7a65d904364d4c049c38ce64 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:54:32 +0200 Subject: [PATCH 13/19] fix(agent): take a listener call's unknown error as gone Murmur's slice declares no exceptions for getListeningUsers and stopListening, so a channel or session gone meanwhile ended the round. --- src/mumblermapi/agent.py | 14 ++++--- tests/fake_murmur.py | 9 +++- tests/test_agent.py | 88 ++++++++++++++++++++++++++++++++-------- 3 files changed, 86 insertions(+), 25 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index 662fd51..09890e5 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -184,7 +184,7 @@ def _sessions(server: Any) -> list[Session]: return [Session(session, user.name, user.channel) for session, user in server.getUsers().items()] -def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, units: bool) -> list[str]: +def _enforce(ice: ModuleType, mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, units: bool) -> list[str]: """Make Murmur match the policy, and return the paths of nets Murmur refused to create. Until the policy is known, Units/ and Missions/ are left as they are. @@ -235,9 +235,11 @@ def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, unit # Read again: anyone who entered a net before its rules were written is still inside, and reconcile may # have moved people remaining = [s for s in _sessions(server) if s.session not in kicked] + # Murmur's slice declares no exceptions for the listener calls, so Ice reports a session or channel that is + # gone as an unknown one listeners = {} for channel_id in access.admitted: - with _may_be_gone(mumble): + with _may_be_gone(mumble, ice.UnknownUserException): listeners[channel_id] = server.getListeningUsers(channel_id) actions = violations(access, remaining, listeners, shadows(existing, roots["Missions"])) for session, target in actions.move: @@ -247,7 +249,7 @@ def _enforce(mumble: ModuleType, server: Any, policy: Policy, ids: UserIds, unit state.channel = target server.setState(state) for session, channel_id in actions.unlisten: - with _may_be_gone(mumble): + with _may_be_gone(mumble, ice.UnknownUserException): LOGGER.info("Stopping session %d listening to channel %d", session, channel_id) server.stopListening(session, channel_id) return left_out @@ -268,10 +270,10 @@ def _presence(mumble: ModuleType, server: Any) -> list[Entry]: @contextmanager -def _may_be_gone(mumble: ModuleType) -> Iterator[None]: +def _may_be_gone(mumble: ModuleType, *also: type[Exception]) -> Iterator[None]: try: yield - except (mumble.InvalidSessionException, mumble.InvalidChannelException): + except (mumble.InvalidSessionException, mumble.InvalidChannelException, *also): pass # the user left, or the temporary channel emptied, meanwhile @@ -317,7 +319,7 @@ def round(self, server: Any, policy: Policy, units: bool) -> None: else: self.next_sweep = time.monotonic() + self.sweep_seconds try: - left_out = _enforce(self.mumble, server, policy, self.ids, units) + left_out = _enforce(self.ice, self.mumble, server, policy, self.ids, units) if self.reporter: self.reporter.report(_presence(self.mumble, server), time.monotonic()) except not_ready as exc: diff --git a/tests/fake_murmur.py b/tests/fake_murmur.py index c89f9ec..81b50b7 100644 --- a/tests/fake_murmur.py +++ b/tests/fake_murmur.py @@ -15,6 +15,10 @@ class MemoryLimitException(IceException): """Ice's: a message is over Ice.MessageSizeMax""" +class UnknownUserException(IceException): + """Ice's: the servant raised an exception its operation does not declare""" + + class InvalidSessionException(IceException): """Murmur's: the session is gone""" @@ -64,6 +68,7 @@ def __init__( ICE = ModuleType("Ice") ICE.Exception = IceException # type: ignore[attr-defined] ICE.MemoryLimitException = MemoryLimitException # type: ignore[attr-defined] +ICE.UnknownUserException = UnknownUserException # type: ignore[attr-defined] MUMBLE = ModuleType("MumbleServer") MUMBLE.InvalidSessionException = InvalidSessionException # type: ignore[attr-defined] MUMBLE.InvalidChannelException = InvalidChannelException # type: ignore[attr-defined] @@ -187,10 +192,12 @@ def setState(self, state: SimpleNamespace) -> None: def getListeningUsers(self, channel_id: int) -> list[int]: if channel_id not in self.channels: - raise InvalidChannelException() + raise UnknownUserException() # Murmur's InvalidChannelException, which the slice does not declare return list(self.listeners.get(channel_id, [])) def stopListening(self, session: int, channel_id: int) -> None: + if session not in self.users or channel_id not in self.channels: + raise UnknownUserException() # as in getListeningUsers self.listeners[channel_id].remove(session) self.log.append(f"unlisten {session} {channel_id}") diff --git a/tests/test_agent.py b/tests/test_agent.py index 3d4851a..8dbe3eb 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -59,7 +59,7 @@ def murmur() -> FakeServer: def test_enforce_pass(ids: UserIds) -> None: """Refused users go first; the tree, ACLs and sessions then follow the policy; a second pass changes nothing""" server = murmur() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.log[0] == "kick 3" platoon, mission = server.id_of("/Units/10"), server.id_of("/Missions/RECON") @@ -76,11 +76,11 @@ def test_enforce_pass(ids: UserIds) -> None: server.users[4].channel = platoon # entered before the net was restricted server.listeners[platoon] = [4, 1] server.log.clear() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.log == ["move 4 0", f"unlisten 4 {platoon}"] server.log.clear() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.log == [] @@ -97,7 +97,7 @@ def add_and_enter(name: str, parent: int) -> int: return channel_id server.addChannel = add_and_enter # type: ignore[method-assign] - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.users[4].channel == 0 @@ -106,7 +106,7 @@ def test_temporary_twin_of_a_net(ids: UserIds) -> None: server = murmur() server.channel(5, 1, "10", temporary=True) server.users[4].channel = 5 - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) platoon = server.id_of("/Units/10") assert not server.channels[platoon].temporary assert server.channels[server.id_of("/Units/10/101")].parent == platoon @@ -117,46 +117,46 @@ def test_temporary_twin_of_a_net(ids: UserIds) -> None: def test_temporary_channel_in_a_restricted_net(ids: UserIds) -> None: """Its creator's rights are dropped; one that empties during the pass is skipped""" server = murmur() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) platoon = server.id_of("/Units/10") server.channel(50, platoon, "huddle", temporary=True) server.channel(51, platoon, "gone", temporary=True) server.acls[50] = ([MUMBLE.ACL(True, False, False, 4, "", 1, 0)], [], True) read = server.getChannels server.getChannels = lambda: read() | {52: SimpleNamespace(**vars(read()[51]) | {"id": 52})} # type: ignore[method-assign] - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.acls[50] == ([], [], True) def test_restricted_nets_are_unlinked(ids: UserIds) -> None: """A link would carry a restricted net's audio to anyone in the other channel""" server = murmur() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) platoon, open_net = server.id_of("/Units/10"), server.id_of("/Teams/Red") state = server.getChannelState(open_net) state.links = [platoon] server.setChannelState(state) - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.channels[platoon].links == [] and server.channels[open_net].links == [] def test_guard_is_open(ids: UserIds) -> None: """Anyone may stay in Guard, and a stand-in named Guard elsewhere sends everyone to it""" server = murmur() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) guard = server.id_of("/Missions/Guard") server.users[4].channel = guard server.channel(60, 0, "Guard", temporary=True) server.users[1].channel = 60 server.log.clear() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.users[4].channel == guard and server.users[1].channel == guard def test_enforce_before_policy(ids: UserIds) -> None: """Without mumblermapi's state yet, refused users are still kicked but Units/ and Missions/ stay as they are""" server = murmur() - agent._enforce(MUMBLE, server, POLICY, ids, units=False) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=False) assert server.log == ["kick 3"] assert server.id_of("/Units/20") == 2 and server.id_of("/Missions") assert server.acls == {} @@ -185,7 +185,7 @@ def test_a_refused_net_stalls_no_other(ids: UserIds) -> None: ), ) refused = "/Units" + "/00" * server.nesting_limit - assert agent._enforce(MUMBLE, server, policy, ids, units=True) == [refused] + assert agent._enforce(ICE, MUMBLE, server, policy, ids, units=True) == [refused] assert server.id_of("/Units" + "/00" * (server.nesting_limit - 1)) assert acl_of(*server.getACL(server.id_of("/Units/10"))) == members_only([1]) @@ -194,7 +194,7 @@ def test_a_refused_net_stalls_no_other(ids: UserIds) -> None: assert server.users[4].channel == 0 and server.listeners[stale] == [1] server.log.clear() - assert agent._enforce(MUMBLE, server, policy, ids, units=True) == [refused] + assert agent._enforce(ICE, MUMBLE, server, policy, ids, units=True) == [refused] assert server.log == [] @@ -208,13 +208,13 @@ def test_other_murmur_errors_end_the_pass(ids: UserIds) -> None: server = murmur() server.addChannel = wrong_secret # type: ignore[method-assign] with pytest.raises(InvalidSecretException): - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) def test_the_deepest_net_has_room_for_temporary_channels(ids: UserIds) -> None: """Nets as deep as mumblermapi takes them fit in Murmur, with a level left for members' temporary channels""" server = murmur() - assert agent._enforce(MUMBLE, server, Policy(version=2, units=(chain(MAX_DEPTH, "x"),)), ids, units=True) == [] + assert agent._enforce(ICE, MUMBLE, server, Policy(version=2, units=(chain(MAX_DEPTH, "x"),)), ids, units=True) == [] temporary = server.addChannel("huddle", server.id_of("/Units" + "/x" * MAX_DEPTH)) with pytest.raises(NestingLimitException): server.addChannel("deeper", temporary) @@ -233,7 +233,7 @@ def test_refused_nets_are_warned_about_when_they_change(caplog: pytest.LogCaptur def test_presence(ids: UserIds) -> None: """Who is where, by path""" server = murmur() - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert agent._presence(MUMBLE, server) == [ {"callsign": "OTHER", "channel": "/"}, {"callsign": "VOICE1", "channel": "/"}, @@ -414,6 +414,58 @@ def test_server_lookup() -> None: agent._server(meta, None) +def test_nets_that_emptied_meanwhile(ids: UserIds) -> None: + """A temporary channel gone before its listeners are read does not stop the rest of the pass""" + server = murmur() + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + platoon = server.id_of("/Units/10") + server.users[4].channel = platoon + server.channel(99, platoon, "huddle", temporary=True) + server.log.clear() + real = server.getListeningUsers + + def emptied(channel_id: int) -> list[int]: + server.channels.pop(99, None) # emptied, so Murmur removed it, after we listed it + return real(channel_id) + + server.getListeningUsers = emptied # type: ignore[method-assign] + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.log == ["move 4 0"] + + +def test_listener_calls_end_the_pass_on_other_errors(ids: UserIds) -> None: + """Only "gone" is taken as gone""" + + def oversized(channel_id: int) -> list[int]: + raise MemoryLimitException() + + server = murmur() + server.getListeningUsers = oversized # type: ignore[method-assign] + with pytest.raises(MemoryLimitException): + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + + +def test_listeners_that_left_meanwhile(ids: UserIds) -> None: + """A listener gone before they are stopped does not keep the others listening""" + server = murmur() + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + platoon = server.id_of("/Units/10") + server.listeners[platoon] = [4, 2, 1] # OTHER and VOICE3 are no members + real = server.stopListening + gone: list[int] = [] + + def leaving(session: int, channel_id: int) -> None: + if not gone: + gone.append(session) + del server.users[session] + real(session, channel_id) + + server.stopListening = leaving # type: ignore[method-assign] + server.log.clear() + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.log == [f"unlisten {({2, 4} - set(gone)).pop()} {platoon}"] + + def test_sessions_that_left_meanwhile(ids: UserIds) -> None: """A user gone before their kick or move does not stop the rest of the pass""" server = murmur() @@ -424,5 +476,5 @@ def gone_first(session: int, reason: str) -> None: real_kick(session, reason) server.kickUser = gone_first # type: ignore[method-assign] - agent._enforce(MUMBLE, server, POLICY, ids, units=True) + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) assert server.id_of("/Missions/RECON") and server.users[2].channel == server.id_of("/Missions/RECON") From cbbe99a45bdf3f0f55111557cf364ee122332e63 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 15:55:54 +0200 Subject: [PATCH 14/19] fix(tak): read the other missions when one cannot be read One mission's timeout or garbled answer froze every mission net, and an unexpected shape or error ended the watcher. That mission now keeps its last known subscribers, and no error ends the watcher. --- src/mumblermapi/tak.py | 30 ++++++++++++++++++++++++------ tests/test_tak.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/src/mumblermapi/tak.py b/src/mumblermapi/tak.py index de2273b..7054e96 100644 --- a/src/mumblermapi/tak.py +++ b/src/mumblermapi/tak.py @@ -78,10 +78,18 @@ def key(self) -> Path: return self.data_dir / "tak.key" +def _entries(doc: Any) -> list[dict[str, Any]]: + """The objects in a TAK answer's data list; raises TypeError for any other shape""" + data = doc.get("data", []) if isinstance(doc, dict) else None + if not isinstance(data, list): + raise TypeError("TAK's answer has no data list") + return [entry for entry in data if isinstance(entry, dict)] + + def mission_names(doc: Any) -> list[str]: """Names from GET /Marti/api/missions that can be Murmur channel names""" names = [] - for mission in doc.get("data", []): + for mission in _entries(doc): name = str(mission.get("name", "")) if NAME_RE.fullmatch(name): names.append(name) @@ -92,7 +100,7 @@ def mission_names(doc: Any) -> list[str]: def subscribers(doc: Any) -> frozenset[str]: """Callsigns from GET /Marti/api/missions/{name}/subscriptions/roles""" - return frozenset(str(sub["username"]) for sub in doc.get("data", []) if sub.get("username")) + return frozenset(str(sub["username"]) for sub in _entries(doc) if sub.get("username")) def needs_enrolment(cert: Path, now: datetime) -> bool: @@ -146,9 +154,13 @@ def tls_context(settings: TakSettings) -> ssl.SSLContext: async def read_missions( - session: aiohttp.ClientSession, settings: TakSettings, context: ssl.SSLContext | bool + session: aiohttp.ClientSession, + settings: TakSettings, + context: ssl.SSLContext | bool, + known: Mapping[str, frozenset[str]], ) -> dict[str, frozenset[str]]: - """Every mission we can see, with its subscribers' callsigns""" + """Every mission we can see, with its subscribers' callsigns. A mission whose subscribers cannot be read + now keeps those in known, as the last read.""" async def get(path: str) -> Any: # TAK is reached by its service name but its certificate carries the public name. @@ -167,6 +179,10 @@ async def get(path: str) -> Any: except aiohttp.ClientResponseError as exc: # Password-protected missions, or one deleted meanwhile: no net LOGGER.info("No subscribers for mission %r: HTTP %d", name, exc.status) + except (aiohttp.ClientError, ValueError, TypeError, RecursionError, TimeoutError) as exc: + LOGGER.warning("Keeping the last known subscribers of mission %r: %r", name, exc) + if name in known: + missions[name] = known[name] return missions @@ -178,10 +194,12 @@ async def watch(store: Store, settings: TakSettings, stop: asyncio.Event) -> Non if needs_enrolment(settings.cert, datetime.now(UTC)): await enrol(session, settings) LOGGER.info("Registered with TAK as %s", settings.cn) - missions = await read_missions(session, settings, tls_context(settings)) + missions = await read_missions(session, settings, tls_context(settings), store.missions()) if store.set_missions(missions): LOGGER.info("Mission nets: %s", ", ".join(sorted(store.missions())) or "none") - except (aiohttp.ClientError, OSError, ValueError, KeyError, RuntimeError, TimeoutError) as exc: + except (aiohttp.ClientError, OSError, ValueError, TypeError, KeyError, RuntimeError, TimeoutError) as exc: LOGGER.warning("Keeping the last known missions: %r", exc) # a timeout's str() is empty + except Exception: + LOGGER.exception("Keeping the last known missions") # the watcher must not end with contextlib.suppress(TimeoutError): await asyncio.wait_for(stop.wait(), settings.poll_seconds) diff --git a/tests/test_tak.py b/tests/test_tak.py index 7ad19a6..be94e2c 100644 --- a/tests/test_tak.py +++ b/tests/test_tak.py @@ -8,6 +8,7 @@ from pathlib import Path from typing import Any +import aiohttp import pytest from aiohttp import web from aiohttp.test_utils import TestServer @@ -50,6 +51,46 @@ def test_parsing() -> None: assert mission_names(MISSIONS) == ["RECON", "LOCKED", "NOBODY"] assert mission_names({"data": [{"name": "RECON\n"}]}) == [] # "$" alone would let the newline through assert subscribers(SUBSCRIBERS["RECON"]) == {"VOICE1", "VOICE3"} + assert subscribers({"data": ["VOICE9", {"username": "VOICE1"}]}) == {"VOICE1"} + odd: object + for odd in ([], {"data": {}}, "junk"): + with pytest.raises(TypeError): + mission_names(odd) + + +def test_one_unreadable_mission_holds_up_no_other() -> None: + """A mission whose subscribers cannot be read now keeps the last known; the others are read as usual""" + + names = ["RECON", "ODIN", "THOR", "DEEP", "SLOW"] + + async def missions(_: web.Request) -> web.Response: + return web.json_response({"data": [{"name": name} for name in names]}) + + async def roles(request: web.Request) -> web.Response: + name = request.match_info["name"] + if name == "SLOW": + await asyncio.sleep(1) + if name == "DEEP": + return web.Response(text="[" * 100_000) # nested past Python's recursion limit + return web.json_response(SUBSCRIBERS[name]) if name == "RECON" else web.Response(text="") + + async def read() -> dict[str, frozenset[str]]: + app = web.Application() + app.router.add_get("/Marti/api/missions", missions) + app.router.add_get("/Marti/api/missions/{name}/subscriptions/roles", roles) + server = TestServer(app) + await server.start_server() + try: + settings = TakSettings( + tak_url=str(server.make_url("")).rstrip("/"), tak_server_name="tak.example.fi", cn="mumble.example.fi" + ) + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=0.2)) as session: + return await tak.read_missions(session, settings, False, known) + finally: + await server.close() + + known = {name: frozenset({f"VOICE{i}"}) for i, name in enumerate(("ODIN", "DEEP", "SLOW"))} + assert asyncio.run(read()) == {"RECON": frozenset({"VOICE1", "VOICE3"}), **known} def test_needs_enrolment(tmp_path: Path, pki: Pki) -> None: From f18d9ff99e4da4188ede7a13f39d9d2e5af8704d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 16:06:54 +0200 Subject: [PATCH 15/19] fix(ocsp): count a response that cannot be decoded as unavailable An unknown signature algorithm, for example, raised past the checker, and in the certificate sweep that ended the agent. --- src/mumblermapi/ocsp.py | 52 ++++++++++++++++++++++++----------------- tests/test_ocsp.py | 16 +++++++++++++ 2 files changed, 46 insertions(+), 22 deletions(-) diff --git a/src/mumblermapi/ocsp.py b/src/mumblermapi/ocsp.py index 673c18c..07de7a0 100644 --- a/src/mumblermapi/ocsp.py +++ b/src/mumblermapi/ocsp.py @@ -11,7 +11,7 @@ from datetime import datetime, timedelta from cryptography import x509 -from cryptography.exceptions import InvalidSignature +from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa from cryptography.hazmat.primitives.serialization import Encoding @@ -166,24 +166,32 @@ def _query(self, identity: Identity, now: datetime) -> ocsp.OCSPCertStatus: self._down_until[url] = self._clock() + self._retry_seconds raise try: - response = ocsp.load_der_ocsp_response(body) - except ValueError as exc: - raise OcspUnavailable("unparseable OCSP response") from exc - if response.response_status != ocsp.OCSPResponseStatus.SUCCESSFUL: - raise OcspUnavailable(f"OCSP responder refused: {response.response_status.name}") - responder = _responder(response, identity.issuer) - _verify_signature( - responder.public_key(), - response.signature, - response.tbs_response_bytes, - response.signature_hash_algorithm, - ) - for single in response.responses: - if single.serial_number != identity.leaf.serial_number: - continue - if single.this_update_utc > now + CLOCK_SKEW: - raise OcspUnavailable("OCSP response is from the future") - if single.next_update_utc is not None and single.next_update_utc < now - CLOCK_SKEW: - raise OcspUnavailable("OCSP response is stale") - return single.certificate_status - raise OcspUnavailable("OCSP response does not cover the certificate") + return _status(body, identity, now) + except (ValueError, TypeError, UnsupportedAlgorithm) as exc: + raise OcspUnavailable(f"undecodable OCSP response: {exc!r}") from exc + + +def _status(body: bytes, identity: Identity, now: datetime) -> ocsp.OCSPCertStatus: + """The certificate's status in a verified, current response; raises OcspUnavailable""" + try: + response = ocsp.load_der_ocsp_response(body) + except ValueError as exc: + raise OcspUnavailable("unparseable OCSP response") from exc + if response.response_status != ocsp.OCSPResponseStatus.SUCCESSFUL: + raise OcspUnavailable(f"OCSP responder refused: {response.response_status.name}") + responder = _responder(response, identity.issuer) + _verify_signature( + responder.public_key(), + response.signature, + response.tbs_response_bytes, + response.signature_hash_algorithm, + ) + for single in response.responses: + if single.serial_number != identity.leaf.serial_number: + continue + if single.this_update_utc > now + CLOCK_SKEW: + raise OcspUnavailable("OCSP response is from the future") + if single.next_update_utc is not None and single.next_update_utc < now - CLOCK_SKEW: + raise OcspUnavailable("OCSP response is stale") + return single.certificate_status + raise OcspUnavailable("OCSP response does not cover the certificate") diff --git a/tests/test_ocsp.py b/tests/test_ocsp.py index 2f5935a..25ff5a8 100644 --- a/tests/test_ocsp.py +++ b/tests/test_ocsp.py @@ -10,11 +10,13 @@ import pytest from cryptography import x509 +from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.serialization import Encoding from cryptography.x509 import ocsp from cryptography.x509.oid import AuthorityInformationAccessOID, ExtendedKeyUsageOID +from mumblermapi import ocsp as ocsp_module from mumblermapi.identity import Identity from mumblermapi.ocsp import OcspChecker, OcspUnavailable, http_post, responder_url @@ -158,6 +160,20 @@ def test_a_failed_responder_is_left_alone_a_while(pki: Pki) -> None: assert len(fetch.requests) == 3 +@pytest.mark.parametrize( + "error", [UnsupportedAlgorithm("signature algorithm"), ValueError("bad extension"), TypeError("bad key")] +) +def test_undecodable_response(pki: Pki, monkeypatch: pytest.MonkeyPatch, error: Exception) -> None: + """A response cryptography cannot fully read, such as one signed with an unknown algorithm, is no answer""" + + def unknown(*args: object) -> None: + raise error + + monkeypatch.setattr(ocsp_module, "_verify_signature", unknown) + with pytest.raises(OcspUnavailable, match="undecodable"): + _checker(FakeFetch(_response(pki))).is_revoked(_identity(pki), NOW) + + def test_delegated_responder(pki: Pki) -> None: """A responder certificate issued by the CA for OCSP signing is accepted""" delegate = issue("OCSP", pki.ca, eku=[ExtendedKeyUsageOID.OCSP_SIGNING]) From acb45af9db8c25ae6f1d94b719968b3d8642669c Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 16:08:06 +0200 Subject: [PATCH 16/19] fix(agent): stay up through an unexpected error Only Ice errors were caught in a round, and only some in the policy poll, so any other error ended the agent, and Murmur's authenticator and every login with it. --- src/mumblermapi/agent.py | 7 ++++++- src/mumblermapi/policy.py | 5 ++++- tests/test_agent.py | 24 ++++++++++++++++++++++++ tests/test_policy.py | 4 +++- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index 09890e5..3e93fc6 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -308,7 +308,8 @@ def round(self, server: Any, policy: Policy, units: bool) -> None: The sweep goes first, on its own, so that no lasting failure to enforce the policy stops disconnecting revoked certificates. Presence follows enforcement, so a pass that keeps failing stops the reports and - mumblermapi's health shows it. + mumblermapi's health shows it. No error ends the agent: Murmur's authenticator, and so every login, would + go with it. """ not_ready = (self.ice.Exception, RuntimeError) if time.monotonic() >= self.next_sweep: @@ -316,6 +317,8 @@ def round(self, server: Any, policy: Policy, units: bool) -> None: _sweep(self.mumble, server, self.auth) except not_ready as exc: self._failed("the certificate sweep", exc) + except Exception: + LOGGER.exception("Unexpected error in the certificate sweep") else: self.next_sweep = time.monotonic() + self.sweep_seconds try: @@ -324,6 +327,8 @@ def round(self, server: Any, policy: Policy, units: bool) -> None: self.reporter.report(_presence(self.mumble, server), time.monotonic()) except not_ready as exc: self._failed("the plan", exc) + except Exception: + LOGGER.exception("Unexpected error in the plan") else: self.left_out = _warn_left_out(left_out, self.left_out) diff --git a/src/mumblermapi/policy.py b/src/mumblermapi/policy.py index b35d2fa..9af95b2 100644 --- a/src/mumblermapi/policy.py +++ b/src/mumblermapi/policy.py @@ -148,9 +148,12 @@ def refresh(self) -> bool: raise ValueError(f"HTTP {status}") data = json.loads(body) policy = parse_state(data) - except (OSError, http.client.HTTPException, ValueError, TypeError, KeyError) as exc: + except (OSError, http.client.HTTPException, ValueError, TypeError, KeyError, RecursionError) as exc: LOGGER.warning("Keeping policy version %d, none newer from mumblermapi: %s", self.policy.version, exc) return False + except Exception: + LOGGER.exception("Keeping policy version %d, mumblermapi's state makes no sense", self.policy.version) + return False # The ETag also follows mumblermapi's ticket key; older mumblermapis send the version alone self._etag = str(data.get("etag", policy.version)) self.ready = True diff --git a/tests/test_agent.py b/tests/test_agent.py index 8dbe3eb..b679c4a 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -336,6 +336,30 @@ def oversized(*args: object) -> Any: ] +def test_an_unexpected_error_ends_no_round( + ids: UserIds, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """The agent stays up, with Murmur's authenticator; a failed sweep holds up nothing, a failed plan stops + presence""" + + def broken(*args: object) -> Any: + raise KeyError("a bug") + + monkeypatch.setattr(agent, "_sweep", broken) + reports: list[object] = [] + loop = rounds(ids, reports) + with caplog.at_level(logging.ERROR, logger=agent.__name__): + loop.round(murmur(), POLICY, units=True) + monkeypatch.setattr(agent, "_enforce", broken) + loop.round(murmur(), POLICY, units=True) + assert len(reports) == 1 and loop.next_sweep == 0 + assert [(r.getMessage(), bool(r.exc_info)) for r in caplog.records] == [ + ("Unexpected error in the certificate sweep", True), + ("Unexpected error in the certificate sweep", True), + ("Unexpected error in the plan", True), + ] + + def test_a_round_warns_about_refused_nets(ids: UserIds, caplog: pytest.LogCaptureFixture) -> None: """Once, not every round""" server = murmur() diff --git a/tests/test_policy.py b/tests/test_policy.py index fe078bd..3385959 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -103,6 +103,8 @@ def test_source_polls_with_etag_and_survives_outages() -> None: http.client.IncompleteRead(b"{"), (500, b""), (200, b"junk"), + (200, b"[" * 100_000), # nested past Python's recursion limit + (200, b'{"version": 1e400}'), # no int (200, b"{}"), (200, body), ) @@ -112,7 +114,7 @@ def test_source_polls_with_etag_and_survives_outages() -> None: assert source.ready assert source.policy.version == 7 assert get.headers[0] == {} - for _ in range(6): + for _ in range(8): assert source.refresh() is False assert get.headers[1] == {"If-None-Match": "7"} assert source.refresh() is False # same document again From c300930c79337751977114b924a2ece2428bbb36 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 16:42:48 +0200 Subject: [PATCH 17/19] fix(agent): replace access rules too large to read A member can give their temporary channel rules over Ice's limit, and reading them before writing ours stopped every later net's rules, the moves and presence, every round. --- src/mumblermapi/agent.py | 7 ++++++- tests/test_agent.py | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index 3e93fc6..f7d5604 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -219,7 +219,12 @@ def _enforce(ice: ModuleType, mumble: ModuleType, server: Any, policy: Policy, i ) for channel_id, acl in access.acls.items(): with _may_be_gone(mumble): - if acl_of(*server.getACL(channel_id)) != acl: + try: + current: Acl | None = acl_of(*server.getACL(channel_id)) + except ice.MemoryLimitException: + # Rules too large to read, such as a member's own in their temporary channel: ours replace them + current = None + if current != acl: _set_acl(mumble, server, channel_id, acl) LOGGER.info("Set access rules of channel %d", channel_id) # A link carries a restricted net's audio to whoever is in the other channel, and one made while its maker diff --git a/tests/test_agent.py b/tests/test_agent.py index b679c4a..0a8fcb0 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -457,6 +457,32 @@ def emptied(channel_id: int) -> list[int]: assert server.log == ["move 4 0"] +def test_rules_too_large_to_read_are_replaced(ids: UserIds) -> None: + """A member's own rules in their temporary channel, past Ice's limit, are overwritten; the pass goes on""" + server = murmur() + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + platoon = server.id_of("/Units/10") + server.channel(99, platoon, "huddle", temporary=True) + server.acls[99] = ([], [MUMBLE.Group("x" * 100, False, True, True, [], [], [])], True) + server.users[4].channel = platoon # an outsider, to be moved out after the rules are written + real = server.getACL + + def limited(channel_id: int) -> tuple[list[Any], list[Any], bool]: + acls = real(channel_id) + if any(len(group.name) > 50 for group in acls[1]): + raise MemoryLimitException() + return acls + + server.getACL = limited # type: ignore[method-assign] + server.log.clear() + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert "acl 99" in server.log and server.users[4].channel == 0 + + server.log.clear() + agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.log == [] + + def test_listener_calls_end_the_pass_on_other_errors(ids: UserIds) -> None: """Only "gone" is taken as gone""" From b6a9651867ab43f5f0bf92fab6da9c6117111976 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 16:43:08 +0200 Subject: [PATCH 18/19] fix(agent): count a channel already gone as removed A temporary channel that emptied between reading the tree and removing it ended the round. --- src/mumblermapi/agent.py | 6 ++++-- tests/fake_murmur.py | 2 ++ tests/test_agent.py | 10 ++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py index f7d5604..90ca0a3 100644 --- a/src/mumblermapi/agent.py +++ b/src/mumblermapi/agent.py @@ -149,8 +149,10 @@ def set_description(self, channel_id: int, description: str) -> None: self._server.setChannelState(state) def remove_channel(self, channel_id: int) -> None: - """Remove a channel; Murmur moves its users to the parent""" - self._server.removeChannel(channel_id) + """Remove a channel; Murmur moves its users to the parent. One already gone, such as a temporary channel that + emptied meanwhile, counts as removed.""" + with _may_be_gone(self._mumble): + self._server.removeChannel(channel_id) def _sweep(mumble: ModuleType, server: Any, auth: Authenticator) -> None: diff --git a/tests/fake_murmur.py b/tests/fake_murmur.py index 81b50b7..a432540 100644 --- a/tests/fake_murmur.py +++ b/tests/fake_murmur.py @@ -150,6 +150,8 @@ def setChannelState(self, state: SimpleNamespace) -> None: self.channels[state.id] = state def removeChannel(self, channel_id: int) -> None: + if channel_id not in self.channels: + raise InvalidChannelException() parent = self.channels[channel_id].parent gone = {channel_id} while more := {c.id for c in self.channels.values() if c.parent in gone} - gone: diff --git a/tests/test_agent.py b/tests/test_agent.py index 0a8fcb0..693611c 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -419,6 +419,16 @@ def test_ice_takes_what_murmur_sends() -> None: assert properties["Ice.ImplicitContext"] == "Shared" +def test_a_channel_already_gone_counts_as_removed() -> None: + """Such as a squatting temporary channel that emptied between reading the tree and removing it""" + server = FakeServer() + server.channel(5, 0, "RECON", temporary=True) + channels = agent.IceChannels(server, MUMBLE) + channels.remove_channel(5) + channels.remove_channel(5) + assert server.log == ["remove 5"] + + def test_channel_description() -> None: """New channels get their description""" server = FakeServer() From cc16d8c95117e7394c9abaca53b4c30fc32e4e63 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Thu, 19 Nov 2026 16:43:22 +0200 Subject: [PATCH 19/19] chore: bump version to 1.0.5+261119 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/mumblermapi/__init__.py | 2 +- uv.lock | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 55510d4..f6ca5c3 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.0.4+261119" +current_version = "1.0.5+261119" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index d6f8c1f..51fa1a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mumblermapi" -version = "1.0.4+261119" +version = "1.0.5+261119" description = "Murmur (Mumble server) integration for the OpenDefence platform" license = { text = "GPL-2.0-only" } readme = "README.md" diff --git a/src/mumblermapi/__init__.py b/src/mumblermapi/__init__.py index 7eb5b21..30c782e 100644 --- a/src/mumblermapi/__init__.py +++ b/src/mumblermapi/__init__.py @@ -1,3 +1,3 @@ """Murmur integration for the OpenDefence platform""" -__version__ = "1.0.4+261119" +__version__ = "1.0.5+261119" diff --git a/uv.lock b/uv.lock index 8c366ce..89a5234 100644 --- a/uv.lock +++ b/uv.lock @@ -964,7 +964,7 @@ wheels = [ [[package]] name = "mumblermapi" -version = "1.0.4+261119" +version = "1.0.5+261119" source = { editable = "." } dependencies = [ { name = "aiohttp" },