Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
00040cb
fix(store): nest nets only as deep as Murmur allows
benjamsf Nov 19, 2026
2dd0db5
fix(agent): skip a net Murmur refuses instead of stalling every net
benjamsf Nov 19, 2026
46b9a50
fix(agent): sweep certificates before enforcing the plan
benjamsf Nov 19, 2026
cba3ac6
feat(store): assign web voice slots per browser
benjamsf Nov 19, 2026
f4f1834
fix(voice): let mumblermapi pick each browser's slot
benjamsf Nov 19, 2026
fa2226b
chore: bump version to 1.0.4+261119
benjamsf Nov 19, 2026
f8f8f53
fix(agent): answer Murmur even when a login check fails
benjamsf Nov 19, 2026
7f046ce
fix(authenticator): refuse overlong usernames before reading them
benjamsf Nov 19, 2026
65437ee
fix(agent): take every login Murmur can forward
benjamsf Nov 19, 2026
b2fbc0f
fix(userids): hand out an id only once it is saved
benjamsf Nov 19, 2026
fdbbffc
fix: treat malformed HTTP answers as unavailable
benjamsf Nov 19, 2026
1cbf69e
fix(ocsp): leave a failed responder alone for a while
benjamsf Nov 19, 2026
fbfb8e7
fix(agent): take a listener call's unknown error as gone
benjamsf Nov 19, 2026
cbbe99a
fix(tak): read the other missions when one cannot be read
benjamsf Nov 19, 2026
f18d9ff
fix(ocsp): count a response that cannot be decoded as unavailable
benjamsf Nov 19, 2026
acb45af
fix(agent): stay up through an unexpected error
benjamsf Nov 19, 2026
c300930
fix(agent): replace access rules too large to read
benjamsf Nov 19, 2026
b6a9651
fix(agent): count a channel already gone as removed
benjamsf Nov 19, 2026
cc16d8c
chore: bump version to 1.0.5+261119
benjamsf Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .bumpversion.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "1.0.3+261117"
current_version = "1.0.5+261119"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)\\+(?P<build>\\d+)"
serialize = ["{major}.{minor}.{patch}+{build}"]
search = "{current_version}"
Expand Down
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<callsign>---web-<n>` 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
`<callsign>---web-<n>` 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.<domain>/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.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "mumblermapi"
version = "1.0.3+261117"
version = "1.0.5+261119"
description = "Murmur (Mumble server) integration for the OpenDefence platform"
license = { text = "GPL-2.0-only" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion src/mumblermapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Murmur integration for the OpenDefence platform"""

__version__ = "1.0.3+261117"
__version__ = "1.0.5+261119"
174 changes: 138 additions & 36 deletions src/mumblermapi/agent.py

Large diffs are not rendered by default.

16 changes: 11 additions & 5 deletions src/mumblermapi/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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, <callsign>---web-<slot>")
username: str = Field(description="The Mumble username it logs in: <callsign>---web-<this browser's slot>")


class PresenceEntry(BaseModel):
Expand Down Expand Up @@ -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()
Expand Down
7 changes: 6 additions & 1 deletion src/mumblermapi/authenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
39 changes: 28 additions & 11 deletions src/mumblermapi/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,24 @@
# 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.
MAX_NETS = 1000
# 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


Expand All @@ -57,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
Expand Down Expand Up @@ -202,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"""
Expand All @@ -211,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:
Expand All @@ -232,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
Expand All @@ -241,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]:
Expand Down
72 changes: 46 additions & 26 deletions src/mumblermapi/ocsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import http.client
import logging
import threading
import time
Expand All @@ -10,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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -101,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__(
Expand All @@ -110,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()
Expand Down Expand Up @@ -151,27 +157,41 @@ 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:
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")
body = self._fetch(url, request.public_bytes(Encoding.DER), self._timeout)
except OcspUnavailable:
self._down_until[url] = self._clock() + self._retry_seconds
raise
try:
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")
12 changes: 9 additions & 3 deletions src/mumblermapi/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import http.client
import json
import logging
import urllib.request
Expand Down Expand Up @@ -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""
Expand Down Expand Up @@ -145,8 +148,11 @@ 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, 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))
Expand Down
3 changes: 2 additions & 1 deletion src/mumblermapi/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import http.client
import json
import logging
import urllib.error
Expand Down Expand Up @@ -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:
Expand Down
Loading