diff --git a/.bumpversion.toml b/.bumpversion.toml index f6ca5c3..0c82751 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.0.5+261119" +current_version = "1.1.0+261125" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index ec5c5c3..2183d49 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -6,11 +6,11 @@ permissions: contents: read jobs: - checks: - # The version bump only: prek runs below, where its hooks' Python, UI and tools are installed - uses: pvarki/config-ci-library/.github/workflows/general-check.yml@5a0c4ca0d9e53135ea5ed3427840641d4ccb6aa2 # v0.14.2+261026 - with: - run-prek: false + bumpversion: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: pvarki/config-ci-library/.github/actions/validate-bumpversion@5a0c4ca0d9e53135ea5ed3427840641d4ccb6aa2 # v0.14.2+261026 prek: runs-on: ubuntu-latest @@ -28,7 +28,7 @@ jobs: - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 publish: - needs: [checks, prek] + needs: [bumpversion, prek] runs-on: arc-runner-set permissions: contents: read diff --git a/README.md b/README.md index 0cbd6b1..fa86169 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,10 @@ One image, three parts: - **`murmur-agent`** runs as a sidecar next to Murmur and talks to it over Ice on localhost. It: - authenticates every connection by its TAK client certificate. The chain must lead to the platform CA, the certificate must not be revoked (rmapi OCSP), and the callsign in the Mumble username must equal - the certificate CN. + the certificate CN. Murmur gives each username a session of its own, so a callsign gets at most four + phone slots `---` (ODVoice takes one per ATAK install) beside its bare name and its nine + browser slots. A fifth is refused for the rest of the deployment, as a slot keeps its user id; a person + who needs more devices gets a new callsign. - refuses and disconnects callsigns that are revoked or have voice turned off in mumblermapi - keeps the channel tree in place: - `Units/` from mumblermapi. Each net is open, invite-only (its members and those of invite-only nets @@ -20,7 +23,7 @@ One image, three parts: - reports who is connected where back to mumblermapi - **`mumblermapi`** is the registered rmapi product, in its own pod. It: - receives rmapi's user events - - keeps the `Units/` nets and their members in SQLite + - keeps users, the `Units/` nets and their members in Postgres - reads TAK missions and their subscribers with a plain TAK user identity, obtained through rmapi's product interop - serves the agent's desired state, the admin API and the UI remote @@ -64,11 +67,19 @@ kubelet probes it too and a restart mends none of what it finds. `healthy` and ` every 15 s and logs each change: - `no ready Linkerd proxy in mumblermapi's pod ()`: rmapi, murmur-agent and browser tickets are refused +- `the database cannot be reached ()`: tickets, user events and admin changes fail - `murmur-agent has not reported for s` (or since mumblermapi started): Murmur or the agent is away or refused - `the voice gateway is not ready ()`: browsers cannot talk `` is the HTTP status that came back, or why none did: `name resolution failed`, `connection refused` or -`timed out` (after 2 s). A failed lookup points at the cluster, such as in-cluster DNS or the node, not at voice. +`timed out` (after 2 s). For the database it is the first line of the driver's error, or `timed out`. A failed +lookup points at the cluster, such as in-cluster DNS or the node, not at voice. + +## Database + +mumblermapi keeps its state in its own CloudNativePG cluster, `mumble-postgres`. It creates its tables at start +with SQLModel's `create_all`, as rmapi does. That only adds missing tables, so a change to an existing table needs a +migration of its own. ## Configuration @@ -77,19 +88,21 @@ Like every Deploy App product, mumblermapi reads the product manifest the platfo (`rasenmaeher.mtls.base_uri`), and its own name (`product.dns`), which is its TAK identity's CN. Without a manifest the in-cluster defaults apply. The variables below override it. -| Variable | Used by | Meaning | -| -------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `MURMUR_ICE_SECRET` | agent | Murmur's Ice write secret (required) | -| `AGENT_STATE_URL` | agent | mumblermapi's `/api/v1/agent/state`; unset runs on `AGENT_CHANNELS_FILE` alone | -| `AGENT_PRESENCE_URL` | agent | mumblermapi's `/api/v1/agent/presence`; unset reports nothing | -| `AGENT_CA_BUNDLE`, `AGENT_DATA_DIR`, `AGENT_OCSP_URL`, `AGENT_POLL_SECONDS`, `AGENT_SWEEP_SECONDS` | agent | see `config.py` | -| `MUMBLERMAPI_DATABASE`, `MUMBLERMAPI_TEMPLATES_DIR`, `MUMBLERMAPI_UI_DIR` | mumblermapi | SQLite file, channel plan templates admins may apply (`*.yaml`: `name`, `description`, `channels`, each channel with an optional `access` of `open`, `invite` or `inherit`; none is applied by default), built UI | -| `MUMBLERMAPI_RMAPI_IDENTITY`, `MUMBLERMAPI_AGENT_IDENTITY` | mumblermapi | Linkerd identities allowed to send user events and read agent state | -| `MUMBLERMAPI_TRAEFIK_IDENTITY`, `MUMBLERMAPI_CA_BUNDLE` | mumblermapi | The edge whose forwarded certificate voice tickets are minted for, and the CAs it must chain to | -| `AGENT_GATEWAY_CA` | agent | The voice gateway's CA; unset lets no browser in | -| `MUMBLERMAPI_PROXY_READY_URL`, `MUMBLERMAPI_GATEWAY_READY_URL` | mumblermapi | What the health check asks: this pod's Linkerd proxy, default `http://127.0.0.1:4191/ready`, and the voice gateway's `/readyz`; empty skips that check | -| `MUMBLERMAPI_TAK_URL`, `MUMBLERMAPI_TAK_SERVER_NAME`, `MUMBLERMAPI_TAK_CN` | mumblermapi | TAK's API, the name on TAK's certificate, our TAK identity's CN (default: the manifest's `product.dns`); unset leaves `Missions/` empty | -| `MUMBLERMAPI_RMAPI_URL` | mumblermapi | rmapi, for our TAK certificate and TAK rights (default: the manifest's `rasenmaeher.mtls.base_uri`) | +| Variable | Used by | Meaning | +| -------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `MTLS_TRUST_L5D`, `MTLS_REQUIRE_L5D`, `MTLS_TRUSTED_INGRESS_IDENTITIES` | mumblermapi | How libpvarki knows who calls the API. On opendefence-platform: `true`, `true` and Traefik's Linkerd identity. Unset, it trusts an `X-ClientCert-DN` header from anyone | +| `MURMUR_ICE_SECRET` | agent | Murmur's Ice write secret (required) | +| `AGENT_STATE_URL` | agent | mumblermapi's `/api/v1/agent/state`; unset runs on `AGENT_CHANNELS_FILE` alone | +| `AGENT_PRESENCE_URL` | agent | mumblermapi's `/api/v1/agent/presence`; unset reports nothing | +| `AGENT_CA_BUNDLE`, `AGENT_DATA_DIR`, `AGENT_OCSP_URL`, `AGENT_POLL_SECONDS`, `AGENT_SWEEP_SECONDS` | agent | see `agent/config.py` | +| `MUMBLERMAPI_DATABASE_HOST`, `_PORT`, `_NAME`, `_USER`, `_PASSWORD` | mumblermapi | mumblermapi's Postgres, from CloudNativePG's app secret (`host`, `port`, `dbname`, `username`, `password`); default `mumble-postgres-rw:5432`, database and user `mumble` | +| `MUMBLERMAPI_TEMPLATES_DIR`, `MUMBLERMAPI_UI_DIR` | mumblermapi | Channel plan templates admins may apply (`*.yaml`: `name`, `description`, `channels`, each channel with an optional `access` of `open`, `invite` or `inherit`; none is applied by default), built UI | +| `MUMBLERMAPI_RMAPI_IDENTITY`, `MUMBLERMAPI_AGENT_IDENTITY` | mumblermapi | Linkerd identities allowed to send user events and read agent state | +| `MUMBLERMAPI_TRAEFIK_IDENTITY`, `MUMBLERMAPI_CA_BUNDLE` | mumblermapi | The edge whose forwarded certificate voice tickets are minted for, and the CAs it must chain to | +| `AGENT_GATEWAY_CA` | agent | The voice gateway's CA; unset lets no browser in | +| `MUMBLERMAPI_PROXY_READY_URL`, `MUMBLERMAPI_GATEWAY_READY_URL` | mumblermapi | What the health check asks: this pod's Linkerd proxy, default `http://127.0.0.1:4191/ready`, and the voice gateway's `/readyz`; empty skips that check | +| `MUMBLERMAPI_TAK_URL`, `MUMBLERMAPI_TAK_SERVER_NAME`, `MUMBLERMAPI_TAK_CN` | mumblermapi | TAK's API, the name on TAK's certificate, our TAK identity's CN (default: the manifest's `product.dns`); unset leaves `Missions/` empty | +| `MUMBLERMAPI_RMAPI_URL` | mumblermapi | rmapi, for our TAK certificate and TAK rights (default: the manifest's `rasenmaeher.mtls.base_uri`) | Mission nets need takrmapi's `/api/v1/interop/add` and rmapi calling it without a double slash. Both are upstream changes that `VOICE-PLAN.md` tracks. @@ -98,7 +111,7 @@ upstream changes that `VOICE-PLAN.md` tracks. ```bash uv sync -uv run pytest +uv run pytest # starts a Postgres in Docker (tests/docker-compose.yml) uv run mypy src tests pnpm -C ui install diff --git a/pyproject.toml b/pyproject.toml index 51fa1a5..acd036c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "mumblermapi" -version = "1.0.5+261119" +version = "1.1.0+261125" description = "Murmur (Mumble server) integration for the OpenDefence platform" license = { text = "GPL-2.0-only" } readme = "README.md" @@ -11,8 +11,11 @@ dependencies = [ "cryptography>=46.0", "fastapi>=0.143,<1.0", "libpvarki>=2.2,<3.0", + "psycopg2-binary>=2.9,<3.0", "pydantic>=2.14,<3.0", + "pydantic-settings>=2.8,<3.0", "pyyaml>=6.0,<7.0", + "sqlmodel>=0.0.37,<1.0", "uvicorn>=0.30,<1.0", ] @@ -27,6 +30,7 @@ dev = [ "pyrefly>=1.3,<2", "pytest>=8.0,<9.0", "pytest-cov>=6.0,<7.0", + "pytest-docker>=3.2,<4.0", "types-pyyaml>=6.0,<7.0", ] @@ -66,3 +70,8 @@ ignore_missing_imports = true replace-imports-with-any = ["Ice", "MumbleServer"] # The tests are a package of their own beside src search-path = ["src", "."] + +[[tool.pyrefly.sub-config]] +# Table classes name their table with a plain string where SQLModel declares a declared_attr +matches = "src/mumblermapi/store/tables.py" +errors = { bad-override = false } diff --git a/src/mumblermapi/__init__.py b/src/mumblermapi/__init__.py index 30c782e..0091fdc 100644 --- a/src/mumblermapi/__init__.py +++ b/src/mumblermapi/__init__.py @@ -1,3 +1,3 @@ """Murmur integration for the OpenDefence platform""" -__version__ = "1.0.5+261119" +__version__ = "1.1.0+261125" diff --git a/src/mumblermapi/agent.py b/src/mumblermapi/agent.py deleted file mode 100644 index 90ca0a3..0000000 --- a/src/mumblermapi/agent.py +++ /dev/null @@ -1,405 +0,0 @@ -"""murmur-agent: the Ice glue between Murmur and the authentication and channel logic. - -Ice comes from the container image (Ubuntu's python3-zeroc-ice, the same Ice 3.7 that Murmur links), so this -module imports it lazily. The glue is unit-tested against a fake Murmur; loading Ice and the run loop need -the real one. -""" - -from __future__ import annotations - -import logging -import signal -import threading -import time -from collections.abc import Callable, Iterator -from contextlib import contextmanager -from dataclasses import dataclass, field -from importlib.resources import files -from types import ModuleType -from typing import Any - -from libpvarki.logging import add_trace_and_audit, init_logging - -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 -from .identity import CertVerifier -from .ocsp import OcspChecker -from .policy import Policy, PolicySource, from_plan -from .presence import Entry, PresenceReporter, channel_paths, presence -from .userids import UserIds - -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 - import Ice # provided by the container image - - slice_dir = Ice.getSliceDir() or _SLICE_FALLBACK_DIR - Ice.loadSlice("", ["-I" + slice_dir, str(files("mumblermapi") / "MumbleServer.ice")]) - import MumbleServer # generated by loadSlice above - - 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 _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""" - - class IceAuthenticator(mumble.ServerAuthenticator): # type: ignore[misc,name-defined] - """Murmur calls these for every login""" - - def authenticate( - self, - name: str, - pw: str, - certificates: list[bytes], - certhash: str, - certstrong: bool, - current: Any = None, - ) -> tuple[int, str, list[str]]: - # 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 - 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 = _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 _answer(lambda: auth.name_to_id(name), UNKNOWN) - - def idToName(self, id: int, current: Any = None) -> str: - del current - return _answer(lambda: auth.id_to_name(id), "") - - def idToTexture(self, id: int, current: Any = None) -> bytes: - del id, current - return b"" - - return IceAuthenticator() - - -class IceChannels: - """The reconciler's view of a Murmur virtual server""" - - def __init__(self, server: Any, mumble: ModuleType) -> None: - self._server = server - self._mumble = mumble - - def channels(self) -> list[ExistingChannel]: - """Every channel on the server""" - return [ - ExistingChannel(c.id, c.parent, c.name, c.temporary, c.description, tuple(c.links)) - for c in self._server.getChannels().values() - ] - - def add_channel(self, name: str, parent: int, description: str) -> int: - """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 - self._server.setChannelState(state) - return channel_id - - def set_description(self, channel_id: int, description: str) -> None: - """Change a channel's description""" - state = self._server.getChannelState(channel_id) - state.description = description - self._server.setChannelState(state) - - def remove_channel(self, channel_id: int) -> None: - """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: - """Disconnect users whose certificate no longer passes, such as after a revocation""" - for session, user in server.getUsers().items(): - try: - chain = [bytes(cert) for cert in server.getCertificateList(session)] - except mumble.InvalidSessionException: - continue # left meanwhile - refusal = auth.refusal(user.name, chain) - if refusal is not None and not refusal.transient: - with _may_be_gone(mumble): - LOGGER.warning("Disconnecting %r: %s", user.name, refusal.reason) - server.kickUser(session, refusal.reason) - - -def _set_acl(mumble: ModuleType, server: Any, channel_id: int, acl: Acl) -> None: - inherit, rules, groups = acl - server.setACL( - channel_id, - [mumble.ACL(here, subs, False, user, group, allow, deny) for here, subs, user, group, allow, deny in rules], - [ - mumble.Group(name, False, inh, inheritable, list(add), list(rem), []) - for name, inh, inheritable, add, rem in groups - ], - inherit, - ) - - -def _sessions(server: Any) -> list[Session]: - return [Session(session, user.name, user.channel) for session, user in server.getUsers().items()] - - -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. - - 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) - for session in kicked: - with _may_be_gone(mumble): - LOGGER.warning("Disconnecting session %d: refused by mumblermapi", session) - server.kickUser(session, "revoked or voice disabled in Deploy App") - - 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 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") - removed += prune(channels, policy.mission_specs(), roots["Missions"], "/Missions") - if removed: - LOGGER.info("Removed channels: %s", ", ".join(removed)) - existing = channels.channels() - names = ids.names() - access = combine( - plan(policy.units, existing, roots["Units"], names), - plan(policy.missions, existing, roots["Missions"], names), - ) - for channel_id, acl in access.acls.items(): - with _may_be_gone(mumble): - 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 - # still had access outlives the access. Restricted nets are never linked. - for channel in existing: - if channel.links and channel.id in access.admitted: - with _may_be_gone(mumble): - state = server.getChannelState(channel.id) - LOGGER.info("Unlinking channel %d from %s", channel.id, state.links) - state.links = [] - server.setChannelState(state) - - # 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, ice.UnknownUserException): - listeners[channel_id] = server.getListeningUsers(channel_id) - actions = violations(access, remaining, listeners, shadows(existing, roots["Missions"])) - for session, target in actions.move: - with _may_be_gone(mumble): - state = server.getState(session) - LOGGER.info("Moving %r from channel %d to %d", state.name, state.channel, target) - state.channel = target - server.setState(state) - for session, channel_id in actions.unlisten: - 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 - - -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(mumble: ModuleType, server: Any) -> list[Entry]: - """Who is connected, and in which net""" - return presence(_sessions(server), channel_paths(IceChannels(server, mumble).channels())) - - -@contextmanager -def _may_be_gone(mumble: ModuleType, *also: type[Exception]) -> Iterator[None]: - try: - yield - except (mumble.InvalidSessionException, mumble.InvalidChannelException, *also): - pass # the user left, or the temporary channel emptied, meanwhile - - -def _server(meta: Any, server_id: int | None) -> Any: - """The configured virtual server, or the only one running""" - if server_id is not None: - server = meta.getServer(server_id) - if server is None: - raise RuntimeError(f"Murmur has no virtual server {server_id}") - return server - booted = meta.getBootedServers() - if len(booted) != 1: - raise RuntimeError(f"expected one running virtual server, Murmur has {len(booted)}") - 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. 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: - try: - _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: - 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: - 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) - - 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""" - ice, mumble = _load_ice() - config.data_dir.mkdir(parents=True, exist_ok=True) - ids = UserIds(config.data_dir / "user-ids.json") - # With mumblermapi, its store is the plan; without it, the channels file is. - source = PolicySource(config.state_url, Policy()) if config.state_url else None - fixed = None if source else from_plan(load_plan(config.channels_file)) - - def policy() -> Policy: - return source.policy if source else fixed or Policy() - - reporter = PresenceReporter(config.presence_url) if config.presence_url else None - - auth = Authenticator( - CertVerifier.from_pem_file(config.ca_bundle), - OcspChecker(url_override=config.ocsp_url, cache_seconds=config.ocsp_cache_seconds), - ids, - policy=policy, - gateway=CertVerifier.from_pem_file(config.gateway_ca) if config.gateway_ca else None, - ) - - init_data = ice.InitializationData() - init_data.properties = _properties(ice) - with ice.initialize(init_data) as communicator: - communicator.getImplicitContext().put("secret", config.ice_secret) - 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( - communicator.stringToProxy(f"Meta:tcp -h {config.ice_host} -p {config.ice_port}") - ) - rounds = Rounds(ice, mumble, auth, ids, reporter, config.sweep_seconds) - while not stop.is_set(): - if source: - source.refresh() - try: - server = _server(meta, config.server_id) - # Re-registering every round re-attaches the authenticator after a Murmur restart. - server.setAuthenticator(authenticator) - 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) - - -def main() -> None: # pragma: no cover # the container entrypoint - """murmur-agent entrypoint""" - add_trace_and_audit() - init_logging(logging.INFO) - config = AgentConfig.from_env() - stop = threading.Event() - for signum in (signal.SIGTERM, signal.SIGINT): - signal.signal(signum, lambda *_: stop.set()) - LOGGER.info("murmur-agent starting for Murmur at %s:%d", config.ice_host, config.ice_port) - run(config, stop) diff --git a/src/mumblermapi/agent/__init__.py b/src/mumblermapi/agent/__init__.py new file mode 100644 index 0000000..c5df08f --- /dev/null +++ b/src/mumblermapi/agent/__init__.py @@ -0,0 +1,86 @@ +"""murmur-agent: the Ice glue between Murmur and the authentication and channel logic. + +Ice comes from the container image (Ubuntu's python3-zeroc-ice, the same Ice 3.7 that Murmur links), so the +agent imports it lazily. The glue is unit-tested against a fake Murmur; loading Ice and the run loop need +the real one. +""" + +from __future__ import annotations + +import logging +import signal +import threading + +from libpvarki.logging import add_trace_and_audit, init_logging + +from ..channels import load_plan +from ..identity import CertVerifier +from .authenticator import Authenticator +from .config import AgentConfig +from .ice import ADAPTER, load_ice, properties, servant, virtual_server +from .ocsp import OcspChecker +from .policy import Policy, PolicySource, from_plan +from .presence import PresenceReporter +from .rounds import Rounds +from .userids import UserIds + +LOGGER = logging.getLogger(__name__) + + +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() + config.data_dir.mkdir(parents=True, exist_ok=True) + ids = UserIds(config.data_dir / "user-ids.json") + # With mumblermapi, its store is the plan; without it, the channels file is. + source = PolicySource(config.state_url, Policy()) if config.state_url else None + fixed = None if source else from_plan(load_plan(config.channels_file)) + + def policy() -> Policy: + return source.policy if source else fixed or Policy() + + reporter = PresenceReporter(config.presence_url) if config.presence_url else None + + auth = Authenticator( + CertVerifier.from_pem_file(config.ca_bundle), + OcspChecker(url_override=config.ocsp_url, cache_seconds=config.ocsp_cache_seconds), + ids, + policy=policy, + gateway=CertVerifier.from_pem_file(config.gateway_ca) if config.gateway_ca else None, + ) + + init_data = ice.InitializationData() + init_data.properties = properties(ice) + with ice.initialize(init_data) as communicator: + communicator.getImplicitContext().put("secret", config.ice_secret) + 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( + communicator.stringToProxy(f"Meta:tcp -h {config.ice_host} -p {config.ice_port}") + ) + rounds = Rounds(ice, mumble, auth, ids, reporter, config.sweep_seconds) + while not stop.is_set(): + if source: + source.refresh() + try: + server = virtual_server(meta, config.server_id) + # Re-registering every round re-attaches the authenticator after a Murmur restart. + server.setAuthenticator(authenticator) + 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) + + +def main() -> None: # pragma: no cover # the container entrypoint + """murmur-agent entrypoint""" + add_trace_and_audit() + init_logging(logging.INFO) + config = AgentConfig() + stop = threading.Event() + for signum in (signal.SIGTERM, signal.SIGINT): + signal.signal(signum, lambda *_: stop.set()) + LOGGER.info("murmur-agent starting for Murmur at %s:%d", config.ice_host, config.ice_port) + run(config, stop) diff --git a/src/mumblermapi/authenticator.py b/src/mumblermapi/agent/authenticator.py similarity index 94% rename from src/mumblermapi/authenticator.py rename to src/mumblermapi/agent/authenticator.py index 5787464..534a9b1 100644 --- a/src/mumblermapi/authenticator.py +++ b/src/mumblermapi/agent/authenticator.py @@ -8,11 +8,11 @@ from datetime import UTC, datetime from typing import Protocol -from .identity import CertVerifier, Identity, IdentityError, Username, bind, parse_username +from ..identity import CertVerifier, Identity, IdentityError, Username, bind, parse_username +from ..tickets import AUDIT, is_web_slot, verify from .ocsp import OcspUnavailable from .policy import Policy -from .tickets import AUDIT, is_web_slot, verify -from .userids import UserIds +from .userids import SlotsFull, UserIds LOGGER = logging.getLogger(__name__) @@ -130,7 +130,11 @@ def authenticate(self, name: str, certificates: list[bytes], ticket: str = "") - if refusal is not None: 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) + try: + user_id = self._ids.get_or_assign(name) + except SlotsFull as exc: + LOGGER.log(AUDIT, "Refused %r: %s", name, exc) + return REJECT LOGGER.info("Accepted %r as user %d", name, user_id) return user_id diff --git a/src/mumblermapi/agent/config.py b/src/mumblermapi/agent/config.py new file mode 100644 index 0000000..5f65377 --- /dev/null +++ b/src/mumblermapi/agent/config.py @@ -0,0 +1,43 @@ +"""murmur-agent settings, from the environment""" + +from __future__ import annotations + +from pathlib import Path + +from pydantic import Field, field_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class AgentConfig(BaseSettings): + """Where Murmur is, what to trust, and how often to look; AGENT_* variables, and MURMUR_* for Murmur's own""" + + ice_secret: str = Field(default="", validation_alias="MURMUR_ICE_SECRET") # required, see _secret + ice_host: str = Field(default="127.0.0.1", validation_alias="MURMUR_ICE_HOST") + ice_port: int = Field(default=6502, validation_alias="MURMUR_ICE_PORT") + callback_port: int = 6503 + # None: the one virtual server Murmur runs (1.6 numbers it 0, older ones 1) + server_id: int | None = Field(default=None, validation_alias="MURMUR_SERVER_ID") + ca_bundle: Path = Path("/trust/ca-cert.pem") + channels_file: Path = Path("/config/channels.yaml") + data_dir: Path = Path("/data/agent") + ocsp_url: str | None = None + ocsp_cache_seconds: float = 300.0 + sweep_seconds: float = 60.0 # full certificate and OCSP recheck of everyone connected + state_url: str | None = None # mumblermapi's /api/v1/agent/state; None runs on the channels file alone + poll_seconds: float = 5.0 # how soon mumblermapi changes reach Murmur + presence_url: str | None = None # where to report who is connected; None reports nothing + gateway_ca: Path | None = None # the voice gateway's own CA; None lets no browser in + + model_config = SettingsConfigDict(env_prefix="AGENT_", frozen=True) + + @field_validator("ice_secret") + @classmethod + def _secret(cls, secret: str) -> str: + if not secret: + raise ValueError("MURMUR_ICE_SECRET must be set: Murmur's Ice interface must never run without a secret") + return secret + + @field_validator("server_id", "ocsp_url", "state_url", "presence_url", "gateway_ca", mode="before") + @classmethod + def _empty_is_unset(cls, value: object) -> object: + return None if value == "" else value diff --git a/src/mumblermapi/enforce.py b/src/mumblermapi/agent/enforce.py similarity index 98% rename from src/mumblermapi/enforce.py rename to src/mumblermapi/agent/enforce.py index 4cd3dc2..50182d6 100644 --- a/src/mumblermapi/enforce.py +++ b/src/mumblermapi/agent/enforce.py @@ -6,9 +6,9 @@ from dataclasses import dataclass from typing import Any -from .channels import ExistingChannel -from .identity import IdentityError, normalize_callsign, parse_username +from ..identity import IdentityError, normalize_callsign, parse_username from .policy import Policy, Unit +from .reconcile import ExistingChannel # Murmur ACL bits a restricted net keeps for its members. Traverse stays, so everyone still sees the tree. ENTER, SPEAK, WHISPER, TEXT_MESSAGE, MAKE_TEMP_CHANNEL, LISTEN = 0x04, 0x08, 0x100, 0x200, 0x400, 0x800 diff --git a/src/mumblermapi/agent/ice.py b/src/mumblermapi/agent/ice.py new file mode 100644 index 0000000..02b332b --- /dev/null +++ b/src/mumblermapi/agent/ice.py @@ -0,0 +1,157 @@ +"""murmur-agent's Ice glue: loading Ice, the authenticator Murmur calls and the channels as the reconciler sees them""" + +from __future__ import annotations + +import logging +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from importlib.resources import files +from types import ModuleType +from typing import Any + +from .authenticator import TRY_LATER, UNKNOWN, Authenticator +from .reconcile import ChannelRefused, ExistingChannel + +LOGGER = logging.getLogger(__name__) +_SLICE_FALLBACK_DIR = "/usr/share/ice/slice" +# Murmur forwards unchecked logins of up to 8 MiB, each invalid UTF-8 byte re-encoded as three, and drops the +# authenticator when a call fails: anything smaller lets anyone stop every login. The certificate chain comes on top. +MURMUR_MESSAGE_BYTES = 0x7FFFFF +ADAPTER = "Agent" +ADAPTER_MESSAGE_KIB = 3 * MURMUR_MESSAGE_BYTES // 1024 + 1024 +# Murmur lists every user or channel in one answer; this holds several hundred users with full comments, though +# 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 + """Ice, and the MumbleServer module it builds from Murmur's slice""" + import Ice # provided by the container image + + slice_dir = Ice.getSliceDir() or _SLICE_FALLBACK_DIR + Ice.loadSlice("", ["-I" + slice_dir, str(files("mumblermapi") / "MumbleServer.ice")]) + import MumbleServer # generated by loadSlice above + + 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 properties(ice: ModuleType) -> Any: + """The secret goes with every call, and messages may be as large as Murmur makes them""" + props = ice.createProperties() + props.setProperty("Ice.ImplicitContext", "Shared") + props.setProperty("Ice.MessageSizeMax", str(ICE_MESSAGE_KIB)) + props.setProperty(f"{ADAPTER}.MessageSizeMax", str(ADAPTER_MESSAGE_KIB)) + return props + + +def servant(mumble: ModuleType, auth: Authenticator) -> Any: + """A ServerAuthenticator that delegates to the Ice-free Authenticator""" + + class IceAuthenticator(mumble.ServerAuthenticator): # type: ignore[misc,name-defined] + """Murmur calls these for every login""" + + def authenticate( + self, + name: str, + pw: str, + certificates: list[bytes], + certhash: str, + certstrong: bool, + current: Any = None, + ) -> tuple[int, str, list[str]]: + # 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 + 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 = _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 _answer(lambda: auth.name_to_id(name), UNKNOWN) + + def idToName(self, id: int, current: Any = None) -> str: + del current + return _answer(lambda: auth.id_to_name(id), "") + + def idToTexture(self, id: int, current: Any = None) -> bytes: + del id, current + return b"" + + return IceAuthenticator() + + +class IceChannels: + """The reconciler's view of a Murmur virtual server""" + + def __init__(self, server: Any, mumble: ModuleType) -> None: + self._server = server + self._mumble = mumble + + def channels(self) -> list[ExistingChannel]: + """Every channel on the server""" + return [ + ExistingChannel(c.id, c.parent, c.name, c.temporary, c.description, tuple(c.links)) + for c in self._server.getChannels().values() + ] + + def add_channel(self, name: str, parent: int, description: str) -> int: + """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 + self._server.setChannelState(state) + return channel_id + + def set_description(self, channel_id: int, description: str) -> None: + """Change a channel's description""" + state = self._server.getChannelState(channel_id) + state.description = description + self._server.setChannelState(state) + + def remove_channel(self, channel_id: int) -> None: + """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) + + +@contextmanager +def may_be_gone(mumble: ModuleType, *also: type[Exception]) -> Iterator[None]: + """Murmur's errors for a user or channel that went meanwhile, and also, count as done""" + try: + yield + except (mumble.InvalidSessionException, mumble.InvalidChannelException, *also): + pass # the user left, or the temporary channel emptied, meanwhile + + +def virtual_server(meta: Any, server_id: int | None) -> Any: + """The configured virtual server, or the only one running""" + if server_id is not None: + server = meta.getServer(server_id) + if server is None: + raise RuntimeError(f"Murmur has no virtual server {server_id}") + return server + booted = meta.getBootedServers() + if len(booted) != 1: + raise RuntimeError(f"expected one running virtual server, Murmur has {len(booted)}") + return booted[0] diff --git a/src/mumblermapi/ocsp.py b/src/mumblermapi/agent/ocsp.py similarity index 99% rename from src/mumblermapi/ocsp.py rename to src/mumblermapi/agent/ocsp.py index 07de7a0..1365867 100644 --- a/src/mumblermapi/ocsp.py +++ b/src/mumblermapi/agent/ocsp.py @@ -18,7 +18,7 @@ from cryptography.x509 import ocsp from cryptography.x509.oid import AuthorityInformationAccessOID, ExtendedKeyUsageOID -from .identity import Identity +from ..identity import Identity LOGGER = logging.getLogger(__name__) MAX_RESPONSE_BYTES = 64 * 1024 diff --git a/src/mumblermapi/policy.py b/src/mumblermapi/agent/policy.py similarity index 99% rename from src/mumblermapi/policy.py rename to src/mumblermapi/agent/policy.py index 9af95b2..c0e0f1f 100644 --- a/src/mumblermapi/policy.py +++ b/src/mumblermapi/agent/policy.py @@ -9,7 +9,7 @@ from collections.abc import Callable from dataclasses import dataclass, field -from .channels import ACCESS, GUARD, ChannelSpec +from ..channels import ACCESS, GUARD, ChannelSpec LOGGER = logging.getLogger(__name__) MAX_STATE_BYTES = 4 * 1024 * 1024 diff --git a/src/mumblermapi/presence.py b/src/mumblermapi/agent/presence.py similarity index 98% rename from src/mumblermapi/presence.py rename to src/mumblermapi/agent/presence.py index 131a30b..0035dcd 100644 --- a/src/mumblermapi/presence.py +++ b/src/mumblermapi/agent/presence.py @@ -10,8 +10,8 @@ from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field -from .channels import ExistingChannel from .enforce import Session, callsign_of +from .reconcile import ExistingChannel LOGGER = logging.getLogger(__name__) diff --git a/src/mumblermapi/agent/reconcile.py b/src/mumblermapi/agent/reconcile.py new file mode 100644 index 0000000..4e49f1c --- /dev/null +++ b/src/mumblermapi/agent/reconcile.py @@ -0,0 +1,103 @@ +"""The channel tree the agent keeps in Murmur""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Protocol + +from ..channels import ChannelSpec + + +class ChannelRefused(Exception): + """Murmur will not create the channel there, as when it would nest past Murmur's limit""" + + +@dataclass(frozen=True) +class ExistingChannel: + """A channel as Murmur reports it""" + + id: int + parent: int + name: str + temporary: bool = False + description: str = "" + links: tuple[int, ...] = () + + +class ChannelServer(Protocol): + """The part of Murmur the reconciler needs""" + + 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; raises ChannelRefused when Murmur will not have it there""" + + def set_description(self, channel_id: int, description: str) -> None: + """Change a channel's description""" + + 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) -> 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, which moves anyone + in it to its parent. A temporary 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. + """ + 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: + path = f"{prefix}/{spec.name}" + channel = existing.get((parent, spec.name)) + if channel is not None and channel.temporary: + # A user's temporary channel must not stand in for a net: its creator keeps rights over it and + # whatever is built inside. Murmur moves the people in it to the parent. + server.remove_channel(channel.id) + channel = None + if channel is None: + 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 + if channel.description != spec.description: + server.set_description(channel_id, spec.description) + walk(spec.children, channel_id, path) + + walk(desired, root, "") + return created, refused + + +def prune(server: ChannelServer, desired: tuple[ChannelSpec, ...], root: int, prefix: str = "") -> list[str]: + """Remove the permanent channels under root that desired no longer has, and return their paths. + + Temporary channels belong to the users in them, and Murmur removes them once they are empty. + """ + children: dict[int, list[ExistingChannel]] = {} + for channel in server.channels(): + children.setdefault(channel.parent, []).append(channel) + removed: list[str] = [] + + def walk(specs: tuple[ChannelSpec, ...], parent: int, prefix: str) -> None: + wanted = {spec.name: spec for spec in specs} + for channel in children.get(parent, []): + path = f"{prefix}/{channel.name}" + spec = wanted.get(channel.name) + if spec is not None: + walk(spec.children, channel.id, path) + elif not channel.temporary: + server.remove_channel(channel.id) + removed.append(path) + + walk(desired, root, prefix) + return removed diff --git a/src/mumblermapi/agent/rounds.py b/src/mumblermapi/agent/rounds.py new file mode 100644 index 0000000..6d19560 --- /dev/null +++ b/src/mumblermapi/agent/rounds.py @@ -0,0 +1,190 @@ +"""What murmur-agent does with Murmur each round: the certificate sweep, the enforcement pass and presence""" + +from __future__ import annotations + +import logging +import time +from dataclasses import dataclass, field +from types import ModuleType +from typing import Any + +from ..channels import desired_tree +from .authenticator import Authenticator +from .enforce import Acl, Session, acl_of, combine, plan, refused, shadows, violations +from .ice import ICE_MESSAGE_KIB, IceChannels, may_be_gone +from .policy import Policy +from .presence import Entry, PresenceReporter, channel_paths, presence +from .reconcile import prune, reconcile +from .userids import UserIds + +LOGGER = logging.getLogger(__name__) + + +def _sweep(mumble: ModuleType, server: Any, auth: Authenticator) -> None: + """Disconnect users whose certificate no longer passes, such as after a revocation""" + for session, user in server.getUsers().items(): + try: + chain = [bytes(cert) for cert in server.getCertificateList(session)] + except mumble.InvalidSessionException: + continue # left meanwhile + refusal = auth.refusal(user.name, chain) + if refusal is not None and not refusal.transient: + with may_be_gone(mumble): + LOGGER.warning("Disconnecting %r: %s", user.name, refusal.reason) + server.kickUser(session, refusal.reason) + + +def _set_acl(mumble: ModuleType, server: Any, channel_id: int, acl: Acl) -> None: + inherit, rules, groups = acl + server.setACL( + channel_id, + [mumble.ACL(here, subs, False, user, group, allow, deny) for here, subs, user, group, allow, deny in rules], + [ + mumble.Group(name, False, inh, inheritable, list(add), list(rem), []) + for name, inh, inheritable, add, rem in groups + ], + inherit, + ) + + +def _sessions(server: Any) -> list[Session]: + return [Session(session, user.name, user.channel) for session, user in server.getUsers().items()] + + +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. + + 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) + for session in kicked: + with may_be_gone(mumble): + LOGGER.warning("Disconnecting session %d: refused by mumblermapi", session) + server.kickUser(session, "revoked or voice disabled in Deploy App") + + 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 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") + removed += prune(channels, policy.mission_specs(), roots["Missions"], "/Missions") + if removed: + LOGGER.info("Removed channels: %s", ", ".join(removed)) + existing = channels.channels() + names = ids.names() + access = combine( + plan(policy.units, existing, roots["Units"], names), + plan(policy.missions, existing, roots["Missions"], names), + ) + for channel_id, acl in access.acls.items(): + with may_be_gone(mumble): + 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 + # still had access outlives the access. Restricted nets are never linked. + for channel in existing: + if channel.links and channel.id in access.admitted: + with may_be_gone(mumble): + state = server.getChannelState(channel.id) + LOGGER.info("Unlinking channel %d from %s", channel.id, state.links) + state.links = [] + server.setChannelState(state) + + # 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, ice.UnknownUserException): + listeners[channel_id] = server.getListeningUsers(channel_id) + actions = violations(access, remaining, listeners, shadows(existing, roots["Missions"])) + for session, target in actions.move: + with may_be_gone(mumble): + state = server.getState(session) + LOGGER.info("Moving %r from channel %d to %d", state.name, state.channel, target) + state.channel = target + server.setState(state) + for session, channel_id in actions.unlisten: + 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 + + +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(mumble: ModuleType, server: Any) -> list[Entry]: + """Who is connected, and in which net""" + return presence(_sessions(server), channel_paths(IceChannels(server, mumble).channels())) + + +@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. 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: + try: + _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: + 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: + 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) + + 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) diff --git a/src/mumblermapi/userids.py b/src/mumblermapi/agent/userids.py similarity index 67% rename from src/mumblermapi/userids.py rename to src/mumblermapi/agent/userids.py index 7172d9e..2097ff3 100644 --- a/src/mumblermapi/userids.py +++ b/src/mumblermapi/agent/userids.py @@ -7,6 +7,18 @@ import threading from pathlib import Path +from ..identity import SLOT_SEPARATOR +from ..tickets import is_web_slot + +# The "---" names outside web- that one callsign may hold: ODVoice takes one per ATAK install. +# Murmur gives every name a session of its own, so without a limit one certificate could fill the server. +# Browsers have their own nine web- slots (tickets.py) and the bare callsign is one name more. +PHONE_SLOTS = 4 + + +class SlotsFull(Exception): + """The callsign already holds all its phone slots""" + class UserIds: """Assigns each name a positive id once and remembers it on disk. @@ -39,12 +51,20 @@ def _save(self, by_name: dict[str, int]) -> None: tmp.write_text(json.dumps(by_name, indent=1, sort_keys=True), encoding="utf-8") os.replace(tmp, self._path) + def _phone_slots(self, callsign: str) -> int: + slots = (n.partition(SLOT_SEPARATOR) for n in self._by_name) + return sum(1 for c, _, slot in slots if c == callsign and slot and not is_web_slot(slot)) + def get_or_assign(self, name: str) -> int: - """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.""" + """The name's id, assigning the next free one the first time; raises SlotsFull for a phone slot over + PHONE_SLOTS. 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: + callsign, _, slot = name.partition(SLOT_SEPARATOR) + if slot and not is_web_slot(slot) and self._phone_slots(callsign) >= PHONE_SLOTS: + raise SlotsFull(f"{callsign} already has its {PHONE_SLOTS} phone slots") user_id = max(self._by_id, default=0) + 1 self._save({**self._by_name, name: user_id}) self._by_name[name] = user_id diff --git a/src/mumblermapi/api.py b/src/mumblermapi/api.py deleted file mode 100644 index b99cbf5..0000000 --- a/src/mumblermapi/api.py +++ /dev/null @@ -1,667 +0,0 @@ -"""mumblermapi: the Deploy App product integration for voice""" - -from __future__ import annotations - -import asyncio -import base64 -import binascii -import json -import logging -import os -import re -import time -from collections.abc import AsyncIterator, Mapping -from contextlib import asynccontextmanager -from dataclasses import asdict -from datetime import UTC, datetime -from pathlib import Path -from typing import Annotated, Any, Literal -from urllib.parse import unquote - -import yaml -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from cryptography.hazmat.primitives.serialization import Encoding -from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, Response -from fastapi.concurrency import run_in_threadpool -from fastapi.responses import PlainTextResponse -from fastapi.staticfiles import StaticFiles -from libpvarki.middleware import MTLSHeader -from libpvarki.schemas.generic import OperationResultResponse -from libpvarki.schemas.product import ProductDescription, ProductHealthCheckResponse, UserCRUDRequest -from pydantic import BaseModel, ConfigDict, Field - -from . import kraftwerk -from .channels import GUARD, ChannelPlanError, ChannelSpec, load_yaml, parse_plan -from .health import watch as watch_health -from .identity import CertVerifier, IdentityError, normalize_callsign -from .store import Channel, NoSuchChannel, Store, StoreError -from .tak import TakSettings, watch -from .tickets import AUDIT, mint, public_key, web_username - -LOGGER = logging.getLogger(__name__) -SHORTNAME = "mumble" -# murmur-agent reports presence at least every 30 s; older than this and nobody can say who is online -PRESENCE_TTL = 90.0 -UI_PATH = f"/ui/{SHORTNAME}" # where Traefik serves the UI remote, on rmui's mTLS host -MAX_PLAN_BYTES = 1 << 20 # an imported channel plan; a full plan of 1000 nets with members is about half of this -TITLES = {"fi": "Puhe", "sv": "Röst", "en": "Voice"} -DESCRIPTIONS = { - "fi": "Puheryhmät TAKiin: PTT-kanavat ryhmälle, joukkueelle ja komppanialle", - "sv": "Röstkanaler för TAK: tryck-och-tala för grupp, pluton och kompani", - "en": "Voice for TAK: push-to-talk channels for squad, platoon and company", -} -ADMIN_DESCRIPTIONS = { - "fi": "Puheverkot: yksiköiden kanavat, jäsenet ja puheen esto", - "sv": "Röstnät: enheternas kanaler, medlemmar och spärr av röst", - "en": "Voice nets: unit channels, members and turning voice off", -} - - -class Settings(BaseModel): - """Where things are and who the peers are; from the environment and the product manifest""" - - database: Path = Path("/data/mumblermapi.db") - templates_dir: Path = Path("/templates") # channel plan templates an admin may choose to apply - ui_dir: Path = Path("/ui") # the built UI remote, served at UI_PATH when present - tak: TakSettings | None = None # where to read missions from; None leaves Missions/ empty - # Linkerd identities of the only callers of the user and agent endpoints - rmapi_identity: str = "rmapi.opendefence-system.serviceaccount.identity.linkerd.cluster.local" - agent_identity: str = "murmur.app-mumble.serviceaccount.identity.linkerd.cluster.local" - # The edge, whose forwarded client certificate voice tickets are minted for, and the CAs it must chain to - traefik_identity: str = "traefik.traefik-system.serviceaccount.identity.linkerd.cluster.local" - ca_bundle: Path = Path("/trust/ca-cert.pem") - # What the health check asks (health.py); an empty URL is not checked - proxy_ready_url: str = "http://127.0.0.1:4191/ready" # this pod's Linkerd proxy - gateway_ready_url: str = "http://voice-gateway.app-mumble.svc.cluster.local:8080/readyz" - - @classmethod - def from_env(cls, manifest: Mapping[str, Any] | None = None) -> Settings: - """MUMBLERMAPI_* variables, then the product manifest (kraftwerk.py), then the defaults""" - env = os.environ - manifest = kraftwerk.read() if manifest is None else manifest - rmapi_identity = kraftwerk.value(manifest, "rasenmaeher", "certcn") or cls().rmapi_identity - return cls( - database=Path(env.get("MUMBLERMAPI_DATABASE", cls().database)), - templates_dir=Path(env.get("MUMBLERMAPI_TEMPLATES_DIR", cls().templates_dir)), - ui_dir=Path(env.get("MUMBLERMAPI_UI_DIR", cls().ui_dir)), - tak=TakSettings.from_env(env, manifest), - rmapi_identity=env.get("MUMBLERMAPI_RMAPI_IDENTITY", rmapi_identity), - agent_identity=env.get("MUMBLERMAPI_AGENT_IDENTITY", cls().agent_identity), - traefik_identity=env.get("MUMBLERMAPI_TRAEFIK_IDENTITY", cls().traefik_identity), - ca_bundle=Path(env.get("MUMBLERMAPI_CA_BUNDLE", cls().ca_bundle)), - proxy_ready_url=env.get("MUMBLERMAPI_PROXY_READY_URL", cls().proxy_ready_url), - gateway_ready_url=env.get("MUMBLERMAPI_GATEWAY_READY_URL", cls().gateway_ready_url), - ) - - -# ---- request bodies -Access = Literal["open", "invite", "inherit"] - - -class NewChannel(BaseModel): - """A channel to create""" - - name: str = Field(min_length=1, max_length=100) - description: str = Field(default="", max_length=1000) - parent: int = 0 - access: Access | None = None - - -class ChannelEdit(BaseModel): - """A new name, description or access for a channel; omitted fields stay""" - - name: str | None = Field(default=None, min_length=1, max_length=100) - description: str | None = Field(default=None, max_length=1000) - access: Access | None = None - - -# A template's id is its file stem; only such ids are offered or accepted -TEMPLATE_ID = r"^[a-z0-9][a-z0-9-]{0,63}$" - - -class TemplateChoice(BaseModel): - """Which template to apply. A JSON body, so a cross-site form cannot send it.""" - - template: str = Field(pattern=TEMPLATE_ID) - - -class VoiceSetting(BaseModel): - """Whether a callsign may use voice""" - - enabled: bool - - -class TicketRequest(BaseModel): - """Which browser is joining. A JSON body, so a cross-site form cannot send it.""" - - model_config = ConfigDict(extra="forbid") - - # 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): - """What the browser hands the voice gateway""" - - 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-") - - -class PresenceEntry(BaseModel): - """One connected session: its callsign as Mumble shows it, and its net""" - - callsign: str = Field(max_length=200) - channel: str = Field(max_length=2000) - - -class PresenceReport(BaseModel): - """Everyone connected, from murmur-agent""" - - sessions: list[PresenceEntry] = Field(max_length=5000) - - -class ProductComponent(BaseModel): - """How rmui shows the product""" - - type: Literal["link", "markdown", "component"] - ref: str - - -class ProductDescriptionExtended(BaseModel): - """rmapi's v2 description, which forbids extra keys""" - - model_config = ConfigDict(extra="forbid") - - shortname: str - title: str - icon: str | None - description: str - language: str - docs: str | None - component: ProductComponent - - -# ---- identity checks -def _cn(request: Request) -> str: - return str(request.state.mtlsdn.get("CN", "")) - - -def from_rmapi(request: Request) -> None: - """Only rmapi may send user lifecycle events""" - if _cn(request) != request.app.state.settings.rmapi_identity: - raise HTTPException(status_code=403) - - -def from_agent(request: Request) -> None: - """Only the murmur pod's agent may read the desired state""" - if _cn(request) != request.app.state.settings.agent_identity: - raise HTTPException(status_code=403) - - -def admin_callsign(request: Request) -> str: - """The caller must be a Deploy App admin""" - callsign = _cn(request) - user = request.app.state.store.user(callsign) - if user is None or not user.admin or user.revoked: - raise HTTPException(status_code=403) - return callsign - - -def get_store(request: Request) -> Store: - """The app's store""" - store: Store = request.app.state.store - return store - - -StoreDep = Annotated[Store, Depends(get_store)] -AdminDep = Annotated[str, Depends(admin_callsign)] - - -# ---- routes -users = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True)), Depends(from_rmapi)]) - - -@users.post("/created") -def user_created(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: - """A user got a certificate""" - store.upsert_user(user.callsign, user.uuid) - store.set_user_flag(user.callsign, "revoked", False) - LOGGER.info("User %s created", user.callsign) - return OperationResultResponse(success=True) - - -@users.post("/revoked") -def user_revoked(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: - """A user's certificate was revoked: murmur-agent disconnects them on its next poll""" - store.set_user_flag(user.callsign, "revoked", True, uuid=user.uuid) - LOGGER.info("User %s revoked", user.callsign) - return OperationResultResponse(success=True) - - -@users.post("/promoted") -def user_promoted(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: - """A user became an admin""" - store.set_user_flag(user.callsign, "admin", True, uuid=user.uuid) - return OperationResultResponse(success=True) - - -@users.post("/demoted") -def user_demoted(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: - """A user is no longer an admin""" - store.set_user_flag(user.callsign, "admin", False, uuid=user.uuid) - return OperationResultResponse(success=True) - - -@users.put("/updated") -def user_updated(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: - """A user's details changed""" - store.upsert_user(user.callsign, user.uuid) - return OperationResultResponse(success=True) - - -agent = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True)), Depends(from_agent)]) - - -def _channel_dict(channel: Channel) -> dict[str, Any]: - return asdict(channel) - - -@agent.get("/state") -def agent_state(request: Request, store: StoreDep) -> Response: - """Everything murmur-agent enforces; 304 while nothing has changed. The ticket key changes on every start - while the store's version does not, so the ETag carries both.""" - version = store.version() - ticket_key = public_key(request.app.state.ticket_key) - etag = f"{version}-{ticket_key[:16]}" - if request.headers.get("if-none-match") == etag: - return Response(status_code=304, headers={"ETag": etag}) - all_users = store.users() - body = { - "version": version, - "etag": etag, - "ticket_keys": [ticket_key], - "refused": sorted(u.callsign for u in all_users if u.revoked or u.voice_disabled), - "units": [_channel_dict(c) for c in store.tree()], - "missions": [{"name": name, "members": sorted(members)} for name, members in sorted(store.missions().items())], - } - return Response(json.dumps(body), media_type="application/json", headers={"ETag": etag}) - - -@agent.post("/presence") -def agent_presence(report: PresenceReport, request: Request) -> None: - """Who is connected where, for the admin UI; kept in memory only""" - online: dict[str, list[str]] = {} - for entry in report.sessions: - online.setdefault(entry.callsign, []).append(entry.channel) - request.app.state.presence = (time.monotonic(), online) - - -def presence_of(request: Request) -> dict[str, list[str]] | None: - """Callsign (in Mumble's form) to nets, or None when murmur-agent has not reported lately""" - received, online = request.app.state.presence - if time.monotonic() - received > PRESENCE_TTL: - return None - return dict(online) - - -admin = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True))]) - - -@admin.get("/channels") -def list_channels(_: AdminDep, store: StoreDep) -> list[dict[str, Any]]: - """The Units/ tree with members""" - return [_channel_dict(c) for c in store.tree()] - - -@admin.post("/channels") -def create_channel(channel: NewChannel, who: AdminDep, store: StoreDep) -> dict[str, int]: - """Create a Units/ channel""" - try: - parse_plan({"channels": [{"name": channel.name, "description": channel.description}]}) - channel_id = store.add_channel(channel.name, channel.description, channel.parent, channel.access) - except (StoreError, ChannelPlanError) as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - LOGGER.info("%s created channel %r", who, channel.name) - return {"id": channel_id} - - -@admin.delete("/channels/{channel_id}") -def delete_channel(channel_id: int, who: AdminDep, store: StoreDep) -> None: - """Remove a channel and everything under it""" - try: - store.remove_channel(channel_id) - except StoreError as exc: - raise HTTPException(status_code=404, detail=str(exc)) from exc - LOGGER.info("%s removed channel %d", who, channel_id) - - -@admin.patch("/channels/{channel_id}") -def edit_channel(channel_id: int, edit: ChannelEdit, who: AdminDep, store: StoreDep) -> None: - """Rename a channel, change its description, or change who may use it""" - try: - if edit.name is not None: - parse_plan({"channels": [{"name": edit.name}]}) - store.update_channel(channel_id, edit.name, edit.description, edit.access) - except NoSuchChannel as exc: - raise HTTPException(status_code=404, detail=str(exc)) from exc - except (ChannelPlanError, StoreError) as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - LOGGER.info("%s edited channel %d", who, channel_id) - - -@admin.delete("/channels") -def clear_channels(who: AdminDep, store: StoreDep) -> dict[str, int]: - """Remove the whole channel plan; the voice server moves everyone out of the removed nets""" - removed = store.clear() - LOGGER.info("%s removed the channel plan, %d channels", who, removed) - return {"removed": removed} - - -@admin.put("/channels/{channel_id}/members/{callsign}") -def add_member(channel_id: int, callsign: str, _: AdminDep, store: StoreDep) -> None: - """Make a callsign a member of a channel""" - if store.user(callsign) is None: - raise HTTPException(status_code=404, detail=f"unknown callsign {callsign}") - try: - store.set_member(channel_id, callsign, True) - except StoreError as exc: - raise HTTPException(status_code=404, detail=str(exc)) from exc - - -@admin.delete("/channels/{channel_id}/members/{callsign}") -def remove_member(channel_id: int, callsign: str, _: AdminDep, store: StoreDep) -> None: - """Take a callsign off a channel""" - try: - store.set_member(channel_id, callsign, False) - except StoreError as exc: - raise HTTPException(status_code=404, detail=str(exc)) from exc - - -def _plan_of(channels: list[Channel]) -> list[dict[str, Any]]: - return [ - {"name": c.name, "description": c.description, "access": c.access} - | ({"members": sorted(c.members)} if c.members else {}) - | ({"channels": _plan_of(c.children)} if c.children else {}) - for c in channels - ] - - -@admin.get("/channels/export", response_class=PlainTextResponse) -def export_channels(_: AdminDep, store: StoreDep) -> str: - """The tree in the 2022 channel plan schema""" - return str(yaml.safe_dump({"channels": _plan_of(store.tree())}, allow_unicode=True, sort_keys=False)) - - -@admin.post("/channels/import") -async def import_channels(request: Request, who: AdminDep, store: StoreDep) -> dict[str, int]: - """Add a channel plan (YAML, 2022 schema); existing channels are kept""" - # The browser sends the client certificate to any site's request, so refuse the content types a cross-site - # form can POST without a CORS preflight. - if request.headers.get("content-type", "").split(";")[0].strip() not in ("application/yaml", "application/x-yaml"): - raise HTTPException(status_code=415, detail="send the plan as application/yaml") - body = bytearray() - async for chunk in request.stream(): - body += chunk - if len(body) > MAX_PLAN_BYTES: - raise HTTPException(status_code=413, detail=f"a channel plan may be at most {MAX_PLAN_BYTES} bytes") - # Parsed and stored in the thread pool, as the other admin routes are, so a large plan stalls no other request - try: - plan: tuple[ChannelSpec, ...] = await run_in_threadpool(lambda: parse_plan(load_yaml(bytes(body)))) - except (ChannelPlanError, yaml.YAMLError) as exc: - raise HTTPException(status_code=400, detail=str(exc)) from exc - created = await run_in_threadpool(store.import_plan, plan) - LOGGER.info("%s imported a channel plan, %d new channels", who, created) - return {"created": created} - - -def templates(settings: Settings) -> dict[str, dict[str, Any]]: - """The plan templates on disk by id (file stem): name, description and the plan itself""" - found: dict[str, dict[str, Any]] = {} - if not settings.templates_dir.is_dir(): - return found - for path in sorted(settings.templates_dir.glob("*.yaml")): - if not re.match(TEMPLATE_ID, path.stem): - LOGGER.warning("Skipping template %s: name it in lowercase letters, digits and dashes", path.name) - continue - try: - data = load_yaml(path.read_text(encoding="utf-8")) - plan = parse_plan(data) - except (OSError, yaml.YAMLError, ChannelPlanError) as exc: - LOGGER.warning("Skipping template %s: %s", path.name, exc) - continue - found[path.stem] = { - "name": str(data.get("name", path.stem)), - "description": str(data.get("description", "")), - "plan": plan, - } - return found - - -def _count(plan: tuple[ChannelSpec, ...]) -> int: - return sum(1 + _count(spec.children) for spec in plan) - - -@admin.get("/templates") -def list_templates(request: Request, _: AdminDep) -> list[dict[str, Any]]: - """Channel plan templates an admin can apply, such as the standard company plan""" - return [ - {"id": key, "name": t["name"], "description": t["description"], "nets": _count(t["plan"])} - for key, t in templates(request.app.state.settings).items() - ] - - -@admin.post("/templates/apply") -def apply_template(choice: TemplateChoice, request: Request, who: AdminDep, store: StoreDep) -> dict[str, int]: - """Add a template's nets; nets that already exist are kept as they are""" - template = templates(request.app.state.settings).get(choice.template) - if template is None: - raise HTTPException(status_code=404, detail=f"no template {choice.template}") - created = store.import_plan(template["plan"]) - LOGGER.info("%s applied template %s, %d new channels", who, choice.template, created) - return {"created": created} - - -@admin.get("/users") -def list_users(request: Request, _: AdminDep, store: StoreDep) -> list[dict[str, Any]]: - """Every known callsign, for the member picker, with the nets each is connected to (None: unknown)""" - online = presence_of(request) - return [ - asdict(u) | {"uuid": None, "online": None if online is None else online.get(normalize_callsign(u.callsign), [])} - for u in store.users() - ] - - -@admin.get("/missions") -def list_missions(_: AdminDep, store: StoreDep) -> list[dict[str, Any]]: - """Guard, open to everyone, then the mission nets and their subscribers as last read from TAK; those are - managed in TAK, not here""" - return [{"name": GUARD, "members": [], "open": True}] + [ - {"name": name, "members": sorted(members), "open": False} for name, members in sorted(store.missions().items()) - ] - - -@admin.put("/users/{callsign}/voice") -def set_voice(callsign: str, setting: VoiceSetting, who: AdminDep, store: StoreDep) -> None: - """Turn voice off or on for one callsign, without touching their Deploy App identity""" - if store.user(callsign) is None: - raise HTTPException(status_code=404, detail=f"unknown callsign {callsign}") - store.set_user_flag(callsign, "voice_disabled", not setting.enabled) - LOGGER.info("%s set voice %s for %s", who, "on" if setting.enabled else "off", callsign) - - -FORWARDED_CERT = "x-forwarded-tls-client-cert" - - -def forwarded_leaf(request: Request) -> bytes: - """The client certificate Traefik verified, as DER. Traefik sends each certificate's PEM body, leaf first, - comma-separated, and overwrites the header when a client sends one of its own.""" - first = unquote(request.headers.get(FORWARDED_CERT, "")).split(",")[0] - try: - return base64.b64decode(first, validate=True) - except (binascii.Error, ValueError): - return b"" - - -voice = APIRouter() - - -def _refuse(status: int, why: str, who: str = "") -> HTTPException: - LOGGER.log(AUDIT, "Refused a voice ticket%s: %s", f" for {who}" if who else "", why) - return HTTPException(status_code=status, detail=why) - - -@voice.post("/token") -def voice_ticket(choice: TicketRequest, request: Request, store: StoreDep) -> Ticket: - """A ticket for the caller's browser to join voice through the voice gateway, as the person whose client - certificate Traefik verified. murmur-agent checks that certificate again when the gateway logs in.""" - settings: Settings = request.app.state.settings - if request.headers.get("l5d-client-id") != settings.traefik_identity: - raise _refuse(403, "tickets are only for requests through the edge") - verifier: CertVerifier | None = request.app.state.verifier - if verifier is None: - raise HTTPException(status_code=503, detail="no CA bundle to check client certificates against") - try: - identity = verifier.verify([forwarded_leaf(request)], datetime.now(UTC)) - except IdentityError as exc: - raise _refuse(403, str(exc)) from exc - record = store.user(identity.callsign) - if record is None: - # Users enrolled before voice was installed stay unknown until rmapi next tells us about them - 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) - 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, now), username=username) - - -public = APIRouter() - - -@public.get("/healthcheck") -def healthcheck(request: Request) -> ProductHealthCheckResponse: - """Voice's health for rmapi, from the background check, with what is wrong in extra. Always 200: the kubelet - probes this too, and restarting the process mends none of what the check finds.""" - found = request.app.state.health - return ProductHealthCheckResponse(healthy=not found, extra="; ".join(found)) - - -@public.get("/description/{language}") -def description(language: str) -> ProductDescription: - """What rmui shows for this product""" - if language not in DESCRIPTIONS: - raise HTTPException(status_code=404) - return ProductDescription( - shortname=SHORTNAME, title="Voice", icon=None, description=DESCRIPTIONS[language], language=language - ) - - -def _extended(language: str, texts: dict[str, str]) -> ProductDescriptionExtended: - language = language if language in texts else "en" - return ProductDescriptionExtended( - shortname=SHORTNAME, - title=TITLES[language], - icon=f"{UI_PATH[1:]}/voicelogo.svg", - description=texts[language], - language=language, - docs=None, - component=ProductComponent(type="component", ref=f"{UI_PATH}/remoteEntry.js"), - ) - - -public_v2 = APIRouter() - - -@public_v2.get("/description/{language}") -def description_v2(language: str) -> ProductDescriptionExtended: - """The product tile and its UI remote""" - return _extended(language, DESCRIPTIONS) - - -@public_v2.get("/admin/description/{language}") -def admin_description(language: str) -> ProductDescriptionExtended: - """The admin tools entry; it opens the same remote, which shows admins more""" - return _extended(language, ADMIN_DESCRIPTIONS) - - -clients = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True)), Depends(from_rmapi)]) - - -@clients.post("/data") -def client_data(user: UserCRUDRequest, store: StoreDep) -> dict[str, dict[str, Any]]: - """What the UI remote shows this user; rmapi asks on the user's behalf""" - record = store.user(user.callsign) - nets: list[str] = [] - - def walk(channels: list[Channel], path: str) -> None: - for channel in channels: - here = f"{path}/{channel.name}" - # Kept members of a net that is not members-only are not let in by it - if channel.access == "invite" and user.callsign in channel.members: - nets.append(here) - walk(channel.children, here) - - walk(store.tree(), "/Units") - nets += [f"/Missions/{name}" for name, members in sorted(store.missions().items()) if user.callsign in members] - return { - "data": { - "admin": bool(record and record.admin and not record.revoked), - # Callsigns mumblermapi has not heard of yet are not refused either - "voice": not (record and (record.revoked or record.voice_disabled)), - "nets": nets, - } - } - - -class UiFiles(StaticFiles): - """The UI remote. Browsers revalidate every file, so a new release shows on the next load rather than - whenever a heuristically cached remoteEntry.js expires.""" - - def file_response(self, *args: Any, **kwargs: Any) -> Response: - response = super().file_response(*args, **kwargs) - response.headers["Cache-Control"] = "no-cache" - return response - - -def create_app(settings: Settings | None = None) -> FastAPI: - """The FastAPI app""" - settings = settings or Settings.from_env() - store = Store(settings.database) - - @asynccontextmanager - async def lifespan(app: FastAPI) -> AsyncIterator[None]: - stop = asyncio.Event() - missions = asyncio.create_task(watch(store, settings.tak, stop)) if settings.tak else None - health = asyncio.create_task(watch_health(app, stop, PRESENCE_TTL)) - yield - stop.set() - await health - if missions: - await missions - - app = FastAPI(docs_url="/api/docs", openapi_url="/api/openapi.json", lifespan=lifespan) - app.state.settings = settings - app.state.store = store - app.state.presence = (float("-inf"), {}) - app.state.health = [] # what keeps voice from working, from the background check (health.py) - # Voice tickets live a minute, so the signing key lives in memory only and changes with every start. - app.state.ticket_key = Ed25519PrivateKey.generate() - app.state.verifier = CertVerifier.from_pem_file(settings.ca_bundle) if settings.ca_bundle.is_file() else None - app.include_router(users, prefix="/api/v1/users") - app.include_router(agent, prefix="/api/v1/agent") - app.include_router(admin, prefix="/api/v1/admin") - app.include_router(voice, prefix="/api/v1/voice") - app.include_router(public, prefix="/api/v1") - app.include_router(clients, prefix="/api/v2/clients") - app.include_router(public_v2, prefix="/api/v2") - if settings.ui_dir.is_dir(): - app.mount(UI_PATH, UiFiles(directory=settings.ui_dir), name="ui") - return app diff --git a/src/mumblermapi/api/__init__.py b/src/mumblermapi/api/__init__.py new file mode 100644 index 0000000..751f9fd --- /dev/null +++ b/src/mumblermapi/api/__init__.py @@ -0,0 +1,30 @@ +"""The integration's HTTP API, one module per router""" + +from fastapi import APIRouter + +from .admin_channels import router as admin_channels_router +from .admin_templates import router as admin_templates_router +from .admin_users import router as admin_users_router +from .clients import router as clients_router +from .description import router as description_router +from .description import router_v2 as description_router_v2 +from .description import router_v2_admin as description_admin_router +from .healthcheck import router as healthcheck_router +from .murmur_agent import router as murmur_agent_router +from .usercrud import router as usercrud_router +from .voice import router as voice_router + +all_routers = APIRouter() +all_routers.include_router(usercrud_router, prefix="/users", tags=["users"]) +all_routers.include_router(murmur_agent_router, prefix="/agent", tags=["agent"]) +all_routers.include_router(admin_channels_router, prefix="/admin", tags=["admin"]) +all_routers.include_router(admin_templates_router, prefix="/admin", tags=["admin"]) +all_routers.include_router(admin_users_router, prefix="/admin", tags=["admin"]) +all_routers.include_router(voice_router, prefix="/voice", tags=["voice"]) +all_routers.include_router(healthcheck_router, prefix="/healthcheck", tags=["healthcheck"]) +all_routers.include_router(description_router, prefix="/description", tags=["description"]) + +all_routers_v2 = APIRouter() +all_routers_v2.include_router(description_router_v2, prefix="/description", tags=["description"]) +all_routers_v2.include_router(description_admin_router, prefix="/admin/description", tags=["description"]) +all_routers_v2.include_router(clients_router, prefix="/clients", tags=["clients"]) diff --git a/src/mumblermapi/api/admin_channels.py b/src/mumblermapi/api/admin_channels.py new file mode 100644 index 0000000..b1cc7ce --- /dev/null +++ b/src/mumblermapi/api/admin_channels.py @@ -0,0 +1,139 @@ +"""Admin routes for the nets: the Units/ tree and its members, plans in and out, and the mission nets""" + +from __future__ import annotations + +import logging +from dataclasses import asdict +from typing import Any + +import yaml +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.concurrency import run_in_threadpool +from fastapi.responses import PlainTextResponse +from libpvarki.middleware import MTLSHeader + +from ..channels import GUARD, ChannelPlanError, ChannelSpec, load_yaml, parse_plan +from ..store import Channel, NoSuchChannel, StoreError +from .deps import AdminDep, StoreDep +from .models import Callsign, ChannelEdit, NewChannel + +LOGGER = logging.getLogger(__name__) +MAX_PLAN_BYTES = 1 << 20 # an imported channel plan; a full plan of 1000 nets with members is about half of this + +router = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True))]) + + +@router.get("/channels") +def list_channels(_: AdminDep, store: StoreDep) -> list[dict[str, Any]]: + """The Units/ tree with members""" + return [asdict(c) for c in store.tree()] + + +@router.post("/channels") +def create_channel(channel: NewChannel, who: AdminDep, store: StoreDep) -> dict[str, int]: + """Create a Units/ channel""" + try: + parse_plan({"channels": [{"name": channel.name, "description": channel.description}]}) + channel_id = store.add_channel(channel.name, channel.description, channel.parent, channel.access) + except (StoreError, ChannelPlanError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + LOGGER.info("%s created channel %r", who, channel.name) + return {"id": channel_id} + + +@router.delete("/channels/{channel_id}") +def delete_channel(channel_id: int, who: AdminDep, store: StoreDep) -> None: + """Remove a channel and everything under it""" + try: + store.remove_channel(channel_id) + except StoreError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + LOGGER.info("%s removed channel %d", who, channel_id) + + +@router.patch("/channels/{channel_id}") +def edit_channel(channel_id: int, edit: ChannelEdit, who: AdminDep, store: StoreDep) -> None: + """Rename a channel, change its description, or change who may use it""" + try: + if edit.name is not None: + parse_plan({"channels": [{"name": edit.name}]}) + store.update_channel(channel_id, edit.name, edit.description, edit.access) + except NoSuchChannel as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + except (ChannelPlanError, StoreError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + LOGGER.info("%s edited channel %d", who, channel_id) + + +@router.delete("/channels") +def clear_channels(who: AdminDep, store: StoreDep) -> dict[str, int]: + """Remove the whole channel plan; the voice server moves everyone out of the removed nets""" + removed = store.clear() + LOGGER.info("%s removed the channel plan, %d channels", who, removed) + return {"removed": removed} + + +@router.put("/channels/{channel_id}/members/{callsign}") +def add_member(channel_id: int, callsign: Callsign, _: AdminDep, store: StoreDep) -> None: + """Make a callsign a member of a channel""" + if store.user(callsign) is None: + raise HTTPException(status_code=404, detail=f"unknown callsign {callsign}") + try: + store.set_member(channel_id, callsign, True) + except StoreError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + +@router.delete("/channels/{channel_id}/members/{callsign}") +def remove_member(channel_id: int, callsign: Callsign, _: AdminDep, store: StoreDep) -> None: + """Take a callsign off a channel""" + try: + store.set_member(channel_id, callsign, False) + except StoreError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + +def _plan_of(channels: list[Channel]) -> list[dict[str, Any]]: + return [ + {"name": c.name, "description": c.description, "access": c.access} + | ({"members": sorted(c.members)} if c.members else {}) + | ({"channels": _plan_of(c.children)} if c.children else {}) + for c in channels + ] + + +@router.get("/channels/export", response_class=PlainTextResponse) +def export_channels(_: AdminDep, store: StoreDep) -> str: + """The tree in the 2022 channel plan schema""" + return str(yaml.safe_dump({"channels": _plan_of(store.tree())}, allow_unicode=True, sort_keys=False)) + + +@router.post("/channels/import") +async def import_channels(request: Request, who: AdminDep, store: StoreDep) -> dict[str, int]: + """Add a channel plan (YAML, 2022 schema); existing channels are kept""" + # The browser sends the client certificate to any site's request, so refuse the content types a cross-site + # form can POST without a CORS preflight. + if request.headers.get("content-type", "").split(";")[0].strip() not in ("application/yaml", "application/x-yaml"): + raise HTTPException(status_code=415, detail="send the plan as application/yaml") + body = bytearray() + async for chunk in request.stream(): + body += chunk + if len(body) > MAX_PLAN_BYTES: + raise HTTPException(status_code=413, detail=f"a channel plan may be at most {MAX_PLAN_BYTES} bytes") + # Parsed and stored in the thread pool, as the other admin routes are, so a large plan stalls no other request + try: + plan: tuple[ChannelSpec, ...] = await run_in_threadpool(lambda: parse_plan(load_yaml(bytes(body)))) + except (ChannelPlanError, yaml.YAMLError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + created = await run_in_threadpool(store.import_plan, plan) + LOGGER.info("%s imported a channel plan, %d new channels", who, created) + return {"created": created} + + +@router.get("/missions") +def list_missions(_: AdminDep, store: StoreDep) -> list[dict[str, Any]]: + """Guard, open to everyone, then the mission nets and their subscribers as last read from TAK; those are + managed in TAK, not here""" + return [{"name": GUARD, "members": [], "open": True}] + [ + {"name": name, "members": sorted(members), "open": False} for name, members in sorted(store.missions().items()) + ] diff --git a/src/mumblermapi/api/admin_templates.py b/src/mumblermapi/api/admin_templates.py new file mode 100644 index 0000000..2fe27c8 --- /dev/null +++ b/src/mumblermapi/api/admin_templates.py @@ -0,0 +1,67 @@ +"""Admin routes for the channel plan templates the image ships""" + +from __future__ import annotations + +import logging +import re +from typing import Any + +import yaml +from fastapi import APIRouter, Depends, HTTPException, Request +from libpvarki.middleware import MTLSHeader + +from ..channels import ChannelPlanError, ChannelSpec, load_yaml, parse_plan +from ..config import Settings +from .deps import AdminDep, StoreDep +from .models import TEMPLATE_ID, TemplateChoice + +LOGGER = logging.getLogger(__name__) + +router = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True))]) + + +def templates(settings: Settings) -> dict[str, dict[str, Any]]: + """The plan templates on disk by id (file stem): name, description and the plan itself""" + found: dict[str, dict[str, Any]] = {} + if not settings.templates_dir.is_dir(): + return found + for path in sorted(settings.templates_dir.glob("*.yaml")): + if not re.match(TEMPLATE_ID, path.stem): + LOGGER.warning("Skipping template %s: name it in lowercase letters, digits and dashes", path.name) + continue + try: + data = load_yaml(path.read_text(encoding="utf-8")) + plan = parse_plan(data) + except (OSError, yaml.YAMLError, ChannelPlanError) as exc: + LOGGER.warning("Skipping template %s: %s", path.name, exc) + continue + found[path.stem] = { + "name": str(data.get("name", path.stem)), + "description": str(data.get("description", "")), + "plan": plan, + } + return found + + +def _count(plan: tuple[ChannelSpec, ...]) -> int: + return sum(1 + _count(spec.children) for spec in plan) + + +@router.get("/templates") +def list_templates(request: Request, _: AdminDep) -> list[dict[str, Any]]: + """Channel plan templates an admin can apply, such as the standard company plan""" + return [ + {"id": key, "name": t["name"], "description": t["description"], "nets": _count(t["plan"])} + for key, t in templates(request.app.state.settings).items() + ] + + +@router.post("/templates/apply") +def apply_template(choice: TemplateChoice, request: Request, who: AdminDep, store: StoreDep) -> dict[str, int]: + """Add a template's nets; nets that already exist are kept as they are""" + template = templates(request.app.state.settings).get(choice.template) + if template is None: + raise HTTPException(status_code=404, detail=f"no template {choice.template}") + created = store.import_plan(template["plan"]) + LOGGER.info("%s applied template %s, %d new channels", who, choice.template, created) + return {"created": created} diff --git a/src/mumblermapi/api/admin_users.py b/src/mumblermapi/api/admin_users.py new file mode 100644 index 0000000..fa63a6d --- /dev/null +++ b/src/mumblermapi/api/admin_users.py @@ -0,0 +1,38 @@ +"""Admin routes for the people: who is known and online, and whose voice is off""" + +from __future__ import annotations + +import logging +from dataclasses import asdict +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, Request +from libpvarki.middleware import MTLSHeader + +from ..identity import normalize_callsign +from .deps import AdminDep, StoreDep +from .models import Callsign, VoiceSetting +from .murmur_agent import presence_of + +LOGGER = logging.getLogger(__name__) + +router = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True))]) + + +@router.get("/users") +def list_users(request: Request, _: AdminDep, store: StoreDep) -> list[dict[str, Any]]: + """Every known callsign, for the member picker, with the nets each is connected to (None: unknown)""" + online = presence_of(request) + return [ + asdict(u) | {"uuid": None, "online": None if online is None else online.get(normalize_callsign(u.callsign), [])} + for u in store.users() + ] + + +@router.put("/users/{callsign}/voice") +def set_voice(callsign: Callsign, setting: VoiceSetting, who: AdminDep, store: StoreDep) -> None: + """Turn voice off or on for one callsign, without touching their Deploy App identity""" + if store.user(callsign) is None: + raise HTTPException(status_code=404, detail=f"unknown callsign {callsign}") + store.set_user_flag(callsign, "voice_disabled", not setting.enabled) + LOGGER.info("%s set voice %s for %s", who, "on" if setting.enabled else "off", callsign) diff --git a/src/mumblermapi/api/clients.py b/src/mumblermapi/api/clients.py new file mode 100644 index 0000000..35f6961 --- /dev/null +++ b/src/mumblermapi/api/clients.py @@ -0,0 +1,40 @@ +"""What rmapi asks on a user's behalf: the data the UI remote shows them""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, Depends +from libpvarki.middleware import MTLSHeader +from libpvarki.schemas.product import UserCRUDRequest + +from ..store import Channel +from .deps import StoreDep, from_rmapi + +router = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True)), Depends(from_rmapi)]) + + +@router.post("/data") +def client_data(user: UserCRUDRequest, store: StoreDep) -> dict[str, dict[str, Any]]: + """What the UI remote shows this user""" + record = store.user(user.callsign) + nets: list[str] = [] + + def walk(channels: list[Channel], path: str) -> None: + for channel in channels: + here = f"{path}/{channel.name}" + # Kept members of a net that is not members-only are not let in by it + if channel.access == "invite" and user.callsign in channel.members: + nets.append(here) + walk(channel.children, here) + + walk(store.tree(), "/Units") + nets += [f"/Missions/{name}" for name, members in sorted(store.missions().items()) if user.callsign in members] + return { + "data": { + "admin": bool(record and record.admin and not record.revoked), + # Callsigns mumblermapi has not heard of yet are not refused either + "voice": not (record and (record.revoked or record.voice_disabled)), + "nets": nets, + } + } diff --git a/src/mumblermapi/api/deps.py b/src/mumblermapi/api/deps.py new file mode 100644 index 0000000..b67beb6 --- /dev/null +++ b/src/mumblermapi/api/deps.py @@ -0,0 +1,44 @@ +"""Dependencies the routes share: who is calling, and the store""" + +from __future__ import annotations + +from typing import Annotated + +from fastapi import Depends, HTTPException, Request + +from ..store import Store + + +def _cn(request: Request) -> str: + return str(request.state.mtlsdn.get("CN", "")) + + +def from_rmapi(request: Request) -> None: + """Only rmapi may send user lifecycle events""" + if _cn(request) != request.app.state.settings.rmapi_identity: + raise HTTPException(status_code=403) + + +def from_agent(request: Request) -> None: + """Only the murmur pod's agent may read the desired state""" + if _cn(request) != request.app.state.settings.agent_identity: + raise HTTPException(status_code=403) + + +def admin_callsign(request: Request) -> str: + """The caller must be a Deploy App admin""" + callsign = _cn(request) + user = request.app.state.store.user(callsign) + if user is None or not user.admin or user.revoked: + raise HTTPException(status_code=403) + return callsign + + +def get_store(request: Request) -> Store: + """The app's store""" + store: Store = request.app.state.store + return store + + +StoreDep = Annotated[Store, Depends(get_store)] +AdminDep = Annotated[str, Depends(admin_callsign)] diff --git a/src/mumblermapi/api/description.py b/src/mumblermapi/api/description.py new file mode 100644 index 0000000..fff45b9 --- /dev/null +++ b/src/mumblermapi/api/description.py @@ -0,0 +1,60 @@ +"""The product descriptions rmui shows; anyone may read them""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException +from libpvarki.schemas.product import ProductDescription + +from ..config import SHORTNAME, UI_PATH +from .models import ProductComponent, ProductDescriptionExtended + +TITLES = {"fi": "Puhe", "sv": "Röst", "en": "Voice"} +DESCRIPTIONS = { + "fi": "Puheryhmät TAKiin: PTT-kanavat ryhmälle, joukkueelle ja komppanialle", + "sv": "Röstkanaler för TAK: tryck-och-tala för grupp, pluton och kompani", + "en": "Voice for TAK: push-to-talk channels for squad, platoon and company", +} +ADMIN_DESCRIPTIONS = { + "fi": "Puheverkot: yksiköiden kanavat, jäsenet ja puheen esto", + "sv": "Röstnät: enheternas kanaler, medlemmar och spärr av röst", + "en": "Voice nets: unit channels, members and turning voice off", +} + +router = APIRouter() +router_v2 = APIRouter() +router_v2_admin = APIRouter() + + +@router.get("/{language}") +def description(language: str) -> ProductDescription: + """What rmui shows for this product""" + if language not in DESCRIPTIONS: + raise HTTPException(status_code=404) + return ProductDescription( + shortname=SHORTNAME, title="Voice", icon=None, description=DESCRIPTIONS[language], language=language + ) + + +def _extended(language: str, texts: dict[str, str]) -> ProductDescriptionExtended: + language = language if language in texts else "en" + return ProductDescriptionExtended( + shortname=SHORTNAME, + title=TITLES[language], + icon=f"{UI_PATH[1:]}/voicelogo.svg", + description=texts[language], + language=language, + docs=f"https://docs.opendefence.fi/{language}/guides/voice-guide", + component=ProductComponent(type="component", ref=f"{UI_PATH}/remoteEntry.js"), + ) + + +@router_v2.get("/{language}") +def description_v2(language: str) -> ProductDescriptionExtended: + """The product tile and its UI remote""" + return _extended(language, DESCRIPTIONS) + + +@router_v2_admin.get("/{language}") +def admin_description(language: str) -> ProductDescriptionExtended: + """The admin tools entry; it opens the same remote, which shows admins more""" + return _extended(language, ADMIN_DESCRIPTIONS) diff --git a/src/mumblermapi/api/healthcheck.py b/src/mumblermapi/api/healthcheck.py new file mode 100644 index 0000000..87f4062 --- /dev/null +++ b/src/mumblermapi/api/healthcheck.py @@ -0,0 +1,16 @@ +"""The health check rmapi and the kubelet ask""" + +from __future__ import annotations + +from fastapi import APIRouter, Request +from libpvarki.schemas.product import ProductHealthCheckResponse + +router = APIRouter() + + +@router.get("") +def healthcheck(request: Request) -> ProductHealthCheckResponse: + """Voice's health for rmapi, from the background check, with what is wrong in extra. Always 200: the kubelet + probes this too, and restarting the process mends none of what the check finds.""" + found = request.app.state.health + return ProductHealthCheckResponse(healthy=not found, extra="; ".join(found)) diff --git a/src/mumblermapi/api/models.py b/src/mumblermapi/api/models.py new file mode 100644 index 0000000..be616d1 --- /dev/null +++ b/src/mumblermapi/api/models.py @@ -0,0 +1,103 @@ +"""Request and response bodies""" + +from __future__ import annotations + +from typing import Annotated, Literal + +from fastapi import Path +from pydantic import BaseModel, ConfigDict, Field + +from ..channels import MAX_DESCRIPTION, Access + +# Postgres text cannot hold NUL +Description = Annotated[str, Field(max_length=MAX_DESCRIPTION, pattern=r"^[^\x00]*$")] +Callsign = Annotated[str, Path(pattern=r"^[^\x00]+$")] + + +class NewChannel(BaseModel): + """A channel to create""" + + name: str = Field(min_length=1, max_length=100) + description: Description = "" + parent: int = 0 + access: Access | None = None + + +class ChannelEdit(BaseModel): + """A new name, description or access for a channel; omitted fields stay""" + + name: str | None = Field(default=None, min_length=1, max_length=100) + description: Description | None = None + access: Access | None = None + + +# A template's id is its file stem; only such ids are offered or accepted +TEMPLATE_ID = r"^[a-z0-9][a-z0-9-]{0,63}$" + + +class TemplateChoice(BaseModel): + """Which template to apply. A JSON body, so a cross-site form cannot send it.""" + + template: str = Field(pattern=TEMPLATE_ID) + + +class VoiceSetting(BaseModel): + """Whether a callsign may use voice""" + + enabled: bool + + +class TicketRequest(BaseModel): + """Which browser is joining. A JSON body, so a cross-site form cannot send it.""" + + model_config = ConfigDict(extra="forbid") + + # 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): + """What the browser hands the voice gateway""" + + 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-") + + +class PresenceEntry(BaseModel): + """One connected session: its callsign as Mumble shows it, and its net""" + + callsign: str = Field(max_length=200) + channel: str = Field(max_length=2000) + + +class PresenceReport(BaseModel): + """Everyone connected, from murmur-agent""" + + sessions: list[PresenceEntry] = Field(max_length=5000) + + +class ProductComponent(BaseModel): + """How rmui shows the product""" + + type: Literal["link", "markdown", "component"] + ref: str + + +class ProductDescriptionExtended(BaseModel): + """rmapi's v2 description, which forbids extra keys""" + + model_config = ConfigDict(extra="forbid") + + shortname: str + title: str + icon: str | None + description: str + language: str + docs: str | None + component: ProductComponent diff --git a/src/mumblermapi/api/murmur_agent.py b/src/mumblermapi/api/murmur_agent.py new file mode 100644 index 0000000..6a65a81 --- /dev/null +++ b/src/mumblermapi/api/murmur_agent.py @@ -0,0 +1,57 @@ +"""What murmur-agent reads and reports: the state to enforce, and who is connected where""" + +from __future__ import annotations + +import json +import time +from dataclasses import asdict + +from fastapi import APIRouter, Depends, Request, Response +from libpvarki.middleware import MTLSHeader + +from ..tickets import public_key +from .deps import StoreDep, from_agent +from .models import PresenceReport + +# murmur-agent reports presence at least every 30 s; older than this and nobody can say who is online +PRESENCE_TTL = 90.0 + +router = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True)), Depends(from_agent)]) + + +@router.get("/state") +def agent_state(request: Request, store: StoreDep) -> Response: + """Everything murmur-agent enforces; 304 while nothing has changed. The ticket key changes on every start + while the store's version does not, so the ETag carries both.""" + version = store.version() + ticket_key = public_key(request.app.state.ticket_key) + etag = f"{version}-{ticket_key[:16]}" + if request.headers.get("if-none-match") == etag: + return Response(status_code=304, headers={"ETag": etag}) + all_users = store.users() + body = { + "version": version, + "etag": etag, + "ticket_keys": [ticket_key], + "refused": sorted(u.callsign for u in all_users if u.revoked or u.voice_disabled), + "units": [asdict(c) for c in store.tree()], + "missions": [{"name": name, "members": sorted(members)} for name, members in sorted(store.missions().items())], + } + return Response(json.dumps(body), media_type="application/json", headers={"ETag": etag}) + + +@router.post("/presence") +def agent_presence(report: PresenceReport, request: Request) -> None: + """Who is connected where, for the admin UI; kept in memory only""" + online: dict[str, list[str]] = {} + for entry in report.sessions: + online.setdefault(entry.callsign, []).append(entry.channel) + request.app.state.presence = (time.monotonic(), online) + + +def presence_of(request: Request) -> dict[str, list[str]] | None: + """Callsign (in Mumble's form) to nets, or None when murmur-agent has not reported lately""" + received, online = request.app.state.presence + if time.monotonic() - received > PRESENCE_TTL: + return None + return dict(online) diff --git a/src/mumblermapi/api/usercrud.py b/src/mumblermapi/api/usercrud.py new file mode 100644 index 0000000..057c293 --- /dev/null +++ b/src/mumblermapi/api/usercrud.py @@ -0,0 +1,54 @@ +"""User lifecycle events from rmapi""" + +from __future__ import annotations + +import logging + +from fastapi import APIRouter, Depends +from libpvarki.middleware import MTLSHeader +from libpvarki.schemas.generic import OperationResultResponse +from libpvarki.schemas.product import UserCRUDRequest + +from .deps import StoreDep, from_rmapi + +LOGGER = logging.getLogger(__name__) + +router = APIRouter(dependencies=[Depends(MTLSHeader(auto_error=True)), Depends(from_rmapi)]) + + +@router.post("/created") +def user_created(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: + """A user got a certificate""" + store.upsert_user(user.callsign, user.uuid) + store.set_user_flag(user.callsign, "revoked", False) + LOGGER.info("User %s created", user.callsign) + return OperationResultResponse(success=True) + + +@router.post("/revoked") +def user_revoked(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: + """A user's certificate was revoked: murmur-agent disconnects them on its next poll""" + store.set_user_flag(user.callsign, "revoked", True, uuid=user.uuid) + LOGGER.info("User %s revoked", user.callsign) + return OperationResultResponse(success=True) + + +@router.post("/promoted") +def user_promoted(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: + """A user became an admin""" + store.set_user_flag(user.callsign, "admin", True, uuid=user.uuid) + return OperationResultResponse(success=True) + + +@router.post("/demoted") +def user_demoted(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: + """A user is no longer an admin""" + store.set_user_flag(user.callsign, "admin", False, uuid=user.uuid) + return OperationResultResponse(success=True) + + +@router.put("/updated") +def user_updated(user: UserCRUDRequest, store: StoreDep) -> OperationResultResponse: + """A user's details changed""" + store.upsert_user(user.callsign, user.uuid) + return OperationResultResponse(success=True) diff --git a/src/mumblermapi/api/voice.py b/src/mumblermapi/api/voice.py new file mode 100644 index 0000000..4f94c3f --- /dev/null +++ b/src/mumblermapi/api/voice.py @@ -0,0 +1,66 @@ +"""Voice tickets: how a browser joins voice through the voice gateway""" + +from __future__ import annotations + +import base64 +import binascii +import logging +import time +from datetime import UTC, datetime +from urllib.parse import unquote + +from cryptography.hazmat.primitives.serialization import Encoding +from fastapi import APIRouter, HTTPException, Request + +from ..config import Settings +from ..identity import CertVerifier, IdentityError, normalize_callsign +from ..tickets import AUDIT, mint, web_username +from .deps import StoreDep +from .models import Ticket, TicketRequest + +LOGGER = logging.getLogger(__name__) +FORWARDED_CERT = "x-forwarded-tls-client-cert" + +router = APIRouter() + + +def forwarded_leaf(request: Request) -> bytes: + """The client certificate Traefik verified, as DER. Traefik sends each certificate's PEM body, leaf first, + comma-separated, and overwrites the header when a client sends one of its own.""" + first = unquote(request.headers.get(FORWARDED_CERT, "")).split(",")[0] + try: + return base64.b64decode(first, validate=True) + except (binascii.Error, ValueError): + return b"" + + +def _refuse(status: int, why: str, who: str = "") -> HTTPException: + LOGGER.log(AUDIT, "Refused a voice ticket%s: %s", f" for {who}" if who else "", why) + return HTTPException(status_code=status, detail=why) + + +@router.post("/token") +def voice_ticket(choice: TicketRequest, request: Request, store: StoreDep) -> Ticket: + """A ticket for the caller's browser to join voice through the voice gateway, as the person whose client + certificate Traefik verified. murmur-agent checks that certificate again when the gateway logs in.""" + settings: Settings = request.app.state.settings + if request.headers.get("l5d-client-id") != settings.traefik_identity: + raise _refuse(403, "tickets are only for requests through the edge") + verifier: CertVerifier | None = request.app.state.verifier + if verifier is None: + raise HTTPException(status_code=503, detail="no CA bundle to check client certificates against") + try: + identity = verifier.verify([forwarded_leaf(request)], datetime.now(UTC)) + except IdentityError as exc: + raise _refuse(403, str(exc)) from exc + record = store.user(identity.callsign) + if record is None: + # Users enrolled before voice was installed stay unknown until rmapi next tells us about them + 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) + 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, now), username=username) diff --git a/src/mumblermapi/app.py b/src/mumblermapi/app.py new file mode 100644 index 0000000..e3ac70b --- /dev/null +++ b/src/mumblermapi/app.py @@ -0,0 +1,61 @@ +"""mumblermapi: the Deploy App product integration for voice""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from fastapi import FastAPI, Response +from fastapi.staticfiles import StaticFiles + +from .api import all_routers, all_routers_v2 +from .api.murmur_agent import PRESENCE_TTL +from .config import UI_PATH, Settings +from .health import watch as watch_health +from .identity import CertVerifier +from .store import Store, engine +from .tak import watch + + +class UiFiles(StaticFiles): + """The UI remote. Browsers revalidate every file, so a new release shows on the next load rather than + whenever a heuristically cached remoteEntry.js expires.""" + + def file_response(self, *args: Any, **kwargs: Any) -> Response: + response = super().file_response(*args, **kwargs) + response.headers["Cache-Control"] = "no-cache" + return response + + +def create_app(settings: Settings | None = None) -> FastAPI: + """The FastAPI app""" + settings = settings or Settings.from_env() + store = Store(engine(settings.database.url)) + + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncIterator[None]: + stop = asyncio.Event() + missions = asyncio.create_task(watch(store, settings.tak, stop)) if settings.tak else None + health = asyncio.create_task(watch_health(app, stop, PRESENCE_TTL)) + yield + stop.set() + await health + if missions: + await missions + + app = FastAPI(docs_url="/api/docs", openapi_url="/api/openapi.json", lifespan=lifespan) + app.state.settings = settings + app.state.store = store + app.state.presence = (float("-inf"), {}) + app.state.health = [] # what keeps voice from working, from the background check (health.py) + # Voice tickets live a minute, so the signing key lives in memory only and changes with every start. + app.state.ticket_key = Ed25519PrivateKey.generate() + app.state.verifier = CertVerifier.from_pem_file(settings.ca_bundle) if settings.ca_bundle.is_file() else None + app.include_router(all_routers, prefix="/api/v1") + app.include_router(all_routers_v2, prefix="/api/v2") + if settings.ui_dir.is_dir(): + app.mount(UI_PATH, UiFiles(directory=settings.ui_dir), name="ui") + return app diff --git a/src/mumblermapi/channels.py b/src/mumblermapi/channels.py index 1142903..ef3af16 100644 --- a/src/mumblermapi/channels.py +++ b/src/mumblermapi/channels.py @@ -1,11 +1,11 @@ -"""The channel tree the agent keeps in Murmur""" +"""The channel plan: its names and limits, how it is read and the tree it makes""" from __future__ import annotations import re from dataclasses import dataclass from pathlib import Path -from typing import Any, Protocol +from typing import Any, Literal import yaml from yaml.constructor import ConstructorError @@ -33,29 +33,24 @@ # A TAK mission of the same name is ignored rather than allowed to gate it. GUARD = "Guard" -# 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. +# Murmur's default channelname pattern, its " -=" range made a literal dash, capped at 100. Murmur checks names from +# clients only, never over Ice, so this is the only gate. 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. +# Murmur's default channel limit; it 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. +# About what a 1 MiB plan holds written out in full, each aliased members list counted in every net MAX_MEMBERS = 100_000 -# 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's default channelnestinglimit, which holds over Ice too. The root is level 0 and Units/ level 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. +# Leaves the last level for members' temporary channels, and stops aliased nesting before Python's recursion limit MAX_DEPTH = MURMUR_NESTING_LIMIT - 2 -MAX_DESCRIPTION = 1000 # as long as the admin API lets a description be +MAX_DESCRIPTION = 1000 # Who may use a Units/ net: everyone, only its members (and those of invite-only nets above it), or the same # as the net above it. A top-level net has nothing above it, so "inherit" there means open. +Access = Literal["open", "invite", "inherit"] ACCESS = ("open", "invite", "inherit") @@ -63,10 +58,6 @@ 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 @@ -75,7 +66,7 @@ class ChannelSpec: name: str description: str = "" children: tuple[ChannelSpec, ...] = () - access: str = "" + access: Access | Literal[""] = "" members: tuple[str, ...] = () @@ -109,8 +100,8 @@ def _parse_list(items: object, where: str, room: _Room, depth: int = 1) -> tuple raise ChannelPlanError(f"{at}: invalid name {shown}") if name in seen: raise ChannelPlanError(f"{at}: duplicate name {name!r}") - if not isinstance(description, str) or len(description) > MAX_DESCRIPTION: - raise ChannelPlanError(f"{at}: description must be text of at most {MAX_DESCRIPTION} characters") + if not isinstance(description, str) or len(description) > MAX_DESCRIPTION or "\x00" in description: + raise ChannelPlanError(f"{at}: description must be text of at most {MAX_DESCRIPTION} characters, no NUL") access = item.get("access", "") if access not in ("", *ACCESS): raise ChannelPlanError(f"{at}: access must be one of {', '.join(ACCESS)}") @@ -191,96 +182,3 @@ def desired_tree(units: tuple[ChannelSpec, ...], missions: tuple[ChannelSpec, .. ChannelSpec("Teams", "ATAK team colours", tuple(ChannelSpec(colour) for colour in TEAM_COLOURS)), ChannelSpec("Roles", "ATAK roles", tuple(ChannelSpec(role) for role in ROLES)), ) - - -@dataclass(frozen=True) -class ExistingChannel: - """A channel as Murmur reports it""" - - id: int - parent: int - name: str - temporary: bool = False - description: str = "" - links: tuple[int, ...] = () - - -class ChannelServer(Protocol): - """The part of Murmur the reconciler needs""" - - 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; raises ChannelRefused when Murmur will not have it there""" - - def set_description(self, channel_id: int, description: str) -> None: - """Change a channel's description""" - - 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) -> 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. 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: - path = f"{prefix}/{spec.name}" - channel = existing.get((parent, spec.name)) - if channel is not None and channel.temporary: - # A user's temporary channel must not stand in for a net: its creator keeps rights over it and - # whatever is built inside. Murmur moves the people in it to the parent. - server.remove_channel(channel.id) - channel = None - if channel is None: - 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 - if channel.description != spec.description: - server.set_description(channel_id, spec.description) - walk(spec.children, channel_id, path) - - walk(desired, root, "") - return created, refused - - -def prune(server: ChannelServer, desired: tuple[ChannelSpec, ...], root: int, prefix: str = "") -> list[str]: - """Remove the permanent channels under root that desired no longer has, and return their paths. - - Temporary channels belong to the users in them, and Murmur removes them once they are empty. - """ - children: dict[int, list[ExistingChannel]] = {} - for channel in server.channels(): - children.setdefault(channel.parent, []).append(channel) - removed: list[str] = [] - - def walk(specs: tuple[ChannelSpec, ...], parent: int, prefix: str) -> None: - wanted = {spec.name: spec for spec in specs} - for channel in children.get(parent, []): - path = f"{prefix}/{channel.name}" - spec = wanted.get(channel.name) - if spec is not None: - walk(spec.children, channel.id, path) - elif not channel.temporary: - server.remove_channel(channel.id) - removed.append(path) - - walk(desired, root, prefix) - return removed diff --git a/src/mumblermapi/config.py b/src/mumblermapi/config.py index 53827c3..4e1be07 100644 --- a/src/mumblermapi/config.py +++ b/src/mumblermapi/config.py @@ -1,54 +1,47 @@ -"""murmur-agent settings, from the environment""" +"""The integration's settings""" from __future__ import annotations -import os from collections.abc import Mapping -from dataclasses import dataclass from pathlib import Path +from typing import Any +from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict -@dataclass(frozen=True) -class AgentConfig: - """Where Murmur is, what to trust, and how often to look""" +from . import kraftwerk +from .store import DatabaseSettings +from .tak import TakSettings - ice_secret: str - ice_host: str = "127.0.0.1" - ice_port: int = 6502 - callback_port: int = 6503 - server_id: int | None = None # None: the one virtual server Murmur runs (1.6 numbers it 0, older ones 1) +SHORTNAME = "mumble" +UI_PATH = f"/ui/{SHORTNAME}" # where Traefik serves the UI remote, on rmui's mTLS host + + +class Settings(BaseSettings): + """Where things are and who the peers are; MUMBLERMAPI_* variables, and the product manifest through from_env""" + + database: DatabaseSettings = Field(default_factory=DatabaseSettings) + templates_dir: Path = Path("/templates") # channel plan templates an admin may choose to apply + ui_dir: Path = Path("/ui") # the built UI remote, served at UI_PATH when present + tak: TakSettings | None = None # where to read missions from; None leaves Missions/ empty + # Linkerd identities of the only callers of the user and agent endpoints + rmapi_identity: str = "rmapi.opendefence-system.serviceaccount.identity.linkerd.cluster.local" + agent_identity: str = "murmur.app-mumble.serviceaccount.identity.linkerd.cluster.local" + # The edge, whose forwarded client certificate voice tickets are minted for, and the CAs it must chain to + traefik_identity: str = "traefik.traefik-system.serviceaccount.identity.linkerd.cluster.local" ca_bundle: Path = Path("/trust/ca-cert.pem") - channels_file: Path = Path("/config/channels.yaml") - data_dir: Path = Path("/data/agent") - ocsp_url: str | None = None - ocsp_cache_seconds: float = 300.0 - sweep_seconds: float = 60.0 # full certificate and OCSP recheck of everyone connected - state_url: str | None = None # mumblermapi's /api/v1/agent/state; None runs on the channels file alone - poll_seconds: float = 5.0 # how soon mumblermapi changes reach Murmur - presence_url: str | None = None # where to report who is connected; None reports nothing - gateway_ca: Path | None = None # the voice gateway's own CA; None lets no browser in + # What the health check asks (health.py); an empty URL is not checked + proxy_ready_url: str = "http://127.0.0.1:4191/ready" # this pod's Linkerd proxy + gateway_ready_url: str = "http://voice-gateway.app-mumble.svc.cluster.local:8080/readyz" + + model_config = SettingsConfigDict(env_prefix="MUMBLERMAPI_") @classmethod - def from_env(cls, env: Mapping[str, str] = os.environ) -> AgentConfig: - """Read MURMUR_* and AGENT_* variables; the Ice secret is mandatory""" - secret = env.get("MURMUR_ICE_SECRET", "") - if not secret: - raise ValueError("MURMUR_ICE_SECRET must be set: Murmur's Ice interface must never run without a secret") - defaults = cls(ice_secret=secret) - return cls( - ice_secret=secret, - ice_host=env.get("MURMUR_ICE_HOST", defaults.ice_host), - ice_port=int(env.get("MURMUR_ICE_PORT", defaults.ice_port)), - callback_port=int(env.get("AGENT_CALLBACK_PORT", defaults.callback_port)), - server_id=int(env["MURMUR_SERVER_ID"]) if env.get("MURMUR_SERVER_ID") else None, - ca_bundle=Path(env.get("AGENT_CA_BUNDLE", defaults.ca_bundle)), - channels_file=Path(env.get("AGENT_CHANNELS_FILE", defaults.channels_file)), - data_dir=Path(env.get("AGENT_DATA_DIR", defaults.data_dir)), - ocsp_url=env.get("AGENT_OCSP_URL") or None, - ocsp_cache_seconds=float(env.get("AGENT_OCSP_CACHE_SECONDS", defaults.ocsp_cache_seconds)), - sweep_seconds=float(env.get("AGENT_SWEEP_SECONDS", defaults.sweep_seconds)), - state_url=env.get("AGENT_STATE_URL") or None, - poll_seconds=float(env.get("AGENT_POLL_SECONDS", defaults.poll_seconds)), - presence_url=env.get("AGENT_PRESENCE_URL") or None, - gateway_ca=Path(env["AGENT_GATEWAY_CA"]) if env.get("AGENT_GATEWAY_CA") else None, - ) + def from_env(cls, manifest: Mapping[str, Any] | None = None) -> Settings: + """MUMBLERMAPI_* variables, then the product manifest (kraftwerk.py), then the defaults""" + manifest = kraftwerk.read() if manifest is None else manifest + settings = cls(tak=TakSettings.from_env(manifest=manifest)) + certcn = kraftwerk.value(manifest, "rasenmaeher", "certcn") + if certcn and "rmapi_identity" not in settings.model_fields_set: + return settings.model_copy(update={"rmapi_identity": certcn}) + return settings diff --git a/src/mumblermapi/console.py b/src/mumblermapi/console.py index e1565e1..f3ef3e6 100644 --- a/src/mumblermapi/console.py +++ b/src/mumblermapi/console.py @@ -7,7 +7,7 @@ import uvicorn from libpvarki.logging import add_trace_and_audit, init_logging -from .api import create_app +from .app import create_app def main() -> None: # pragma: no cover # the container entrypoint diff --git a/src/mumblermapi/health.py b/src/mumblermapi/health.py index cf513c7..9fc4ae5 100644 --- a/src/mumblermapi/health.py +++ b/src/mumblermapi/health.py @@ -12,6 +12,7 @@ from typing import Any import aiohttp +from sqlalchemy.exc import SQLAlchemyError LOGGER = logging.getLogger(__name__) @@ -51,8 +52,20 @@ def _cause(answer: Answer) -> str: return answer if isinstance(answer, str) else f"HTTP {answer}" +async def database_down(version: Callable[[], int]) -> str | None: + """Why the database did not answer the store's cheapest read in time, or None when it did""" + try: + await asyncio.wait_for(asyncio.to_thread(version), FETCH_SECONDS) + except TimeoutError: + return "timed out" + except SQLAlchemyError as exc: + return str(exc).splitlines()[0] + return None + + async def problems( fetch: Fetch, + version: Callable[[], int], proxy_ready_url: str, gateway_ready_url: str, presence_age: float, @@ -73,6 +86,8 @@ async def problems( f"no ready Linkerd proxy in mumblermapi's pod ({_cause(answer)}): rmapi, murmur-agent and browser " "tickets are refused" ) + if cause := await database_down(version): + found.append(f"the database cannot be reached ({cause}): tickets, user events and admin changes fail") if uptime > presence_ttl and presence_age > presence_ttl: since = "since mumblermapi started" if math.isinf(presence_age) else f"for {presence_age:.0f} s" found.append(f"murmur-agent has not reported {since}: Murmur or the agent is away or refused") @@ -91,7 +106,13 @@ async def watch(app: Any, stop: asyncio.Event, presence_ttl: float) -> None: now = time.monotonic() received, _ = app.state.presence found = await problems( - fetch, settings.proxy_ready_url, settings.gateway_ready_url, now - received, now - started, presence_ttl + fetch, + app.state.store.version, + settings.proxy_ready_url, + settings.gateway_ready_url, + now - received, + now - started, + presence_ttl, ) if found != app.state.health: if found: diff --git a/src/mumblermapi/store.py b/src/mumblermapi/store.py deleted file mode 100644 index fc66a39..0000000 --- a/src/mumblermapi/store.py +++ /dev/null @@ -1,369 +0,0 @@ -"""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 - -import sqlite3 -import threading -from dataclasses import dataclass, field -from pathlib import Path - -from .channels import ACCESS, GUARD, MAX_DEPTH, ChannelSpec -from .tickets import WEB_SLOTS - -SCHEMA = """ -CREATE TABLE IF NOT EXISTS users ( - callsign TEXT PRIMARY KEY, - uuid TEXT NOT NULL, - admin INTEGER NOT NULL DEFAULT 0, - revoked INTEGER NOT NULL DEFAULT 0, - voice_disabled INTEGER NOT NULL DEFAULT 0 -); --- AUTOINCREMENT: a removed channel's id is never reused, so a stale admin page cannot hit a new channel -CREATE TABLE IF NOT EXISTS channels ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - parent INTEGER NOT NULL DEFAULT 0, -- 0 is Units/ itself - name TEXT NOT NULL, - description TEXT NOT NULL DEFAULT '', - access TEXT NOT NULL DEFAULT '', -- open, invite or inherit; '' only in stores older than the column - UNIQUE (parent, name) -); -CREATE TABLE IF NOT EXISTS members ( - channel INTEGER NOT NULL, - callsign TEXT NOT NULL, - PRIMARY KEY (channel, callsign) -); --- The last mission list read from TAK, with subscriber callsigns; kept while TAK cannot be reached -CREATE TABLE IF NOT EXISTS mission_members ( - mission TEXT NOT NULL, - 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); -""" - - -_SET_FLAG = { - "admin": "UPDATE users SET admin = ? WHERE callsign = ?", - "revoked": "UPDATE users SET revoked = ? WHERE callsign = ?", - "voice_disabled": "UPDATE users SET voice_disabled = ? WHERE callsign = ?", -} - - -class StoreError(ValueError): - """The change is not possible""" - - -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""" - - callsign: str - uuid: str - admin: bool - revoked: bool - voice_disabled: bool - - -@dataclass -class Channel: - """A Units/ channel; access says whether its members restrict it (see channels.ACCESS)""" - - id: int - name: str - description: str - access: str = "open" - members: list[str] = field(default_factory=list) - children: list[Channel] = field(default_factory=list) - - -class Store: - """SQLite-backed state. Every change bumps a version so murmur-agent can poll cheaply.""" - - def __init__(self, path: Path) -> None: - # Default isolation: "with self._db" then wraps each change in one transaction, so a multi-statement - # change (a subtree removal, a plan clear) lands whole or not at all. - self._db = sqlite3.connect(path, check_same_thread=False) - self._db.execute("PRAGMA foreign_keys = ON") - self._db.executescript(SCHEMA) - self._migrate() - self._lock = threading.Lock() - - def _migrate(self) -> None: - """Give stores from before explicit access the access they had implicitly: members restricted a net""" - with self._db: - columns = {row[1] for row in self._db.execute("PRAGMA table_info(channels)")} - if "access" not in columns: - self._db.execute("ALTER TABLE channels ADD COLUMN access TEXT NOT NULL DEFAULT ''") - self._db.execute( - "UPDATE channels SET access = CASE" - " WHEN EXISTS (SELECT 1 FROM members m WHERE m.channel = channels.id) THEN 'invite'" - " WHEN parent = 0 THEN 'open' ELSE 'inherit' END WHERE access = ''" - ) - - @staticmethod - def _access(access: str | None, parent: int) -> str: - """The default, and a top-level net cannot inherit from anything: that is open""" - if access is not None and access not in ACCESS: - raise StoreError(f"access must be one of {', '.join(ACCESS)}") - if parent == 0 and access in (None, "inherit"): - return "open" - return access or "inherit" - - # ---- version - def version(self) -> int: - """Changes whenever anything murmur-agent cares about changes""" - with self._lock: - row = self._db.execute("SELECT value FROM meta WHERE key = 'version'").fetchone() - return int(row[0]) - - 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""" - with self._lock, self._db: - self._db.execute( - "INSERT INTO users (callsign, uuid) VALUES (?, ?) ON CONFLICT (callsign) DO UPDATE SET uuid = ?", - (callsign, uuid, uuid), - ) - self._bump() - - def set_user_flag(self, callsign: str, flag: str, value: bool, uuid: str = "") -> None: - """Set admin, revoked or voice_disabled; creates the user if rmapi's created event was missed""" - if flag not in _SET_FLAG: - raise StoreError(f"unknown flag {flag}") - with self._lock, self._db: - self._db.execute("INSERT OR IGNORE INTO users (callsign, uuid) VALUES (?, ?)", (callsign, uuid)) - self._db.execute(_SET_FLAG[flag], (int(value), callsign)) - self._bump() - - def users(self) -> list[User]: - """Every known user""" - with self._lock: - rows = self._db.execute( - "SELECT callsign, uuid, admin, revoked, voice_disabled FROM users ORDER BY callsign" - ).fetchall() - return [User(r[0], r[1], bool(r[2]), bool(r[3]), bool(r[4])) for r in rows] - - def user(self, callsign: str) -> User | None: - """One user, if known""" - return next((u for u in self.users() if u.callsign == callsign), 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, 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 ChannelExists(f"channel {name!r} already exists there") from exc - self._bump() - return int(cur.lastrowid or 0) - - def remove_channel(self, channel_id: int) -> None: - """Remove a channel with everything under it""" - with self._lock, self._db: - if not self._db.execute("SELECT 1 FROM channels WHERE id = ?", (channel_id,)).fetchone(): - raise NoSuchChannel(f"no channel {channel_id}") - ids = [ - r[0] - for r in self._db.execute( - "WITH RECURSIVE sub(id) AS (SELECT ? UNION SELECT c.id FROM channels c JOIN sub ON c.parent = sub.id)" - " SELECT id FROM sub", - (channel_id,), - ) - ] - self._db.executemany("DELETE FROM members WHERE channel = ?", [(i,) for i in ids]) - self._db.executemany("DELETE FROM channels WHERE id = ?", [(i,) for i in ids]) - self._bump() - - def update_channel( - self, channel_id: int, name: str | None = None, description: str | None = None, access: str | None = None - ) -> None: - """Rename a channel, change its description, or change who may use it""" - with self._lock, self._db: - row = self._db.execute( - "SELECT name, description, access, parent FROM channels WHERE id = ?", (channel_id,) - ).fetchone() - if not row: - raise NoSuchChannel(f"no channel {channel_id}") - new_access = row[2] if access is None else self._access(access, row[3]) - try: - self._db.execute( - "UPDATE channels SET name = ?, description = ?, access = ? WHERE id = ?", - ( - row[0] if name is None else name, - row[1] if description is None else description, - new_access, - channel_id, - ), - ) - except sqlite3.IntegrityError as exc: - raise ChannelExists(f"channel {name!r} already exists there") from exc - self._bump() - - def clear(self) -> int: - """Remove every Units/ channel and membership; returns how many channels went""" - with self._lock, self._db: - removed = int(self._db.execute("SELECT COUNT(*) FROM channels").fetchone()[0]) - self._db.execute("DELETE FROM members") - self._db.execute("DELETE FROM channels") - self._bump() - return removed - - def set_member(self, channel_id: int, callsign: str, member: bool) -> None: - """Add or remove a member. Members are invited, so adding one makes the net invite-only.""" - with self._lock, self._db: - if not self._db.execute("SELECT 1 FROM channels WHERE id = ?", (channel_id,)).fetchone(): - raise NoSuchChannel(f"no channel {channel_id}") - if member: - self._db.execute( - "INSERT OR IGNORE INTO members (channel, callsign) VALUES (?, ?)", (channel_id, callsign) - ) - self._db.execute("UPDATE channels SET access = 'invite' WHERE id = ?", (channel_id,)) - else: - self._db.execute("DELETE FROM members WHERE channel = ? AND callsign = ?", (channel_id, callsign)) - self._bump() - - def tree(self) -> list[Channel]: - """The Units/ tree with members""" - with self._lock: - rows = self._db.execute( - "SELECT id, parent, name, description, access FROM channels ORDER BY name" - ).fetchall() - members = self._db.execute("SELECT channel, callsign FROM members ORDER BY callsign").fetchall() - nodes = {r[0]: Channel(r[0], r[2], r[3], r[4]) for r in rows} - for channel, callsign in members: - nodes[channel].members.append(callsign) - top: list[Channel] = [] - for r in rows: - (nodes[r[1]].children if r[1] in nodes else top).append(nodes[r[0]]) - return top - - def import_plan(self, plan: tuple[ChannelSpec, ...], parent: int = 0) -> int: - """Add a channel plan (the 2022 YAML schema) under a channel; returns how many channels were created. - Nets that exist are kept as they are; new ones get the plan's access and members.""" - created = 0 - for spec in plan: - try: - channel_id = self.add_channel(spec.name, spec.description, parent, spec.access or None) - created += 1 - if spec.members: - with self._lock, self._db: - self._db.executemany( - "INSERT OR IGNORE INTO members (channel, callsign) VALUES (?, ?)", - [(channel_id, callsign) for callsign in spec.members], - ) - self._bump() - except ChannelExists: - with self._lock: - row = self._db.execute( - "SELECT id FROM channels WHERE parent = ? AND name = ?", (parent, spec.name) - ).fetchone() - channel_id = int(row[0]) - created += self.import_plan(spec.children, channel_id) - return created - - # ---- missions - def missions(self) -> dict[str, frozenset[str]]: - """TAK missions and their subscribers, as last read""" - with self._lock: - rows = self._db.execute("SELECT mission, callsign FROM mission_members").fetchall() - result: dict[str, set[str]] = {} - for mission, callsign in rows: - result.setdefault(mission, set()).add(callsign) - return {mission: frozenset(members) for mission, members in result.items()} - - def set_missions(self, missions: dict[str, frozenset[str]]) -> bool: - """Replace the missions; True, and a new version, only when something changed. A TAK mission named - like Guard is left out: Guard stays open to everyone.""" - wanted = {mission: members for mission, members in missions.items() if members and mission != GUARD} - if wanted == self.missions(): - return False - with self._lock, self._db: - self._db.execute("DELETE FROM mission_members") - self._db.executemany( - "INSERT INTO mission_members (mission, callsign) VALUES (?, ?)", - [(mission, callsign) for mission, members in wanted.items() for callsign in members], - ) - self._bump() - return True - - 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/store/__init__.py b/src/mumblermapi/store/__init__.py new file mode 100644 index 0000000..9d8d3be --- /dev/null +++ b/src/mumblermapi/store/__init__.py @@ -0,0 +1,17 @@ +"""mumblermapi's state, in Postgres""" + +from .database import DatabaseSettings, engine +from .errors import ChannelExists, NoSuchChannel, StoreError, TooDeep +from .store import Channel, Store, User + +__all__ = [ + "Channel", + "ChannelExists", + "DatabaseSettings", + "NoSuchChannel", + "Store", + "StoreError", + "TooDeep", + "User", + "engine", +] diff --git a/src/mumblermapi/store/database.py b/src/mumblermapi/store/database.py new file mode 100644 index 0000000..a0c9efa --- /dev/null +++ b/src/mumblermapi/store/database.py @@ -0,0 +1,40 @@ +"""Where mumblermapi's Postgres is""" + +from __future__ import annotations + +from functools import cache + +from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict +from sqlalchemy import URL, Engine +from sqlmodel import create_engine + + +class DatabaseSettings(BaseSettings): + """The parts of the DSN, as the keys of CloudNativePG's app secret hold them; MUMBLERMAPI_DATABASE_* variables""" + + host: str = "mumble-postgres-rw" + port: int = 5432 + name: str = "mumble" + user: str = "mumble" + password: str = Field(default="", repr=False) + + model_config = SettingsConfigDict(env_prefix="MUMBLERMAPI_DATABASE_", frozen=True) + + @property + def url(self) -> URL: + """The DSN""" + return URL.create( + "postgresql+psycopg2", + username=self.user, + password=self.password, + host=self.host, + port=self.port, + database=self.name, + ) + + +@cache +def engine(url: URL) -> Engine: + """One engine, and so one connection pool, per database for the life of the process""" + return create_engine(url, pool_pre_ping=True) diff --git a/src/mumblermapi/store/errors.py b/src/mumblermapi/store/errors.py new file mode 100644 index 0000000..e8fd063 --- /dev/null +++ b/src/mumblermapi/store/errors.py @@ -0,0 +1,17 @@ +"""What the store refuses""" + + +class StoreError(ValueError): + """The change is not possible""" + + +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""" diff --git a/src/mumblermapi/store/store.py b/src/mumblermapi/store/store.py new file mode 100644 index 0000000..0326076 --- /dev/null +++ b/src/mumblermapi/store/store.py @@ -0,0 +1,279 @@ +"""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 + +from collections.abc import Generator +from contextlib import contextmanager +from dataclasses import dataclass, field +from typing import Literal + +from sqlalchemy import Engine, func +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.exc import IntegrityError +from sqlmodel import Session, SQLModel, col, delete, select, update + +from ..channels import GUARD, MAX_DEPTH, Access, ChannelSpec +from ..tickets import WEB_SLOTS +from .errors import ChannelExists, NoSuchChannel, TooDeep +from .tables import ChannelRow, MemberRow, MetaRow, MissionMemberRow, UserRow, WebSlotRow + + +@dataclass(frozen=True) +class User: + """A Deploy App user as rmapi reported it""" + + callsign: str + uuid: str + admin: bool + revoked: bool + voice_disabled: bool + + +@dataclass +class Channel: + """A Units/ channel; access says whether its members restrict it (see channels.ACCESS)""" + + id: int + name: str + description: str + access: str = "open" + members: list[str] = field(default_factory=list) + children: list[Channel] = field(default_factory=list) + + +def _access(access: Access | None, parent: int) -> Access: + """The default, and a top-level net cannot inherit from anything: that is open""" + if parent == 0 and access in (None, "inherit"): + return "open" + return access or "inherit" + + +def _depth(parents: dict[int, int], channel_id: int) -> int: + """How deep a channel is: 1 at the top of Units/""" + depth = 0 + while channel_id: + channel_id, depth = parents[channel_id], depth + 1 + return depth + + +def _subtree(parents: dict[int, int], channel_id: int) -> list[int]: + """A channel and every channel under it""" + found: list[int] = [] + todo = [channel_id] + while todo: + found.append(todo.pop()) + todo += [child for child, parent in parents.items() if parent == found[-1]] + return found + + +class Store: + """The state in Postgres. Every change bumps a version so murmur-agent can poll cheaply.""" + + def __init__(self, engine: Engine) -> None: + self._engine = engine + SQLModel.metadata.create_all(engine) + with Session(engine) as session, session.begin(): + session.exec(insert(MetaRow).values(key="version", value=1).on_conflict_do_nothing()) + + @contextmanager + def _change(self) -> Generator[Session]: + """A transaction that bumps the version. Changes lock the version's row first and so take turns: each + one checks what the ones before it left, not what they are halfway through.""" + with Session(self._engine) as session, session.begin(): + session.exec(select(MetaRow).where(MetaRow.key == "version").with_for_update()) + yield session + session.exec(update(MetaRow).where(col(MetaRow.key) == "version").values(value=col(MetaRow.value) + 1)) + + @staticmethod + def _parents(session: Session) -> dict[int, int]: + """Each channel's parent""" + return dict(session.exec(select(ChannelRow.id, ChannelRow.parent)).all()) + + def version(self) -> int: + """Changes whenever anything murmur-agent cares about changes""" + with Session(self._engine) as session: + return session.exec(select(MetaRow.value).where(MetaRow.key == "version")).one() + + def upsert_user(self, callsign: str, uuid: str) -> None: + """A user was created or updated in rmapi""" + with self._change() as session: + session.exec( + insert(UserRow) + .values(callsign=callsign, uuid=uuid) + .on_conflict_do_update(index_elements=["callsign"], set_={"uuid": uuid}) + ) + + def set_user_flag( + self, callsign: str, flag: Literal["admin", "revoked", "voice_disabled"], value: bool, uuid: str = "" + ) -> None: + """Set admin, revoked or voice_disabled; creates the user if rmapi's created event was missed""" + with self._change() as session: + session.exec( + insert(UserRow) + .values(callsign=callsign, uuid=uuid, **{flag: value}) + .on_conflict_do_update(index_elements=["callsign"], set_={flag: value}) + ) + + def users(self) -> list[User]: + """Every known user""" + with Session(self._engine) as session: + rows = session.exec(select(UserRow).order_by(col(UserRow.callsign))).all() + return [User(**row.model_dump()) for row in rows] + + def user(self, callsign: str) -> User | None: + """One user, if known""" + with Session(self._engine) as session: + row = session.get(UserRow, callsign) + return User(**row.model_dump()) if row else None + + def add_channel(self, name: str, description: str = "", parent: int = 0, access: Access | None = None) -> int: + """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 = _access(access, parent) + try: + with self._change() as session: + if parent: + parents = self._parents(session) + if parent not in parents: + raise NoSuchChannel(f"no channel {parent}") + # Murmur refuses a channel past its nesting limit, and the agent would leave the net out + if _depth(parents, parent) >= MAX_DEPTH: + raise TooDeep(f"nets nest at most {MAX_DEPTH} deep") + new = insert(ChannelRow).values(parent=parent, name=name, description=description, access=access) + return int(session.exec(new.returning(col(ChannelRow.id))).scalar_one()) + except IntegrityError as exc: + raise ChannelExists(f"channel {name!r} already exists there") from exc + + def remove_channel(self, channel_id: int) -> None: + """Remove a channel with everything under it""" + with self._change() as session: + parents = self._parents(session) + if channel_id not in parents: + raise NoSuchChannel(f"no channel {channel_id}") + gone = _subtree(parents, channel_id) + session.exec(delete(MemberRow).where(col(MemberRow.channel).in_(gone))) + session.exec(delete(ChannelRow).where(col(ChannelRow.id).in_(gone))) + + def update_channel( + self, channel_id: int, name: str | None = None, description: str | None = None, access: Access | None = None + ) -> None: + """Rename a channel, change its description, or change who may use it""" + try: + with self._change() as session: + row = session.get(ChannelRow, channel_id) + if row is None: + raise NoSuchChannel(f"no channel {channel_id}") + if name is not None: + row.name = name + if description is not None: + row.description = description + if access is not None: + row.access = _access(access, row.parent) + except IntegrityError as exc: + raise ChannelExists(f"channel {name!r} already exists there") from exc + + def clear(self) -> int: + """Remove every Units/ channel and membership; returns how many channels went""" + with self._change() as session: + session.exec(delete(MemberRow)) + return session.exec(delete(ChannelRow)).rowcount + + def set_member(self, channel_id: int, callsign: str, member: bool) -> None: + """Add or remove a member. Members are invited, so adding one makes the net invite-only.""" + with self._change() as session: + row = session.get(ChannelRow, channel_id) + if row is None: + raise NoSuchChannel(f"no channel {channel_id}") + if member: + session.exec(insert(MemberRow).values(channel=channel_id, callsign=callsign).on_conflict_do_nothing()) + row.access = "invite" + else: + session.exec( + delete(MemberRow).where(col(MemberRow.channel) == channel_id, col(MemberRow.callsign) == callsign) + ) + + def tree(self) -> list[Channel]: + """The Units/ tree with members""" + with Session(self._engine) as session: + rows = session.exec( + select(ChannelRow, MemberRow.callsign) + .outerjoin(MemberRow, col(MemberRow.channel) == col(ChannelRow.id)) + .order_by(col(ChannelRow.name), col(MemberRow.callsign)) + ).all() + nodes: dict[int, Channel] = {} + parents: dict[int, int] = {} + for row, member in rows: + node = nodes.setdefault(row.id, Channel(row.id, row.name, row.description, row.access)) + parents[row.id] = row.parent + if member: + node.members.append(member) + top: list[Channel] = [] + for channel_id, node in nodes.items(): + parent = parents[channel_id] + (nodes[parent].children if parent in nodes else top).append(node) + return top + + def import_plan(self, plan: tuple[ChannelSpec, ...], parent: int = 0) -> int: + """Add a channel plan (the 2022 YAML schema) under a channel; returns how many channels were created. + Nets that exist are kept as they are; new ones get the plan's access and members.""" + created = 0 + for spec in plan: + try: + channel_id = self.add_channel(spec.name, spec.description, parent, spec.access or None) + created += 1 + if spec.members: + with self._change() as session: + members = [{"channel": channel_id, "callsign": callsign} for callsign in spec.members] + session.exec(insert(MemberRow).values(members).on_conflict_do_nothing()) + except ChannelExists: + with Session(self._engine) as session: + existing = select(ChannelRow.id).where(ChannelRow.parent == parent, ChannelRow.name == spec.name) + channel_id = session.exec(existing).one() + created += self.import_plan(spec.children, channel_id) + return created + + def missions(self) -> dict[str, frozenset[str]]: + """TAK missions and their subscribers, as last read""" + result: dict[str, set[str]] = {} + with Session(self._engine) as session: + for row in session.exec(select(MissionMemberRow)): + result.setdefault(row.mission, set()).add(row.callsign) + return {mission: frozenset(members) for mission, members in result.items()} + + def set_missions(self, missions: dict[str, frozenset[str]]) -> bool: + """Replace the missions; True, and a new version, only when something changed. A TAK mission named + like Guard is left out: Guard stays open to everyone.""" + wanted = {mission: members for mission, members in missions.items() if members and mission != GUARD} + if wanted == self.missions(): + return False + with self._change() as session: + session.exec(delete(MissionMemberRow)) + session.add_all( + MissionMemberRow(mission=mission, callsign=callsign) + for mission, members in wanted.items() + for callsign in members + ) + return True + + 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 Session(self._engine) as session, session.begin(): + # One request per callsign at a time, so two new browsers cannot both take the same free slot + session.exec(select(func.pg_advisory_xact_lock(func.hashtext(callsign)))) + held = session.exec(select(WebSlotRow).where(WebSlotRow.callsign == callsign)).all() + row = next((r for r in held if r.browser == browser), None) + if row is None: + taken = {r.slot for r in held} + slot = next((s for s in WEB_SLOTS if s not in taken), None) + if slot is None: + # The browser whose last ticket is oldest loses its slot, even if it is still in voice + row = min(held, key=lambda r: (r.used_at, r.slot)) + row.browser = browser + else: + row = WebSlotRow(callsign=callsign, browser=browser, slot=slot, used_at=now) + session.add(row) + row.used_at = now + return row.slot diff --git a/src/mumblermapi/store/tables.py b/src/mumblermapi/store/tables.py new file mode 100644 index 0000000..73976fa --- /dev/null +++ b/src/mumblermapi/store/tables.py @@ -0,0 +1,71 @@ +"""The tables mumblermapi keeps in Postgres""" + +from __future__ import annotations + +from sqlalchemy import Column, Identity, Integer, UniqueConstraint +from sqlmodel import Field, SQLModel + + +class UserRow(SQLModel, table=True): + """A Deploy App user as rmapi reported it""" + + __tablename__ = "users" + + callsign: str = Field(primary_key=True) + uuid: str + admin: bool = False + revoked: bool = False + voice_disabled: bool = False + + +class ChannelRow(SQLModel, table=True): + """A Units/ net. Ids come from an identity column and are never reused, so a stale admin page cannot reach + a net made after the one it shows.""" + + __tablename__ = "channels" + __table_args__ = (UniqueConstraint("parent", "name"),) + + id: int = Field(sa_column=Column(Integer, Identity(), primary_key=True)) + parent: int = 0 # 0 is Units/ itself + name: str + description: str = "" + access: str # open, invite or inherit (channels.ACCESS) + + +class MemberRow(SQLModel, table=True): + """A callsign invited to a net""" + + __tablename__ = "members" + + channel: int = Field(primary_key=True) + callsign: str = Field(primary_key=True) + + +class MissionMemberRow(SQLModel, table=True): + """The last mission list read from TAK, with subscriber callsigns; kept while TAK cannot be reached""" + + __tablename__ = "mission_members" + + mission: str = Field(primary_key=True) + callsign: str = Field(primary_key=True) + + +class WebSlotRow(SQLModel, table=True): + """Which web slot each of a callsign's browsers logs in with, so two browsers never share one""" + + __tablename__ = "web_slots" + __table_args__ = (UniqueConstraint("callsign", "slot"),) + + callsign: str = Field(primary_key=True) # as in the Mumble username + browser: str = Field(primary_key=True) # the id the browser keeps for itself + slot: int + used_at: float # wall-clock seconds of the last ticket + + +class MetaRow(SQLModel, table=True): + """Counters: "version" changes whenever anything murmur-agent enforces does""" + + __tablename__ = "meta" + + key: str = Field(primary_key=True) + value: int diff --git a/src/mumblermapi/tak.py b/src/mumblermapi/tak.py index 7054e96..5f50b79 100644 --- a/src/mumblermapi/tak.py +++ b/src/mumblermapi/tak.py @@ -194,9 +194,11 @@ 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), store.missions()) - if store.set_missions(missions): - LOGGER.info("Mission nets: %s", ", ".join(sorted(store.missions())) or "none") + known = await asyncio.to_thread(store.missions) + missions = await read_missions(session, settings, tls_context(settings), known) + if await asyncio.to_thread(store.set_missions, missions): + nets = await asyncio.to_thread(store.missions) + LOGGER.info("Mission nets: %s", ", ".join(sorted(nets)) or "none") 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: diff --git a/tests/agent_helpers.py b/tests/agent_helpers.py new file mode 100644 index 0000000..7c37669 --- /dev/null +++ b/tests/agent_helpers.py @@ -0,0 +1,65 @@ +"""What the murmur-agent test files use: a Murmur with users in it, a policy for it and a fake authenticator""" + +from __future__ import annotations + +from typing import Any + +from mumblermapi.agent.authenticator import Refusal +from mumblermapi.agent.policy import Policy, Unit + +from .fake_murmur import FakeServer, InvalidSecretException + +POLICY = Policy( + version=2, + refused=frozenset({"BAD"}), + units=(Unit(1, "10", members=frozenset({"VOICE1"}), children=(Unit(2, "101"),)),), + missions=(Unit(0, "RECON", members=frozenset({"VOICE3"})),), +) + + +def murmur() -> FakeServer: + """A server with a stale unit net, a client's stand-in for the RECON mission net, and four users""" + server = FakeServer() + server.channel(1, 0, "Units") + server.channel(2, 1, "20") + server.channel(3, 0, "RECON", temporary=True) + server.connect(1, "VOICE1---a", 0, userid=1) + server.connect(2, "VOICE3---b", 3, userid=2) + server.connect(3, "BAD---c", 0, userid=3) + server.connect(4, "OTHER---d", 3, userid=4) + return server + + +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 wrong_secret(*args: object, **kwargs: object) -> Any: + """What every Murmur call raises once the Ice secret no longer matches""" + raise InvalidSecretException() + + +class FakeAuth: + """Refuses BAD for good and LATER for now""" + + def refusal(self, name: str, certificates: list[bytes]) -> Refusal | None: + if name.startswith("BAD"): + return Refusal("revoked") + if name.startswith("LATER"): + return Refusal("OCSP down", transient=True) + return None + + def authenticate(self, name: str, certificates: list[bytes], ticket: str = "") -> int: + if ticket == "signed": + return 8 + return 7 if certificates == [b"cert"] else -1 + + def id_to_name(self, user_id: int) -> str: + return "VOICE1---a" if user_id == 7 else "" + + def name_to_id(self, name: str) -> int: + return 7 if name == "VOICE1---a" else -2 diff --git a/tests/conftest.py b/tests/conftest.py index b3e9347..14913bd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,9 +1,11 @@ -"""A throwaway PKI shaped like the platform's: external root -> external CA -> client certificates""" +"""Shared fixtures: a throwaway PKI shaped like the platform's, a Postgres, the API as the cluster runs it, and +user ids""" from __future__ import annotations from dataclasses import dataclass from datetime import UTC, datetime, timedelta +from pathlib import Path import pytest from cryptography import x509 @@ -11,6 +13,14 @@ from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.serialization import Encoding from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from fastapi.testclient import TestClient +from pytest_docker.plugin import Services +from sqlmodel import SQLModel + +from mumblermapi.agent.userids import UserIds +from mumblermapi.app import create_app +from mumblermapi.config import Settings +from mumblermapi.store import DatabaseSettings, Store, engine # Today, so certificates the code checks against the real clock are valid when the tests run NOW = datetime.now(UTC).replace(microsecond=0) @@ -99,3 +109,76 @@ def pki_fixture() -> Pki: root = issue("Test External Root", ca=True) ca = issue("Test External CA", root, ca=True) return Pki(root=root, ca=ca, alpha=issue("ALPHA 1", ca)) + + +@pytest.fixture(scope="session", name="postgres") +def postgres_fixture(docker_ip: str, docker_services: Services) -> DatabaseSettings: + """The Postgres from docker-compose.yml, up and ready""" + port = docker_services.port_for("postgres", 5432) + return DatabaseSettings(host=docker_ip, port=port, password="mumbletestpwd") # pragma: allowlist secret + + +@pytest.fixture(name="database") +def database_fixture(postgres: DatabaseSettings) -> DatabaseSettings: + """The test Postgres with no tables, so each test starts from an empty store""" + SQLModel.metadata.drop_all(engine(postgres.url)) + return postgres + + +@pytest.fixture(name="store") +def store_fixture(database: DatabaseSettings) -> Store: + """A fresh store""" + return Store(engine(database.url)) + + +@pytest.fixture(name="ids") +def ids_fixture(tmp_path: Path) -> UserIds: + """User ids for the users of agent_helpers.murmur(), as the authenticator would have handed them out""" + ids = UserIds(tmp_path / "ids.json") + for name in ("VOICE1---a", "VOICE3---b", "BAD---c", "OTHER---d"): + ids.get_or_assign(name) + return ids + + +RMAPI = "rmapi.opendefence-system.serviceaccount.identity.linkerd.cluster.local" +AGENT = "murmur.app-mumble.serviceaccount.identity.linkerd.cluster.local" +TRAEFIK = "traefik.traefik-system.serviceaccount.identity.linkerd.cluster.local" +PLAN = "channels:\n - name: 10\n description: Alfa\n channels:\n - name: 101\n" + + +def as_(identity: str) -> dict[str, str]: + """How a caller arrives in the mesh: services by Linkerd identity, people through Traefik with their cert DN""" + if "." in identity: + return {"l5d-client-id": identity} + return {"l5d-client-id": TRAEFIK, "X-ClientCert-DN": f"CN={identity}"} + + +def user(callsign: str) -> dict[str, str]: + """A UserCRUDRequest body""" + return {"uuid": f"uuid-{callsign}", "callsign": callsign, "x509cert": ""} + + +@pytest.fixture(name="client") +def client_fixture(database: DatabaseSettings, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient: + """An app configured as in the cluster, with the company template applied by an admin""" + monkeypatch.setenv("MTLS_TRUST_L5D", "1") + monkeypatch.setenv("MTLS_REQUIRE_L5D", "1") + monkeypatch.setenv("MTLS_TRUSTED_INGRESS_IDENTITIES", TRAEFIK) + templates = tmp_path / "templates" + templates.mkdir() + (templates / "company.yaml").write_text(f"name: Komppania\ndescription: Vakiosuunnitelma\n{PLAN}") + (templates / "broken.yaml").write_text("nets: []\n") + (templates / "Company_2022.yaml").write_text(PLAN) # an id the apply endpoint would refuse + ui = tmp_path / "ui" + ui.mkdir() + (ui / "remoteEntry.js").write_text("export {}") + settings = Settings( + database=database, templates_dir=templates, ui_dir=ui, rmapi_identity=RMAPI, agent_identity=AGENT + ) + client = TestClient(create_app(settings)) + for callsign in ("VOICE1", "VOICE3"): + assert client.post("/api/v1/users/created", json=user(callsign), headers=as_(RMAPI)).json()["success"] + client.post("/api/v1/users/promoted", json=user("VOICE1"), headers=as_(RMAPI)) + applied = client.post("/api/v1/admin/templates/apply", json={"template": "company"}, headers=as_("VOICE1")) + assert applied.json() == {"created": 2} + return client diff --git a/tests/docker-compose.yml b/tests/docker-compose.yml new file mode 100644 index 0000000..6147dbb --- /dev/null +++ b/tests/docker-compose.yml @@ -0,0 +1,18 @@ +# The Postgres the tests run against (conftest.py), started by pytest-docker +services: + postgres: + image: postgres:18.3 + environment: + POSTGRES_USER: mumble + POSTGRES_DB: mumble + POSTGRES_PASSWORD: mumbletestpwd # pragma: allowlist secret + # As CloudNativePG creates databases; the locale sets the order names sort in + POSTGRES_INITDB_ARGS: --locale=C --encoding=UTF8 + ports: + - "5432" + healthcheck: + # Over TCP: while it initialises, the image runs a server on its socket only + test: pg_isready --host=127.0.0.1 --username=mumble --dbname=mumble + interval: 1s + timeout: 5s + retries: 30 diff --git a/tests/fake_murmur.py b/tests/fake_murmur.py index a432540..8671200 100644 --- a/tests/fake_murmur.py +++ b/tests/fake_murmur.py @@ -97,7 +97,6 @@ def __post_init__(self) -> None: 0, SimpleNamespace(id=0, parent=-1, name="Root", temporary=False, description="", links=[]) ) - # ---- setup helpers def channel(self, channel_id: int, parent: int, name: str, temporary: bool = False) -> None: """Add a channel as if a user or admin had made it""" self.channels[channel_id] = SimpleNamespace( @@ -123,7 +122,6 @@ def id_of(self, path: str) -> int: channel_id = next(c.id for c in self.channels.values() if c.parent == channel_id and c.name == name) return channel_id - # ---- the Ice operations the agent uses def getChannels(self) -> dict[int, SimpleNamespace]: return dict(self.channels) diff --git a/tests/murmur_acl.py b/tests/murmur_acl.py index b9e55fb..4ea3721 100644 --- a/tests/murmur_acl.py +++ b/tests/murmur_acl.py @@ -7,7 +7,7 @@ from collections.abc import Mapping -from mumblermapi.enforce import OPEN, Acl +from mumblermapi.agent.enforce import OPEN, Acl WRITE, ENTER, MOVE, LISTEN = 0x1, 0x4, 0x20, 0x800 DEFAULT = 0x2 | ENTER | 0x8 | 0x100 | 0x200 | LISTEN # Traverse, Enter, Speak, Whisper, TextMessage, Listen diff --git a/tests/test_admin_channels_api.py b/tests/test_admin_channels_api.py new file mode 100644 index 0000000..5293ed9 --- /dev/null +++ b/tests/test_admin_channels_api.py @@ -0,0 +1,147 @@ +"""Admins manage the nets: the Units/ tree, its members, plans in and out, and the mission nets""" + +from __future__ import annotations + +import yaml +from fastapi.testclient import TestClient + +from mumblermapi.api.admin_channels import MAX_PLAN_BYTES +from mumblermapi.channels import MAX_DEPTH + +from .conftest import RMAPI, as_, user + + +def test_admin_channel_management(client: TestClient) -> None: + """Admins manage channels and members; others may not""" + assert client.get("/api/v1/admin/channels", headers=as_("VOICE3")).status_code == 403 + tree = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() + squad = tree[0]["children"][0]["id"] + assert client.put(f"/api/v1/admin/channels/{squad}/members/VOICE3", headers=as_("VOICE1")).status_code == 200 + assert client.put(f"/api/v1/admin/channels/{squad}/members/GHOST", headers=as_("VOICE1")).status_code == 404 + assert client.put("/api/v1/admin/channels/999/members/VOICE3", headers=as_("VOICE1")).status_code == 404 + assert client.put(f"/api/v1/admin/channels/{squad}/members/A%00B", headers=as_("VOICE1")).status_code == 422 + tree = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() + assert tree[0]["children"][0]["members"] == ["VOICE3"] + assert client.delete(f"/api/v1/admin/channels/{squad}/members/VOICE3", headers=as_("VOICE1")).status_code == 200 + assert client.delete("/api/v1/admin/channels/999/members/VOICE3", headers=as_("VOICE1")).status_code == 404 + assert client.delete(f"/api/v1/admin/channels/{squad}/members/A%00B", headers=as_("VOICE1")).status_code == 422 + + new = client.post( + "/api/v1/admin/channels", json={"name": "07 TJ", "description": "Tulenjohto"}, headers=as_("VOICE1") + ) + assert new.status_code == 200 + assert client.post("/api/v1/admin/channels", json={"name": "07 TJ"}, headers=as_("VOICE1")).status_code == 400 + assert client.post("/api/v1/admin/channels", json={"name": "a/b"}, headers=as_("VOICE1")).status_code == 400 + too_long = {"name": "08", "description": "x" * 1001} + assert client.post("/api/v1/admin/channels", json=too_long, headers=as_("VOICE1")).status_code == 422 + with_nul = {"name": "08", "description": "a\x00b"} + assert client.post("/api/v1/admin/channels", json=with_nul, headers=as_("VOICE1")).status_code == 422 + cross_site_form = as_("VOICE1") | {"Content-Type": "text/plain"} + assert client.post("/api/v1/admin/channels", content='{"name": "X"}', headers=cross_site_form).status_code == 422 + assert client.delete(f"/api/v1/admin/channels/{new.json()['id']}", headers=as_("VOICE1")).status_code == 200 + assert client.delete("/api/v1/admin/channels/999", headers=as_("VOICE1")).status_code == 404 + + +def test_plan_export_and_import(client: TestClient) -> None: + """Channel plans go out and come in as the 2022 YAML schema""" + exported = client.get("/api/v1/admin/channels/export", headers=as_("VOICE1")).text + assert "name: '10'" in exported and "name: '101'" in exported + yaml_from = as_("VOICE1") | {"Content-Type": "application/yaml"} + added = client.post( + "/api/v1/admin/channels/import", content="channels:\n - name: 20\n - name: 10\n", headers=yaml_from + ) + assert added.json() == {"created": 1} + bad = client.post("/api/v1/admin/channels/import", content="nets: []", headers=yaml_from) + assert bad.status_code == 400 + with_nul = 'channels:\n - name: 30\n - name: 31\n description: "a\\0b"\n' + assert client.post("/api/v1/admin/channels/import", content=with_nul, headers=yaml_from).status_code == 400 + assert [c["name"] for c in client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()] == ["10", "20"] + merged = client.post( + "/api/v1/admin/channels/import", content="a: &a {name: 40}\nchannels: [{<<: *a}]", headers=yaml_from + ) + assert merged.status_code == 400 and "merge keys" in merged.json()["detail"] + cross_site_form = as_("VOICE1") | {"Content-Type": "text/plain"} + forged = client.post("/api/v1/admin/channels/import", content="channels:\n - name: 30\n", headers=cross_site_form) + assert forged.status_code == 415 + huge = client.post("/api/v1/admin/channels/import", content=b"#" * (MAX_PLAN_BYTES + 1), headers=yaml_from) + 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_missions(client: TestClient) -> None: + """Admins see mission nets with subscribers; subscribers see theirs among their nets""" + store = client.app.state.store # type: ignore[attr-defined] + store.set_missions({"RECON": frozenset({"VOICE3"}), "Guard": frozenset({"VOICE1"})}) + assert client.get("/api/v1/admin/missions", headers=as_("VOICE3")).status_code == 403 + assert client.get("/api/v1/admin/missions", headers=as_("VOICE1")).json() == [ + {"name": "Guard", "members": [], "open": True}, + {"name": "RECON", "members": ["VOICE3"], "open": False}, + ] + data = client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"] + assert data["nets"] == ["/Missions/RECON"] + + +def test_edit_channel(client: TestClient) -> None: + """Admins rename nets and change descriptions; clashes, bad names and unknown nets are refused""" + tree = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() + platoon = tree[0]["id"] + url = f"/api/v1/admin/channels/{platoon}" + assert client.patch(url, json={"description": "Alfa-joukkue"}, headers=as_("VOICE3")).status_code == 403 + assert client.patch(url, json={"description": "Alfa-joukkue"}, headers=as_("VOICE1")).status_code == 200 + assert client.patch(url, json={"name": "11"}, headers=as_("VOICE1")).status_code == 200 + renamed = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()[0] + assert (renamed["name"], renamed["description"]) == ("11", "Alfa-joukkue") + client.post("/api/v1/admin/channels", json={"name": "20"}, headers=as_("VOICE1")) + assert client.patch(url, json={"name": "20"}, headers=as_("VOICE1")).status_code == 400 + assert client.patch(url, json={"name": "a/b"}, headers=as_("VOICE1")).status_code == 400 + assert client.patch(url, json={"description": "a\x00b"}, headers=as_("VOICE1")).status_code == 422 + assert client.patch("/api/v1/admin/channels/999", json={"name": "x"}, headers=as_("VOICE1")).status_code == 404 + + +def test_channel_access(client: TestClient) -> None: + """Admins make nets open or invite-only; the plan export keeps it""" + created = client.post( + "/api/v1/admin/channels", json={"name": "07 TJ", "access": "invite"}, headers=as_("VOICE1") + ).json() + url = f"/api/v1/admin/channels/{created['id']}" + tree = {c["name"]: c for c in client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()} + assert (tree["10"]["access"], tree["07 TJ"]["access"]) == ("open", "invite") + assert tree["10"]["children"][0]["access"] == "inherit" + assert client.patch(url, json={"access": "secret"}, headers=as_("VOICE1")).status_code == 422 + assert client.patch(url, json={"access": "open"}, headers=as_("VOICE1")).status_code == 200 + assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()[0]["access"] == "open" + exported = client.get("/api/v1/admin/channels/export", headers=as_("VOICE1")).text + assert "access: open" in exported and "access: inherit" in exported + # The export restores the plan as it was, members included + client.put(url + "/members/VOICE3", headers=as_("VOICE1")) + exported = client.get("/api/v1/admin/channels/export", headers=as_("VOICE1")).text + assert client.delete("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 200 + yaml_from = as_("VOICE1") | {"Content-Type": "application/yaml"} + client.post("/api/v1/admin/channels/import", content=exported, headers=yaml_from) + restored = {c["name"]: c for c in client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()} + assert (restored["07 TJ"]["access"], restored["07 TJ"]["members"]) == ("invite", ["VOICE3"]) + + +def test_clear_plan(client: TestClient) -> None: + """Admins remove the whole plan at once""" + assert client.delete("/api/v1/admin/channels", headers=as_("VOICE3")).status_code == 403 + assert client.delete("/api/v1/admin/channels", headers=as_("VOICE1")).json() == {"removed": 2} + assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() == [] diff --git a/tests/test_admin_templates_api.py b/tests/test_admin_templates_api.py new file mode 100644 index 0000000..3b1ebdd --- /dev/null +++ b/tests/test_admin_templates_api.py @@ -0,0 +1,41 @@ +"""The channel plan templates admins apply""" + +from __future__ import annotations + +from pathlib import Path + +from fastapi.testclient import TestClient + +from mumblermapi.api.admin_templates import templates +from mumblermapi.config import Settings + +from .conftest import as_ + + +def test_templates(client: TestClient) -> None: + """Admins list templates (broken files and unusable names skipped) and apply one; applying again adds + nothing""" + assert client.get("/api/v1/admin/templates", headers=as_("VOICE3")).status_code == 403 + assert client.get("/api/v1/admin/templates", headers=as_("VOICE1")).json() == [ + {"id": "company", "name": "Komppania", "description": "Vakiosuunnitelma", "nets": 2} + ] + apply = "/api/v1/admin/templates/apply" + assert client.post(apply, json={"template": "company"}, headers=as_("VOICE1")).json() == {"created": 0} + assert client.post(apply, json={"template": "nope"}, headers=as_("VOICE1")).status_code == 404 + assert client.post(apply, json={"template": "../etc"}, headers=as_("VOICE1")).status_code == 422 + cross_site_form = as_("VOICE1") | {"Content-Type": "text/plain"} + assert client.post(apply, content='{"template": "company"}', headers=cross_site_form).status_code == 422 + + +def test_templates_dir_missing(tmp_path: Path) -> None: + """Without a templates directory there is simply nothing to offer""" + settings = Settings(templates_dir=tmp_path / "none") + assert templates(settings) == {} + + +def test_shipped_templates_are_offered() -> None: + """Each template the image ships loads: templates() skips a file it cannot read with only a warning""" + shipped = Path(__file__).parents[1] / "templates" + offered = templates(Settings(templates_dir=shipped)) + assert "komppania" in offered + assert sorted(offered) == sorted(path.stem for path in shipped.glob("*.yaml")) diff --git a/tests/test_admin_users_api.py b/tests/test_admin_users_api.py new file mode 100644 index 0000000..3457e5e --- /dev/null +++ b/tests/test_admin_users_api.py @@ -0,0 +1,27 @@ +"""What admins see and set per person""" + +from __future__ import annotations + +from fastapi.testclient import TestClient + +from .conftest import AGENT, as_ + + +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() + assert [u["callsign"] for u in users] == ["VOICE1", "VOICE3"] + assert all(u["uuid"] is None for u in users) + assert ( + client.put("/api/v1/admin/users/VOICE3/voice", json={"enabled": False}, headers=as_("VOICE1")).status_code + == 200 + ) + assert ( + client.put("/api/v1/admin/users/GHOST/voice", json={"enabled": False}, headers=as_("VOICE1")).status_code == 404 + ) + assert ( + client.put("/api/v1/admin/users/A%00B/voice", json={"enabled": False}, headers=as_("VOICE1")).status_code == 422 + ) + assert client.get("/api/v1/agent/state", headers=as_(AGENT)).json()["refused"] == ["VOICE3"] + client.put("/api/v1/admin/users/VOICE3/voice", json={"enabled": True}, headers=as_("VOICE1")) + assert client.get("/api/v1/agent/state", headers=as_(AGENT)).json()["refused"] == [] diff --git a/tests/test_agent.py b/tests/test_agent.py deleted file mode 100644 index 693611c..0000000 --- a/tests/test_agent.py +++ /dev/null @@ -1,540 +0,0 @@ -"""murmur-agent's Ice glue, against an in-memory Murmur""" - -from __future__ import annotations - -import logging -from pathlib import Path -from types import SimpleNamespace -from typing import Any - -import pytest - -from mumblermapi import agent -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 -from mumblermapi.presence import PresenceReporter -from mumblermapi.userids import UserIds - -from .fake_murmur import ( - ICE, - MUMBLE, - FakeServer, - InvalidSecretException, - MemoryLimitException, - NestingLimitException, -) - -POLICY = Policy( - version=2, - refused=frozenset({"BAD"}), - units=(Unit(1, "10", members=frozenset({"VOICE1"}), children=(Unit(2, "101"),)),), - missions=(Unit(0, "RECON", members=frozenset({"VOICE3"})),), -) - - -@pytest.fixture(name="ids") -def ids_fixture(tmp_path: Path) -> UserIds: - """User ids as the authenticator would have handed them out""" - ids = UserIds(tmp_path / "ids.json") - for name in ("VOICE1---a", "VOICE3---b", "BAD---c", "OTHER---d"): - ids.get_or_assign(name) - return ids - - -def murmur() -> FakeServer: - """A server with a stale unit net, a client's stand-in for the RECON mission net, and four users""" - server = FakeServer() - server.channel(1, 0, "Units") - server.channel(2, 1, "20") - server.channel(3, 0, "RECON", temporary=True) - server.connect(1, "VOICE1---a", 0, userid=1) - server.connect(2, "VOICE3---b", 3, userid=2) - server.connect(3, "BAD---c", 0, userid=3) - server.connect(4, "OTHER---d", 3, userid=4) - return server - - -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(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") - assert server.id_of("/Units/10/101") and server.id_of("/Teams/Red") and server.id_of("/Roles/Medic") - assert "remove 2" in server.log - assert acl_of(*server.getACL(platoon)) == members_only([1]) - assert acl_of(*server.getACL(mission)) == members_only([2]) - # Guard is a mission net open to everyone: no rules of its own, and nobody is moved out of it - guard = server.id_of("/Missions/Guard") - assert acl_of(*server.getACL(guard)) == OPEN - # The subscriber goes from the stand-in to the real net, the outsider to the root - assert server.users[2].channel == mission and server.users[4].channel == 0 - - server.users[4].channel = platoon # entered before the net was restricted - server.listeners[platoon] = [4, 1] - server.log.clear() - agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) - assert server.log == ["move 4 0", f"unlisten 4 {platoon}"] - - server.log.clear() - agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) - assert server.log == [] - - -def test_entered_before_the_rules(ids: UserIds) -> None: - """Someone who enters a net between its creation and its ACL is moved out in the same pass""" - server = murmur() - server.users[4].channel = 0 - create = server.addChannel - - def add_and_enter(name: str, parent: int) -> int: - channel_id = create(name, parent) - if name == "10": - server.users[4].channel = channel_id - return channel_id - - server.addChannel = add_and_enter # type: ignore[method-assign] - agent._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) - assert server.users[4].channel == 0 - - -def test_temporary_twin_of_a_net(ids: UserIds) -> None: - """A temporary channel made in a net's place before the net exists is replaced by the real, restricted net""" - server = murmur() - server.channel(5, 1, "10", temporary=True) - server.users[4].channel = 5 - 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 - assert acl_of(*server.getACL(platoon)) == members_only([1]) - assert server.users[4].channel == 1 - - -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(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(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(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(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(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(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(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 == {} - - -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(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]) - 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(ICE, 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(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(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) - - -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(ICE, MUMBLE, server, POLICY, ids, units=True) - assert agent._presence(MUMBLE, server) == [ - {"callsign": "OTHER", "channel": "/"}, - {"callsign": "VOICE1", "channel": "/"}, - {"callsign": "VOICE3", "channel": "/Missions/RECON"}, - ] - - -class FakeAuth: - """Refuses BAD for good and LATER for now""" - - def refusal(self, name: str, certificates: list[bytes]) -> Refusal | None: - if name.startswith("BAD"): - return Refusal("revoked") - if name.startswith("LATER"): - return Refusal("OCSP down", transient=True) - return None - - def authenticate(self, name: str, certificates: list[bytes], ticket: str = "") -> int: - if ticket == "signed": - return 8 - return 7 if certificates == [b"cert"] else -1 - - def id_to_name(self, user_id: int) -> str: - return "VOICE1---a" if user_id == 7 else "" - - def name_to_id(self, name: str) -> int: - return 7 if name == "VOICE1---a" else -2 - - -def test_sweep() -> None: - """Only lasting refusals disconnect; sessions that left meanwhile are skipped""" - server = FakeServer() - server.connect(1, "BAD---x") - server.connect(2, "LATER---y") - server.connect(3, "GOOD---z") - vanishing = server.getCertificateList - - def certificates(session: int) -> list[bytes]: - if session == 3: - del server.users[3] - return vanishing(session) - - server.getCertificateList = certificates # type: ignore[method-assign] - agent._sweep(MUMBLE, server, FakeAuth()) # type: ignore[arg-type] - 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_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_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() - 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] - assert servant.authenticate("VOICE1---a", "", [b"cert"], "hash", True) == (7, "", []) - assert servant.authenticate("VOICE1---web-1", "signed", [b"gateway"], "hash", False) == (8, "", []) - assert servant.getInfo(7) == (True, {MUMBLE.UserInfo.UserName: "VOICE1---a"}) - assert servant.getInfo(8) == (False, {}) - assert servant.nameToId("VOICE1---a") == 7 and servant.idToName(7) == "VOICE1---a" - 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_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_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() - channel_id = agent.IceChannels(server, MUMBLE).add_channel("10", 0, "Alfa") - assert server.channels[channel_id].description == "Alfa" - - -def test_server_lookup() -> None: - """A configured server id, or the one running server""" - one = SimpleNamespace(name="one") - meta: Any = SimpleNamespace(getServer=lambda i: one if i == 1 else None, getBootedServers=lambda: [one]) - assert agent._server(meta, 1) is one and agent._server(meta, None) is one - with pytest.raises(RuntimeError): - agent._server(meta, 2) - meta.getBootedServers = list - with pytest.raises(RuntimeError): - 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_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""" - - 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() - real_kick = server.kickUser - - def gone_first(session: int, reason: str) -> None: - del server.users[session] - real_kick(session, reason) - - server.kickUser = gone_first # type: ignore[method-assign] - 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") diff --git a/tests/test_agent_config.py b/tests/test_agent_config.py new file mode 100644 index 0000000..f97648b --- /dev/null +++ b/tests/test_agent_config.py @@ -0,0 +1,71 @@ +"""Agent settings""" + +from pathlib import Path + +import pytest + +from mumblermapi.agent.config import AgentConfig + +FAKE_SECRET = "not-a-real-ice-secret" # nosec B105 # pragma: allowlist secret + + +def config(monkeypatch: pytest.MonkeyPatch, **env: str) -> AgentConfig: + """The settings with these variables set""" + for name, value in env.items(): + monkeypatch.setenv(name, value) + return AgentConfig() + + +def test_defaults(monkeypatch: pytest.MonkeyPatch) -> None: + """Only the secret is required, and an empty variable leaves an optional setting unset""" + empty = ("MURMUR_SERVER_ID", "AGENT_OCSP_URL", "AGENT_STATE_URL", "AGENT_PRESENCE_URL", "AGENT_GATEWAY_CA") + settings = config(monkeypatch, MURMUR_ICE_SECRET=FAKE_SECRET, **dict.fromkeys(empty, "")) + assert settings == AgentConfig.model_construct(ice_secret=FAKE_SECRET) + assert settings.ocsp_url is None + + +def test_overrides(monkeypatch: pytest.MonkeyPatch) -> None: + """Every setting can come from the environment""" + settings = config( + monkeypatch, + MURMUR_ICE_SECRET=FAKE_SECRET, + MURMUR_ICE_HOST="10.0.0.1", + MURMUR_ICE_PORT="7000", + AGENT_CALLBACK_PORT="7001", + MURMUR_SERVER_ID="2", + AGENT_CA_BUNDLE="/ca.pem", + AGENT_CHANNELS_FILE="/c.yaml", + AGENT_DATA_DIR="/d", + AGENT_OCSP_URL="http://ocsp", + AGENT_OCSP_CACHE_SECONDS="10", + AGENT_SWEEP_SECONDS="5", + AGENT_STATE_URL="http://mumblermapi/api/v1/agent/state", + AGENT_POLL_SECONDS="2", + AGENT_PRESENCE_URL="http://mumblermapi/api/v1/agent/presence", + AGENT_GATEWAY_CA="/gateway/ca.crt", + ) + assert settings == AgentConfig.model_construct( + ice_secret=FAKE_SECRET, + ice_host="10.0.0.1", + ice_port=7000, + callback_port=7001, + server_id=2, + ca_bundle=Path("/ca.pem"), + channels_file=Path("/c.yaml"), + data_dir=Path("/d"), + ocsp_url="http://ocsp", + ocsp_cache_seconds=10.0, + sweep_seconds=5.0, + state_url="http://mumblermapi/api/v1/agent/state", + poll_seconds=2.0, + presence_url="http://mumblermapi/api/v1/agent/presence", + gateway_ca=Path("/gateway/ca.crt"), + ) + + +@pytest.mark.parametrize("env", [{}, {"MURMUR_ICE_SECRET": ""}]) +def test_secret_required(monkeypatch: pytest.MonkeyPatch, env: dict[str, str]) -> None: + """No secret, no agent""" + monkeypatch.delenv("MURMUR_ICE_SECRET", raising=False) + with pytest.raises(ValueError, match="never run without a secret"): + config(monkeypatch, **env) diff --git a/tests/test_agent_enforce.py b/tests/test_agent_enforce.py new file mode 100644 index 0000000..54e4340 --- /dev/null +++ b/tests/test_agent_enforce.py @@ -0,0 +1,272 @@ +"""murmur-agent's enforcement pass and presence, against an in-memory Murmur""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +import pytest + +from mumblermapi.agent import rounds +from mumblermapi.agent.enforce import OPEN, acl_of, members_only +from mumblermapi.agent.policy import Policy, Unit +from mumblermapi.agent.userids import UserIds +from mumblermapi.channels import MAX_DEPTH + +from .agent_helpers import POLICY, chain, murmur, wrong_secret +from .fake_murmur import ICE, MUMBLE, InvalidSecretException, MemoryLimitException, NestingLimitException + + +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() + rounds._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") + assert server.id_of("/Units/10/101") and server.id_of("/Teams/Red") and server.id_of("/Roles/Medic") + assert "remove 2" in server.log + assert acl_of(*server.getACL(platoon)) == members_only([1]) + assert acl_of(*server.getACL(mission)) == members_only([2]) + # Guard is a mission net open to everyone: no rules of its own, and nobody is moved out of it + guard = server.id_of("/Missions/Guard") + assert acl_of(*server.getACL(guard)) == OPEN + # The subscriber goes from the stand-in to the real net, the outsider to the root + assert server.users[2].channel == mission and server.users[4].channel == 0 + + server.users[4].channel = platoon # entered before the net was restricted + server.listeners[platoon] = [4, 1] + server.log.clear() + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.log == ["move 4 0", f"unlisten 4 {platoon}"] + + server.log.clear() + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.log == [] + + +def test_entered_before_the_rules(ids: UserIds) -> None: + """Someone who enters a net between its creation and its ACL is moved out in the same pass""" + server = murmur() + server.users[4].channel = 0 + create = server.addChannel + + def add_and_enter(name: str, parent: int) -> int: + channel_id = create(name, parent) + if name == "10": + server.users[4].channel = channel_id + return channel_id + + server.addChannel = add_and_enter # type: ignore[method-assign] + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.users[4].channel == 0 + + +def test_temporary_twin_of_a_net(ids: UserIds) -> None: + """A temporary channel made in a net's place before the net exists is replaced by the real, restricted net""" + server = murmur() + server.channel(5, 1, "10", temporary=True) + server.users[4].channel = 5 + rounds._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 + assert acl_of(*server.getACL(platoon)) == members_only([1]) + assert server.users[4].channel == 1 + + +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() + rounds._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] + rounds._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() + rounds._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) + rounds._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() + rounds._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() + rounds._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() + rounds._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 == {} + + +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 rounds._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]) + 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 rounds._enforce(ICE, MUMBLE, server, policy, ids, units=True) == [refused] + assert server.log == [] + + +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): + rounds._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() + policy = Policy(version=2, units=(chain(MAX_DEPTH, "x"),)) + assert rounds._enforce(ICE, MUMBLE, server, policy, ids, units=True) == [] + temporary = server.addChannel("huddle", server.id_of("/Units" + "/x" * MAX_DEPTH)) + with pytest.raises(NestingLimitException): + server.addChannel("deeper", temporary) + + +def test_presence(ids: UserIds) -> None: + """Who is where, by path""" + server = murmur() + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert rounds._presence(MUMBLE, server) == [ + {"callsign": "OTHER", "channel": "/"}, + {"callsign": "VOICE1", "channel": "/"}, + {"callsign": "VOICE3", "channel": "/Missions/RECON"}, + ] + + +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() + rounds._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] + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + 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() + rounds._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() + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert "acl 99" in server.log and server.users[4].channel == 0 + + server.log.clear() + rounds._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""" + + def oversized(channel_id: int) -> list[int]: + raise MemoryLimitException() + + server = murmur() + server.getListeningUsers = oversized # type: ignore[method-assign] + with pytest.raises(MemoryLimitException): + rounds._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() + rounds._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() + rounds._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() + real_kick = server.kickUser + + def gone_first(session: int, reason: str) -> None: + del server.users[session] + real_kick(session, reason) + + server.kickUser = gone_first # type: ignore[method-assign] + rounds._enforce(ICE, MUMBLE, server, POLICY, ids, units=True) + assert server.id_of("/Missions/RECON") and server.users[2].channel == server.id_of("/Missions/RECON") diff --git a/tests/test_agent_ice.py b/tests/test_agent_ice.py new file mode 100644 index 0000000..b06487a --- /dev/null +++ b/tests/test_agent_ice.py @@ -0,0 +1,91 @@ +"""murmur-agent's Ice glue, against an in-memory Murmur""" + +from __future__ import annotations + +import logging +from types import SimpleNamespace +from typing import Any + +import pytest + +from mumblermapi.agent import ice +from mumblermapi.agent.authenticator import TRY_LATER, UNKNOWN + +from .agent_helpers import FakeAuth +from .fake_murmur import MUMBLE, FakeServer + + +def test_servant() -> None: + """Murmur's ServerAuthenticator calls reach the authenticator""" + servant = ice.servant(MUMBLE, FakeAuth()) # type: ignore[arg-type] + assert servant.authenticate("VOICE1---a", "", [b"cert"], "hash", True) == (7, "", []) + assert servant.authenticate("VOICE1---web-1", "signed", [b"gateway"], "hash", False) == (8, "", []) + assert servant.getInfo(7) == (True, {MUMBLE.UserInfo.UserName: "VOICE1---a"}) + assert servant.getInfo(8) == (False, {}) + assert servant.nameToId("VOICE1---a") == 7 and servant.idToName(7) == "VOICE1---a" + 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 = ice.servant(MUMBLE, BrokenAuth(error)) # type: ignore[arg-type] + with caplog.at_level(logging.ERROR, logger=ice.__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_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] = {} + runtime: Any = SimpleNamespace(createProperties=lambda: SimpleNamespace(setProperty=properties.__setitem__)) + ice.properties(runtime) + assert int(properties[f"{ice.ADAPTER}.MessageSizeMax"]) * 1024 >= 3 * 0x7FFFFF + 512 * 1024 + assert properties["Ice.MessageSizeMax"] == str(ice.ICE_MESSAGE_KIB) + 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 = ice.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() + channel_id = ice.IceChannels(server, MUMBLE).add_channel("10", 0, "Alfa") + assert server.channels[channel_id].description == "Alfa" + + +def test_server_lookup() -> None: + """A configured server id, or the one running server""" + one = SimpleNamespace(name="one") + meta: Any = SimpleNamespace(getServer=lambda i: one if i == 1 else None, getBootedServers=lambda: [one]) + assert ice.virtual_server(meta, 1) is one and ice.virtual_server(meta, None) is one + with pytest.raises(RuntimeError): + ice.virtual_server(meta, 2) + meta.getBootedServers = list + with pytest.raises(RuntimeError): + ice.virtual_server(meta, None) diff --git a/tests/test_agent_rounds.py b/tests/test_agent_rounds.py new file mode 100644 index 0000000..52a2b22 --- /dev/null +++ b/tests/test_agent_rounds.py @@ -0,0 +1,135 @@ +"""murmur-agent's rounds: the certificate sweep, the plan and presence, and what a failure in one holds up""" + +from __future__ import annotations + +import logging +from typing import Any + +import pytest + +from mumblermapi.agent import rounds +from mumblermapi.agent.policy import Policy +from mumblermapi.agent.presence import PresenceReporter +from mumblermapi.agent.userids import UserIds + +from .agent_helpers import POLICY, FakeAuth, chain, murmur, wrong_secret +from .fake_murmur import ICE, MUMBLE, FakeServer, MemoryLimitException + + +def test_sweep() -> None: + """Only lasting refusals disconnect; sessions that left meanwhile are skipped""" + server = FakeServer() + server.connect(1, "BAD---x") + server.connect(2, "LATER---y") + server.connect(3, "GOOD---z") + vanishing = server.getCertificateList + + def certificates(session: int) -> list[bytes]: + if session == 3: + del server.users[3] + return vanishing(session) + + server.getCertificateList = certificates # type: ignore[method-assign] + rounds._sweep(MUMBLE, server, FakeAuth()) # type: ignore[arg-type] + assert server.log == ["kick 1"] + + +def make_rounds(ids: UserIds, reports: list[object] | None = None) -> rounds.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 rounds.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 = make_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 = make_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_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=rounds.__name__): + make_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_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(rounds, "_sweep", broken) + reports: list[object] = [] + loop = make_rounds(ids, reports) + with caplog.at_level(logging.ERROR, logger=rounds.__name__): + loop.round(murmur(), POLICY, units=True) + monkeypatch.setattr(rounds, "_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() + policy = Policy(version=2, units=(chain(server.nesting_limit + 1, "00"),)) + loop = make_rounds(ids) + with caplog.at_level(logging.WARNING, logger=rounds.__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_refused_nets_are_warned_about_when_they_change(caplog: pytest.LogCaptureFixture) -> None: + """Not every round""" + with caplog.at_level(logging.WARNING, logger=rounds.__name__): + before = rounds._warn_left_out(["/Units/a"], []) + before = rounds._warn_left_out(["/Units/a"], before) + before = rounds._warn_left_out(["/Units/a", "/Units/b"], before) + rounds._warn_left_out([], before) + assert [r.getMessage().rsplit(": ", 1)[1] for r in caplog.records] == ["/Units/a", "/Units/a, /Units/b"] diff --git a/tests/test_api.py b/tests/test_api.py deleted file mode 100644 index 2896fdc..0000000 --- a/tests/test_api.py +++ /dev/null @@ -1,372 +0,0 @@ -"""The mumblermapi integration API""" - -from __future__ import annotations - -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" -AGENT = "murmur.app-mumble.serviceaccount.identity.linkerd.cluster.local" -TRAEFIK = "traefik.traefik-system.serviceaccount.identity.linkerd.cluster.local" -PLAN = "channels:\n - name: 10\n description: Alfa\n channels:\n - name: 101\n" - - -def as_(identity: str) -> dict[str, str]: - """How a caller arrives in the mesh: services by Linkerd identity, people through Traefik with their cert DN""" - if "." in identity: - return {"l5d-client-id": identity} - return {"l5d-client-id": TRAEFIK, "X-ClientCert-DN": f"CN={identity}"} - - -def user(callsign: str) -> dict[str, str]: - """A UserCRUDRequest body""" - return {"uuid": f"uuid-{callsign}", "callsign": callsign, "x509cert": ""} - - -@pytest.fixture(name="client") -def client_fixture(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient: - """An app configured as in the cluster, with the company template applied by an admin""" - monkeypatch.setenv("MTLS_TRUST_L5D", "1") - monkeypatch.setenv("MTLS_REQUIRE_L5D", "1") - monkeypatch.setenv("MTLS_TRUSTED_INGRESS_IDENTITIES", TRAEFIK) - templates = tmp_path / "templates" - templates.mkdir() - (templates / "company.yaml").write_text(f"name: Komppania\ndescription: Vakiosuunnitelma\n{PLAN}") - (templates / "broken.yaml").write_text("nets: []\n") - (templates / "Company_2022.yaml").write_text(PLAN) # an id the apply endpoint would refuse - ui = tmp_path / "ui" - ui.mkdir() - (ui / "remoteEntry.js").write_text("export {}") - settings = Settings( - database=tmp_path / "db.sqlite", templates_dir=templates, ui_dir=ui, rmapi_identity=RMAPI, agent_identity=AGENT - ) - client = TestClient(create_app(settings)) - for callsign in ("VOICE1", "VOICE3"): - assert client.post("/api/v1/users/created", json=user(callsign), headers=as_(RMAPI)).json()["success"] - client.post("/api/v1/users/promoted", json=user("VOICE1"), headers=as_(RMAPI)) - applied = client.post("/api/v1/admin/templates/apply", json={"template": "company"}, headers=as_("VOICE1")) - assert applied.json() == {"created": 2} - return client - - -def test_user_events_only_from_rmapi(client: TestClient) -> None: - """Anyone but rmapi is refused, and an unauthenticated caller too""" - assert client.post("/api/v1/users/promoted", json=user("VOICE3"), headers=as_("VOICE3")).status_code == 403 - assert client.post("/api/v1/users/created", json=user("X")).status_code == 403 - - -def test_agent_state_and_versions(client: TestClient) -> None: - """The agent gets the applied tree, then 304 until something changes""" - assert client.get("/api/v1/agent/state", headers=as_("VOICE1")).status_code == 403 - first = client.get("/api/v1/agent/state", headers=as_(AGENT)) - state = first.json() - assert state["refused"] == [] - assert [c["name"] for c in state["units"]] == ["10"] - assert state["units"][0]["children"][0]["name"] == "101" - etag = first.headers["ETag"] - assert client.get("/api/v1/agent/state", headers=as_(AGENT) | {"If-None-Match": etag}).status_code == 304 - client.post("/api/v1/users/revoked", json=user("VOICE3"), headers=as_(RMAPI)) - changed = client.get("/api/v1/agent/state", headers=as_(AGENT) | {"If-None-Match": etag}) - assert changed.status_code == 200 - assert changed.json()["refused"] == ["VOICE3"] - assert changed.json()["missions"] == [] - - -def test_admin_channel_management(client: TestClient) -> None: - """Admins manage channels and members; others may not""" - assert client.get("/api/v1/admin/channels", headers=as_("VOICE3")).status_code == 403 - tree = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() - squad = tree[0]["children"][0]["id"] - assert client.put(f"/api/v1/admin/channels/{squad}/members/VOICE3", headers=as_("VOICE1")).status_code == 200 - assert client.put(f"/api/v1/admin/channels/{squad}/members/GHOST", headers=as_("VOICE1")).status_code == 404 - assert client.put("/api/v1/admin/channels/999/members/VOICE3", headers=as_("VOICE1")).status_code == 404 - tree = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() - assert tree[0]["children"][0]["members"] == ["VOICE3"] - assert client.delete(f"/api/v1/admin/channels/{squad}/members/VOICE3", headers=as_("VOICE1")).status_code == 200 - assert client.delete("/api/v1/admin/channels/999/members/VOICE3", headers=as_("VOICE1")).status_code == 404 - - new = client.post( - "/api/v1/admin/channels", json={"name": "07 TJ", "description": "Tulenjohto"}, headers=as_("VOICE1") - ) - assert new.status_code == 200 - assert client.post("/api/v1/admin/channels", json={"name": "07 TJ"}, headers=as_("VOICE1")).status_code == 400 - assert client.post("/api/v1/admin/channels", json={"name": "a/b"}, headers=as_("VOICE1")).status_code == 400 - too_long = {"name": "08", "description": "x" * 1001} - assert client.post("/api/v1/admin/channels", json=too_long, headers=as_("VOICE1")).status_code == 422 - cross_site_form = as_("VOICE1") | {"Content-Type": "text/plain"} - assert client.post("/api/v1/admin/channels", content='{"name": "X"}', headers=cross_site_form).status_code == 422 - assert client.delete(f"/api/v1/admin/channels/{new.json()['id']}", headers=as_("VOICE1")).status_code == 200 - assert client.delete("/api/v1/admin/channels/999", headers=as_("VOICE1")).status_code == 404 - - -def test_plan_export_and_import(client: TestClient) -> None: - """Channel plans go out and come in as the 2022 YAML schema""" - exported = client.get("/api/v1/admin/channels/export", headers=as_("VOICE1")).text - assert "name: '10'" in exported and "name: '101'" in exported - yaml_from = as_("VOICE1") | {"Content-Type": "application/yaml"} - added = client.post( - "/api/v1/admin/channels/import", content="channels:\n - name: 20\n - name: 10\n", headers=yaml_from - ) - assert added.json() == {"created": 1} - bad = client.post("/api/v1/admin/channels/import", content="nets: []", headers=yaml_from) - assert bad.status_code == 400 - merged = client.post( - "/api/v1/admin/channels/import", content="a: &a {name: 40}\nchannels: [{<<: *a}]", headers=yaml_from - ) - assert merged.status_code == 400 and "merge keys" in merged.json()["detail"] - cross_site_form = as_("VOICE1") | {"Content-Type": "text/plain"} - forged = client.post("/api/v1/admin/channels/import", content="channels:\n - name: 30\n", headers=cross_site_form) - assert forged.status_code == 415 - huge = client.post("/api/v1/admin/channels/import", content=b"#" * (api.MAX_PLAN_BYTES + 1), headers=yaml_from) - 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() - assert [u["callsign"] for u in users] == ["VOICE1", "VOICE3"] - assert all(u["uuid"] is None for u in users) - assert ( - client.put("/api/v1/admin/users/VOICE3/voice", json={"enabled": False}, headers=as_("VOICE1")).status_code - == 200 - ) - assert ( - client.put("/api/v1/admin/users/GHOST/voice", json={"enabled": False}, headers=as_("VOICE1")).status_code == 404 - ) - assert client.get("/api/v1/agent/state", headers=as_(AGENT)).json()["refused"] == ["VOICE3"] - client.put("/api/v1/admin/users/VOICE3/voice", json={"enabled": True}, headers=as_("VOICE1")) - assert client.get("/api/v1/agent/state", headers=as_(AGENT)).json()["refused"] == [] - - -def test_demoted_and_revoked_admins_lose_access(client: TestClient) -> None: - """Admin rights follow rmapi""" - client.post("/api/v1/users/demoted", json=user("VOICE1"), headers=as_(RMAPI)) - assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 403 - client.post("/api/v1/users/promoted", json=user("VOICE1"), headers=as_(RMAPI)) - client.put("/api/v1/users/updated", json=user("VOICE1"), headers=as_(RMAPI)) - assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 200 - client.post("/api/v1/users/revoked", json=user("VOICE1"), headers=as_(RMAPI)) - assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 403 - - -def test_public_endpoints(client: TestClient) -> None: - """Health and descriptions need no identity""" - assert client.get("/api/v1/healthcheck").json()["healthy"] is True - assert client.get("/api/v1/description/fi").json()["shortname"] == "mumble" - assert client.get("/api/v1/description/de").status_code == 404 - - -def test_v2_descriptions(client: TestClient) -> None: - """rmui gets the tile, the admin entry and the remote's address; unknown languages fall back to English""" - tile = client.get("/api/v2/description/fi").json() - assert tile["title"] == "Puhe" - assert tile["component"] == {"type": "component", "ref": "/ui/mumble/remoteEntry.js"} - assert tile["icon"] == "ui/mumble/voicelogo.svg" - assert client.get("/api/v2/description/de").json()["language"] == "en" - assert "members" in client.get("/api/v2/admin/description/en").json()["description"] - remote = client.get("/ui/mumble/remoteEntry.js") - assert remote.status_code == 200 and "javascript" in remote.headers["content-type"] - assert remote.headers["cache-control"] == "no-cache" # a new release shows on the next load - assert client.get("/ui/mumble/%2e%2e/db.sqlite").status_code == 404 - - -def test_client_data(client: TestClient) -> None: - """rmapi asks for a user's view on their behalf: nets, admin flag and whether voice works""" - squad = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()[0]["children"][0]["id"] - client.put(f"/api/v1/admin/channels/{squad}/members/VOICE3", headers=as_("VOICE1")) - assert client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_("VOICE3")).status_code == 403 - data = client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"] - assert data == {"admin": False, "voice": True, "nets": ["/Units/10/101"]} - client.patch(f"/api/v1/admin/channels/{squad}", json={"access": "inherit"}, headers=as_("VOICE1")) - data = client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"] - assert data["nets"] == [] # a kept membership lets nobody in - client.patch(f"/api/v1/admin/channels/{squad}", json={"access": "invite"}, headers=as_("VOICE1")) - assert client.post("/api/v2/clients/data", json=user("VOICE1"), headers=as_(RMAPI)).json()["data"]["admin"] - client.put("/api/v1/admin/users/VOICE3/voice", json={"enabled": False}, headers=as_("VOICE1")) - assert not client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"]["voice"] - stranger = client.post("/api/v2/clients/data", json=user("NEW"), headers=as_(RMAPI)).json()["data"] - assert stranger == {"admin": False, "voice": True, "nets": []} - - -def test_mesh_identity(client: TestClient) -> None: - """Without a Linkerd identity nobody is anyone, not even with a forged DN header""" - assert client.get("/api/v1/admin/channels", headers={"X-ClientCert-DN": "CN=VOICE1"}).status_code == 403 - forged_via_other_service = {"l5d-client-id": AGENT, "X-ClientCert-DN": "CN=VOICE1"} - assert client.get("/api/v1/admin/channels", headers=forged_via_other_service).status_code == 403 - - -def test_console_entrypoint() -> None: - """The container entrypoint is importable""" - from mumblermapi import console - - assert callable(console.main) - - -def test_presence(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: - """The agent reports who is where; admins see it per user; without fresh reports nobody knows""" - users = client.get("/api/v1/admin/users", headers=as_("VOICE1")).json() - assert {u["callsign"]: u["online"] for u in users} == {"VOICE1": None, "VOICE3": None} - report = {"sessions": [{"callsign": "VOICE1", "channel": "/Units/10"}, {"callsign": "VOICE1", "channel": "/"}]} - assert client.post("/api/v1/agent/presence", json=report, headers=as_("VOICE1")).status_code == 403 - assert client.post("/api/v1/agent/presence", json=report, headers=as_(AGENT)).status_code == 200 - users = client.get("/api/v1/admin/users", headers=as_("VOICE1")).json() - assert {u["callsign"]: u["online"] for u in users} == {"VOICE1": ["/Units/10", "/"], "VOICE3": []} - monkeypatch.setattr(api, "PRESENCE_TTL", -1.0) - assert all(u["online"] is None for u in client.get("/api/v1/admin/users", headers=as_("VOICE1")).json()) - - -def test_missions(client: TestClient) -> None: - """Admins see mission nets with subscribers; subscribers see theirs among their nets""" - store = client.app.state.store # type: ignore[attr-defined] - store.set_missions({"RECON": frozenset({"VOICE3"}), "Guard": frozenset({"VOICE1"})}) - assert client.get("/api/v1/admin/missions", headers=as_("VOICE3")).status_code == 403 - assert client.get("/api/v1/admin/missions", headers=as_("VOICE1")).json() == [ - {"name": "Guard", "members": [], "open": True}, - {"name": "RECON", "members": ["VOICE3"], "open": False}, - ] - data = client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"] - assert data["nets"] == ["/Missions/RECON"] - - -def test_settings_from_env(monkeypatch: pytest.MonkeyPatch) -> None: - """Every setting comes from MUMBLERMAPI_* variables; TAK is off unless configured""" - for name, value in { - "MUMBLERMAPI_DATABASE": "/d/db.sqlite", - "MUMBLERMAPI_TEMPLATES_DIR": "/t", - "MUMBLERMAPI_UI_DIR": "/u", - "MUMBLERMAPI_RMAPI_IDENTITY": "rm", - "MUMBLERMAPI_AGENT_IDENTITY": "ag", - }.items(): - monkeypatch.setenv(name, value) - settings = Settings.from_env() - assert settings == Settings( - database=Path("/d/db.sqlite"), - templates_dir=Path("/t"), - ui_dir=Path("/u"), - rmapi_identity="rm", - agent_identity="ag", - ) - assert settings.tak is None - - -def test_lifespan_runs_the_mission_watcher(tmp_path: Path) -> None: - """With TAK configured, the watcher runs for the app's life and stops with it""" - tak_settings = TakSettings( - tak_url="https://127.0.0.1:9", tak_server_name="tak.example.fi", cn="mumble.example.fi", - rmapi_url="http://127.0.0.1:9/", data_dir=tmp_path / "tak", poll_seconds=60, - ) # fmt: skip - # Empty health URLs: the health check, which also runs for the app's life, asks nothing outside the test - settings = Settings( - database=tmp_path / "db.sqlite", - ui_dir=tmp_path / "no-ui", - tak=tak_settings, - proxy_ready_url="", - gateway_ready_url="", - ) - app = create_app(settings) - with TestClient(app) as client: - assert client.get("/api/v1/healthcheck").status_code == 200 - assert client.get("/ui/mumble/remoteEntry.js").status_code == 404 - - -def test_templates(client: TestClient) -> None: - """Admins list templates (broken files and unusable names skipped) and apply one; applying again adds - nothing""" - assert client.get("/api/v1/admin/templates", headers=as_("VOICE3")).status_code == 403 - assert client.get("/api/v1/admin/templates", headers=as_("VOICE1")).json() == [ - {"id": "company", "name": "Komppania", "description": "Vakiosuunnitelma", "nets": 2} - ] - apply = "/api/v1/admin/templates/apply" - assert client.post(apply, json={"template": "company"}, headers=as_("VOICE1")).json() == {"created": 0} - assert client.post(apply, json={"template": "nope"}, headers=as_("VOICE1")).status_code == 404 - assert client.post(apply, json={"template": "../etc"}, headers=as_("VOICE1")).status_code == 422 - cross_site_form = as_("VOICE1") | {"Content-Type": "text/plain"} - assert client.post(apply, content='{"template": "company"}', headers=cross_site_form).status_code == 422 - - -def test_templates_dir_missing(tmp_path: Path) -> None: - """Without a templates directory there is simply nothing to offer""" - settings = Settings(database=tmp_path / "db.sqlite", templates_dir=tmp_path / "none") - assert api.templates(settings) == {} - - -def test_shipped_templates_are_offered() -> None: - """Each template the image ships loads: templates() skips a file it cannot read with only a warning""" - shipped = Path(__file__).parents[1] / "templates" - offered = api.templates(Settings(templates_dir=shipped)) - assert "komppania" in offered - assert sorted(offered) == sorted(path.stem for path in shipped.glob("*.yaml")) - - -def test_edit_channel(client: TestClient) -> None: - """Admins rename nets and change descriptions; clashes, bad names and unknown nets are refused""" - tree = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() - platoon = tree[0]["id"] - url = f"/api/v1/admin/channels/{platoon}" - assert client.patch(url, json={"description": "Alfa-joukkue"}, headers=as_("VOICE3")).status_code == 403 - assert client.patch(url, json={"description": "Alfa-joukkue"}, headers=as_("VOICE1")).status_code == 200 - assert client.patch(url, json={"name": "11"}, headers=as_("VOICE1")).status_code == 200 - renamed = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()[0] - assert (renamed["name"], renamed["description"]) == ("11", "Alfa-joukkue") - client.post("/api/v1/admin/channels", json={"name": "20"}, headers=as_("VOICE1")) - assert client.patch(url, json={"name": "20"}, headers=as_("VOICE1")).status_code == 400 - assert client.patch(url, json={"name": "a/b"}, headers=as_("VOICE1")).status_code == 400 - assert client.patch("/api/v1/admin/channels/999", json={"name": "x"}, headers=as_("VOICE1")).status_code == 404 - - -def test_channel_access(client: TestClient) -> None: - """Admins make nets open or invite-only; the plan export keeps it""" - created = client.post( - "/api/v1/admin/channels", json={"name": "07 TJ", "access": "invite"}, headers=as_("VOICE1") - ).json() - url = f"/api/v1/admin/channels/{created['id']}" - tree = {c["name"]: c for c in client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()} - assert (tree["10"]["access"], tree["07 TJ"]["access"]) == ("open", "invite") - assert tree["10"]["children"][0]["access"] == "inherit" - assert client.patch(url, json={"access": "secret"}, headers=as_("VOICE1")).status_code == 422 - assert client.patch(url, json={"access": "open"}, headers=as_("VOICE1")).status_code == 200 - assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()[0]["access"] == "open" - exported = client.get("/api/v1/admin/channels/export", headers=as_("VOICE1")).text - assert "access: open" in exported and "access: inherit" in exported - # The export restores the plan as it was, members included - client.put(url + "/members/VOICE3", headers=as_("VOICE1")) - exported = client.get("/api/v1/admin/channels/export", headers=as_("VOICE1")).text - assert client.delete("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 200 - yaml_from = as_("VOICE1") | {"Content-Type": "application/yaml"} - client.post("/api/v1/admin/channels/import", content=exported, headers=yaml_from) - restored = {c["name"]: c for c in client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()} - assert (restored["07 TJ"]["access"], restored["07 TJ"]["members"]) == ("invite", ["VOICE3"]) - - -def test_clear_plan(client: TestClient) -> None: - """Admins remove the whole plan at once""" - assert client.delete("/api/v1/admin/channels", headers=as_("VOICE3")).status_code == 403 - assert client.delete("/api/v1/admin/channels", headers=as_("VOICE1")).json() == {"removed": 2} - assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json() == [] diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..6de0690 --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,80 @@ +"""The app as a whole: settings, entrypoint, lifespan and who the mesh says is calling""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from mumblermapi.app import create_app +from mumblermapi.config import Settings +from mumblermapi.store import DatabaseSettings +from mumblermapi.tak import TakSettings + +from .conftest import AGENT + + +def test_settings_from_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Every setting comes from MUMBLERMAPI_* variables; TAK is off unless configured""" + for name, value in { + "MUMBLERMAPI_DATABASE_HOST": "db.example.fi", + "MUMBLERMAPI_DATABASE_PORT": "6543", + "MUMBLERMAPI_DATABASE_NAME": "voice", + "MUMBLERMAPI_DATABASE_USER": "voiceapi", + "MUMBLERMAPI_DATABASE_PASSWORD": "secret", # pragma: allowlist secret + "MUMBLERMAPI_TEMPLATES_DIR": "/t", + "MUMBLERMAPI_UI_DIR": "/u", + "MUMBLERMAPI_RMAPI_IDENTITY": "rm", + "MUMBLERMAPI_AGENT_IDENTITY": "ag", + }.items(): + monkeypatch.setenv(name, value) + settings = Settings.from_env() + assert settings == Settings( + database=DatabaseSettings( + host="db.example.fi", + port=6543, + name="voice", + user="voiceapi", + password="secret", # pragma: allowlist secret + ), + templates_dir=Path("/t"), + ui_dir=Path("/u"), + rmapi_identity="rm", + agent_identity="ag", + ) + assert settings.tak is None + + +def test_console_entrypoint() -> None: + """The container entrypoint is importable""" + from mumblermapi import console + + assert callable(console.main) + + +def test_lifespan_runs_the_mission_watcher(database: DatabaseSettings, tmp_path: Path) -> None: + """With TAK configured, the watcher runs for the app's life and stops with it""" + tak_settings = TakSettings( + tak_url="https://127.0.0.1:9", tak_server_name="tak.example.fi", cn="mumble.example.fi", + rmapi_url="http://127.0.0.1:9/", data_dir=tmp_path / "tak", poll_seconds=60, + ) # fmt: skip + # Empty health URLs: the health check, which also runs for the app's life, asks nothing outside the test + settings = Settings( + database=database, + ui_dir=tmp_path / "no-ui", + tak=tak_settings, + proxy_ready_url="", + gateway_ready_url="", + ) + app = create_app(settings) + with TestClient(app) as client: + assert client.get("/api/v1/healthcheck").status_code == 200 + assert client.get("/ui/mumble/remoteEntry.js").status_code == 404 + + +def test_mesh_identity(client: TestClient) -> None: + """Without a Linkerd identity nobody is anyone, not even with a forged DN header""" + assert client.get("/api/v1/admin/channels", headers={"X-ClientCert-DN": "CN=VOICE1"}).status_code == 403 + forged_via_other_service = {"l5d-client-id": AGENT, "X-ClientCert-DN": "CN=VOICE1"} + assert client.get("/api/v1/admin/channels", headers=forged_via_other_service).status_code == 403 diff --git a/tests/test_authenticator.py b/tests/test_authenticator.py index 14e75dd..896606d 100644 --- a/tests/test_authenticator.py +++ b/tests/test_authenticator.py @@ -8,11 +8,11 @@ import pytest -from mumblermapi.authenticator import MAX_NAME_LENGTH, REJECT, TRY_LATER, UNKNOWN, Authenticator, Refusal +from mumblermapi.agent.authenticator import MAX_NAME_LENGTH, REJECT, TRY_LATER, UNKNOWN, Authenticator, Refusal +from mumblermapi.agent.ocsp import OcspUnavailable +from mumblermapi.agent.policy import Policy +from mumblermapi.agent.userids import PHONE_SLOTS, UserIds from mumblermapi.identity import CertVerifier, Identity -from mumblermapi.ocsp import OcspUnavailable -from mumblermapi.policy import Policy -from mumblermapi.userids import UserIds from .conftest import NOW, Pki, issue @@ -50,6 +50,17 @@ def test_accepts_matching_certificate(pki: Pki, tmp_path: Path) -> None: assert auth.id_to_name(first) == "ALPHA_1---vs1" +def test_rejects_a_phone_slot_over_the_limit(pki: Pki, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + """One certificate cannot take a new name, and a place on the server, for every slot it makes up""" + auth = _auth(pki, tmp_path) + for n in range(PHONE_SLOTS): + assert auth.authenticate(f"ALPHA_1---vs{n}", [pki.alpha.der]) > 0 + with caplog.at_level(logging.DEBUG): + assert auth.authenticate("ALPHA_1---vs-new", [pki.alpha.der]) == REJECT + assert caplog.records[-1].getMessage().endswith(f"ALPHA_1 already has its {PHONE_SLOTS} phone slots") + assert auth.authenticate("ALPHA_1---vs0", [pki.alpha.der]) > 0 + + @pytest.mark.parametrize( "name", ["BRAVO_2---vs1", "ALPHA 1---vs1", "ALPHA_1---bad slot", ""], diff --git a/tests/test_channels.py b/tests/test_channels.py index 2739d4b..e442f5e 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -1,4 +1,4 @@ -"""Channel plan parsing and reconciliation""" +"""Channel plan parsing""" from __future__ import annotations @@ -15,15 +15,11 @@ ROLES, TEAM_COLOURS, ChannelPlanError, - ChannelRefused, ChannelSpec, - ExistingChannel, desired_tree, load_plan, load_yaml, parse_plan, - prune, - reconcile, ) PLAN = """ @@ -63,6 +59,7 @@ def test_load_plan(tmp_path: Path) -> None: ({"channels": [{"name": "Alpha\n"}]}, "invalid name"), ({"channels": [{"name": "a", "description": 3}]}, "description"), ({"channels": [{"name": "a", "description": "x" * 1001}]}, "at most 1000 characters"), + ({"channels": [{"name": "a", "description": "a\x00b"}]}, "no NUL"), # Postgres text cannot hold it ({"channels": [{"name": "a"}, {"name": "a"}]}, "duplicate"), ({"channels": [{"name": "a", "access": "secret"}]}, "access must be"), ({"channels": [{"name": "a", "channels": [{"name": True}]}]}, r"channels\[0\]\.channels\[0\]"), @@ -74,121 +71,6 @@ def test_parse_plan_rejects(data: object, match: str) -> None: parse_plan(data) -def test_desired_tree() -> None: - """Units/ carries the plan and Missions/ TAK's missions; Teams/ and Roles/ are fixed""" - units, missions, teams, roles = desired_tree((ChannelSpec("10"),), (ChannelSpec("RECON"),)) - assert units == ChannelSpec("Units", "Organisation nets", (ChannelSpec("10"),)) - assert missions.name == "Missions" and missions.children == (ChannelSpec("RECON"),) - assert desired_tree(())[1].children == () - assert [c.name for c in teams.children] == list(TEAM_COLOURS) - assert len(TEAM_COLOURS) == 14 - assert [c.name for c in roles.children] == list(ROLES) - - -class FakeServer: - """An in-memory Murmur channel list; 0 is the root""" - - def __init__(self, existing: list[ExistingChannel] | None = None) -> None: - self.existing = existing or [] - self.descriptions: dict[int, str] = {} - - def channels(self) -> list[ExistingChannel]: - return [ExistingChannel(0, -1, "Root"), *self.existing] - - def add_channel(self, name: str, parent: int, description: str) -> int: - channel_id = len(self.existing) + 1 - self.existing.append(ExistingChannel(channel_id, parent, name, description=description)) - self.descriptions[channel_id] = description - return channel_id - - def set_description(self, channel_id: int, description: str) -> None: - self.descriptions[channel_id] = description - self.existing = [ - ExistingChannel(c.id, c.parent, c.name, c.temporary, description) if c.id == channel_id else c - for c in self.existing - ] - - def remove_channel(self, channel_id: int) -> None: - gone = {channel_id} - while True: - more = {c.id for c in self.existing if c.parent in gone} - gone - if not more: - break - gone |= more - self.existing = [c for c in self.existing if c.id not in gone] - - -def test_reconcile_creates_tree_once() -> None: - """An empty server gets the whole tree; a second pass changes nothing""" - server = FakeServer() - desired = desired_tree( - parse_plan({"channels": [{"name": "10", "description": "A", "channels": [{"name": "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) == ([], []) - - -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"),)),)) - 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( - [ - ExistingChannel(1, 0, "Units"), - ExistingChannel(2, 1, "10"), - ExistingChannel(3, 2, "101"), - ExistingChannel(4, 2, "102"), - ExistingChannel(5, 4, "102 A"), - ExistingChannel(6, 1, "20"), - ExistingChannel(7, 2, "huddle", temporary=True), - ExistingChannel(8, 0, "Teams"), - ] - ) - removed = prune(server, (ChannelSpec("10", children=(ChannelSpec("101"),)),), root=1, prefix="/Units") - assert removed == ["/Units/10/102", "/Units/20"] - assert sorted(c.id for c in server.existing) == [1, 2, 3, 7, 8] - assert prune(server, (ChannelSpec("10", children=(ChannelSpec("101"),)),), root=1) == [] - - -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 server.descriptions == {2: "Alfa-joukkue"} - server.descriptions.clear() - reconcile(server, plan) - assert server.descriptions == {} - - def test_parse_plan_access() -> None: """A plan may say who gets into each net; leaving it out keeps the default""" plan = parse_plan( @@ -332,3 +214,14 @@ def test_load_yaml_reads_an_exported_plan_back() -> None: ] } assert load_yaml(yaml.safe_dump(plan, allow_unicode=True, sort_keys=False)) == plan + + +def test_desired_tree() -> None: + """Units/ carries the plan and Missions/ TAK's missions; Teams/ and Roles/ are fixed""" + units, missions, teams, roles = desired_tree((ChannelSpec("10"),), (ChannelSpec("RECON"),)) + assert units == ChannelSpec("Units", "Organisation nets", (ChannelSpec("10"),)) + assert missions.name == "Missions" and missions.children == (ChannelSpec("RECON"),) + assert desired_tree(())[1].children == () + assert [c.name for c in teams.children] == list(TEAM_COLOURS) + assert len(TEAM_COLOURS) == 14 + assert [c.name for c in roles.children] == list(ROLES) diff --git a/tests/test_clients_api.py b/tests/test_clients_api.py new file mode 100644 index 0000000..06f1726 --- /dev/null +++ b/tests/test_clients_api.py @@ -0,0 +1,25 @@ +"""What rmapi asks on a user's behalf""" + +from __future__ import annotations + +from fastapi.testclient import TestClient + +from .conftest import RMAPI, as_, user + + +def test_client_data(client: TestClient) -> None: + """rmapi asks for a user's view on their behalf: nets, admin flag and whether voice works""" + squad = client.get("/api/v1/admin/channels", headers=as_("VOICE1")).json()[0]["children"][0]["id"] + client.put(f"/api/v1/admin/channels/{squad}/members/VOICE3", headers=as_("VOICE1")) + assert client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_("VOICE3")).status_code == 403 + data = client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"] + assert data == {"admin": False, "voice": True, "nets": ["/Units/10/101"]} + client.patch(f"/api/v1/admin/channels/{squad}", json={"access": "inherit"}, headers=as_("VOICE1")) + data = client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"] + assert data["nets"] == [] # a kept membership lets nobody in + client.patch(f"/api/v1/admin/channels/{squad}", json={"access": "invite"}, headers=as_("VOICE1")) + assert client.post("/api/v2/clients/data", json=user("VOICE1"), headers=as_(RMAPI)).json()["data"]["admin"] + client.put("/api/v1/admin/users/VOICE3/voice", json={"enabled": False}, headers=as_("VOICE1")) + assert not client.post("/api/v2/clients/data", json=user("VOICE3"), headers=as_(RMAPI)).json()["data"]["voice"] + stranger = client.post("/api/v2/clients/data", json=user("NEW"), headers=as_(RMAPI)).json()["data"] + assert stranger == {"admin": False, "voice": True, "nets": []} diff --git a/tests/test_config.py b/tests/test_config.py deleted file mode 100644 index 9c98e20..0000000 --- a/tests/test_config.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Agent settings""" - -from pathlib import Path - -import pytest - -from mumblermapi.config import AgentConfig - -FAKE_SECRET = "not-a-real-ice-secret" # nosec B105 # pragma: allowlist secret - - -def test_defaults() -> None: - """Only the secret is required""" - config = AgentConfig.from_env({"MURMUR_ICE_SECRET": FAKE_SECRET}) - assert config == AgentConfig(ice_secret=FAKE_SECRET) - assert config.ocsp_url is None - - -def test_overrides() -> None: - """Every setting can come from the environment""" - config = AgentConfig.from_env( - { - "MURMUR_ICE_SECRET": FAKE_SECRET, - "MURMUR_ICE_HOST": "10.0.0.1", - "MURMUR_ICE_PORT": "7000", - "AGENT_CALLBACK_PORT": "7001", - "MURMUR_SERVER_ID": "2", - "AGENT_CA_BUNDLE": "/ca.pem", - "AGENT_CHANNELS_FILE": "/c.yaml", - "AGENT_DATA_DIR": "/d", - "AGENT_OCSP_URL": "http://ocsp", - "AGENT_OCSP_CACHE_SECONDS": "10", - "AGENT_SWEEP_SECONDS": "5", - "AGENT_STATE_URL": "http://mumblermapi/api/v1/agent/state", - "AGENT_POLL_SECONDS": "2", - "AGENT_PRESENCE_URL": "http://mumblermapi/api/v1/agent/presence", - "AGENT_GATEWAY_CA": "/gateway/ca.crt", - } - ) - assert config == AgentConfig( - ice_secret=FAKE_SECRET, - ice_host="10.0.0.1", - ice_port=7000, - callback_port=7001, - server_id=2, - ca_bundle=Path("/ca.pem"), - channels_file=Path("/c.yaml"), - data_dir=Path("/d"), - ocsp_url="http://ocsp", - ocsp_cache_seconds=10.0, - sweep_seconds=5.0, - state_url="http://mumblermapi/api/v1/agent/state", - poll_seconds=2.0, - presence_url="http://mumblermapi/api/v1/agent/presence", - gateway_ca=Path("/gateway/ca.crt"), - ) - - -@pytest.mark.parametrize("env", [{}, {"MURMUR_ICE_SECRET": ""}]) -def test_secret_required(env: dict[str, str]) -> None: - """No secret, no agent""" - with pytest.raises(ValueError, match="never run without a secret"): - AgentConfig.from_env(env) diff --git a/tests/test_description_api.py b/tests/test_description_api.py new file mode 100644 index 0000000..079b66f --- /dev/null +++ b/tests/test_description_api.py @@ -0,0 +1,34 @@ +"""What anyone may read: the product descriptions and the UI remote""" + +from __future__ import annotations + +from fastapi.testclient import TestClient + + +def test_descriptions(client: TestClient) -> None: + """Descriptions need no identity""" + assert client.get("/api/v1/description/fi").json()["shortname"] == "mumble" + assert client.get("/api/v1/description/de").status_code == 404 + + +def test_v2_descriptions(client: TestClient) -> None: + """rmui gets the tile, the admin entry and the remote's address; unknown languages fall back to English""" + tile = client.get("/api/v2/description/fi").json() + assert tile["title"] == "Puhe" + assert tile["component"] == {"type": "component", "ref": "/ui/mumble/remoteEntry.js"} + assert tile["icon"] == "ui/mumble/voicelogo.svg" + assert client.get("/api/v2/description/de").json()["language"] == "en" + assert "members" in client.get("/api/v2/admin/description/en").json()["description"] + remote = client.get("/ui/mumble/remoteEntry.js") + assert remote.status_code == 200 and "javascript" in remote.headers["content-type"] + assert remote.headers["cache-control"] == "no-cache" # a new release shows on the next load + assert client.get("/ui/mumble/%2e%2e/templates/company.yaml").status_code == 404 + + +def test_v2_descriptions_link_the_voice_guide(client: TestClient) -> None: + """Both entries link the guide in their language; unknown languages get the English page""" + guide = "https://docs.opendefence.fi/{}/guides/voice-guide" + for language in ("fi", "sv", "en"): + assert client.get(f"/api/v2/description/{language}").json()["docs"] == guide.format(language) + assert client.get("/api/v2/description/de").json()["docs"] == guide.format("en") + assert client.get("/api/v2/admin/description/en").json()["docs"] == guide.format("en") diff --git a/tests/test_enforce.py b/tests/test_enforce.py index f3e0c66..3705cbf 100644 --- a/tests/test_enforce.py +++ b/tests/test_enforce.py @@ -4,8 +4,7 @@ from types import SimpleNamespace -from mumblermapi.channels import ExistingChannel -from mumblermapi.enforce import ( +from mumblermapi.agent.enforce import ( OPEN, OPEN_OVERRIDE, Access, @@ -21,7 +20,8 @@ shadows, violations, ) -from mumblermapi.policy import Policy, Unit +from mumblermapi.agent.policy import Policy, Unit +from mumblermapi.agent.reconcile import ExistingChannel from .murmur_acl import created_by, may_enter diff --git a/tests/test_gateway_auth.py b/tests/test_gateway_auth.py index 5015aa2..d226b23 100644 --- a/tests/test_gateway_auth.py +++ b/tests/test_gateway_auth.py @@ -9,11 +9,11 @@ import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from mumblermapi.authenticator import REJECT, TRY_LATER, Authenticator +from mumblermapi.agent.authenticator import REJECT, TRY_LATER, Authenticator +from mumblermapi.agent.policy import Policy, PolicySource, parse_state +from mumblermapi.agent.userids import UserIds from mumblermapi.identity import CertVerifier -from mumblermapi.policy import Policy, PolicySource, parse_state from mumblermapi.tickets import mint, public_key -from mumblermapi.userids import UserIds from .conftest import NOW, Issued, Pki, issue from .test_authenticator import FakeRevocation diff --git a/tests/test_health.py b/tests/test_health.py index aa030b1..9a79b5b 100644 --- a/tests/test_health.py +++ b/tests/test_health.py @@ -16,20 +16,29 @@ from aiohttp.abc import AbstractResolver, ResolveResult from fastapi.testclient import TestClient -from mumblermapi.api import PRESENCE_TTL, Settings, create_app +from mumblermapi import health +from mumblermapi.api.murmur_agent import PRESENCE_TTL +from mumblermapi.app import create_app +from mumblermapi.config import Settings from mumblermapi.health import Answer, fetcher, problems, watch, why +from mumblermapi.store import DatabaseSettings, engine PROXY = "http://proxy/ready" GATEWAY = "http://gateway/readyz" -def check(answers: dict[str, Answer], presence_age: float = 10.0, uptime: float = 1000.0) -> list[str]: +def check( + answers: dict[str, Answer], + presence_age: float = 10.0, + uptime: float = 1000.0, + version: Callable[[], int] = lambda: 1, +) -> list[str]: """problems() against fixed answers: an URL missing from answers timed out""" async def fetch(url: str) -> Answer: return answers.get(url, "timed out") - return asyncio.run(problems(fetch, PROXY, GATEWAY, presence_age, uptime, PRESENCE_TTL)) + return asyncio.run(problems(fetch, version, PROXY, GATEWAY, presence_age, uptime, PRESENCE_TTL)) def test_all_well() -> None: @@ -58,6 +67,28 @@ def test_each_problem_named_with_its_cause() -> None: assert check({PROXY: 200, GATEWAY: 503}) == ["the voice gateway is not ready (HTTP 503): browsers cannot talk"] +def test_database_away(monkeypatch: pytest.MonkeyPatch) -> None: + """Postgres refusing or not answering, with the first line of the driver's error as the cause""" + nobody = engine(DatabaseSettings(host="127.0.0.1", port=_closed_port()).url) + + def refused() -> int: + with nobody.connect(): + return 1 + + [found] = check({PROXY: 200, GATEWAY: 204}, version=refused) + assert found.startswith("the database cannot be reached ((psycopg2.OperationalError) connection to server") + assert found.endswith("Connection refused): tickets, user events and admin changes fail") + + def stalled() -> int: + time.sleep(0.1) + return 1 + + monkeypatch.setattr(health, "FETCH_SECONDS", 0.01) + assert check({PROXY: 200, GATEWAY: 204}, version=stalled) == [ + "the database cannot be reached (timed out): tickets, user events and admin changes fail" + ] + + def test_agent_gets_its_first_report_window() -> None: """Right after a start the agent has not reported yet; that is no problem until PRESENCE_TTL passed""" assert check({PROXY: 200, GATEWAY: 204}, presence_age=float("inf"), uptime=5.0) == [] @@ -67,7 +98,7 @@ def test_unchecked_urls() -> None: async def fetch(url: str) -> Answer: raise AssertionError(url) - assert asyncio.run(problems(fetch, "", "", 1.0, 1000.0, PRESENCE_TTL)) == [] + assert asyncio.run(problems(fetch, lambda: 1, "", "", 1.0, 1000.0, PRESENCE_TTL)) == [] class NoNames(AbstractResolver): @@ -150,7 +181,10 @@ def test_watch_logs_each_change(caplog: pytest.LogCaptureFixture) -> None: """A problem is logged with its cause when it appears, and the recovery when it goes""" gone = f"http://127.0.0.1:{_closed_port()}/readyz" state = SimpleNamespace( - settings=SimpleNamespace(proxy_ready_url="", gateway_ready_url=gone), presence=(time.monotonic(), {}), health=[] + settings=SimpleNamespace(proxy_ready_url="", gateway_ready_url=gone), + store=SimpleNamespace(version=lambda: 1), + presence=(time.monotonic(), {}), + health=[], ) app: Any = SimpleNamespace(state=state) @@ -173,9 +207,9 @@ async def one_round() -> None: assert caplog.records[-1].getMessage() == "Voice is healthy" -def test_healthcheck_reports_the_last_check(tmp_path: Path) -> None: +def test_healthcheck_reports_the_last_check(database: DatabaseSettings, tmp_path: Path) -> None: """Always 200 for the kubelet; rmapi reads healthy and why not""" - app = create_app(Settings(database=tmp_path / "db.sqlite", templates_dir=tmp_path, ui_dir=tmp_path / "none")) + app = create_app(Settings(database=database, templates_dir=tmp_path, ui_dir=tmp_path / "none")) client = TestClient(app) assert client.get("/api/v1/healthcheck").json() == {"healthy": True, "extra": ""} problem = "the voice gateway is not ready (name resolution failed): browsers cannot talk" @@ -185,10 +219,15 @@ def test_healthcheck_reports_the_last_check(tmp_path: Path) -> None: assert response.json() == {"healthy": False, "extra": problem} -def test_lifespan_runs_the_health_check(tmp_path: Path) -> None: +def test_healthcheck_needs_no_identity(client: TestClient) -> None: + """The kubelet asks without one""" + assert client.get("/api/v1/healthcheck").json()["healthy"] is True + + +def test_lifespan_runs_the_health_check(database: DatabaseSettings, tmp_path: Path) -> None: """With nothing to ask (empty URLs) and the agent's first window still open, the running check finds nothing""" settings = Settings( - database=tmp_path / "db.sqlite", + database=database, templates_dir=tmp_path, ui_dir=tmp_path / "none", proxy_ready_url="", diff --git a/tests/test_kraftwerk.py b/tests/test_kraftwerk.py index 6c86396..6f3f0d3 100644 --- a/tests/test_kraftwerk.py +++ b/tests/test_kraftwerk.py @@ -5,7 +5,7 @@ import pytest from mumblermapi import kraftwerk -from mumblermapi.api import Settings +from mumblermapi.config import Settings from mumblermapi.tak import TakSettings MANIFEST = { diff --git a/tests/test_murmur_agent_api.py b/tests/test_murmur_agent_api.py new file mode 100644 index 0000000..d49fee0 --- /dev/null +++ b/tests/test_murmur_agent_api.py @@ -0,0 +1,40 @@ +"""What murmur-agent reads and reports""" + +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from mumblermapi.api import murmur_agent + +from .conftest import AGENT, RMAPI, as_, user + + +def test_agent_state_and_versions(client: TestClient) -> None: + """The agent gets the applied tree, then 304 until something changes""" + assert client.get("/api/v1/agent/state", headers=as_("VOICE1")).status_code == 403 + first = client.get("/api/v1/agent/state", headers=as_(AGENT)) + state = first.json() + assert state["refused"] == [] + assert [c["name"] for c in state["units"]] == ["10"] + assert state["units"][0]["children"][0]["name"] == "101" + etag = first.headers["ETag"] + assert client.get("/api/v1/agent/state", headers=as_(AGENT) | {"If-None-Match": etag}).status_code == 304 + client.post("/api/v1/users/revoked", json=user("VOICE3"), headers=as_(RMAPI)) + changed = client.get("/api/v1/agent/state", headers=as_(AGENT) | {"If-None-Match": etag}) + assert changed.status_code == 200 + assert changed.json()["refused"] == ["VOICE3"] + assert changed.json()["missions"] == [] + + +def test_presence(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: + """The agent reports who is where; admins see it per user; without fresh reports nobody knows""" + users = client.get("/api/v1/admin/users", headers=as_("VOICE1")).json() + assert {u["callsign"]: u["online"] for u in users} == {"VOICE1": None, "VOICE3": None} + report = {"sessions": [{"callsign": "VOICE1", "channel": "/Units/10"}, {"callsign": "VOICE1", "channel": "/"}]} + assert client.post("/api/v1/agent/presence", json=report, headers=as_("VOICE1")).status_code == 403 + assert client.post("/api/v1/agent/presence", json=report, headers=as_(AGENT)).status_code == 200 + users = client.get("/api/v1/admin/users", headers=as_("VOICE1")).json() + assert {u["callsign"]: u["online"] for u in users} == {"VOICE1": ["/Units/10", "/"], "VOICE3": []} + monkeypatch.setattr(murmur_agent, "PRESENCE_TTL", -1.0) + assert all(u["online"] is None for u in client.get("/api/v1/admin/users", headers=as_("VOICE1")).json()) diff --git a/tests/test_ocsp.py b/tests/test_ocsp.py index 25ff5a8..ca19436 100644 --- a/tests/test_ocsp.py +++ b/tests/test_ocsp.py @@ -16,9 +16,9 @@ from cryptography.x509 import ocsp from cryptography.x509.oid import AuthorityInformationAccessOID, ExtendedKeyUsageOID -from mumblermapi import ocsp as ocsp_module +from mumblermapi.agent import ocsp as ocsp_module +from mumblermapi.agent.ocsp import OcspChecker, OcspUnavailable, http_post, responder_url from mumblermapi.identity import Identity -from mumblermapi.ocsp import OcspChecker, OcspUnavailable, http_post, responder_url from .conftest import NOW, Issued, Pki, issue diff --git a/tests/test_policy.py b/tests/test_policy.py index 3385959..c50c2d0 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -10,8 +10,8 @@ import pytest +from mumblermapi.agent.policy import MAX_STATE_BYTES, Policy, PolicySource, Unit, from_plan, http_get, parse_state from mumblermapi.channels import GUARD, ChannelSpec -from mumblermapi.policy import MAX_STATE_BYTES, Policy, PolicySource, Unit, from_plan, http_get, parse_state STATE = { "version": 7, diff --git a/tests/test_presence.py b/tests/test_presence.py index 3d3c916..bc066ce 100644 --- a/tests/test_presence.py +++ b/tests/test_presence.py @@ -9,9 +9,9 @@ import pytest -from mumblermapi.channels import ExistingChannel -from mumblermapi.enforce import Session -from mumblermapi.presence import PresenceReporter, channel_paths, http_post_json, presence +from mumblermapi.agent.enforce import Session +from mumblermapi.agent.presence import PresenceReporter, channel_paths, http_post_json, presence +from mumblermapi.agent.reconcile import ExistingChannel CHANNELS = [ ExistingChannel(0, -1, "Root"), diff --git a/tests/test_reconcile.py b/tests/test_reconcile.py new file mode 100644 index 0000000..c203afc --- /dev/null +++ b/tests/test_reconcile.py @@ -0,0 +1,110 @@ +"""Reconciling Murmur's channels with the plan""" + +from __future__ import annotations + +from mumblermapi.agent.reconcile import ChannelRefused, ExistingChannel, prune, reconcile +from mumblermapi.channels import ChannelSpec, desired_tree, parse_plan + + +class FakeChannels: + """An in-memory Murmur channel list; 0 is the root""" + + def __init__(self, existing: list[ExistingChannel] | None = None) -> None: + self.existing = existing or [] + self.descriptions: dict[int, str] = {} + + def channels(self) -> list[ExistingChannel]: + return [ExistingChannel(0, -1, "Root"), *self.existing] + + def add_channel(self, name: str, parent: int, description: str) -> int: + channel_id = len(self.existing) + 1 + self.existing.append(ExistingChannel(channel_id, parent, name, description=description)) + self.descriptions[channel_id] = description + return channel_id + + def set_description(self, channel_id: int, description: str) -> None: + self.descriptions[channel_id] = description + self.existing = [ + ExistingChannel(c.id, c.parent, c.name, c.temporary, description) if c.id == channel_id else c + for c in self.existing + ] + + def remove_channel(self, channel_id: int) -> None: + gone = {channel_id} + while True: + more = {c.id for c in self.existing if c.parent in gone} - gone + if not more: + break + gone |= more + self.existing = [c for c in self.existing if c.id not in gone] + + +def test_reconcile_creates_tree_once() -> None: + """An empty server gets the whole tree; a second pass changes nothing""" + server = FakeChannels() + desired = desired_tree( + parse_plan({"channels": [{"name": "10", "description": "A", "channels": [{"name": "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) == ([], []) + + +def test_reconcile_fills_gaps_only() -> None: + """Existing channels are kept, and missing children land under them""" + server = FakeChannels([ExistingChannel(7, 0, "Units")]) + 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(FakeChannels): + 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_reconcile_corrects_descriptions() -> None: + """An edited description reaches Murmur once; an unchanged one is left alone""" + server = FakeChannels([ExistingChannel(1, 0, "Units"), ExistingChannel(2, 1, "10", description="old")]) + plan = (ChannelSpec("Units", children=(ChannelSpec("10", "Alfa-joukkue"),)),) + assert reconcile(server, plan) == ([], []) + assert server.descriptions == {2: "Alfa-joukkue"} + server.descriptions.clear() + reconcile(server, plan) + assert server.descriptions == {} + + +def test_prune_removes_what_the_plan_dropped() -> None: + """Dropped permanent channels go with their subtrees; kept ones and users' temporary channels stay""" + server = FakeChannels( + [ + ExistingChannel(1, 0, "Units"), + ExistingChannel(2, 1, "10"), + ExistingChannel(3, 2, "101"), + ExistingChannel(4, 2, "102"), + ExistingChannel(5, 4, "102 A"), + ExistingChannel(6, 1, "20"), + ExistingChannel(7, 2, "huddle", temporary=True), + ExistingChannel(8, 0, "Teams"), + ] + ) + removed = prune(server, (ChannelSpec("10", children=(ChannelSpec("101"),)),), root=1, prefix="/Units") + assert removed == ["/Units/10/102", "/Units/20"] + assert sorted(c.id for c in server.existing) == [1, 2, 3, 7, 8] + assert prune(server, (ChannelSpec("10", children=(ChannelSpec("101"),)),), root=1) == [] diff --git a/tests/test_store.py b/tests/test_store.py index 76651e2..e23aa9b 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -1,21 +1,14 @@ """The mumblermapi store""" -import sqlite3 -from pathlib import Path +from concurrent.futures import ThreadPoolExecutor import pytest from mumblermapi.channels import MAX_DEPTH, ChannelSpec -from mumblermapi.store import Channel, ChannelExists, Store, StoreError, TooDeep +from mumblermapi.store import Channel, ChannelExists, DatabaseSettings, Store, StoreError, TooDeep, engine from mumblermapi.tickets import WEB_SLOTS -@pytest.fixture(name="store") -def store_fixture(tmp_path: Path) -> Store: - """A fresh store""" - return Store(tmp_path / "state.db") - - def test_users_and_flags(store: Store) -> None: """Users arrive from rmapi; flags change them and bump the version""" v0 = store.version() @@ -29,13 +22,11 @@ def test_users_and_flags(store: Store) -> None: assert store.user("BRAVO 2") == bravo assert store.user("NOBODY") is None assert store.version() == v0 + 4 - with pytest.raises(StoreError): - store.set_user_flag("ALPHA 1", "root", True) def test_channel_tree_and_members(store: Store) -> None: """Channels nest, carry members, and go away with their subtree""" - assert store.is_empty() + assert store.tree() == [] platoon = store.add_channel("10", "Alfa-joukkue") squad = store.add_channel("101", "Ryhmä 1", parent=platoon) store.add_channel("20") @@ -63,7 +54,7 @@ def test_import_plan_is_idempotent(store: Store) -> None: plan = (ChannelSpec("10", "A", (ChannelSpec("101"), ChannelSpec("102"))), ChannelSpec("07 TJ")) assert store.import_plan(plan) == 4 assert store.import_plan(plan) == 0 - assert not store.is_empty() + assert [c.name for c in store.tree()] == ["07 TJ", "10"] def _chain(store: Store, depth: int) -> int: @@ -96,16 +87,14 @@ def test_import_under_a_net_too_deep(store: Store) -> None: store.import_plan((ChannelSpec("y"),), deepest) -def test_persists(tmp_path: Path) -> None: +def test_persists(store: Store, database: DatabaseSettings) -> None: """State survives a restart""" - first = Store(tmp_path / "state.db") - first.add_channel("10") - assert [c.name for c in Store(tmp_path / "state.db").tree()] == ["10"] + store.add_channel("10") + assert [c.name for c in Store(engine(database.url)).tree()] == ["10"] -def test_missions(tmp_path: Path) -> None: +def test_missions(store: Store) -> None: """Missions are replaced as a whole; only a change bumps the version; missions without subscribers are dropped""" - store = Store(tmp_path / "db.sqlite") before = store.version() assert store.set_missions({"RECON": frozenset({"VOICE1", "VOICE3"}), "EMPTY": frozenset()}) assert store.missions() == {"RECON": frozenset({"VOICE1", "VOICE3"})} @@ -116,17 +105,15 @@ def test_missions(tmp_path: Path) -> None: assert store.missions() == {} -def test_channel_ids_are_never_reused(tmp_path: Path) -> None: +def test_channel_ids_are_never_reused(store: Store) -> None: """A stale reference to a removed channel cannot reach a channel made after it""" - store = Store(tmp_path / "db.sqlite") first = store.add_channel("10") store.remove_channel(first) assert store.add_channel("20") > first -def test_update_channel(tmp_path: Path) -> None: +def test_update_channel(store: Store) -> None: """Names and descriptions change in place; a clash with a sibling is refused""" - store = Store(tmp_path / "db.sqlite") ten = store.add_channel("10", "Alfa") store.add_channel("20") before = store.version() @@ -140,43 +127,19 @@ def test_update_channel(tmp_path: Path) -> None: store.update_channel(999, description="x") -def test_clear(tmp_path: Path) -> None: +def test_clear(store: Store) -> None: """The whole plan goes at once, members too, and new ids do not reuse old ones""" - store = Store(tmp_path / "db.sqlite") ten = store.add_channel("10") store.add_channel("101", parent=ten) store.upsert_user("VOICE1", "u1") store.set_member(ten, "VOICE1", True) assert store.clear() == 2 - assert store.tree() == [] and store.is_empty() + assert store.tree() == [] assert store.add_channel("10") > ten -def test_changes_are_atomic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A change that fails halfway leaves nothing behind""" - store = Store(tmp_path / "db.sqlite") - ten = store.add_channel("10") - store.add_channel("101", parent=ten) - store.upsert_user("VOICE1", "u1") - store.set_member(ten, "VOICE1", True) - before = store.version() - - class Boom(Exception): - pass - - def fail(*args: object) -> None: - raise Boom - - monkeypatch.setattr(store, "_bump", fail) - with pytest.raises(Boom): - store.clear() - assert [c.name for c in store.tree()] == ["10"] and store.tree()[0].members == ["VOICE1"] - assert store.version() == before - - -def test_access_defaults_and_changes(tmp_path: Path) -> None: +def test_access_defaults_and_changes(store: Store) -> None: """Top-level nets start open and sub-nets follow their parent; a top-level net cannot inherit""" - store = Store(tmp_path / "db.sqlite") ten = store.add_channel("10") squad = store.add_channel("101", parent=ten) fire = store.add_channel("07 TJ", access="invite") @@ -189,15 +152,10 @@ def test_access_defaults_and_changes(tmp_path: Path) -> None: store.update_channel(fire, description="Tulenjohto") assert [(c.name, c.access) for c in store.tree()] == [("07 TJ", "invite"), ("10", "open")] assert store.tree()[1].children[0].access == "open" - with pytest.raises(StoreError): - store.update_channel(ten, access="secret") - with pytest.raises(StoreError): - store.add_channel("20", access="secret") -def test_member_makes_net_invite_only(tmp_path: Path) -> None: +def test_member_makes_net_invite_only(store: Store) -> None: """Adding a member closes an open net; removing the last one leaves it closed, and opening it keeps them""" - store = Store(tmp_path / "db.sqlite") ten = store.add_channel("10") store.set_member(ten, "ALPHA", True) assert store.tree()[0].access == "invite" @@ -208,17 +166,15 @@ def test_member_makes_net_invite_only(tmp_path: Path) -> None: assert (store.tree()[0].access, store.tree()[0].members) == ("open", ["ALPHA"]) -def test_import_keeps_plan_access(tmp_path: Path) -> None: +def test_import_keeps_plan_access(store: Store) -> None: """A plan's access lands as written; unspecified access takes the default""" - store = Store(tmp_path / "db.sqlite") store.import_plan((ChannelSpec("10", access="invite", children=(ChannelSpec("101"),)),)) platoon = store.tree()[0] assert (platoon.access, platoon.children[0].access) == ("invite", "inherit") -def test_import_restores_members(tmp_path: Path) -> None: +def test_import_restores_members(store: Store) -> None: """New nets get the plan's members; a net that exists keeps its own""" - store = Store(tmp_path / "db.sqlite") kept = store.add_channel("20", access="invite") store.set_member(kept, "BRAVO", True) plan = ( @@ -229,40 +185,15 @@ def test_import_restores_members(tmp_path: Path) -> None: assert {c.name: c.members for c in store.tree()} == {"10": ["VOICE1"], "20": ["BRAVO"]} -def test_migrates_implicit_access(tmp_path: Path) -> None: - """A store from before explicit access keeps the access its members gave it""" - path = tmp_path / "db.sqlite" - old = sqlite3.connect(path) - old.executescript( - """ - CREATE TABLE channels (id INTEGER PRIMARY KEY AUTOINCREMENT, parent INTEGER NOT NULL DEFAULT 0, - name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', UNIQUE (parent, name)); - CREATE TABLE members (channel INTEGER NOT NULL, callsign TEXT NOT NULL, PRIMARY KEY (channel, callsign)); - INSERT INTO channels (id, parent, name) VALUES (1, 0, '10'), (2, 1, '101'), (3, 1, '102'), (4, 0, '20'); - INSERT INTO members VALUES (1, 'LEADER'), (2, 'ALPHA'); - """ - ) - old.commit() - old.close() - store = Store(path) - platoon, company = store.tree() - assert (platoon.access, [c.access for c in platoon.children], company.access) == ( - "invite", - ["invite", "inherit"], - "open", - ) - - -def test_web_slots_per_browser(tmp_path: Path) -> None: +def test_web_slots_per_browser(store: Store, database: DatabaseSettings) -> 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") + reopened = Store(engine(database.url)) assert reopened.web_slot("ALPHA_1", "phone-browser-0002", 104.0) == 2 assert reopened.web_slot("ALPHA_1", "tablet-browser-03", 105.0) == 3 @@ -276,3 +207,10 @@ def test_tenth_browser_takes_the_oldest_slot(store: Store) -> None: 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 + + +def test_browsers_asking_at_once_get_slots_of_their_own(store: Store) -> None: + """New browsers of one callsign asking at the same moment never share a slot""" + with ThreadPoolExecutor(len(WEB_SLOTS)) as pool: + slots = pool.map(lambda slot: store.web_slot("ALPHA_1", f"browser-number-{slot:02}", 100.0), WEB_SLOTS) + assert sorted(slots) == list(WEB_SLOTS) diff --git a/tests/test_tak.py b/tests/test_tak.py index be94e2c..5c548c7 100644 --- a/tests/test_tak.py +++ b/tests/test_tak.py @@ -136,8 +136,8 @@ async def roles(request: web.Request) -> web.Response: async def _cycle( - pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, interop_ok: bool = True -) -> tuple[Store, TakSettings, list[str]]: + store: Store, pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, interop_ok: bool = True +) -> tuple[TakSettings, list[str]]: calls: list[str] = [] server = TestServer(fake_services(pki, calls, interop_ok)) await server.start_server() @@ -147,7 +147,6 @@ async def _cycle( tak_url=base.rstrip("/"), tak_server_name="tak.example.fi", cn="mumble.example.fi", rmapi_url=base, data_dir=tmp_path / "tak", poll_seconds=0.01, ) # fmt: skip - store = Store(tmp_path / "db.sqlite") stop = asyncio.Event() monkeypatch.setattr(tak, "tls_context", lambda _: False) original = store.set_missions @@ -161,7 +160,7 @@ def set_and_stop(missions: dict[str, frozenset[str]]) -> bool: await asyncio.wait_for(_until(lambda: stop.is_set() or len(calls) >= 4), 5) stop.set() await task - return store, settings, calls + return settings, calls finally: await server.close() @@ -171,31 +170,33 @@ async def _until(condition: Any) -> None: await asyncio.sleep(0.01) -def test_enrols_then_reads_missions(pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_enrols_then_reads_missions(store: Store, pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """A certificate from rmapi, TAK rights via interop, then missions with subscribers into the store""" - store, settings, calls = asyncio.run(_cycle(pki, tmp_path, monkeypatch)) + settings, calls = asyncio.run(_cycle(store, pki, tmp_path, monkeypatch)) assert calls[:2] == ["sign:CN=mumble.example.fi", "interop:mumble.example.fi"] assert store.missions() == {"RECON": frozenset({"VOICE1", "VOICE3"})} assert settings.cert.exists() and settings.key.exists() assert settings.key.stat().st_mode & 0o077 == 0 -def test_refused_interop_keeps_old_identity(pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_refused_interop_keeps_old_identity( + store: Store, pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: """If takrmapi refuses, the identity in use stays as it was (none here) and no missions are read""" - store, settings, calls = asyncio.run(_cycle(pki, tmp_path, monkeypatch, interop_ok=False)) + settings, calls = asyncio.run(_cycle(store, pki, tmp_path, monkeypatch, interop_ok=False)) assert "interop:mumble.example.fi" in calls assert not settings.cert.exists() and not settings.key.exists() assert store.missions() == {} def test_refused_interop_is_retried_with_the_same_certificate( - pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + store: Store, pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """rmapi signs once; later polls retry only the interop, and the accepted retry installs that certificate""" - _, settings, calls = asyncio.run(_cycle(pki, tmp_path, monkeypatch, interop_ok=False)) + settings, calls = asyncio.run(_cycle(store, pki, tmp_path, monkeypatch, interop_ok=False)) assert calls.count("sign:CN=mumble.example.fi") == 1 and calls.count("interop:mumble.example.fi") >= 2 pending = (settings.data_dir / "tak.pem.new").read_bytes() - store, settings, calls = asyncio.run(_cycle(pki, tmp_path, monkeypatch)) + settings, calls = asyncio.run(_cycle(store, pki, tmp_path, monkeypatch)) assert calls[0] == "interop:mumble.example.fi" and "sign:CN=mumble.example.fi" not in calls assert settings.cert.read_bytes() == pending and settings.key.exists() assert store.missions() == {"RECON": frozenset({"VOICE1", "VOICE3"})} diff --git a/tests/test_usercrud_api.py b/tests/test_usercrud_api.py new file mode 100644 index 0000000..2244b02 --- /dev/null +++ b/tests/test_usercrud_api.py @@ -0,0 +1,24 @@ +"""User lifecycle events from rmapi""" + +from __future__ import annotations + +from fastapi.testclient import TestClient + +from .conftest import RMAPI, as_, user + + +def test_user_events_only_from_rmapi(client: TestClient) -> None: + """Anyone but rmapi is refused, and an unauthenticated caller too""" + assert client.post("/api/v1/users/promoted", json=user("VOICE3"), headers=as_("VOICE3")).status_code == 403 + assert client.post("/api/v1/users/created", json=user("X")).status_code == 403 + + +def test_demoted_and_revoked_admins_lose_access(client: TestClient) -> None: + """Admin rights follow rmapi""" + client.post("/api/v1/users/demoted", json=user("VOICE1"), headers=as_(RMAPI)) + assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 403 + client.post("/api/v1/users/promoted", json=user("VOICE1"), headers=as_(RMAPI)) + client.put("/api/v1/users/updated", json=user("VOICE1"), headers=as_(RMAPI)) + assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 200 + client.post("/api/v1/users/revoked", json=user("VOICE1"), headers=as_(RMAPI)) + assert client.get("/api/v1/admin/channels", headers=as_("VOICE1")).status_code == 403 diff --git a/tests/test_userids.py b/tests/test_userids.py index 9591cfe..6a13f00 100644 --- a/tests/test_userids.py +++ b/tests/test_userids.py @@ -4,7 +4,7 @@ import pytest -from mumblermapi.userids import UserIds +from mumblermapi.agent.userids import PHONE_SLOTS, SlotsFull, UserIds def test_assign_and_persist(tmp_path: Path) -> None: @@ -58,3 +58,18 @@ def full(*args: object) -> None: 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") + + +def test_phone_slots_are_limited_per_callsign(tmp_path: Path) -> None: + """A callsign gets PHONE_SLOTS slots outside web-; its bare name, its web- slots and other callsigns do not + count, and the slots it has keep their ids""" + ids = UserIds(tmp_path / "ids.json") + phones = [ids.get_or_assign(f"A---vs{n}") for n in range(PHONE_SLOTS)] + for name in ("A", "A---web-1", "A---web-9", "AB---vs9", "B---vs9"): + ids.get_or_assign(name) + with pytest.raises(SlotsFull): + ids.get_or_assign("A---vs-new") + assert ids.id_for("A---vs-new") is None + assert [ids.get_or_assign(f"A---vs{n}") for n in range(PHONE_SLOTS)] == phones + with pytest.raises(SlotsFull): + UserIds(tmp_path / "ids.json").get_or_assign("A---VS0") diff --git a/tests/test_voice_api.py b/tests/test_voice_api.py index f995d87..d8522ab 100644 --- a/tests/test_voice_api.py +++ b/tests/test_voice_api.py @@ -11,11 +11,12 @@ from cryptography.hazmat.primitives.serialization import Encoding from fastapi.testclient import TestClient -from mumblermapi.api import Settings, create_app +from mumblermapi.app import create_app +from mumblermapi.config import Settings +from mumblermapi.store import DatabaseSettings from mumblermapi.tickets import verify -from .conftest import Issued, Pki, issue -from .test_api import AGENT, RMAPI, TRAEFIK, as_, user +from .conftest import AGENT, RMAPI, TRAEFIK, Issued, Pki, as_, issue, user def forwarded(*certs: Issued) -> dict[str, str]: @@ -30,7 +31,7 @@ def edge(*certs: Issued) -> dict[str, str]: @pytest.fixture(name="client") -def client_fixture(pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient: +def client_fixture(pki: Pki, database: DatabaseSettings, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient: """mumblermapi trusting the fixture PKI, which knows ALPHA 1 and BRAVO 2""" monkeypatch.setenv("MTLS_TRUST_L5D", "1") monkeypatch.setenv("MTLS_REQUIRE_L5D", "1") @@ -38,7 +39,7 @@ def client_fixture(pki: Pki, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> bundle = tmp_path / "ca.pem" bundle.write_bytes(pki.root.cert.public_bytes(Encoding.PEM) + pki.ca.cert.public_bytes(Encoding.PEM)) settings = Settings( - database=tmp_path / "db.sqlite", + database=database, templates_dir=tmp_path, ui_dir=tmp_path / "none", rmapi_identity=RMAPI, @@ -153,9 +154,9 @@ def test_refuses_bad_browser_ids_and_other_fields(client: TestClient, pki: Pki, assert client.post("/api/v1/voice/token", json=body, headers=edge(pki.alpha)).status_code == 422 -def test_no_bundle_no_tickets(tmp_path: Path, pki: Pki) -> None: +def test_no_bundle_no_tickets(database: DatabaseSettings, 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") + settings = Settings(database=database, ca_bundle=tmp_path / "missing.pem", ui_dir=tmp_path / "x") client = TestClient(create_app(settings)) assert client.post("/api/v1/voice/token", json=LAPTOP, headers=edge(pki.alpha)).status_code == 503 diff --git a/ui/README.md b/ui/README.md new file mode 100644 index 0000000..df09c28 --- /dev/null +++ b/ui/README.md @@ -0,0 +1,12 @@ +# Voice federated component + +The remote ships no CSS: rmui renders it with its own Tailwind build, so only the classes in that build work. + +- Classes in the files copied from rmui's `components/ui` are always there. Any other class is checked + against an rmui build. +- No `dark:` variants of our own, as rmui never sets `.dark`; the copies keep theirs. +- Hover and active states use `muted`: `accent` and `secondary` follow the deployment theme. +- Keyboard focus on a menu or select item shows a ring, as rmui's CSS has no muted focus background. +- Controls keep 40-44 px touch targets, so the copies' sizes differ from shadcn's. +- `DialogContent` has no built-in close button, whose label would be English only; callers add a translated + `DialogClose`. diff --git a/ui/components.json b/ui/components.json new file mode 100644 index 0000000..380e970 --- /dev/null +++ b/ui/components.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "registries": {} +} diff --git a/ui/package.json b/ui/package.json index 8482dc2..ffb7892 100644 --- a/ui/package.json +++ b/ui/package.json @@ -8,26 +8,44 @@ "scripts": { "build": "tsc && vite build", "dev": "vite --port 4175", - "test": "node --test --experimental-test-coverage test/paths.test.mjs test/api.test.mjs test/mumble.test.mjs test/ptt.test.mjs test/nets.test.mjs" + "test": "vitest run" }, "dependencies": { + "@radix-ui/react-alert-dialog": "^1.2.1", + "@radix-ui/react-dialog": "^1.3.1", + "@radix-ui/react-dropdown-menu": "^2.2.1", + "@radix-ui/react-select": "^2.4.1", + "@radix-ui/react-slot": "^1.5.0", + "@radix-ui/react-switch": "^1.4.1", + "@radix-ui/react-tabs": "^1.2.1", + "@radix-ui/react-toggle-group": "^1.2.1", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "cmdk": "^1.1.1", "i18next": "^25.6.2", + "lucide-react": "^0.552.0", "react": "18.3.1", - "react-i18next": "^16.3.3" + "react-i18next": "^16.3.3", + "tailwind-merge": "^3.7.0" }, "devDependencies": { "@eslint/js": "^10.0.1", "@module-federation/enhanced": "^0.21.2", "@module-federation/vite": "1.7.1", + "@testing-library/dom": "^10.4.2", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.8", "@types/react": "^18.3.12", "@types/react-dom": "^18.3.1", "@vitejs/plugin-react": "^4.7.0", "eslint": "^10.8.0", "eslint-plugin-react-hooks": "^7.1.1", + "jsdom": "^31.0.1", "prettier": "^3.9.6", "react-dom": "18.3.1", "typescript": "^5.6.3", "typescript-eslint": "^8.66.0", - "vite": "^5.4.21" + "vite": "^5.4.21", + "vitest": "^3.2.7" } } diff --git a/ui/pnpm-lock.yaml b/ui/pnpm-lock.yaml index eaae003..5cb2533 100644 --- a/ui/pnpm-lock.yaml +++ b/ui/pnpm-lock.yaml @@ -8,15 +8,54 @@ importers: .: dependencies: + '@radix-ui/react-alert-dialog': + specifier: ^1.2.1 + version: 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-dialog': + specifier: ^1.3.1 + version: 1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-dropdown-menu': + specifier: ^2.2.1 + version: 2.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-select': + specifier: ^2.4.1 + version: 2.4.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-slot': + specifier: ^1.5.0 + version: 1.5.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-switch': + specifier: ^1.4.1 + version: 1.4.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-tabs': + specifier: ^1.2.1 + version: 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-toggle-group': + specifier: ^1.2.1 + version: 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + class-variance-authority: + specifier: ^0.7.1 + version: 0.7.1 + clsx: + specifier: ^2.1.1 + version: 2.1.1 + cmdk: + specifier: ^1.1.1 + version: 1.1.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) i18next: specifier: ^25.6.2 version: 25.10.10(typescript@5.9.3) + lucide-react: + specifier: ^0.552.0 + version: 0.552.0(react@18.3.1) react: specifier: 18.3.1 version: 18.3.1 react-i18next: specifier: ^16.3.3 version: 16.6.6(i18next@25.10.10(typescript@5.9.3))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@5.9.3) + tailwind-merge: + specifier: ^3.7.0 + version: 3.7.0 devDependencies: '@eslint/js': specifier: ^10.0.1 @@ -27,6 +66,15 @@ importers: '@module-federation/vite': specifier: 1.7.1 version: 1.7.1(rollup@4.64.4) + '@testing-library/dom': + specifier: ^10.4.2 + version: 10.4.2 + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@testing-library/user-event': + specifier: ^14.6.8 + version: 14.6.8(@testing-library/dom@10.4.2) '@types/react': specifier: ^18.3.12 version: 18.3.31 @@ -42,6 +90,9 @@ importers: eslint-plugin-react-hooks: specifier: ^7.1.1 version: 7.1.1(eslint@10.12.0(jiti@2.4.2)) + jsdom: + specifier: ^31.0.1 + version: 31.0.1 prettier: specifier: ^3.9.6 version: 3.9.10 @@ -57,6 +108,9 @@ importers: vite: specifier: ^5.4.21 version: 5.4.21 + vitest: + specifier: ^3.2.7 + version: 3.2.7(jsdom@31.0.1) packages: @@ -339,6 +393,30 @@ packages: resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} + '@exodus/bytes@1.16.0': + resolution: {integrity: sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + '@noble/hashes': ^1.8.0 || ^2.0.0 + peerDependenciesMeta: + '@noble/hashes': + optional: true + + '@floating-ui/core@1.8.0': + resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==} + + '@floating-ui/dom@1.8.0': + resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==} + + '@floating-ui/react-dom@2.1.9': + resolution: {integrity: sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==} + peerDependencies: + react: '>=16.8.0' + react-dom: '>=16.8.0' + + '@floating-ui/utils@0.2.12': + resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==} + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -493,6 +571,379 @@ packages: '@emnapi/core': ^1.7.1 '@emnapi/runtime': ^1.7.1 + '@radix-ui/number@1.1.3': + resolution: {integrity: sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA==} + + '@radix-ui/primitive@1.2.0': + resolution: {integrity: sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw==} + + '@radix-ui/react-alert-dialog@1.2.1': + resolution: {integrity: sha512-MWC4N7RY+qsbNrFNo7yQ9ZbdoZEW+B5DtpWxJfUnVCqcQxxqqg3qis3RMPTDbCNaTIdHJSn5XDkl9ZdVWXknLg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-arrow@1.1.17': + resolution: {integrity: sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-collection@1.2.0': + resolution: {integrity: sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-compose-refs@1.1.5': + resolution: {integrity: sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-context@1.3.0': + resolution: {integrity: sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-dialog@1.3.1': + resolution: {integrity: sha512-+0E4qvVTwjAWra9sEhJ+9BTsvHE00zkUuNw1VGh7S+Gc13dfYk+S1PVQdchWDj+XYHhAai7Z7IpzXVDCGsDplg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-direction@1.2.0': + resolution: {integrity: sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-dismissable-layer@1.2.1': + resolution: {integrity: sha512-KIfDcAsx+oVylFZ4xryVKusJUrLLhTQmfnJW4kwk4Km5myvhHCrj04hnWWUC166+xD4DHdH8tQGylwYX1h6+Pg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-dropdown-menu@2.2.1': + resolution: {integrity: sha512-XsHcmYG2AcqnvTqrOXXWcMrhquEIlqucizuDH1MV/qMRW+DndpBCMvNeTRXOxqmG1H5j89M/+I0/34Zdd+zDcQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-focus-guards@1.2.0': + resolution: {integrity: sha512-MPm5R0iRGUDrDnPNxmLBkv+X7pN4XKzt+MbWJEuJQsH3NFH4omrbpXpucyYCCKTSt+na/ZxGhEWQrWTZ0285cA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-focus-scope@1.3.1': + resolution: {integrity: sha512-ugeMhbXt4y5S2T1GnIqbWDKEN962PDwnX1fN0eKOOgf5f63Dh2mn8F1FUySlgW0iF6GiVsRF32DzuDIWTUyQJg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-id@1.1.4': + resolution: {integrity: sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-menu@2.2.1': + resolution: {integrity: sha512-G34BsU90SBj5foYpz8pQqq/Q0Dlfyyl6KitWEfRwXC0QvfwhWNAwS49DWP2+rRJ0iwv20Z2Qx7Sk+T03bGo5JA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-popper@1.4.0': + resolution: {integrity: sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-portal@1.2.0': + resolution: {integrity: sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-presence@1.1.11': + resolution: {integrity: sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-primitive@2.2.0': + resolution: {integrity: sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-roving-focus@1.2.1': + resolution: {integrity: sha512-UwraORzVUeEPMclhO1p0vz0qI+TbdDLO9i+FiOqhJyHKwdpCRCck9yVEscUnAMIzCiuNoQa8D4A9bIpOPXGt6Q==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-select@2.4.1': + resolution: {integrity: sha512-888ZwW0Md6GyptuqYABRX9nLKgoYfcooCyBBvVaX5Jp3e+8Jp2i4Zo/Uy50Hm+Ysn2JfloQXstW4U36w8teVtg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-slot@1.5.0': + resolution: {integrity: sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-switch@1.4.1': + resolution: {integrity: sha512-NpBGwc40rY02ZmSvuyeKk0Bvc8ZsNeTMi4qHvJ+ZH4EiYCv0zIXEgdCW4bVdzgIUeP9xxbLJSxKOUfqITYNmkA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-tabs@1.2.1': + resolution: {integrity: sha512-hRoJlode+hg5ZNlR+3tkfkUliIybdTpD5lkAvHQ9yaXseGf7XVO9Ib2GPEIOuaJJbo7YWYbNpDDRfo8Dhf6/xA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-toggle-group@1.2.1': + resolution: {integrity: sha512-O8Ldx5ao4p4KoW+DO8/PmkOe5mdKNi3F2SseqjVj88wvDGDHe60cUmO0Zm/uHsKrvNgQGV8Efpuh95Tht/h4vw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-toggle@1.2.1': + resolution: {integrity: sha512-+3MUq+WyiBplXYqQ0EIYlq8R4sLQ0T5NbOK7DMdDLCKO93pe2uE0DUJTWWfTBprpJJXxfoF3eMW0xpakVZrYsg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-use-callback-ref@1.1.5': + resolution: {integrity: sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-controllable-state@1.3.0': + resolution: {integrity: sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-effect-event@0.0.5': + resolution: {integrity: sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-is-hydrated@0.1.3': + resolution: {integrity: sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-layout-effect@1.1.4': + resolution: {integrity: sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-rect@1.1.4': + resolution: {integrity: sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-size@1.1.5': + resolution: {integrity: sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-visually-hidden@1.2.13': + resolution: {integrity: sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/rect@1.1.3': + resolution: {integrity: sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==} + '@rolldown/pluginutils@1.0.0-beta.27': resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} @@ -714,9 +1165,37 @@ packages: '@swc/helpers': optional: true + '@testing-library/dom@10.4.2': + resolution: {integrity: sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==} + engines: {node: '>=18'} + + '@testing-library/react@16.3.3': + resolution: {integrity: sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==} + engines: {node: '>=18'} + peerDependencies: + '@testing-library/dom': ^10.0.0 + '@types/react': ^18.0.0 || ^19.0.0 + '@types/react-dom': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@testing-library/user-event@14.6.8': + resolution: {integrity: sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ==} + engines: {node: '>=12', npm: '>=6'} + peerDependencies: + '@testing-library/dom': '>=7.21.4' + '@tybys/wasm-util@0.10.4': resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + '@types/babel__core@7.20.5': resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} @@ -729,6 +1208,12 @@ packages: '@types/babel__traverse@7.28.0': resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/esrecurse@4.3.1': resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} @@ -817,6 +1302,35 @@ packages: peerDependencies: vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 + '@vitest/expect@3.2.7': + resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==} + + '@vitest/mocker@3.2.7': + resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@3.2.7': + resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==} + + '@vitest/runner@3.2.7': + resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==} + + '@vitest/snapshot@3.2.7': + resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==} + + '@vitest/spy@3.2.7': + resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==} + + '@vitest/utils@3.2.7': + resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==} + accepts@1.3.8: resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} engines: {node: '>= 0.6'} @@ -862,10 +1376,29 @@ packages: resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==} engines: {node: '>=6'} + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + ansi-styles@4.3.0: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + + aria-hidden@1.2.6: + resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} + engines: {node: '>=10'} + + aria-query@5.3.0: + resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} @@ -885,6 +1418,12 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + bcp-47-match@2.0.3: + resolution: {integrity: sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==} + + bcp-47@2.1.2: + resolution: {integrity: sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==} + brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -899,6 +1438,10 @@ packages: engines: {node: '>= 0.4.0'} hasBin: true + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + cacheable@2.5.0: resolution: {integrity: sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==} @@ -909,13 +1452,34 @@ packages: caniuse-lite@1.0.30001815: resolution: {integrity: sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==} + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + chalk@3.0.0: resolution: {integrity: sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==} engines: {node: '>=8'} - color-convert@2.0.1: - resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} - engines: {node: '>=7.0.0'} + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + class-variance-authority@0.7.1: + resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + cmdk@1.1.1: + resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==} + peerDependencies: + react: ^18 || ^19 || ^19.0.0-rc + react-dom: ^18 || ^19 || ^19.0.0-rc + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} @@ -959,6 +1523,10 @@ packages: csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + data-urls@8.0.0: + resolution: {integrity: sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==} + engines: {node: ^22.14.0 || >=24.0.0} + date-format@4.0.14: resolution: {integrity: sha512-39BOQLs9ZjKh0/patS9nrT8wc3ioX3/eA/zgbKNopnF2wCqJEoxywwwElATYvRsXdnOxA/OQeQoFZ3rFjVajhg==} engines: {node: '>=4.0'} @@ -972,6 +1540,13 @@ packages: supports-color: optional: true + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + deep-equal@1.0.1: resolution: {integrity: sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==} @@ -996,10 +1571,20 @@ packages: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + destroy@1.2.0: resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + detect-node-es@1.1.0: + resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -1014,6 +1599,10 @@ packages: resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} engines: {node: '>= 0.8'} + entities@9.0.0: + resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} + engines: {node: '>=20.19.0'} + es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -1022,6 +1611,9 @@ packages: resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} engines: {node: '>= 0.4'} + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + es-object-atoms@1.1.2: resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} engines: {node: '>= 0.4'} @@ -1093,6 +1685,9 @@ packages: estree-walker@2.0.2: resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + esutils@2.0.3: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} @@ -1101,6 +1696,10 @@ packages: resolution: {integrity: sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==} engines: {node: '>=0.10.0'} + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -1184,6 +1783,10 @@ packages: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} + get-nonce@1.0.1: + resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} + engines: {node: '>=6'} + get-proto@1.0.1: resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} engines: {node: '>= 0.4'} @@ -1243,6 +1846,10 @@ packages: hookified@2.2.0: resolution: {integrity: sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==} + html-encoding-sniffer@7.0.0: + resolution: {integrity: sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==} + engines: {node: ^22.13.0 || >=24.0.0} + html-parse-stringify@3.1.0: resolution: {integrity: sha512-E0oAXcELOtsXe+BmpJ2EZyedbldPpriV5vICzEuo6xjC/D1lDukOI7KrpfQGF2Qc4wWEy0nk3bFORS2K5ZAhFQ==} @@ -1288,10 +1895,19 @@ packages: ini@1.3.8: resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + is-alphabetical@2.0.1: + resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==} + + is-alphanumerical@2.0.1: + resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==} + is-core-module@2.17.0: resolution: {integrity: sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==} engines: {node: '>= 0.4'} + is-decimal@2.0.1: + resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==} + is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} @@ -1300,6 +1916,9 @@ packages: resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-windows@1.0.2: resolution: {integrity: sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==} engines: {node: '>=0.10.0'} @@ -1319,6 +1938,18 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + js-tokens@9.0.1: + resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} + + jsdom@31.0.1: + resolution: {integrity: sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + peerDependencies: + '@napi-rs/canvas': ^1.0.13 + peerDependenciesMeta: + '@napi-rs/canvas': + optional: true + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} @@ -1380,13 +2011,29 @@ packages: resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} hasBin: true + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + lru-cache@11.5.3: + resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} + engines: {node: 20 || >=22} + lru-cache@5.1.1: resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lucide-react@0.552.0: + resolution: {integrity: sha512-g9WCjmfwqbexSnZE+2cl21PCfXOcqnGeWeMTNAOGEfpPbm/ZF4YIq77Z8qWrxbu660EKuLB4nSLggoKnCb+isw==} + peerDependencies: + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + luxon@3.7.2: resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} engines: {node: '>=12'} + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} @@ -1461,6 +2108,12 @@ packages: resolution: {integrity: sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==} engines: {node: '>=0.10.0'} + parse5-parser-stream@8.1.1: + resolution: {integrity: sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==} + + parse5@8.1.1: + resolution: {integrity: sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==} + parseurl@1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} @@ -1479,6 +2132,13 @@ packages: pathe@1.1.2: resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==} + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -1499,6 +2159,10 @@ packages: engines: {node: '>=14'} hasBin: true + pretty-format@27.5.1: + resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + proxy-from-env@2.1.0: resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==} engines: {node: '>=10'} @@ -1535,10 +2199,43 @@ packages: typescript: optional: true + react-is@17.0.2: + resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + react-refresh@0.17.0: resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==} engines: {node: '>=0.10.0'} + react-remove-scroll-bar@2.3.8: + resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + + react-remove-scroll@2.7.2: + resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + react-style-singleton@2.2.3: + resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + react@18.3.1: resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==} engines: {node: '>=0.10.0'} @@ -1566,6 +2263,10 @@ packages: safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + scheduler@0.23.2: resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==} @@ -1598,6 +2299,9 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + sorted-array-functions@1.3.0: resolution: {integrity: sha512-2sqgzeFlid6N4Z2fUQ1cvFmTOLRi/sEDzSQ0OKYchqgoPmQBVyM3959qYx3fpS6Esef80KjmpgPeEr028dP3OA==} @@ -1605,6 +2309,9 @@ packages: resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + statuses@1.5.0: resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} engines: {node: '>= 0.6'} @@ -1613,10 +2320,16 @@ packages: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + streamroller@3.1.5: resolution: {integrity: sha512-KFxaM7XT+irxvdqSP1LGLgNWbYN7ay5owZ3r/8t77p+EtSUAfUgtl7be3xtqtOmGUl9K9YPO2ca8133RlTjvKw==} engines: {node: '>=8.0'} + strip-literal@3.1.0: + resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} @@ -1625,14 +2338,50 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} + tailwind-merge@3.7.0: + resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@2.0.0: + resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==} + engines: {node: '>=14.0.0'} + + tinyspy@4.0.6: + resolution: {integrity: sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==} + engines: {node: '>=14.0.0'} + + tldts-core@7.6.0: + resolution: {integrity: sha512-0By9U6fw2hNzfJAbBMuo1bsX/OyVlsj0wjGyMPV50RZKoLCRwXBOX0FQqgZDaMo2WjjaEW/ZGyVXicLUFTmXqQ==} + + tldts@7.6.0: + resolution: {integrity: sha512-IFk9SJW/EhTZMpJA1zRdP+69JK4NmJbMx1aRdJvLBR9em1k62eWiwolSWlDRpRdkaAnZ1dDCwFPmRPBNuLGGHA==} + hasBin: true + toidentifier@1.0.1: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} + tough-cookie@6.1.0: + resolution: {integrity: sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==} + engines: {node: '>=16'} + + tr46@7.0.0: + resolution: {integrity: sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==} + engines: {node: ^22.14.0 || >=24.0.0} + ts-api-utils@2.5.0: resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} engines: {node: '>=18.12'} @@ -1666,6 +2415,10 @@ packages: engines: {node: '>=14.17'} hasBin: true + undici@8.13.1: + resolution: {integrity: sha512-Kt7EaPjh0s93lJH/PmW3d5rhkcpUa6fS3jqZ7+YGxNd9L7Xy/i827xe4C2uhhq+pJebM4tQOl5AgHmW11G5Skg==} + engines: {node: '>=22.19.0'} + universalify@0.1.2: resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==} engines: {node: '>= 4.0.0'} @@ -1687,6 +2440,26 @@ packages: uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + use-callback-ref@1.3.3: + resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + use-sidecar@1.1.3: + resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + use-sync-external-store@1.7.0: resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==} peerDependencies: @@ -1696,6 +2469,11 @@ packages: resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} engines: {node: '>= 0.8'} + vite-node@3.2.4: + resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + vite@5.4.21: resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} engines: {node: ^18.0.0 || >=20.0.0} @@ -1727,10 +2505,54 @@ packages: terser: optional: true + vitest@3.2.7: + resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/debug': ^4.1.12 + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@vitest/browser': 3.2.7 + '@vitest/ui': 3.2.7 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/debug': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + void-elements@3.1.0: resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==} engines: {node: '>=0.10.0'} + w3c-xmlserializer@6.0.0: + resolution: {integrity: sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + + webidl-conversions@8.0.1: + resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} + engines: {node: '>=20'} + + whatwg-mimetype@5.0.0: + resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} + engines: {node: '>=20'} + + whatwg-url@17.3.0: + resolution: {integrity: sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==} + engines: {node: ^22.14.0 || >=24.0.0} + which@1.3.1: resolution: {integrity: sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==} hasBin: true @@ -1740,6 +2562,11 @@ packages: engines: {node: '>= 8'} hasBin: true + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + word-wrap@1.2.5: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} @@ -1756,6 +2583,13 @@ packages: utf-8-validate: optional: true + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -2019,6 +2853,25 @@ snapshots: '@eslint/core': 1.2.1 levn: 0.4.1 + '@exodus/bytes@1.16.0': {} + + '@floating-ui/core@1.8.0': + dependencies: + '@floating-ui/utils': 0.2.12 + + '@floating-ui/dom@1.8.0': + dependencies: + '@floating-ui/core': 1.8.0 + '@floating-ui/utils': 0.2.12 + + '@floating-ui/react-dom@2.1.9(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@floating-ui/dom': 1.8.0 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + + '@floating-ui/utils@0.2.12': {} + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -2196,63 +3049,438 @@ snapshots: '@module-federation/error-codes': 0.17.1 '@module-federation/sdk': 0.17.1 - '@module-federation/runtime-core@0.21.6': + '@module-federation/runtime-core@0.21.6': + dependencies: + '@module-federation/error-codes': 0.21.6 + '@module-federation/sdk': 0.21.6 + + '@module-federation/runtime-tools@0.21.6': + dependencies: + '@module-federation/runtime': 0.21.6 + '@module-federation/webpack-bundler-runtime': 0.21.6 + + '@module-federation/runtime@0.17.1': + dependencies: + '@module-federation/error-codes': 0.17.1 + '@module-federation/runtime-core': 0.17.1 + '@module-federation/sdk': 0.17.1 + + '@module-federation/runtime@0.21.6': + dependencies: + '@module-federation/error-codes': 0.21.6 + '@module-federation/runtime-core': 0.21.6 + '@module-federation/sdk': 0.21.6 + + '@module-federation/sdk@0.17.1': {} + + '@module-federation/sdk@0.21.6': {} + + '@module-federation/third-party-dts-extractor@0.21.6': + dependencies: + find-pkg: 2.0.0 + fs-extra: 9.1.0 + resolve: 1.22.8 + + '@module-federation/vite@1.7.1(rollup@4.64.4)': + dependencies: + '@module-federation/runtime': 0.17.1 + '@rollup/pluginutils': 5.4.0(rollup@4.64.4) + defu: 6.1.7 + estree-walker: 2.0.2 + magic-string: 0.30.21 + pathe: 1.1.2 + transitivePeerDependencies: + - rollup + + '@module-federation/webpack-bundler-runtime@0.21.6': + dependencies: + '@module-federation/runtime': 0.21.6 + '@module-federation/sdk': 0.21.6 + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': + dependencies: + '@emnapi/core': 1.11.3 + '@emnapi/runtime': 1.11.3 + '@tybys/wasm-util': 0.10.4 + optional: true + + '@radix-ui/number@1.1.3': {} + + '@radix-ui/primitive@1.2.0': {} + + '@radix-ui/react-alert-dialog@1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-dialog': 1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-arrow@1.1.17(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-collection@1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-slot': 1.5.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-compose-refs@1.1.5(@types/react@18.3.31)(react@18.3.1)': + dependencies: + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-context@1.3.0(@types/react@18.3.31)(react@18.3.1)': + dependencies: + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-dialog@1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-dismissable-layer': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-focus-guards': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-focus-scope': 1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-portal': 1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-presence': 1.1.11(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-slot': 1.5.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + aria-hidden: 1.2.6 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + react-remove-scroll: 2.7.2(@types/react@18.3.31)(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-direction@1.2.0(@types/react@18.3.31)(react@18.3.1)': + dependencies: + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-dismissable-layer@1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-effect-event': 0.0.5(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-dropdown-menu@2.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-menu': 2.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-focus-guards@1.2.0(@types/react@18.3.31)(react@18.3.1)': + dependencies: + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-focus-scope@1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-id@1.1.4(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-menu@2.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-collection': 1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-direction': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-dismissable-layer': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-focus-guards': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-focus-scope': 1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-popper': 1.4.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-portal': 1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-presence': 1.1.11(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-roving-focus': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-slot': 1.5.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@18.3.31)(react@18.3.1) + aria-hidden: 1.2.6 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + react-remove-scroll: 2.7.2(@types/react@18.3.31)(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-popper@1.4.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@floating-ui/react-dom': 2.1.9(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-arrow': 1.1.17(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-rect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-size': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/rect': 1.1.3 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-portal@1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-presence@1.1.11(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-primitive@2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/react-slot': 1.5.0(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-roving-focus@1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-collection': 1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-direction': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-is-hydrated': 0.1.3(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-select@2.4.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/number': 1.1.3 + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-collection': 1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-direction': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-dismissable-layer': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-focus-guards': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-focus-scope': 1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-popper': 1.4.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-portal': 1.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-presence': 1.1.11(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-slot': 1.5.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-visually-hidden': 1.2.13(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + aria-hidden: 1.2.6 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + react-remove-scroll: 2.7.2(@types/react@18.3.31)(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-slot@1.5.0(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 + + '@radix-ui/react-switch@1.4.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-size': 1.1.5(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-tabs@1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-direction': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-presence': 1.1.11(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-roving-focus': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/react-toggle-group@1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': dependencies: - '@module-federation/error-codes': 0.21.6 - '@module-federation/sdk': 0.21.6 + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-context': 1.3.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-direction': 1.2.0(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-roving-focus': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-toggle': 1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) - '@module-federation/runtime-tools@0.21.6': + '@radix-ui/react-toggle@1.2.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': dependencies: - '@module-federation/runtime': 0.21.6 - '@module-federation/webpack-bundler-runtime': 0.21.6 + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) - '@module-federation/runtime@0.17.1': + '@radix-ui/react-use-callback-ref@1.1.5(@types/react@18.3.31)(react@18.3.1)': dependencies: - '@module-federation/error-codes': 0.17.1 - '@module-federation/runtime-core': 0.17.1 - '@module-federation/sdk': 0.17.1 + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@module-federation/runtime@0.21.6': + '@radix-ui/react-use-controllable-state@1.3.0(@types/react@18.3.31)(react@18.3.1)': dependencies: - '@module-federation/error-codes': 0.21.6 - '@module-federation/runtime-core': 0.21.6 - '@module-federation/sdk': 0.21.6 - - '@module-federation/sdk@0.17.1': {} + '@radix-ui/primitive': 1.2.0 + '@radix-ui/react-use-effect-event': 0.0.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@module-federation/sdk@0.21.6': {} + '@radix-ui/react-use-effect-event@0.0.5(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@module-federation/third-party-dts-extractor@0.21.6': + '@radix-ui/react-use-is-hydrated@0.1.3(@types/react@18.3.31)(react@18.3.1)': dependencies: - find-pkg: 2.0.0 - fs-extra: 9.1.0 - resolve: 1.22.8 + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@module-federation/vite@1.7.1(rollup@4.64.4)': + '@radix-ui/react-use-layout-effect@1.1.4(@types/react@18.3.31)(react@18.3.1)': dependencies: - '@module-federation/runtime': 0.17.1 - '@rollup/pluginutils': 5.4.0(rollup@4.64.4) - defu: 6.1.7 - estree-walker: 2.0.2 - magic-string: 0.30.21 - pathe: 1.1.2 - transitivePeerDependencies: - - rollup + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@module-federation/webpack-bundler-runtime@0.21.6': + '@radix-ui/react-use-rect@1.1.4(@types/react@18.3.31)(react@18.3.1)': dependencies: - '@module-federation/runtime': 0.21.6 - '@module-federation/sdk': 0.21.6 + '@radix-ui/rect': 1.1.3 + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@napi-rs/lzma-linux-x64-gnu@1.5.1': - optional: true + '@radix-ui/react-use-size@1.1.5(@types/react@18.3.31)(react@18.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@18.3.31)(react@18.3.1) + react: 18.3.1 + optionalDependencies: + '@types/react': 18.3.31 - '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': + '@radix-ui/react-visually-hidden@1.2.13(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': dependencies: - '@emnapi/core': 1.11.3 - '@emnapi/runtime': 1.11.3 - '@tybys/wasm-util': 0.10.4 - optional: true + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@radix-ui/rect@1.1.3': {} '@rolldown/pluginutils@1.0.0-beta.27': {} @@ -2408,11 +3636,38 @@ snapshots: optionalDependencies: '@module-federation/runtime-tools': 0.21.6 + '@testing-library/dom@10.4.2': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/runtime': 7.29.10 + '@types/aria-query': 5.0.4 + aria-query: 5.3.0 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + picocolors: 1.1.1 + pretty-format: 27.5.1 + + '@testing-library/react@16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@testing-library/dom': 10.4.2 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + '@types/react-dom': 18.3.7(@types/react@18.3.31) + + '@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)': + dependencies: + '@testing-library/dom': 10.4.2 + '@tybys/wasm-util@0.10.4': dependencies: tslib: 2.8.1 optional: true + '@types/aria-query@5.0.4': {} + '@types/babel__core@7.20.5': dependencies: '@babel/parser': 7.29.9 @@ -2434,6 +3689,13 @@ snapshots: dependencies: '@babel/types': 7.29.8 + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + '@types/esrecurse@4.3.1': {} '@types/estree@1.0.9': {} @@ -2556,6 +3818,48 @@ snapshots: transitivePeerDependencies: - supports-color + '@vitest/expect@3.2.7': + dependencies: + '@types/chai': 5.2.3 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.3.3 + tinyrainbow: 2.0.0 + + '@vitest/mocker@3.2.7(vite@5.4.21)': + dependencies: + '@vitest/spy': 3.2.7 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 5.4.21 + + '@vitest/pretty-format@3.2.7': + dependencies: + tinyrainbow: 2.0.0 + + '@vitest/runner@3.2.7': + dependencies: + '@vitest/utils': 3.2.7 + pathe: 2.0.3 + strip-literal: 3.1.0 + + '@vitest/snapshot@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@3.2.7': + dependencies: + tinyspy: 4.0.6 + + '@vitest/utils@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + loupe: 3.2.1 + tinyrainbow: 2.0.0 + accepts@1.3.8: dependencies: mime-types: 2.1.35 @@ -2600,10 +3904,24 @@ snapshots: ansi-colors@4.1.3: {} + ansi-regex@5.0.1: {} + ansi-styles@4.3.0: dependencies: color-convert: 2.0.1 + ansi-styles@5.2.0: {} + + aria-hidden@1.2.6: + dependencies: + tslib: 2.8.1 + + aria-query@5.3.0: + dependencies: + dequal: 2.0.3 + + assertion-error@2.0.1: {} + asynckit@0.4.0: {} at-least-node@1.0.0: {} @@ -2622,6 +3940,14 @@ snapshots: baseline-browser-mapping@2.11.28: {} + bcp-47-match@2.0.3: {} + + bcp-47@2.1.2: + dependencies: + is-alphabetical: 2.0.1 + is-alphanumerical: 2.0.1 + is-decimal: 2.0.1 + brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -2636,6 +3962,8 @@ snapshots: btoa@1.2.1: {} + cac@6.7.14: {} + cacheable@2.5.0: dependencies: '@cacheable/memory': 2.2.0 @@ -2651,11 +3979,39 @@ snapshots: caniuse-lite@1.0.30001815: {} + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + chalk@3.0.0: dependencies: ansi-styles: 4.3.0 supports-color: 7.2.0 + check-error@2.1.3: {} + + class-variance-authority@0.7.1: + dependencies: + clsx: 2.1.1 + + clsx@2.1.1: {} + + cmdk@1.1.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1): + dependencies: + '@radix-ui/react-compose-refs': 1.1.5(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-dialog': 1.3.1(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@radix-ui/react-id': 1.1.4(@types/react@18.3.31)(react@18.3.1) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + transitivePeerDependencies: + - '@types/react' + - '@types/react-dom' + color-convert@2.0.1: dependencies: color-name: 1.1.4 @@ -2695,12 +4051,23 @@ snapshots: csstype@3.2.3: {} + data-urls@8.0.0: + dependencies: + whatwg-mimetype: 5.0.0 + whatwg-url: 17.3.0 + transitivePeerDependencies: + - '@noble/hashes' + date-format@4.0.14: {} debug@4.4.3: dependencies: ms: 2.1.3 + decimal.js@10.6.0: {} + + deep-eql@5.0.2: {} + deep-equal@1.0.1: {} deep-is@0.1.4: {} @@ -2715,8 +4082,14 @@ snapshots: depd@2.0.0: {} + dequal@2.0.3: {} + destroy@1.2.0: {} + detect-node-es@1.1.0: {} + + dom-accessibility-api@0.5.16: {} + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -2729,10 +4102,14 @@ snapshots: encodeurl@2.0.0: {} + entities@9.0.0: {} + es-define-property@1.0.1: {} es-errors@1.3.0: {} + es-module-lexer@1.7.0: {} + es-object-atoms@1.1.2: dependencies: es-errors: 1.3.0 @@ -2853,12 +4230,18 @@ snapshots: estree-walker@2.0.2: {} + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + esutils@2.0.3: {} expand-tilde@2.0.2: dependencies: homedir-polyfill: 1.0.3 + expect-type@1.4.0: {} + fast-deep-equal@3.1.3: {} fast-json-stable-stringify@2.1.0: {} @@ -2941,6 +4324,8 @@ snapshots: hasown: 2.0.4 math-intrinsics: 1.1.0 + get-nonce@1.0.1: {} + get-proto@1.0.1: dependencies: dunder-proto: 1.0.1 @@ -2998,6 +4383,12 @@ snapshots: hookified@2.2.0: {} + html-encoding-sniffer@7.0.0: + dependencies: + '@exodus/bytes': 1.16.0 + transitivePeerDependencies: + - '@noble/hashes' + html-parse-stringify@3.1.0: dependencies: void-elements: 3.1.0 @@ -3046,16 +4437,27 @@ snapshots: ini@1.3.8: {} + is-alphabetical@2.0.1: {} + + is-alphanumerical@2.0.1: + dependencies: + is-alphabetical: 2.0.1 + is-decimal: 2.0.1 + is-core-module@2.17.0: dependencies: hasown: 2.0.4 + is-decimal@2.0.1: {} + is-extglob@2.1.1: {} is-glob@4.0.3: dependencies: is-extglob: 2.1.1 + is-potential-custom-element-name@1.0.1: {} + is-windows@1.0.2: {} isexe@2.0.0: {} @@ -3068,6 +4470,31 @@ snapshots: js-tokens@4.0.0: {} + js-tokens@9.0.1: {} + + jsdom@31.0.1: + dependencies: + '@exodus/bytes': 1.16.0 + bcp-47: 2.1.2 + bcp-47-match: 2.0.3 + data-urls: 8.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 7.0.0 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.3 + parse5: 8.1.1 + parse5-parser-stream: 8.1.1 + saxes: 6.0.0 + tough-cookie: 6.1.0 + undici: 8.13.1 + w3c-xmlserializer: 6.0.0 + webidl-conversions: 8.0.1 + whatwg-mimetype: 5.0.0 + whatwg-url: 17.3.0 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - '@noble/hashes' + jsesc@3.1.0: {} json-schema-traverse@0.4.1: {} @@ -3146,12 +4573,22 @@ snapshots: dependencies: js-tokens: 4.0.0 + loupe@3.2.1: {} + + lru-cache@11.5.3: {} + lru-cache@5.1.1: dependencies: yallist: 3.1.1 + lucide-react@0.552.0(react@18.3.1): + dependencies: + react: 18.3.1 + luxon@3.7.2: {} + lz-string@1.5.0: {} + magic-string@0.30.21: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -3215,6 +4652,14 @@ snapshots: parse-passwd@1.0.0: {} + parse5-parser-stream@8.1.1: + dependencies: + parse5: 8.1.1 + + parse5@8.1.1: + dependencies: + entities: 9.0.0 + parseurl@1.3.3: {} path-exists@4.0.0: {} @@ -3225,6 +4670,10 @@ snapshots: pathe@1.1.2: {} + pathe@2.0.3: {} + + pathval@2.0.1: {} + picocolors@1.1.1: {} picomatch@4.0.7: {} @@ -3239,6 +4688,12 @@ snapshots: prettier@3.9.10: {} + pretty-format@27.5.1: + dependencies: + ansi-regex: 5.0.1 + ansi-styles: 5.2.0 + react-is: 17.0.2 + proxy-from-env@2.1.0: {} punycode@2.3.1: {} @@ -3266,8 +4721,37 @@ snapshots: react-dom: 18.3.1(react@18.3.1) typescript: 5.9.3 + react-is@17.0.2: {} + react-refresh@0.17.0: {} + react-remove-scroll-bar@2.3.8(@types/react@18.3.31)(react@18.3.1): + dependencies: + react: 18.3.1 + react-style-singleton: 2.2.3(@types/react@18.3.31)(react@18.3.1) + tslib: 2.8.1 + optionalDependencies: + '@types/react': 18.3.31 + + react-remove-scroll@2.7.2(@types/react@18.3.31)(react@18.3.1): + dependencies: + react: 18.3.1 + react-remove-scroll-bar: 2.3.8(@types/react@18.3.31)(react@18.3.1) + react-style-singleton: 2.2.3(@types/react@18.3.31)(react@18.3.1) + tslib: 2.8.1 + use-callback-ref: 1.3.3(@types/react@18.3.31)(react@18.3.1) + use-sidecar: 1.1.3(@types/react@18.3.31)(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.31 + + react-style-singleton@2.2.3(@types/react@18.3.31)(react@18.3.1): + dependencies: + get-nonce: 1.0.1 + react: 18.3.1 + tslib: 2.8.1 + optionalDependencies: + '@types/react': 18.3.31 + react@18.3.1: dependencies: loose-envify: 1.4.0 @@ -3321,6 +4805,10 @@ snapshots: safe-buffer@5.2.1: {} + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + scheduler@0.23.2: dependencies: loose-envify: 1.4.0 @@ -3346,14 +4834,20 @@ snapshots: shebang-regex@3.0.0: {} + siginfo@2.0.0: {} + sorted-array-functions@1.3.0: {} source-map-js@1.2.2: {} + stackback@0.0.2: {} + statuses@1.5.0: {} statuses@2.0.2: {} + std-env@3.10.0: {} + streamroller@3.1.5: dependencies: date-format: 4.0.14 @@ -3362,25 +4856,54 @@ snapshots: transitivePeerDependencies: - supports-color + strip-literal@3.1.0: + dependencies: + js-tokens: 9.0.1 + supports-color@7.2.0: dependencies: has-flag: 4.0.0 supports-preserve-symlinks-flag@1.0.0: {} + tailwind-merge@3.7.0: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 + tinypool@1.1.1: {} + + tinyrainbow@2.0.0: {} + + tinyspy@4.0.6: {} + + tldts-core@7.6.0: {} + + tldts@7.6.0: + dependencies: + tldts-core: 7.6.0 + toidentifier@1.0.1: {} + tough-cookie@6.1.0: + dependencies: + tldts: 7.6.0 + + tr46@7.0.0: + dependencies: + punycode: 2.3.1 + ts-api-utils@2.5.0(typescript@5.9.3): dependencies: typescript: 5.9.3 - tslib@2.8.1: - optional: true + tslib@2.8.1: {} tsscmp@1.0.6: {} @@ -3407,6 +4930,8 @@ snapshots: typescript@5.9.3: {} + undici@8.13.1: {} + universalify@0.1.2: {} universalify@2.0.1: {} @@ -3423,12 +4948,45 @@ snapshots: dependencies: punycode: 2.3.1 + use-callback-ref@1.3.3(@types/react@18.3.31)(react@18.3.1): + dependencies: + react: 18.3.1 + tslib: 2.8.1 + optionalDependencies: + '@types/react': 18.3.31 + + use-sidecar@1.1.3(@types/react@18.3.31)(react@18.3.1): + dependencies: + detect-node-es: 1.1.0 + react: 18.3.1 + tslib: 2.8.1 + optionalDependencies: + '@types/react': 18.3.31 + use-sync-external-store@1.7.0(react@18.3.1): dependencies: react: 18.3.1 vary@1.1.2: {} + vite-node@3.2.4: + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 2.0.3 + vite: 5.4.21 + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + vite@5.4.21: dependencies: esbuild: 0.21.5 @@ -3437,8 +4995,62 @@ snapshots: optionalDependencies: fsevents: 2.3.3 + vitest@3.2.7(jsdom@31.0.1): + dependencies: + '@types/chai': 5.2.3 + '@vitest/expect': 3.2.7 + '@vitest/mocker': 3.2.7(vite@5.4.21) + '@vitest/pretty-format': 3.2.7 + '@vitest/runner': 3.2.7 + '@vitest/snapshot': 3.2.7 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.17 + tinypool: 1.1.1 + tinyrainbow: 2.0.0 + vite: 5.4.21 + vite-node: 3.2.4 + why-is-node-running: 2.3.0 + optionalDependencies: + jsdom: 31.0.1 + transitivePeerDependencies: + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + void-elements@3.1.0: {} + w3c-xmlserializer@6.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@8.0.1: {} + + whatwg-mimetype@5.0.0: {} + + whatwg-url@17.3.0: + dependencies: + '@exodus/bytes': 1.16.0 + tr46: 7.0.0 + webidl-conversions: 8.0.1 + transitivePeerDependencies: + - '@noble/hashes' + which@1.3.1: dependencies: isexe: 2.0.0 @@ -3447,10 +5059,19 @@ snapshots: dependencies: isexe: 2.0.0 + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + word-wrap@1.2.5: {} ws@8.18.0: {} + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + yallist@3.1.1: {} yocto-queue@0.1.0: {} diff --git a/ui/public/guide/android-plugins.webp b/ui/public/guide/android-plugins.webp new file mode 100644 index 0000000..48620d2 Binary files /dev/null and b/ui/public/guide/android-plugins.webp differ diff --git a/ui/public/guide/android-talk.webp b/ui/public/guide/android-talk.webp new file mode 100644 index 0000000..64f755e Binary files /dev/null and b/ui/public/guide/android-talk.webp differ diff --git a/ui/public/guide/android.svg b/ui/public/guide/android.svg new file mode 100644 index 0000000..080c6a5 --- /dev/null +++ b/ui/public/guide/android.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/ui/public/guide/browser-talk.en.webp b/ui/public/guide/browser-talk.en.webp new file mode 100644 index 0000000..47d59a7 Binary files /dev/null and b/ui/public/guide/browser-talk.en.webp differ diff --git a/ui/public/guide/browser-talk.fi.webp b/ui/public/guide/browser-talk.fi.webp new file mode 100644 index 0000000..54d8ae0 Binary files /dev/null and b/ui/public/guide/browser-talk.fi.webp differ diff --git a/ui/public/guide/browser-talk.sv.webp b/ui/public/guide/browser-talk.sv.webp new file mode 100644 index 0000000..25af271 Binary files /dev/null and b/ui/public/guide/browser-talk.sv.webp differ diff --git a/ui/src/App.tsx b/ui/src/App.tsx index ad23853..db297c4 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -1,11 +1,12 @@ +import { Flag } from "lucide-react"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import { StatusDot } from "@/components/StatusDot"; +import { addTranslations, NS } from "@/i18n"; +import { MISSIONS, pathLabel } from "@/paths"; import { Admin } from "./admin/Admin"; -import { addTranslations, NS } from "./i18n"; -import { Flag } from "./icons"; -import { MISSIONS, pathLabel } from "./paths"; -import * as ui from "./ui"; +import { OnboardingHandler } from "./guide/OnboardingHandler"; import { Talk } from "./voice/Talk"; // What mumblermapi's /api/v2/clients/data returns for the signed-in user, by way of rmapi @@ -15,50 +16,75 @@ export interface ClientData { nets?: string[]; } +// What rmui passes every remote about the signed-in user besides data +export interface Meta { + callsign?: string; + // Whether guides may open by themselves, and the way to turn that off for every product + autoOpenGuides?: boolean; + onDisableGuides?: () => void; +} + interface Props { data?: ClientData; + meta?: Meta; } -// The signed-in user's voice state and nets, readable without a click function YouLine({ data }: { data: ClientData }) { const { t } = useTranslation(NS); const nets = data.nets ?? []; return ( -
-
+
+
{data.voice === true && ( - - + + {t("voiceOn")} )} {data.voice === false && ( - - + + {t("voiceOff")} )} {data.voice === false ? null : nets.length ? ( nets.map((net) => ( - - {net.startsWith(MISSIONS) && } + + {net.startsWith(MISSIONS) && ( + + )} {pathLabel(net)} )) ) : ( - {t("openNetsOnly")} + + {t("openNetsOnly")} + )}
-

{t("atakHint")}

+

{t("atakHint")}

); } -function VoicePage({ data }: { data: ClientData }) { +function VoicePage({ data, meta }: { data: ClientData; meta: Meta }) { const { t } = useTranslation(NS); return ( -
-

{t("title")}

+
+
+

{t("title")}

+ {/* rmui passes {} until rmapi answers, and the guide decides on mount whether it opens */} + {data.voice !== undefined && ( + + )} +
{data.voice !== false && } {data.admin && } @@ -66,7 +92,7 @@ function VoicePage({ data }: { data: ClientData }) { ); } -export default function MumbleApp({ data = {} }: Props) { +export default function MumbleApp({ data = {}, meta = {} }: Props) { const { i18n } = useTranslation(); const [ready, setReady] = useState(false); @@ -74,5 +100,5 @@ export default function MumbleApp({ data = {} }: Props) { void addTranslations(i18n).then(() => setReady(true)); }, [i18n]); - return ready ? : null; + return ready ? : null; } diff --git a/ui/src/admin/AccessChoice.tsx b/ui/src/admin/AccessChoice.tsx new file mode 100644 index 0000000..7770df6 --- /dev/null +++ b/ui/src/admin/AccessChoice.tsx @@ -0,0 +1,67 @@ +import * as ToggleGroup from "@radix-ui/react-toggle-group"; +import { useId, type RefObject } from "react"; +import { useTranslation } from "react-i18next"; + +import type { Access } from "@/api"; +import { NS } from "@/i18n"; +import { cn } from "@/lib/utils"; +import type { NetNode } from "./tree"; +import type { TreeCtx } from "./types"; + +const CHOICES: [Access, string][] = [ + ["open", "admin.choiceOpen"], + ["invite", "admin.choiceInvite"], + ["inherit", "admin.choiceInherit"], +]; + +// Open, members only, or (below the top level) as the net above. A choice changes who can talk at once, so +// arrow keys only move focus; Space, Enter or a click chooses. +export function AccessChoice({ + node, + ctx, + group, + onChoose, +}: { + node: NetNode; + ctx: TreeCtx; + group: RefObject; + onChoose: (access: Access) => void; +}) { + const { t } = useTranslation(NS); + const { id, access } = node.channel; + const labelId = useId(); + const choices = node.depth ? CHOICES : CHOICES.slice(0, 2); + return ( +
+ + {t("admin.accessLabel")} + + v && v !== access && onChoose(v as Access)} + aria-labelledby={labelId} + className="inline-flex h-12 w-full items-center rounded-lg bg-muted p-px" + > + {choices.map(([value, label]) => ( + + {t(label)} + + ))} + +
+ ); +} diff --git a/ui/src/admin/Admin.tsx b/ui/src/admin/Admin.tsx index bbeb5fc..1df97a5 100644 --- a/ui/src/admin/Admin.tsx +++ b/ui/src/admin/Admin.tsx @@ -1,741 +1,69 @@ import { - useCallback, useEffect, useId, useMemo, useRef, useState, - type ChangeEvent, - type KeyboardEvent as ReactKeyboardEvent, - type ReactNode, type RefObject, } from "react"; import { useTranslation } from "react-i18next"; -import { - api, - type Channel, - type Mission, - type Template, - type User, -} from "../api"; -import { NS, RAW } from "../i18n"; -import { - AlertCircle, - CheckCircle, - CornerLeftUp, - Download, - ListPlus, - Lock, - MoreHorizontal, - Plus, - Search, - Trash, - Upload, - X, -} from "../icons"; -import { - deriveTree, - foldedAncestor, - keyExists, - parentOf, - type Derived, -} from "../paths"; -import * as ui from "../ui"; -import { MissionDetails, NetDetails } from "./Details"; -import { - InlineConfirm, - MissionRow, - NameForm, - NetCard, - adding, -} from "./NetTree"; -import { TemplatePanel } from "./Templates"; -import type { FocusTarget, Mode, Open, Run, TreeCtx } from "./types"; -import { UsersList } from "./Users"; +import { api } from "@/api"; +import { Tabs, TabsContent } from "@/components/ui/tabs"; +import { NS } from "@/i18n"; +import { read, write } from "@/lib/storage"; +import { ClearPlan } from "./ClearPlan"; +import { useAdminData } from "./hooks/useAdminData"; +import { useFocusRequests } from "./hooks/useFocusRequests"; +import { useFolds } from "./hooks/useFolds"; +import { useNotice } from "./hooks/useNotice"; +import { usePlan } from "./hooks/usePlan"; +import { useRun } from "./hooks/useRun"; +import { useWide } from "./hooks/useWide"; +import { MissionDetails } from "./MissionDetails"; +import { NameForm, adding } from "./NameForm"; +import { NetDetails } from "./NetDetails"; +import { NetsTab } from "./NetsTab"; +import { NoticeLine } from "./NoticeLine"; +import { TemplatePanel } from "./TemplatePanel"; +import { Toolbar } from "./Toolbar"; +import { deriveTree, foldedAncestor, keyExists, parentOf } from "./tree"; +import type { Data, Mode, Open, Tab, Top, TreeCtx } from "./types"; +import { UsersList } from "./UsersList"; -// How often presence, nets and missions are fetched again while the page is visible -const REFRESH_MS = 10_000; -const NOTICE_MS = 6_000; -// Larger plans start collapsed to the top level -const EXPAND_UP_TO = 30; -const TAB_KEY = "mumble.adminTab"; -const FOLDS_KEY = "mumble.folds"; // The workspace width from which an open net shows beside the list instead of as its own screen const WIDE_FROM = 760; - -type Tab = "nets" | "users"; -// What shows at the top of the net list: a new net's name, the template chooser, or removing the whole plan -type Top = "net" | "templates" | "clear" | null; - -interface MenuItem { - label: string; - icon: ReactNode; - action: () => void; -} -type TabIds = Record; - -interface Data { - channels: Channel[]; - users: User[]; - missions: Mission[]; -} - -interface Notice { - kind: "error" | "ok"; - text: string; -} +const TAB_KEY = "mumble.adminTab"; function readTab(): Tab { - try { - return localStorage.getItem(TAB_KEY) === "users" ? "users" : "nets"; - } catch { - return "nets"; - } + return read(TAB_KEY) === "users" ? "users" : "nets"; } function saveTab(tab: Tab) { - try { - localStorage.setItem(TAB_KEY, tab); - } catch { - // storage blocked: the tab is simply not remembered - } -} - -// The admin's fold choices by channel id, in this browser only; anything malformed is ignored -function readFolds(): Map { - try { - const raw: unknown = JSON.parse(localStorage.getItem(FOLDS_KEY) ?? "{}"); - if ( - raw && - typeof raw === "object" && - !Array.isArray(raw) && - Object.values(raw).every((v) => typeof v === "boolean") - ) { - return new Map( - Object.entries(raw as Record).map(([id, open]) => [ - Number(id), - open, - ]), - ); - } - } catch { - // storage blocked or not JSON: folds live in memory only - } - return new Map(); -} - -function saveFolds(folds: Map) { - try { - localStorage.setItem(FOLDS_KEY, JSON.stringify(Object.fromEntries(folds))); - } catch { - // storage blocked: folds live in memory only - } -} - -// Whether the workspace (not the viewport: rmui's sidebar takes part of it) is wide enough for the side panel -function useWide(ref: RefObject, min: number): boolean { - const [wide, setWide] = useState(false); - useEffect(() => { - const element = ref.current; - if (!element) return; - const observer = new ResizeObserver(([entry]) => - setWide(entry.contentRect.width >= min), - ); - observer.observe(element); - return () => observer.disconnect(); - }, [ref, min]); - return wide; -} - -function download(yaml: string) { - const url = URL.createObjectURL( - new Blob([yaml], { type: "application/yaml" }), - ); - const link = document.createElement("a"); - link.href = url; - link.download = "voice-channels.yaml"; - link.click(); - URL.revokeObjectURL(url); -} - -const messageOf = (error: unknown) => - error instanceof Error ? error.message : String(error); - -// Templates, import, export and removing the plan are rare, so they sit behind [⋯] -function MoreMenu({ - trigger, - items, -}: { - trigger: RefObject; - items: MenuItem[]; -}) { - const { t } = useTranslation(NS); - const [open, setOpen] = useState(false); - const wrap = useRef(null); - - useEffect(() => { - if (!open) return; - const onPointer = (event: PointerEvent) => { - if (!wrap.current?.contains(event.target as Node)) setOpen(false); - }; - const onKey = (event: KeyboardEvent) => { - if (event.key === "Escape") { - setOpen(false); - trigger.current?.focus(); - } - }; - window.addEventListener("pointerdown", onPointer); - window.addEventListener("keydown", onKey); - return () => { - window.removeEventListener("pointerdown", onPointer); - window.removeEventListener("keydown", onKey); - }; - }, [open, trigger]); - - const choose = (action: () => void) => () => { - setOpen(false); - action(); - }; - - // Arrow keys, Home and End move between the items, as in any menu - const onMenuKey = (event: ReactKeyboardEvent) => { - const items = Array.from( - event.currentTarget.querySelectorAll("[role=menuitem]"), - ); - const at = items.indexOf(document.activeElement as HTMLElement); - const next = { - ArrowDown: (at + 1) % items.length, - ArrowUp: (at - 1 + items.length) % items.length, - Home: 0, - End: items.length - 1, - }[event.key]; - if (next === undefined) return; - event.preventDefault(); - items[next].focus(); - }; - - return ( -
{ - if (!wrap.current?.contains(event.relatedTarget)) { - setOpen(false); - } - }} - > - - {open && ( -
- {items.map((item, index) => ( - - ))} -
- )} -
- ); -} - -function Toolbar({ - tab, - pickTab, - ids, - derived, - users, - query, - setQuery, - addButton, - onAddNet, - moreButton, - menu, -}: { - tab: Tab; - pickTab: (tab: Tab) => void; - ids: TabIds; - derived: Derived | null; - users: User[]; - query: string; - setQuery: (query: string) => void; - addButton: RefObject; - onAddNet: () => void; - moreButton: RefObject; - menu: MenuItem[]; -}) { - const { t } = useTranslation(NS); - const tabButtons = useRef>>({}); - const active = users.filter((u) => !u.revoked); - const online = active.filter((u) => u.online?.length).length; - const tabs: [Tab, string][] = [ - ["nets", t("admin.tabNets")], - ["users", t("admin.tabUsers")], - ]; - return ( -
-
{ - const other: Tab = tab === "nets" ? "users" : "nets"; - const next = ( - { - ArrowLeft: other, - ArrowRight: other, - Home: "nets", - End: "users", - } as Record - )[event.key]; - if (!next) return; - event.preventDefault(); - pickTab(next); - tabButtons.current[next]?.focus(); - }} - > - {tabs.map(([id, label]) => ( - - ))} -
-
-
- - setQuery(event.target.value)} - onKeyDown={(event) => { - if (event.key === "Escape") setQuery(""); - }} - /> - {query && ( - - )} -
- {tab === "nets" && ( - <> - - - - )} -
-
- ); -} - -function NoticeLine({ - notice, - dismiss, -}: { - notice: Notice; - dismiss: () => void; -}) { - const { t } = useTranslation(NS); - const error = notice.kind === "error"; - const Icon = error ? AlertCircle : CheckCircle; - return ( -
- -

{notice.text}

- -
- ); -} - -function GroupHeading({ - label, - count, - online, - known, - testId, -}: { - label: string; - count: number; - online: number; - known: boolean; - testId: string; -}) { - const { t } = useTranslation(NS); - return ( -
- - {label} {count} - - {!known ? ( - {t("admin.presenceUnknown")} - ) : online > 0 ? ( - - - ) : null} -
- ); -} - -function PhoneLegend() { - const { t } = useTranslation(NS); - return ( -
- - - {t("admin.legendMembers")} - - - - {t("admin.legendFollows")} - - {t("admin.legendOpen")} -
- ); -} - -function NetsTab({ - data, - derived, - ctx, - query, - top, - onAddNet, - onTemplates, - fileInput, - details, -}: { - data: Data; - derived: Derived; - ctx: TreeCtx; - query: string; - // The new net's form, the template chooser or the plan's removal, above the cards - top: ReactNode; - onAddNet: () => void; - // Null when no template is on offer - onTemplates: (() => void) | null; - fileInput: RefObject; - details: ReactNode; -}) { - const { t } = useTranslation(NS); - // On a narrow workspace the open net is its own screen in place of the list - if (!ctx.wide && details) return details; - const q = query.trim(); - const empty = !data.channels.length && !q; - const list = - q && !derived.unitMatches && !derived.missionMatches ? ( -

{t("admin.noMatches", { q, ...RAW })}

- ) : ( - <> - {empty && !top ? ( -
- {t("admin.empty")} -
- {onTemplates && ( - - )} - - -
-
- ) : ( - (derived.unitMatches > 0 || top) && ( -
- - {derived.unitMatches > 0 && } -
    - {top &&
  • {top}
  • } - {derived.roots.map((node) => ( - - ))} -
-
- ) - )} - {derived.missionMatches > 0 && ( -
- -
    - {derived.missions - .filter((m) => m.match) - .map((node, index) => ( - - ))} -
-
- )} - - ); - // The split stays in place while nets open and close, so the list never remounts under the pointer - return ctx.wide ? ( -
-
{list}
- {details} -
- ) : ( - list - ); + write(TAB_KEY, tab); } export function Admin() { const { t } = useTranslation(NS); - const [data, setData] = useState(null); const [tab, setTab] = useState(readTab); const [query, setQuery] = useState(""); const [open, setOpen] = useState(null); const [top, setTop] = useState(null); const topNow = useRef(null); - const [templates, setTemplates] = useState([]); - const [overrides, setOverrides] = useState>(readFolds); - // The folds as last written, so a fold made while a sub-net add was in flight is not undone by it - const folds = useRef(overrides); - const [notice, setNotice] = useState(null); - const [pending, setPending] = useState>(() => new Set()); - // Busy controls stay focusable, so a second press must be refused here rather than by the browser - const inFlight = useRef(new Set()); - // The row control asked to take focus, and the net whose title should; each consumed once - const focusTarget = useRef(null); - const titleFocus = useRef(null); + // The button that takes focus once the top panel has gone; a confirmation holds focus until then + const focusAfterTop = useRef | null>( + null, + ); const fileInput = useRef(null); const addButton = useRef(null); const moreButton = useRef(null); const wrap = useRef(null); const wide = useWide(wrap, WIDE_FROM); - const baseId = useId(); - const ids: TabIds = { - nets: `${baseId}-nets`, - users: `${baseId}-users`, - panel: `${baseId}-panel`, - }; - const detailsId = `${baseId}-details`; - // The notice's auto-clear timer, and a counter so a slow older load never overwrites a newer one - const held = useRef<{ timer?: number; seq: number }>({ seq: 0 }); - // What a poll needs from the latest render: the open net, the data it came from, and how to focus a row - const latest = useRef<{ - open: Open | null; - data: Data | null; - focusNet: (key: string | null) => void; - }>({ open: null, data: null, focusNet: () => undefined }); - - const showNotice = useCallback((next: Notice | null) => { - window.clearTimeout(held.current.timer); - setNotice(next); - if (next?.kind === "ok") { - held.current.timer = window.setTimeout(() => setNotice(null), NOTICE_MS); - } - }, []); - - const fail = useCallback( - (error: unknown) => - showNotice({ - kind: "error", - text: t("admin.error", { message: messageOf(error), ...RAW }), - }), - [t, showNotice], - ); - - const load = useCallback(() => { - const seq = ++held.current.seq; - return Promise.all([api.channels(), api.users(), api.missions()]).then( - ([channels, users, missions]) => { - if (seq !== held.current.seq) return; - // A net deleted elsewhere closes its details; focus inside them moves to its parent's row, else - // to the first card - const { open: current, data: before, focusNet } = latest.current; - if (current && !keyExists(current.key, channels, missions)) { - const details = document.getElementById(detailsId); - if (details?.contains(document.activeElement)) { - const parent = - current.key.startsWith("u:") && before - ? parentOf(before.channels, Number(current.key.slice(2))) - : null; - const target = parent || channels[0]?.id; - focusNet(target ? `u:${target}` : null); - } - } - setOpen((cur) => - cur && keyExists(cur.key, channels, missions) ? cur : null, - ); - setData({ channels, users, missions }); - }, - fail, - ); - }, [fail, detailsId]); - - useEffect(() => { - const refresh = () => { - if (!document.hidden) void load(); - }; - refresh(); - const timer = window.setInterval(refresh, REFRESH_MS); - document.addEventListener("visibilitychange", refresh); - return () => { - window.clearInterval(timer); - document.removeEventListener("visibilitychange", refresh); - }; - }, [load]); - - useEffect(() => { - const timers = held.current; - return () => window.clearTimeout(timers.timer); - }, []); - - // Templates come with the image and do not change while the page is open - useEffect(() => { - api.templates().then(setTemplates, fail); - }, [fail]); - - const run: Run = useCallback( - async (key, call, onOk) => { - if (inFlight.current.has(key)) return false; - inFlight.current.add(key); - setPending((keys) => new Set(keys).add(key)); - try { - const result = await call(); - setNotice((current) => (current?.kind === "error" ? null : current)); - onOk?.(result); - await load(); - return true; - } catch (error) { - fail(error); - return false; - } finally { - inFlight.current.delete(key); - setPending((keys) => { - const next = new Set(keys); - next.delete(key); - return next; - }); - } - }, - [load, fail], - ); + const detailsId = useId(); + const { notice, showNotice, fail, clearError } = useNotice(); + const { data, templates, load } = useAdminData(fail, closeRemoved); + const { run, pending } = useRun(load, fail, clearError); + const focus = useFocusRequests(); const derived = useMemo( () => data && deriveTree(data.channels, data.users, data.missions, query), @@ -743,40 +71,62 @@ export function Admin() { ); const searching = query.trim() !== ""; - const expandAll = (derived?.unitCount ?? 0) <= EXPAND_UP_TO; - // While searching every matching card is shown unfolded, and the saved folds are left alone - const isExpanded = (id: number) => - searching || (overrides.get(id) ?? expandAll); + const { isExpanded, setExpanded } = useFolds(derived, searching); // Asks for focus on a net's row; a row hidden by a fold hands it to that card's chevron const focusNet = (key: string | null) => { - focusTarget.current = null; - if (key === null) return; + if (key === null) { + focus.askRow(null); + return; + } const center = !wide; const fold = key.startsWith("u:") && derived ? foldedAncestor(Number(key.slice(2)), derived.byId, isExpanded) : null; - focusTarget.current = + focus.askRow( fold === null ? { key, part: "row", center } - : { key: `u:${fold}`, part: "fold", center }; + : { key: `u:${fold}`, part: "fold", center }, + ); }; + // A net deleted elsewhere closes its details; focus inside them moves to its parent's row, else to the + // first card + function closeRemoved({ channels, missions }: Data) { + if (open && !keyExists(open.key, channels, missions)) { + const details = document.getElementById(detailsId); + if (details?.contains(document.activeElement)) { + const parent = + open.key.startsWith("u:") && data + ? parentOf(data.channels, Number(open.key.slice(2))) + : null; + const target = parent || channels[0]?.id; + focusNet(target ? `u:${target}` : null); + } + } + setOpen((current) => + current && keyExists(current.key, channels, missions) ? current : null, + ); + } + useEffect(() => { - latest.current = { open, data, focusNet }; topNow.current = top; + if (top === null && focusAfterTop.current) { + focusAfterTop.current.current?.focus(); + focusAfterTop.current = null; + } }); const openNet = (key: string) => { setTop(null); - focusTarget.current = null; + focus.askRow(null); // On a wide workspace the selected row toggles its details; focus stays on the row if (wide && open?.key === key) { setOpen(null); return; } - titleFocus.current = key; + focus.askTitle(key); setOpen({ key, mode: "view" }); }; @@ -785,19 +135,9 @@ export function Admin() { setOpen(null); }; - const setExpanded = (id: number, expanded: boolean) => { - // Ids that left the tree are pruned on every write - const next = new Map( - [...folds.current].filter(([known]) => derived?.byId.has(known)), - ).set(id, expanded); - folds.current = next; - setOverrides(next); - saveFolds(next); - }; - - // Panels and forms would take focus again when Verkot is shown, so they close with the tab + // Panels and forms would take focus again when the Nets tab is shown, so they close with the tab const pickTab = (next: Tab) => { - focusTarget.current = null; + focus.askRow(null); setTop(null); setOpen((current) => current && { ...current, mode: "view" }); setTab(next); @@ -806,21 +146,21 @@ export function Admin() { // A phone's net screen gives way to the results as soon as the query changes; focus stays in the field const search = (next: string) => { - focusTarget.current = null; + focus.askRow(null); if (!wide) setOpen(null); setQuery(next); }; - // The search would hide the form behind 'Ei osumia' and filter out the new net, so it is cleared first + // The search would hide the form behind the no-matches line and filter out the new net, so it is cleared first const openTop = (next: Exclude) => { search(""); setOpen(null); setTop(next); }; - const closeTop = (focus: RefObject) => { + const closeTop = (button: RefObject) => { + focusAfterTop.current = button; setTop(null); - focus.current?.focus(); }; // A request's panel closes when it is done, unless something else has taken its place meanwhile @@ -834,86 +174,23 @@ export function Admin() { () => api.addChannel(name, 0), ({ id }) => { setTop(null); - titleFocus.current = `u:${id}`; + focus.askTitle(`u:${id}`); setOpen({ key: `u:${id}`, mode: "view" }); }, ); - const onFile = (event: ChangeEvent) => { - const input = event.currentTarget; - const file = input.files?.[0]; - if (!file) return; - void file - .text() - .then((yaml) => - run( - "import", - () => api.importPlan(yaml), - ({ created }) => - showNotice({ - kind: "ok", - text: t("admin.imported", { count: created }), - }), - ), - ) - .catch(fail) - .finally(() => { - input.value = ""; - }); - }; - - const onExport = () => void api.exportPlan().then(download, fail); - - const applyTemplate = (template: Template) => - void run( - `tpl:${template.id}`, - () => api.applyTemplate(template.id), - ({ created }) => { - closeIfStill("templates"); - showNotice({ - kind: "ok", - text: t("admin.applied", { count: created }), - }); - }, - ); - - const clearPlan = () => - void run("clear", api.clearChannels, ({ removed }) => { - setOpen(null); - closeIfStill("clear"); - showNotice({ kind: "ok", text: t("admin.cleared", { count: removed }) }); - }); - - const menu: MenuItem[] = [ - ...(templates.length - ? [ - { - label: t("admin.useTemplate"), - icon: , - action: () => openTop("templates"), - }, - ] - : []), - { - label: t("admin.importPlan"), - icon: , - action: () => fileInput.current?.click(), - }, - { - label: t("admin.exportPlan"), - icon: , - action: onExport, - }, - ...(data?.channels.length - ? [ - { - label: t("admin.clearAll"), - icon: , - action: () => openTop("clear"), - }, - ] - : []), - ]; + const hasNets = !!data?.channels.length; + const plan = usePlan({ + templates, + hasNets, + fileInput, + run, + showNotice, + fail, + openTop, + closeIfStill, + onCleared: () => setOpen(null), + }); const topPanel = top === "net" ? ( @@ -926,35 +203,11 @@ export function Admin() { ) : top === "templates" ? ( closeTop(moreButton)} /> - ) : top === "clear" && derived ? ( - r.subtreeOnline) && t("admin.movesOut"), - t("admin.clearExportFirst"), - ] - .filter(Boolean) - .join(" ")} - busy={pending.has("clear")} - confirmLabel={t("admin.removeAll")} - extra={ - - } - onCancel={() => closeTop(moreButton)} - onConfirm={clearPlan} - /> ) : null; const openId = @@ -963,7 +216,8 @@ export function Admin() { const openMission = open?.key.startsWith("m:") ? derived?.missions.find((m) => m.mission.name === open.key.slice(2)) : undefined; - const tree: Omit = { + const ctx: TreeCtx | null = derived && { + derived, users: data?.users ?? [], open, wide, @@ -979,104 +233,112 @@ export function Admin() { setExpanded, // The open net hidden by a fold is marked on that card's header (wide only: a phone hides the list) markedFold: - wide && openId !== null && derived + wide && openId !== null ? foldedAncestor(openId, derived.byId, isExpanded) : null, - takeFocus: (key, part) => { - const target = focusTarget.current; - if (target?.key !== key || target.part !== part) return null; - focusTarget.current = null; - return target; - }, - takeTitleFocus: (key) => { - if (titleFocus.current !== key) return false; - titleFocus.current = null; - return true; - }, + takeFocus: focus.takeFocus, + takeTitleFocus: focus.takeTitleFocus, }; - // While a net is open on Verkot, the one notice slot sits at the top of its details, where the action was + // While a net is open on the Nets tab, the one notice slot sits at the top of its details, where the action was const noticeLine = notice && ( showNotice(null)} /> ); const detailsShown = tab === "nets" && (!!openUnit || !!openMission); const details = - derived && open && openUnit ? ( + ctx && open && openUnit ? ( - ) : derived && open && openMission ? ( + ) : ctx && open && openMission ? ( ) : null; + const loading = ( +

+ {t("admin.loading")} +

+ ); + return ( -
- openTop("net")} - moreButton={moreButton} - menu={menu} - /> - - {!detailsShown && noticeLine} -
{ - if (event.key === "Escape" && tab === "nets" && open) { - event.stopPropagation(); - closeNet(); - } - }} - > - {!data || !derived ? ( -

{t("admin.loading")}

- ) : tab === "nets" ? ( - + pickTab(value as Tab)}> + openTop("net")} + moreButton={moreButton} + menu={plan.menu} + /> + + {top === "clear" && derived && ( + openTop("net")} - onTemplates={templates.length ? () => openTop("templates") : null} - fileInput={fileInput} - details={details} - /> - ) : ( - closeTop(moreButton)} /> )} -
+ {!detailsShown && noticeLine} + { + if (event.key === "Escape" && open) { + event.stopPropagation(); + closeNet(); + } + }} + > + {data && ctx ? ( + openTop("net")} + onTemplates={templates.length ? () => openTop("templates") : null} + fileInput={fileInput} + details={details} + /> + ) : ( + loading + )} + + + {data && derived ? ( + + ) : ( + loading + )} + +
); } diff --git a/ui/src/admin/ClearPlan.tsx b/ui/src/admin/ClearPlan.tsx new file mode 100644 index 0000000..9353a7b --- /dev/null +++ b/ui/src/admin/ClearPlan.tsx @@ -0,0 +1,44 @@ +import { Download } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { Button } from "@/components/ui/button"; +import { NS } from "@/i18n"; +import { Confirm } from "./Confirm"; +import type { Derived } from "./tree"; + +export function ClearPlan({ + derived, + busy, + onExport, + onClear, + onClose, +}: { + derived: Derived; + busy: boolean; + onExport: () => void; + onClear: () => void; + onClose: () => void; +}) { + const { t } = useTranslation(NS); + return ( + r.subtreeOnline) && t("admin.movesOut"), + t("admin.clearExportFirst"), + ] + .filter(Boolean) + .join(" ")} + busy={busy} + confirmLabel={t("admin.removeAll")} + extra={ + + } + onCancel={onClose} + onConfirm={onClear} + /> + ); +} diff --git a/ui/src/admin/Confirm.tsx b/ui/src/admin/Confirm.tsx new file mode 100644 index 0000000..5c3b7c5 --- /dev/null +++ b/ui/src/admin/Confirm.tsx @@ -0,0 +1,76 @@ +import type { ReactNode } from "react"; +import { useTranslation } from "react-i18next"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { buttonVariants } from "@/components/ui/button"; +import { NS } from "@/i18n"; + +// Open while rendered: the caller closes it and moves focus. It cannot be cancelled once the request is sent. +export function Confirm({ + title, + detail, + busy, + onCancel, + onConfirm, + confirmLabel, + extra, +}: { + title: string; + detail?: string; + busy: boolean; + onCancel: () => void; + onConfirm: () => void; + confirmLabel?: string; + extra?: ReactNode; +}) { + const { t } = useTranslation(NS); + return ( + { + if (!busy) onCancel(); + }} + > + event.preventDefault()} + // Esc closes the confirmation only, not the net it sits in + onKeyDown={(event) => { + if (event.key === "Escape") event.stopPropagation(); + }} + > + + {title} + {detail && {detail}} + + + {extra} + + {t("admin.cancel")} + + { + // Stays open until the request is done + event.preventDefault(); + onConfirm(); + }} + > + {confirmLabel ?? t("admin.remove")} + + + + + ); +} diff --git a/ui/src/admin/Details.tsx b/ui/src/admin/Details.tsx deleted file mode 100644 index 199c77c..0000000 --- a/ui/src/admin/Details.tsx +++ /dev/null @@ -1,781 +0,0 @@ -import { - useEffect, - useId, - useRef, - useState, - type ReactNode, - type RefObject, -} from "react"; -import { useTranslation } from "react-i18next"; - -import { api, type Access, type ChannelEdit } from "../api"; -import { NS, RAW } from "../i18n"; -import { - ArrowLeft, - CornerLeftUp, - Flag, - Loader, - Lock, - Pencil, - Plus, - Trash, - X, -} from "../icons"; -import { - ancestors, - focusAfterRemove, - pathLabel, - type MissionNode, - type NetNode, - type Rule, -} from "../paths"; -import * as ui from "../ui"; -import { MemberPicker } from "./MemberPicker"; -import { InlineConfirm, NameForm, adding, ruleSentence } from "./NetTree"; -import type { Mode, TreeCtx } from "./types"; - -function InNet({ callsigns }: { callsigns: string[] }) { - const { t } = useTranslation(NS); - if (!callsigns.length) return null; - return ( -

- - {t("admin.inNetNow")} - {callsigns.join(", ")} -

- ); -} - -function AccessLine({ rule }: { rule: Rule }) { - const { t } = useTranslation(NS); - const Icon = - rule.kind === "follows" ? CornerLeftUp : rule.kind === "open" ? null : Lock; - return ( -

- {Icon && } - {ruleSentence(t, rule)} -

- ); -} - -const CHOICES: [Access, string][] = [ - ["open", "admin.choiceOpen"], - ["invite", "admin.choiceInvite"], - ["inherit", "admin.choiceInherit"], -]; - -// Open, members only, or (below the top level) as the net above. A choice changes who can talk at once, so -// arrow keys only move focus; Space, Enter or a click chooses. -function AccessChoice({ - node, - ctx, - group, - onChoose, -}: { - node: NetNode; - ctx: TreeCtx; - group: RefObject; - onChoose: (access: Access) => void; -}) { - const { t } = useTranslation(NS); - const { id, access } = node.channel; - const labelId = useId(); - const choices = node.depth ? CHOICES : CHOICES.slice(0, 2); - const current = choices.some(([value]) => value === access) ? access : "open"; - const buttons = useRef<(HTMLButtonElement | null)[]>([]); - return ( -
- - {t("admin.accessLabel")} - -
{ - const step = { - ArrowRight: 1, - ArrowDown: 1, - ArrowLeft: -1, - ArrowUp: -1, - }[event.key]; - if (step === undefined) return; - event.preventDefault(); - const at = buttons.current.indexOf( - document.activeElement as HTMLButtonElement, - ); - const next = (at + step + choices.length) % choices.length; - buttons.current[next]?.focus(); - }} - > - {choices.map(([value, label], index) => ( - - ))} -
-
- ); -} - -// The open net's name and description; Enter in the name saves, Esc cancels -function EditForm({ - node, - ctx, - onDone, -}: { - node: NetNode; - ctx: TreeCtx; - onDone: () => void; -}) { - const { t } = useTranslation(NS); - const { channel } = node; - const warnId = useId(); - const [name, setName] = useState(channel.name); - const [description, setDescription] = useState(channel.description); - const key = `edit:${channel.id}`; - const renamed = name.trim() !== channel.name; - // Murmur recreates a renamed net, so the warning is read out with the name field and Save - const warn = renamed && node.subtreeOnline; - const describedBy = warn ? warnId : undefined; - const ready = - name.trim() !== "" && (renamed || description !== channel.description); - const save = () => { - if (!ready) return; - const edit: ChannelEdit = {}; - if (renamed) edit.name = name.trim(); - if (description !== channel.description) edit.description = description; - void ctx.run(key, () => api.editChannel(channel.id, edit), onDone); - }; - return ( -
{ - event.preventDefault(); - save(); - }} - onKeyDown={(event) => { - if (event.key === "Escape") { - event.stopPropagation(); - onDone(); - } - }} - > - -