diff --git a/src/hhstream_mcp/__init__.py b/src/hhstream_mcp/__init__.py index 29d51eb..8e20efb 100644 --- a/src/hhstream_mcp/__init__.py +++ b/src/hhstream_mcp/__init__.py @@ -41,3 +41,16 @@ __version__ = "0.1.0" #: an MCP client configuration block is expected to use for it, so a log line #: and a config entry can be matched up by eye. SERVER_NAME = "hhstream" + +#: The HTTP transport's defaults. Here rather than in +#: :mod:`hhstream_mcp.http` because ``server.py`` needs them to build its +#: argument parser, and importing that module to read three numbers would make +#: the stdio transport pay for ``starlette`` and ``uvicorn`` at startup. +#: +#: Loopback, deliberately: binding somewhere a LAN can reach is a second +#: decision, and it wants a firewall rule taken with it. +DEFAULT_HTTP_ADDRESS = "127.0.0.1" +#: One past the live stream's 9988, so a machine running both has no collision +#: and an operator reading `ss -ltnp` sees the pair together. +DEFAULT_HTTP_PORT = 9989 +DEFAULT_HTTP_PATH = "/mcp" diff --git a/src/hhstream_mcp/authorizations.py b/src/hhstream_mcp/authorizations.py new file mode 100644 index 0000000..4547255 --- /dev/null +++ b/src/hhstream_mcp/authorizations.py @@ -0,0 +1,457 @@ +"""The token store: who may reach this server over HTTP. + +Standard library only, and no MCP import, so the whole of it is testable +without the SDK -- the same split :mod:`hhstream_mcp.tools` keeps. + +**This exists because of the HTTP transport and nothing else.** Over stdio the +client spawns the server, and whoever can spawn it already holds the broker's +control socket (``0660``, ``sessions.group``): a token checked by a process the +caller started is a lock whose key is in the same pocket. Bind a port and the +caller is no longer someone who passed a filesystem permission check on the way +in, and that is the moment a credential starts meaning something. + +What is on disk +--------------- + +One JSON object in ``/authorizations.json``:: + + {"version": 1, "grants": [{"id": …, "label": …, "hash": …, …}]} + +**The file holds SHA-256 hashes, not tokens.** Nothing here ever needs the +secret back -- ``mint`` prints it once and forgets it -- so storing the digest +costs nothing and means a readable ``authorizations.json`` is not itself a +credential. No salt and no KDF, deliberately: a token is +:func:`secrets.token_urlsafe` over 32 bytes, so there is no dictionary to +attack and a work factor would only slow the legitimate request path. This +diverges from the live stream, which keeps a phrase in cleartext in the session +record (`docs/plans/2026-10-03-network-stream.md`) -- it has to, because +``serve --stream`` needs it back. + +Expiry is **wall clock**, which is the one place in this project that is the +right choice. Every deadline in the broker is ``CLOCK_BOOTTIME`` (see +:mod:`hhstreamd.clock`) because an idle window must survive an NTP step and +count time spent suspended. A token minted for thirty days is a calendar +statement that has to outlive a reboot, and BOOTTIME resets to zero there. + +Concurrency +----------- + +Two processes write this file: the HTTP server, stamping ``last_used``, and an +operator running ``hhstream-mcp token mint`` in a shell. The atomic replace +borrowed from :func:`hhstreamd.registry.atomic_write_json` keeps a reader from +ever seeing half a file, but it does not stop a lost update -- the server could +rewrite the table it read a moment before the mint landed, and the new token +would vanish. So every read-modify-write takes an exclusive ``flock`` on a +sidecar lock file first. ``verify`` on the hot path takes no lock at all: it +only reads, and a stale read costs one request. +""" + +from __future__ import annotations + +import base64 +import contextlib +import fcntl +import hashlib +import hmac +import json +import logging +import os +import secrets +from collections.abc import Iterator, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from hhstreamd.clock import Clock, iso +from hhstreamd.registry import atomic_write_json + +log = logging.getLogger("hhstream.mcp.auth") + +#: Where the tokens live when nothing says otherwise. **Not** the broker's +#: ``sessions.stateDir``: that directory is ``0700`` owned by the broker's user +#: and holds ``events.jsonl``, the audit trail, and the MCP server runs as +#: whichever user's client spawned it. Handing this shim write access to the +#: audit trail's directory to park a token file in it would be a wider grant +#: than the feature needs. +DEFAULT_STATE_DIR = "/var/lib/hhstream-mcp" +ENV_STATE_DIR = "HHSTREAM_MCP_STATE_DIR" + +#: The file, and the lock beside it. +STORE_NAME = "authorizations.json" +LOCK_NAME = ".authorizations.lock" + +#: Prefix on every minted token. Not a namespace and not parsed on the way in +#: -- it is there so a leaked token is identifiable on sight, in a log, a shell +#: history or a committed config, which is the convention secret scanners are +#: built around. +TOKEN_PREFIX = "hhsmcp_" +#: 32 bytes of ``secrets`` is 256 bits. Nothing about the length is a +#: trade-off: the token is pasted into a client configuration, never typed and +#: never read aloud, which is exactly why this is not +#: :mod:`hhstream_live.phrase` -- a phrase buys sayability with 77 bits, and +#: there is nobody here to say it to. +TOKEN_BYTES = 32 + +#: The on-disk format. Written on every save and refused on load if unknown, +#: so a file from a future version is a named error rather than a table that +#: silently loses the fields this code does not know about. +FORMAT_VERSION = 1 + +#: How often ``last_used`` is allowed to reach the disk. A write per request +#: would turn a read-only tool call into a file replace and a lock round-trip; +#: the stamp is for an operator asking "is this token still in use", and an +#: hour is well inside that question's resolution. Same reasoning, and the +#: same shape, as ``registry.ACTIVITY_FLUSH_INTERVAL_S``. +LAST_USED_FLUSH_S = 3600.0 + +#: Bound on the operator's label, so one pathological ``--label`` cannot make +#: the table unreadable. +MAX_LABEL_CHARS = 128 + + +class StoreError(Exception): + """The store could not be used. Carries a message fit for a CLI error.""" + + +class NoSuchGrant(StoreError): + """A token id that is not in the table.""" + + +def hash_token(token: str) -> str: + """The digest stored for ``token``. Hex, lowercase, 64 characters.""" + + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def mint_token() -> str: + """A fresh bearer token. Returned once and never stored.""" + + return TOKEN_PREFIX + secrets.token_urlsafe(TOKEN_BYTES) + + +def mint_id(taken: set[str]) -> str: + """``<6 base32 chars>`` -- the handle revocation uses. + + An id and not the token: ``token revoke`` takes this, so ending a grant + never means pasting a live secret onto a command line that lands in a shell + history. Shaped like :func:`hhstreamd.registry.mint_id`'s suffix for the + same reason -- base32 lowercase has no character a reader confuses. + """ + + for _ in range(1000): + raw = secrets.token_bytes(5) + candidate = base64.b32encode(raw).decode("ascii").rstrip("=").lower()[:6] + if candidate not in taken: + return candidate + raise StoreError("could not mint an unused token id") # pragma: no cover + + +@dataclass +class Grant: + """One authorization: what the table knows about a token it cannot show.""" + + id: str + hash: str + label: str = "" + created: str = "" + expires_at: float | None = None + last_used: str | None = None + #: The toolsets this token may call, or ``None`` for every tool. Stored + #: from the first version even though the HTTP server is what enforces it, + #: because ``--toolsets`` is a *launch-time* flag and the moment one + #: process serves several callers a per-process tool budget has stopped + #: being a per-caller one. The token is the only place that distinction + #: can live, and adding the field later would be a file-format migration + #: for no reason. + toolsets: tuple[str, ...] | None = None + + def to_dict(self) -> dict[str, Any]: + return { + "id": self.id, + "hash": self.hash, + "label": self.label, + "created": self.created, + "expires_at": self.expires_at, + "last_used": self.last_used, + "toolsets": list(self.toolsets) if self.toolsets is not None else None, + } + + @classmethod + def from_dict(cls, raw: dict[str, Any]) -> Grant: + toolsets = raw.get("toolsets") + return cls( + id=str(raw["id"]), + hash=str(raw["hash"]), + label=str(raw.get("label") or ""), + created=str(raw.get("created") or ""), + expires_at=( + float(raw["expires_at"]) if raw.get("expires_at") is not None else None + ), + last_used=raw.get("last_used") or None, + toolsets=tuple(str(name) for name in toolsets) if toolsets else None, + ) + + def expired(self, now: float) -> bool: + return self.expires_at is not None and now >= self.expires_at + + def expires_iso(self) -> str | None: + return iso(self.expires_at) if self.expires_at is not None else None + + +@dataclass +class Store: + """The table on disk, read and written under a lock.""" + + path: Path + clock: Clock = field(default_factory=Clock) + + @classmethod + def at(cls, state_dir: Path | str | None = None, clock: Clock | None = None) -> Store: + """The store under ``state_dir``, ``$HHSTREAM_MCP_STATE_DIR``, or the default.""" + + root = Path( + state_dir + if state_dir is not None + else os.environ.get(ENV_STATE_DIR, DEFAULT_STATE_DIR) + ) + return cls(path=root / STORE_NAME, clock=clock or Clock()) + + @property + def state_dir(self) -> Path: + return self.path.parent + + # ---- the lock ---------------------------------------------------- + + @contextlib.contextmanager + def _locked(self) -> Iterator[None]: + """Exclusive access for one read-modify-write. + + The lock is a sidecar rather than the store itself, because the store + is *replaced* on every write -- a descriptor held on it would be a + descriptor on an unlinked inode, and the next writer would lock a + different file and think itself alone. + """ + + self.ensure_dir() + lock_path = self.state_dir / LOCK_NAME + fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + def ensure_dir(self) -> None: + """Create the state directory if the supervisor has not. + + In the deployed shape ``StateDirectory=`` in the unit makes this (and + its mode and owner) declarative; the same reasoning, and the same + fallback, as :meth:`hhstreamd.registry.Registry.ensure_dirs`. + """ + + try: + self.state_dir.mkdir(parents=True, exist_ok=True, mode=0o700) + except OSError as exc: + raise StoreError(f"cannot create {self.state_dir}: {exc}") from exc + + # ---- reading ----------------------------------------------------- + + def load(self) -> list[Grant]: + """Every grant, newest last. A missing file is an empty table.""" + + try: + raw = self.path.read_text(encoding="utf-8") + except FileNotFoundError: + return [] + except OSError as exc: + raise StoreError(f"cannot read {self.path}: {exc}") from exc + try: + data = json.loads(raw) + except json.JSONDecodeError as exc: + raise StoreError(f"{self.path} is not valid JSON: {exc}") from exc + if not isinstance(data, dict): + raise StoreError(f"{self.path} is not an authorization table") + version = data.get("version") + if version != FORMAT_VERSION: + raise StoreError( + f"{self.path} is format version {version!r}, and this build " + f"understands {FORMAT_VERSION}. A newer hhstream-mcp wrote it." + ) + try: + return [Grant.from_dict(entry) for entry in data.get("grants", [])] + except (KeyError, TypeError, ValueError) as exc: + raise StoreError(f"{self.path} has an unreadable grant: {exc}") from exc + + def _write(self, grants: Sequence[Grant]) -> None: + """Replace the table. Call under :meth:`_locked`.""" + + self.ensure_dir() + atomic_write_json( + self.path, + {"version": FORMAT_VERSION, "grants": [g.to_dict() for g in grants]}, + ) + # `atomic_write_json` creates the temp file with the default mode, so + # the mode is set on the thing that survives the replace. The file is + # not a credential (it holds digests), but it is the list of who may + # drive this desktop, and that is nobody else's business either. + try: + os.chmod(self.path, 0o600) + except OSError as exc: # pragma: no cover -- the write just succeeded + log.warning("cannot chmod %s: %s", self.path, exc) + + # ---- writing ----------------------------------------------------- + + def mint( + self, + *, + label: str = "", + ttl: float | None = None, + toolsets: Sequence[str] | None = None, + ) -> tuple[Grant, str]: + """Add a grant and return it with its token. The token is not stored.""" + + token = mint_token() + with self._locked(): + grants = self.load() + now = self.clock.wall() + grant = Grant( + id=mint_id({g.id for g in grants}), + hash=hash_token(token), + label=label[:MAX_LABEL_CHARS], + created=iso(now), + expires_at=(now + ttl) if ttl is not None else None, + toolsets=tuple(toolsets) if toolsets else None, + ) + self._write([*grants, grant]) + return grant, token + + def revoke(self, grant_id: str) -> Grant: + """Remove one grant by id. Raises :class:`NoSuchGrant` if it is not there.""" + + with self._locked(): + grants = self.load() + kept = [g for g in grants if g.id != grant_id] + if len(kept) == len(grants): + raise NoSuchGrant( + f"no token with id {grant_id!r}. `hhstream-mcp token list` " + "shows the ids." + ) + gone = next(g for g in grants if g.id == grant_id) + self._write(kept) + return gone + + def revoke_all(self) -> list[Grant]: + """Empty the table. Returns what was in it.""" + + with self._locked(): + grants = self.load() + self._write([]) + return grants + + def prune(self) -> list[Grant]: + """Drop expired grants. Returns what was dropped. + + Not required for correctness -- :meth:`verify` refuses an expired grant + whether or not it is still on disk -- so this is housekeeping, and it + is a separate call rather than a side effect of a read for that reason. + """ + + now = self.clock.wall() + with self._locked(): + grants = self.load() + dead = [g for g in grants if g.expired(now)] + if dead: + self._write([g for g in grants if not g.expired(now)]) + return dead + + # ---- the hot path ------------------------------------------------ + + def verify(self, token: str, *, stamp: bool = True) -> Grant | None: + """The grant this token belongs to, or ``None``. + + ``None`` covers every way a token can fail -- unknown, revoked, expired + -- on purpose. The caller's answer is one 401 either way, and a richer + return would only tempt it into saying which, to someone who should not + be told they guessed a real id. + + The digest comparison is :func:`hmac.compare_digest` even though both + sides are already hashes: the cost is nothing and it keeps the function + free of a timing signal that a later refactor might otherwise make + meaningful. + """ + + if not token: + return None + digest = hash_token(token) + now = self.clock.wall() + try: + grants = self.load() + except StoreError as exc: + # A broken table denies everything rather than allowing anything. + log.error("authorization table unusable, refusing: %s", exc) + return None + for grant in grants: + if not hmac.compare_digest(grant.hash, digest): + continue + if grant.expired(now): + return None + if stamp: + self._stamp(grant, now) + return grant + return None + + def _stamp(self, grant: Grant, now: float) -> None: + """Record that ``grant`` was used, at most once per flush interval. + + Never raises: a stamp that could not be written is not a reason to + refuse a request that was authorized. Same trade as the audit log's + (:mod:`hhstreamd.audit`). + """ + + if grant.last_used: + try: + age = now - _epoch(grant.last_used) + except ValueError: + age = LAST_USED_FLUSH_S + 1.0 + if age < LAST_USED_FLUSH_S: + return + stamped = iso(now) + try: + with self._locked(): + grants = self.load() + for entry in grants: + if entry.id == grant.id: + entry.last_used = stamped + break + else: + # Revoked between the verify and the stamp. Nothing to + # record, and re-adding it would resurrect a dead grant. + return + self._write(grants) + except (StoreError, OSError) as exc: + log.warning("cannot stamp last_used for %s: %s", grant.id, exc) + return + grant.last_used = stamped + + +def _epoch(stamp: str) -> float: + """An ISO stamp this module wrote, back as an epoch.""" + + import datetime as _dt + + return _dt.datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp() + + +__all__ = [ + "DEFAULT_STATE_DIR", + "ENV_STATE_DIR", + "FORMAT_VERSION", + "Grant", + "NoSuchGrant", + "STORE_NAME", + "Store", + "StoreError", + "TOKEN_PREFIX", + "hash_token", + "mint_token", +] diff --git a/src/hhstream_mcp/http.py b/src/hhstream_mcp/http.py new file mode 100644 index 0000000..6f0303f --- /dev/null +++ b/src/hhstream_mcp/http.py @@ -0,0 +1,444 @@ +"""The HTTP transport: Streamable HTTP, behind a bearer token. + +The second module here that imports the SDK, and the only one that imports +Starlette. :mod:`hhstream_mcp.server` stays what it was -- the stdio wiring -- +and nothing in this file is reachable without ``serve --http``. + +Why there is a second transport at all +-------------------------------------- + +Because a token has to travel somewhere. ``docs/CONTRACT-mcp.md`` v1 and v2 +said "stdio, and only stdio", and the reasoning was sound for what the server +then was: the client spawns it, so the caller has already passed a filesystem +permission check, and `0660` on the broker's control socket is the real gate. +Authentication on that shape is theatre -- the caller holds the key to the lock +they are being asked to open. + +A port changes who the caller is. The request now arrives from someone who +never touched the filesystem, and the token is the only thing standing between +them and a desktop they can type into. So the transport and the credential are +one feature and arrive together; neither is useful without the other. + +**stdio remains the default and remains unauthenticated**, for the reason it +always was. This is not auth bolted onto the MCP server; it is a second +transport that needs it. + +What this is not +---------------- + +**Not MCP's authorization specification.** That is OAuth 2.1 plus RFC 9728 +protected-resource metadata: a `401` is supposed to carry a +`WWW-Authenticate` pointing at a metadata document, the client discovers an +authorization server and does a real flow. This serves a static token the +operator minted and pasted into a client config. Consequences, stated rather +than discovered: a client that only knows how to *discover* an authorization +server will not connect, and one that lets you set a header will. See +``docs/TODO/mcp-http-auth-is-not-oauth.md``. + +The deliberate choices in the request path +------------------------------------------ + +* **Loopback by default.** ``--address`` defaults to ``127.0.0.1``. Reaching + the LAN is a second decision, taken twice (the flag and a firewall). +* **DNS-rebinding protection on**, with host and origin allowlists, through the + SDK's own :class:`TransportSecuritySettings`. A browser on the operator's + network is otherwise a usable path to a loopback-bound port. +* **A refusal says nothing.** `401` with an empty body; the token is never + echoed, never logged, and the response does not distinguish unknown from + revoked from expired. The same discipline `hhstream_live.server` already + applies to a wrong phrase, for the same reason. +* **Failed attempts are rate-limited per client**, reusing that app's + :class:`~hhstream_live.server.RateLimiter` rather than growing a second one. + 256-bit tokens make guessing hopeless already; this is so an attacker cannot + even try at line speed and so the attempt is visible in one place. +""" + +from __future__ import annotations + +import contextlib +import logging +from collections.abc import Callable, Sequence +from typing import Any + +import anyio +from mcp.server.lowlevel import NotificationOptions +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from mcp.server.transport_security import TransportSecuritySettings + +from hhstream_live.server import RateLimiter + +from . import ( + DEFAULT_HTTP_ADDRESS, + DEFAULT_HTTP_PATH, + DEFAULT_HTTP_PORT, + SERVER_NAME, + tools, +) +from .authorizations import Grant, Store +from .invoke import Runner + +log = logging.getLogger("hhstream.mcp.http") + +#: Aliases, so this module reads in its own terms. The values live in +#: ``hhstream_mcp/__init__.py``: ``server.py`` builds the parser that advertises +#: them and must not import this module to do it. +DEFAULT_ADDRESS = DEFAULT_HTTP_ADDRESS +DEFAULT_PORT = DEFAULT_HTTP_PORT +DEFAULT_PATH = DEFAULT_HTTP_PATH + +#: Where the verified grant is parked for the duration of one request. The +#: ASGI scope and not a ``contextvar``: in stateful mode the session manager +#: runs the protocol handler in a task owned by the *manager's* lifespan, not +#: by the request, so a contextvar set in middleware would not be visible +#: there. The scope survives, because the transport builds its own +#: ``Request(scope, receive)`` from the very dict this middleware annotated. +SCOPE_KEY = "hhstream_grant" + +#: The scheme, spelled once. Compared case-insensitively on the way in: RFC +#: 9110 makes the scheme token case-insensitive and some clients send `bearer`. +SCHEME = "bearer" + +#: Addresses that mean "this machine only", and for which a Host allowlist can +#: therefore be derived rather than demanded. +LOOPBACK = frozenset({"127.0.0.1", "::1", "localhost"}) +#: Addresses that mean "every interface". Nothing can be derived from one: +#: the Host header will be whatever name the client used to reach us, and this +#: process has no way to know what that is. +WILDCARD = frozenset({"0.0.0.0", "::", "*"}) # noqa: S104 -- named, not bound + + +def default_allowed_hosts(address: str, port: int) -> list[str]: + """The Host values to accept when the operator named none. + + This has to exist because the SDK's DNS-rebinding check is *allowlist only* + with no implicit localhost: :class:`TransportSecuritySettings` with + protection on and an empty ``allowed_hosts`` rejects **every** request with + a 421. Turning the protection off to get a working default would be the + wrong trade -- it is the one thing standing between a loopback-bound port + and any web page the operator opens -- so the default is derived instead. + + A wildcard bind returns the empty list, and the caller refuses to start. + That is deliberate: binding every interface is exactly the case where the + hostnames cannot be guessed and are worth being made to say out loud. + """ + + if address in WILDCARD: + return [] + hosts = {address} | (LOOPBACK if address in LOOPBACK else set()) + out: list[str] = [] + for host in sorted(hosts): + # `::1` has to be bracketed to appear in a Host header at all. + literal = f"[{host}]" if ":" in host else host + out.append(f"{literal}:{port}") + # The `:*` form is the SDK's own wildcard-port pattern. A client that + # reaches a reverse proxy on 443 and is forwarded here sends the port + # it dialled, not ours. + out.append(f"{literal}:*") + out.append(literal) + return out + + +def bearer_token(header: str) -> str | None: + """The token out of an ``Authorization`` value, or ``None``. + + Anything that is not exactly one ``Bearer `` pair is ``None`` -- a + malformed header is a failed attempt, not a thing to repair on the + caller's behalf. + """ + + parts = header.strip().split(None, 1) + if len(parts) != 2 or parts[0].lower() != SCHEME: + return None + token = parts[1].strip() + return token or None + + +class BearerAuth: + """ASGI middleware: every HTTP request carries a live token, or gets a 401. + + Hand-written rather than the SDK's ``RequireAuthMiddleware``, which is + built for the OAuth profile this is not: it wants ``AuthSettings`` with an + issuer and a resource-server URL, and it advertises metadata endpoints that + would then have to exist. Forty lines that say what they do beat a + configuration that claims a flow nobody implemented. + """ + + def __init__( + self, + app: Any, + store: Store, + *, + limiter: RateLimiter | None = None, + ) -> None: + self.app = app + self.store = store + self.limiter = limiter if limiter is not None else RateLimiter() + + async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None: + # `lifespan` is the server talking to itself; only `http` carries a + # caller. A `websocket` scope would reach here if a route grew one, + # and falls into the same refusal as an unauthenticated request. + if scope["type"] == "lifespan": + await self.app(scope, receive, send) + return + if scope["type"] != "http": + await self._refuse(scope, receive, send) + return + + client = (scope.get("client") or ("unknown", 0))[0] + header = _header(scope, b"authorization") + token = bearer_token(header) if header else None + if token is None: + await self._refuse(scope, receive, send, client=client, reason="no bearer token") + return + # A file read, so off the event loop: small, but the discipline is the + # one the rest of this package keeps about blocking work. + grant = await anyio.to_thread.run_sync(lambda: self.store.verify(token)) + if grant is None: + await self._refuse(scope, receive, send, client=client, reason="token refused") + return + scope[SCOPE_KEY] = grant + log.debug("request authorized by token %s", grant.id) + await self.app(scope, receive, send) + + async def _refuse( + self, + scope: dict[str, Any], + receive: Any, + send: Any, + *, + client: str = "unknown", + reason: str = "unauthorized", + ) -> None: + """401, or 429 once a client has missed too often. + + The body is empty in both cases and the log line names the client and + the shape of the failure, never the token or any part of it. + """ + + allowed = self.limiter.allow(client) + status = 401 if allowed else 429 + log.warning("%s from %s: %s", status, client, reason if allowed else "rate limited") + headers = [ + (b"content-length", b"0"), + (b"cache-control", b"no-store"), + (b"x-content-type-options", b"nosniff"), + ] + if status == 401: + # RFC 9110's challenge. A realm and nothing else: there is no + # `as_uri` to point at, because there is no authorization server. + headers.append((b"www-authenticate", f'Bearer realm="{SERVER_NAME}"'.encode())) + await send({"type": "http.response.start", "status": status, "headers": headers}) + await send({"type": "http.response.body", "body": b""}) + + +def _header(scope: dict[str, Any], name: bytes) -> str: + for key, value in scope.get("headers") or (): + if key.lower() == name: + return value.decode("latin-1") + return "" + + +def current_grant(server: Any) -> Grant | None: + """The grant behind the request being handled, if there is one. + + ``None`` whenever there is no request context at all -- which is the stdio + case and the unit tests' case -- so a caller can treat "no grant" as "no + restriction" without asking which transport it is on. + """ + + try: + request = server.request_context.request + except (LookupError, AttributeError): + return None + scope = getattr(request, "scope", None) or {} + grant = scope.get(SCOPE_KEY) + return grant if isinstance(grant, Grant) else None + + +def offered_for(server: Any, base: tuple[tools.Tool, ...]) -> Callable[[], tuple[tools.Tool, ...]]: + """A chooser that narrows ``base`` to the calling token's toolsets. + + The **intersection**, not the token's list: the process was started with + its own ``--toolsets`` and a token cannot widen that. Two independent + narrowings, and a tool has to survive both. + + Resources are deliberately not narrowed, which is worth stating because it + is a real limit and not an oversight. `docs/CONTRACT-mcp.md` §2 keeps + resources out of ``--toolsets`` on the grounds that they are the host's + context rather than the model's budget, and that argument carries over. But + a *token* is an authorization rather than a budget, so the consequence is + that a token scoped to ``frames`` can still read ``hhstream://sessions``. + Read-side scoping is a different feature; see + ``docs/TODO/mcp-tokens-do-not-scope-resources.md``. + """ + + names = {tool.name for tool in base} + + def chooser() -> tuple[tools.Tool, ...]: + grant = current_grant(server) + if grant is None or grant.toolsets is None: + return base + try: + allowed = tools.selected(grant.toolsets) + except tools.UnknownToolset: + # A toolset name that was valid when the token was minted and is + # not a name this build knows. Refusing everything is the safe + # direction: the alternative is a token that silently widens. + log.error( + "token %s names a toolset this build does not know (%s); " + "offering nothing", + grant.id, + ",".join(grant.toolsets), + ) + return () + return tuple(tool for tool in allowed if tool.name in names) + + return chooser + + +def build_app( + runner: Runner, + store: Store, + *, + toolsets: Sequence[str] | None = None, + path: str = DEFAULT_PATH, + allowed_hosts: Sequence[str] | None = None, + allowed_origins: Sequence[str] | None = None, + stateless: bool = False, + json_response: bool = False, +) -> Any: + """The ASGI application: one route, behind :class:`BearerAuth`. + + ``allowed_hosts`` must already be resolved -- :func:`default_allowed_hosts` + is the caller's to apply, because the empty list has to stay meaningful + here: it is what a wildcard bind produces, and it is a refusal rather than + a default. + + ``stateless`` defaults to false -- a client that initializes and then calls + gets one session, which is what the protocol's session header is for. It is + exposed because a deployment that puts several of these behind a load + balancer cannot keep a session pinned, and a stateless server is then the + only honest answer. + """ + + # Imported here and not at module scope: `build_app` is the only thing in + # this file that needs Starlette, and an import error should name the + # feature being started rather than fire on `import hhstream_mcp.http`. + from starlette.applications import Starlette + from starlette.routing import Mount + + from .server import build + + security = TransportSecuritySettings( + enable_dns_rebinding_protection=True, + allowed_hosts=list(allowed_hosts or ()), + # Left empty on purpose when the operator names none. The SDK lets an + # *absent* Origin through and refuses any present one it does not know, + # which is exactly right here: no MCP client sends an Origin, and the + # only thing that does is a web page -- which is the attacker in the + # DNS-rebinding story, not a user of this server. + allowed_origins=list(allowed_origins or ()), + ) + + base = tools.selected(toolsets) + # The two references are circular: the server lists what the chooser + # returns, and the chooser reads the server's request context. One of them + # has to resolve late, and this is the one that safely can -- `chooser` is + # called per request, long after the next statement has bound it. + chooser: Callable[[], tuple[tools.Tool, ...]] + mcp_server = build(runner, toolsets, offered=lambda: chooser()) + chooser = offered_for(mcp_server, base) + + manager = StreamableHTTPSessionManager( + app=mcp_server, + stateless=stateless, + json_response=json_response, + security_settings=security, + ) + + async def handle(scope: Any, receive: Any, send: Any) -> None: + await manager.handle_request(scope, receive, send) + + @contextlib.asynccontextmanager + async def lifespan(_app: Any) -> Any: + # The manager's task group has to be open for the whole life of the + # process: it owns the per-session server tasks. + async with manager.run(): + log.info("http transport ready on %s", path) + yield + + app = Starlette( + debug=False, + routes=[Mount(path, app=handle)], + lifespan=lifespan, + ) + # The token check wraps the *whole* app and not just the route, so a + # request to any other path is a 401 rather than a 404. An unauthenticated + # caller learns nothing about what this server has mounted, including + # whether it is an hhstream server at all. + return BearerAuth(app, store) + + +def serve( + runner: Runner, + store: Store, + *, + address: str = DEFAULT_ADDRESS, + port: int = DEFAULT_PORT, + path: str = DEFAULT_PATH, + toolsets: Sequence[str] | None = None, + allowed_hosts: Sequence[str] | None = None, + allowed_origins: Sequence[str] | None = None, + stateless: bool = False, + json_response: bool = False, +) -> None: + """Run the HTTP transport until the process is signalled.""" + + import uvicorn + + app = build_app( + runner, + store, + toolsets=toolsets, + path=path, + allowed_hosts=allowed_hosts, + allowed_origins=allowed_origins, + stateless=stateless, + json_response=json_response, + ) + config = uvicorn.Config( + app, + host=address, + port=port, + # stderr, like everything else this package logs: the stdio transport's + # discipline about fd 1 is not relaxed just because this process is not + # using it, since the same binary does both. + log_config=None, + access_log=False, + # The default `h11` is fine and the only one in the closure; naming it + # keeps a uvicorn that grew a different default from changing ours. + http="h11", + ) + uvicorn.Server(config).run() + + +def initialization_options(server: Any) -> Any: + """The handshake options, shared with the stdio path.""" + + return server.create_initialization_options(NotificationOptions()) + + +__all__ = [ + "DEFAULT_ADDRESS", + "DEFAULT_PATH", + "DEFAULT_PORT", + "SCOPE_KEY", + "BearerAuth", + "bearer_token", + "build_app", + "current_grant", + "default_allowed_hosts", + "offered_for", + "serve", +] diff --git a/src/hhstream_mcp/server.py b/src/hhstream_mcp/server.py index 12e89e1..c2ed8a3 100644 --- a/src/hhstream_mcp/server.py +++ b/src/hhstream_mcp/server.py @@ -31,6 +31,7 @@ import io import logging import os import sys +from collections.abc import Callable from typing import Any import anyio @@ -41,7 +42,17 @@ from mcp.server.stdio import stdio_server from mcp.shared.exceptions import McpError from pydantic import AnyUrl -from . import SERVER_NAME, __version__, resources, tools +from . import ( + DEFAULT_HTTP_ADDRESS, + DEFAULT_HTTP_PATH, + DEFAULT_HTTP_PORT, + SERVER_NAME, + __version__, + authorizations, + resources, + tokencli, + tools, +) from .invoke import Runner log = logging.getLogger("hhstream.mcp") @@ -177,9 +188,16 @@ def call( "resources/list for the whole read-only half of this server." ) elif name in tools.BY_NAME: + # Two things can have narrowed the offer and the agent cannot tell + # them apart from here, so both are named: `--toolsets` at launch, + # and -- on the HTTP transport -- the toolsets carried by the token + # the request presented. Neither is the agent's to change, which is + # why the remedy is "ask whoever runs this" and not a retry. hint = ( - f" {name!r} exists but this server was started without its " - "toolset, so it is not offered." + f" {name!r} exists but is not offered to this caller: either " + "this server was started without its toolset (--toolsets), or " + "the authorization this request used does not carry it. " + "Neither is yours to change from here." ) return types.CallToolResult( content=[ @@ -267,16 +285,33 @@ def read(runner: Runner, uri: str) -> list[ReadResourceContents]: return [ReadResourceContents(content=body, mime_type=reading.media_type)] -def build(runner: Runner, toolsets: Any = None) -> Server: +def build( + runner: Runner, + toolsets: Any = None, + *, + offered: Callable[[], tuple[tools.Tool, ...]] | None = None, +) -> Server: + """The MCP server over the selected tools. + + ``offered`` is how the HTTP transport narrows the listing per *caller*: a + token can carry its own toolsets, and ``--toolsets`` is a launch-time flag + that stops being a per-caller budget the moment one process serves several + of them (:mod:`hhstream_mcp.http`). It is called on every ``tools/list`` + and every ``tools/call``, so it must be cheap and must not block. + + Omitted -- which is the stdio case -- the selection is fixed at build time + and the handlers close over it, exactly as before. + """ + server: Server = Server( SERVER_NAME, version=__version__, instructions=INSTRUCTIONS ) - available = tools.selected(toolsets) - by_name = {tool.name: tool for tool in available} + fixed = tools.selected(toolsets) + chooser: Callable[[], tuple[tools.Tool, ...]] = offered or (lambda: fixed) @server.list_tools() async def _list() -> list[types.Tool]: - return [describe(tool) for tool in available] + return [describe(tool) for tool in chooser()] @server.list_resources() async def _list_resources() -> list[types.Resource]: @@ -302,6 +337,7 @@ def build(runner: Runner, toolsets: Any = None) -> Server: # loop stays free to answer a ping and to read the next request. The # calls themselves are serialised inside `Runner.run`, because the CLI # prints to a stdout this process shares. + by_name = {tool.name: tool for tool in chooser()} return await anyio.to_thread.run_sync(lambda: call(runner, name, arguments, by_name)) return server @@ -345,13 +381,146 @@ async def serve(server: Server, transport: tuple[Any, Any] | None = None) -> Non ) +def common_options() -> argparse.ArgumentParser: + """The flags both ``hhstream-mcp`` and ``hhstream-mcp serve`` accept. + + A parent parser, so ``--toolsets`` works on either side of the subcommand + and there is one help text for it. Every option here defaults to + ``SUPPRESS``: argparse copies a subparser's namespace over the top-level + one, so a plain default on the subcommand copy would overwrite a value + given *before* the subcommand with ``None``. Suppressed, an option that was + not typed is simply absent, and callers read it with ``getattr``. + """ + + common = argparse.ArgumentParser(add_help=False) + common.add_argument( + "--toolsets", + metavar="NAMES", + default=argparse.SUPPRESS, + help="comma-separated families to offer as tools: " + + ", ".join(tools.TOOLSETS) + + ". Omitted, every tool is offered. Resources are NOT filtered by " + "this -- they are the host's context, not the model's tool budget.", + ) + common.add_argument( + "--list-tools", + action="store_true", + default=argparse.SUPPRESS, + help="print the tool names and exit, without serving. Honours " + "--toolsets, so it is also how to see what a selection would offer.", + ) + common.add_argument( + "--list-resources", + action="store_true", + default=argparse.SUPPRESS, + help="print the resource URIs and templates and exit, without serving.", + ) + return common + + +def add_serve_parser(subparsers: Any, common: argparse.ArgumentParser) -> None: + """``serve`` -- the transports. stdio unless ``--http`` says otherwise.""" + + serve_cmd = subparsers.add_parser( + "serve", + parents=[common], + help="serve the tools (stdio by default, --http for a port)", + description=( + "Serve the surface. With no flags this is the stdio transport and " + "is identical to running `hhstream-mcp` with no subcommand at all, " + "which is what an MCP client's `command` entry should keep doing." + ), + ) + http = serve_cmd.add_argument_group( + "http transport", + description=( + "Streamable HTTP instead of stdio, behind a bearer token minted by " + "`hhstream-mcp token mint`. Every request carries one or gets a " + "401. stdio stays unauthenticated on purpose: the client spawns it, " + "so the caller has already passed a filesystem permission check " + "and holds the broker's socket either way." + ), + ) + http.add_argument( + "--http", + action="store_true", + help="serve Streamable HTTP on --address:--port instead of stdio", + ) + http.add_argument( + "--address", + default=DEFAULT_HTTP_ADDRESS, + metavar="HOST", + help="the address to bind (default: %(default)s). Loopback by default, " + "deliberately: reaching the LAN is a second decision and wants a " + "firewall rule to go with it.", + ) + http.add_argument( + "--port", + type=int, + default=DEFAULT_HTTP_PORT, + help="the port to bind (default: %(default)s)", + ) + http.add_argument( + "--path", + default=DEFAULT_HTTP_PATH, + help="the path the endpoint is mounted at (default: %(default)s)", + ) + http.add_argument( + "--state-dir", + metavar="DIR", + help="where the authorization table lives. Defaults to " + "$HHSTREAM_MCP_STATE_DIR, then /var/lib/hhstream-mcp.", + ) + http.add_argument( + "--allowed-host", + action="append", + default=[], + metavar="HOST", + help="a Host header to accept. Repeatable. DNS-rebinding protection is " + "on, so a host this does not name is refused by the transport before " + "the token is even looked at.", + ) + http.add_argument( + "--allowed-origin", + action="append", + default=[], + metavar="ORIGIN", + help="an Origin header to accept. Repeatable. Nothing needs this unless " + "a browser is the client; a token in a page is a token in a page.", + ) + http.add_argument( + "--stateless", + action="store_true", + help="handle every request on its own, with no session to pin. For a " + "deployment behind a load balancer that cannot keep a client on one " + "process.", + ) + http.add_argument( + "--allow-no-tokens", + action="store_true", + help="start even though the authorization table is empty, which means " + "refusing every request until a token is minted. For provisioning the " + "unit before its first token exists; without it, an empty table is a " + "usage error, because it is almost always a forgotten `token mint`.", + ) + http.add_argument( + "--json-response", + action="store_true", + help="answer with a single JSON body instead of an SSE stream", + ) + + def build_parser() -> argparse.ArgumentParser: + common = common_options() parser = argparse.ArgumentParser( prog="hhstream-mcp", + parents=[common], description=( - "Serve the hhstream CLI as Model Context Protocol tools over stdio. " - "Spawned by an MCP client; it speaks JSON-RPC on stdin/stdout and " - "logs to stderr." + "Serve the hhstream CLI as Model Context Protocol tools. The " + "default transport is stdio: spawned by an MCP client, speaking " + "JSON-RPC on stdin/stdout and logging to stderr. `serve --http` " + "binds a port instead and requires a bearer token; `token` mints " + "and revokes those." ), epilog=( "There is no --socket flag here, deliberately: the sockets are the " @@ -361,25 +530,12 @@ def build_parser() -> argparse.ArgumentParser: "disagree. Set them in the MCP client's `env` block." ), ) - parser.add_argument( - "--toolsets", - metavar="NAMES", - help="comma-separated families to offer as tools: " - + ", ".join(tools.TOOLSETS) - + ". Omitted, every tool is offered. Resources are NOT filtered by " - "this -- they are the host's context, not the model's tool budget.", - ) - parser.add_argument( - "--list-tools", - action="store_true", - help="print the tool names and exit, without serving. Honours " - "--toolsets, so it is also how to see what a selection would offer.", - ) - parser.add_argument( - "--list-resources", - action="store_true", - help="print the resource URIs and templates and exit, without serving.", - ) + # Not required: `hhstream-mcp` and `hhstream-mcp --toolsets=...` have to go + # on serving stdio exactly as they did before this file grew subcommands. + # An MCP client's `command` entry is a configuration someone else wrote. + subparsers = parser.add_subparsers(dest="command", metavar="COMMAND") + add_serve_parser(subparsers, common) + tokencli.add_parser(subparsers) return parser @@ -400,31 +556,44 @@ def chosen_toolsets(raw: str | None) -> list[str] | None: def main(argv: list[str] | None = None) -> int: parser = build_parser() args = parser.parse_args(argv) - # stderr, never stdout: stdout is the transport, and one stray print on it - # is a protocol error the client reports as a parse failure. + # stderr, never stdout: on the stdio transport stdout *is* the transport, + # and one stray print on it is a protocol error the client reports as a + # parse failure. The HTTP transport does not share that hazard, but the + # same binary serves both and one rule is easier to keep than two. logging.basicConfig( level=os.environ.get("HHSTREAM_MCP_LOG", "WARNING").upper(), stream=sys.stderr, format="%(levelname)s %(name)s: %(message)s", ) + + if args.command == "token": + # Before anything claims the transport, which is the whole reason this + # returns here: `token mint` prints a secret on stdout. + token_parser = parser_for(parser, "token") + return tokencli.run(args, token_parser) + try: - toolsets = chosen_toolsets(args.toolsets) + toolsets = chosen_toolsets(getattr(args, "toolsets", None)) offered = tools.selected(toolsets) except tools.UnknownToolset as exc: # argparse's own exit code for a bad argument, because that is what # this is: `choices=` cannot express a comma-separated subset. parser.error(str(exc)) return int(2) # pragma: no cover -- parser.error exits - if args.list_tools: + if getattr(args, "list_tools", False): for tool in offered: print(f"{tool.name}\t{tool.title}") return 0 - if args.list_resources: + if getattr(args, "list_resources", False): for entry in resources.FIXED: print(f"{entry.uri}\t{entry.title}") for entry in resources.TEMPLATES: print(f"{entry.uri_template}\t{entry.title}") return 0 + + if getattr(args, "http", False): + return serve_http(args, toolsets, parser) + log.info( "serving %d tools and %d resources over stdio", len(offered), @@ -437,5 +606,97 @@ def main(argv: list[str] | None = None) -> int: return 0 +def parser_for(parser: argparse.ArgumentParser, name: str) -> argparse.ArgumentParser: + """The subparser called ``name``, for a handler that wants to print its help. + + argparse keeps no public index of these, so it is dug out of the one + ``_SubParsersAction`` this parser has. A miss returns the top-level parser: + a slightly wrong help text is a better failure than an AttributeError in + place of a usage message. + """ + + for action in parser._actions: # noqa: SLF001 -- argparse has no public accessor + if isinstance(action, argparse._SubParsersAction): # noqa: SLF001 + found = action.choices.get(name) + if found is not None: + return found + return parser # pragma: no cover + + +def serve_http( + args: argparse.Namespace, + toolsets: list[str] | None, + parser: argparse.ArgumentParser, +) -> int: + """Run the HTTP transport. Refuses to start with nothing that can connect. + + The empty-table check is the one piece of policy in this function, and it + is here rather than in :mod:`hhstream_mcp.http` because it is a *launch* + decision: a server bound to a port that every request will 401 is almost + always a missing `token mint`, and discovering that from the far side of an + HTTP client is far more work than reading one line on stderr. `--allow-no- + tokens` is the escape hatch for the one case where it is deliberate -- + provisioning the unit before its first token exists. + """ + + # Imported here: `starlette` and `uvicorn` are only needed by this path, + # and the stdio transport must not pay for them or fail on them. + from . import http as http_transport + + store = authorizations.Store.at(getattr(args, "state_dir", None)) + try: + grants = store.load() + except authorizations.StoreError as exc: + print(f"error: {exc}", file=sys.stderr) + return tokencli.EXIT_STORE + if not grants and not args.allow_no_tokens: + parser.error( + f"no tokens in {store.path}: every request would be refused. Mint " + "one with `hhstream-mcp token mint`, or pass --allow-no-tokens to " + "start anyway." + ) + return tokencli.EXIT_USAGE # pragma: no cover -- parser.error exits + + # The Host allowlist, which cannot be left empty: the SDK's DNS-rebinding + # check is allowlist-only with no implicit localhost, so an empty list + # refuses every request with a 421 (see `http.default_allowed_hosts`). + hosts = list(args.allowed_host) or http_transport.default_allowed_hosts( + args.address, args.port + ) + if not hosts: + parser.error( + f"--address {args.address} binds every interface, so the Host " + "header a client will send cannot be derived and DNS-rebinding " + "protection has nothing to check against. Name the hostnames with " + "--allowed-host (repeatable), or bind one address." + ) + return tokencli.EXIT_USAGE # pragma: no cover -- parser.error exits + + log.info( + "serving %d tools and %d resources over http on %s:%d%s, %d token(s), " + "hosts %s", + len(tools.selected(toolsets)), + len(resources.ENTRIES), + args.address, + args.port, + args.path, + len(grants), + ",".join(hosts), + ) + http_transport.serve( + Runner(), + store, + address=args.address, + port=args.port, + path=args.path, + toolsets=toolsets, + allowed_hosts=hosts, + allowed_origins=args.allowed_origin, + stateless=args.stateless, + json_response=args.json_response, + ) + return 0 + + if __name__ == "__main__": # pragma: no cover raise SystemExit(main()) diff --git a/src/hhstream_mcp/tokencli.py b/src/hhstream_mcp/tokencli.py new file mode 100644 index 0000000..1d498ea --- /dev/null +++ b/src/hhstream_mcp/tokencli.py @@ -0,0 +1,270 @@ +"""``hhstream-mcp token`` -- mint, list and revoke the HTTP transport's tokens. + +Standard library only, like :mod:`hhstream_mcp.authorizations` beneath it: the +verbs never open a socket, never talk to the broker and never import the SDK. + +**Nothing here may touch the stdio transport.** :func:`hhstream_mcp.server.main` +calls these and returns before ``claim_transport`` runs, which is the same +structural position ``--list-tools`` and ``--list-resources`` already occupy. +It matters more here than there: ``mint`` prints a secret on stdout, and stdout +is the JSON-RPC stream once a server is serving. + +Exit codes +---------- + +These verbs are **outside** the frozen table in :mod:`hhstreamd.protocol`, +because nothing they do reaches the broker and an agent never calls them. Two +of the codes are chosen by analogy with it anyway, so that a reader who knows +the broker's table is not surprised: + +==== =============================================================== +0 done +2 usage (argparse's own) +3 no token with that id -- the analogue of ``NO_SUCH_SESSION`` +4 the store itself is unusable -- the analogue of ``BAD_STATE`` +==== =============================================================== +""" + +from __future__ import annotations + +import argparse +import sys +from typing import Any + +from hhstream_session.format import DASH, dump_json, render_table +from hhstreamd.clock import parse_duration + +from . import tools +from .authorizations import Grant, NoSuchGrant, Store, StoreError + +EXIT_OK = 0 +EXIT_USAGE = 2 +EXIT_NO_SUCH_TOKEN = 3 +EXIT_STORE = 4 + +#: What `token list` shows. There is no column for the token, and there never +#: can be: the store holds a digest. +HEADERS = ["ID", "LABEL", "CREATED", "EXPIRES", "LAST USED", "TOOLSETS"] + + +def add_parser(subparsers: Any) -> argparse.ArgumentParser: + """Attach the ``token`` command to a subparser set.""" + + token = subparsers.add_parser( + "token", + help="mint, list and revoke the tokens the --http transport accepts", + description=( + "Manage the bearer tokens `hhstream-mcp serve --http` accepts. " + "These do nothing for the stdio transport, which is unauthenticated " + "on purpose: its gate is the filesystem, since the client spawns " + "the server and already needs the broker's socket." + ), + ) + token.add_argument( + "--state-dir", + metavar="DIR", + help="where the authorization table lives. Defaults to " + "$HHSTREAM_MCP_STATE_DIR, then /var/lib/hhstream-mcp. This is NOT the " + "broker's sessions.stateDir: that directory is 0700 owned by the " + "broker's user and holds its audit trail.", + ) + verbs = token.add_subparsers(dest="verb", metavar="VERB") + + mint = verbs.add_parser( + "mint", + help="create a token and print it once", + description=( + "Print a new token on stdout. It is shown HERE AND NOWHERE ELSE: " + "the table on disk keeps a SHA-256 digest, so a token that was not " + "written down cannot be recovered, only revoked and replaced." + ), + ) + mint.add_argument( + "--label", + default="", + help="a note for the operator reading `token list` later, e.g. a client " + "or a host name. Never sent anywhere.", + ) + mint.add_argument( + "--expires-in", + metavar="DURATION", + help="how long the token is valid: 30s, 5m, 3h, 90d, or a bare number " + "of seconds. Omitted, it does not expire.", + ) + mint.add_argument( + "--toolsets", + metavar="NAMES", + help="comma-separated families this token may call: " + + ", ".join(tools.TOOLSETS) + + ". Omitted, it may call every tool. Unlike the server's own " + "--toolsets this is per CALLER, which is the only place the " + "distinction can live once one process serves several of them.", + ) + + listing = verbs.add_parser( + "list", + help="show every token's id, label and age", + description="Show the table. The tokens themselves are not in it.", + ) + listing.add_argument("--json", action="store_true", help="the records, as JSON") + + revoke = verbs.add_parser( + "revoke", + help="remove a token by id", + description=( + "Remove one grant, by the id `token list` shows. By id and not by " + "token, so ending a grant never means pasting a live secret onto a " + "command line that lands in a shell history." + ), + ) + revoke.add_argument("id", nargs="?", help="the token id, as `token list` shows it") + revoke.add_argument( + "--all", action="store_true", help="remove every token instead of one" + ) + + verbs.add_parser( + "prune", + help="drop expired tokens from the table", + description=( + "Housekeeping only. An expired token is refused whether or not it " + "is still on disk, so this changes what `token list` shows and " + "nothing about who can connect." + ), + ) + return token + + +def row_for(grant: Grant) -> list[str]: + return [ + grant.id, + grant.label or DASH, + grant.created or DASH, + grant.expires_iso() or "never", + grant.last_used or "never", + ",".join(grant.toolsets) if grant.toolsets else "all", + ] + + +def run(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + """Dispatch one ``token`` verb. ``parser`` is the ``token`` parser itself.""" + + verb = getattr(args, "verb", None) + if verb is None: + parser.print_help() + return EXIT_USAGE + store = Store.at(getattr(args, "state_dir", None)) + try: + if verb == "mint": + return _mint(args, store, parser) + if verb == "list": + return _list(args, store) + if verb == "revoke": + return _revoke(args, store, parser) + if verb == "prune": + return _prune(store) + except NoSuchGrant as exc: + print(f"error: {exc}", file=sys.stderr) + return EXIT_NO_SUCH_TOKEN + except StoreError as exc: + print(f"error: {exc}", file=sys.stderr) + return EXIT_STORE + parser.error(f"unknown verb: {verb}") # pragma: no cover -- argparse refuses first + return EXIT_USAGE # pragma: no cover + + +def _mint(args: argparse.Namespace, store: Store, parser: argparse.ArgumentParser) -> int: + ttl: float | None = None + if args.expires_in is not None: + try: + ttl = parse_duration(args.expires_in) + except ValueError as exc: + parser.error(f"--expires-in: {exc}") + return EXIT_USAGE # pragma: no cover -- parser.error exits + if ttl == 0: + parser.error("--expires-in: 0 would mint a token that is already expired") + chosen: list[str] | None = None + if args.toolsets is not None: + names = [part.strip() for part in args.toolsets.split(",") if part.strip()] + if not names: + parser.error( + "--toolsets was given no names. Omit it for every tool, or name " + f"some of: {', '.join(tools.TOOLSETS)}" + ) + unknown = [name for name in names if name not in tools.TOOLSETS] + if unknown: + parser.error( + f"--toolsets: no such toolset: {', '.join(repr(u) for u in unknown)}. " + f"Known: {', '.join(tools.TOOLSETS)}" + ) + chosen = names + grant, token = store.mint(label=args.label, ttl=ttl, toolsets=chosen) + # The token on stdout alone, so `... token mint | pbcopy` and friends get + # exactly it; everything a human reads goes to stderr beside it. + print(token) + print( + f"minted {grant.id}" + + (f" ({grant.label})" if grant.label else "") + + f", expires {grant.expires_iso() or 'never'}" + + f", toolsets {','.join(grant.toolsets) if grant.toolsets else 'all'}." + "\nThis is the only time the token is shown. Store it in the client's " + "Authorization header; the table on disk keeps only its digest.", + file=sys.stderr, + ) + return EXIT_OK + + +def _list(args: argparse.Namespace, store: Store) -> int: + grants = store.load() + if args.json: + dump_json([grant.to_dict() for grant in grants]) + return EXIT_OK + if not grants: + print( + f"no tokens in {store.path}. `hhstream-mcp token mint` makes one; " + "until then `serve --http` refuses every request.", + file=sys.stderr, + ) + return EXIT_OK + print(render_table([row_for(grant) for grant in grants], HEADERS)) + return EXIT_OK + + +def _revoke(args: argparse.Namespace, store: Store, parser: argparse.ArgumentParser) -> int: + if args.all and args.id: + parser.error("give an id or --all, not both") + if args.all: + gone = store.revoke_all() + print(f"revoked {len(gone)} token(s).", file=sys.stderr) + return EXIT_OK + if not args.id: + parser.error("which token? give an id, or --all for every one") + return EXIT_USAGE # pragma: no cover -- parser.error exits + grant = store.revoke(args.id) + print( + f"revoked {grant.id}" + (f" ({grant.label})" if grant.label else "") + ".", + file=sys.stderr, + ) + return EXIT_OK + + +def _prune(store: Store) -> int: + dead = store.prune() + print( + f"dropped {len(dead)} expired token(s)." + if dead + else "nothing expired; the table is unchanged.", + file=sys.stderr, + ) + return EXIT_OK + + +__all__ = [ + "EXIT_NO_SUCH_TOKEN", + "EXIT_OK", + "EXIT_STORE", + "EXIT_USAGE", + "HEADERS", + "add_parser", + "row_for", + "run", +]