diff --git a/core/janus/cli.py b/core/janus/cli.py index 0d7335d..87d9d07 100644 --- a/core/janus/cli.py +++ b/core/janus/cli.py @@ -638,17 +638,47 @@ def serve( host: str = typer.Option("127.0.0.1", "--host", help="Bind host"), port: int = typer.Option(8766, "--port", help="Bind port"), db: Optional[str] = typer.Option(None, "--db", help="SQLite path"), + team_tokens: Optional[Path] = typer.Option( + None, "--team-tokens", help="JSON token table for scoped team mode" + ), + audit_log: Optional[Path] = typer.Option( + None, "--audit-log", help="JSONL file for denied requests" + ), ) -> None: """Serve the local JSON API used by the DSH plugin.""" + from .mcp.team_auth import DenialAudit, TeamAuth from .server import make_server load_settings() + if audit_log is not None and team_tokens is None: + raise typer.BadParameter( + "--audit-log needs --team-tokens: denials are only audited in team mode" + ) + team_auth = None + if team_tokens is not None: + try: + config = json.loads(team_tokens.read_text(encoding="utf-8")) + except OSError as exc: + raise typer.BadParameter( + f"cannot read --team-tokens {team_tokens}: {exc}" + ) from exc + except json.JSONDecodeError as exc: + raise typer.BadParameter( + f"--team-tokens {team_tokens} is not valid JSON: {exc}" + ) from exc + try: + team_auth = TeamAuth.from_config( + config, audit=DenialAudit(audit_log) + ) + except ValueError as exc: + raise typer.BadParameter(str(exc)) from exc server = make_server( _open_store(db), host=host, port=port, - token=os.environ.get("JANUS_API_TOKEN") or None, + token=None if team_auth is not None else (os.environ.get("JANUS_API_TOKEN") or None), + team_auth=team_auth, ) bound_port = server.server_address[1] typer.echo(f"janus api on http://{host}:{bound_port}") diff --git a/core/janus/mcp/team_auth.py b/core/janus/mcp/team_auth.py new file mode 100644 index 0000000..f826e33 --- /dev/null +++ b/core/janus/mcp/team_auth.py @@ -0,0 +1,346 @@ +"""Scoped team tokens, per-token rate limits and denial audit for ``janus serve`` (#153). + +The single ``JANUS_API_TOKEN`` remains the local default: one shared secret that +either opens every route or none. That secret cannot say who called, cannot stop +one caller from starving the others, and records nothing when it says no. This +module adds the smallest honest team mode on top of the same HTTP surface: + +* a token maps to a named ``TokenScope`` (``read`` / ``write`` / ``admin``), + and only the sha256 of the token is kept after construction; +* each token gets its own sliding-window counter, so one caller cannot spend + another caller's budget; +* every denial appends one JSON line carrying the token hash prefix, the route + and the reason — never the token itself. + +Nothing here is a transport or a user directory: the operator supplies tokens in +a local config file, the server binds to localhost by default, and an empty token +table refuses to start instead of falling back to open access. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import threading +import time +from collections import deque +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable, Iterable, Mapping, Optional + +SCOPES = ("read", "write", "admin") +WINDOW_SECONDS = 60.0 +DEFAULT_RATE_LIMIT_PER_MIN = 60 + + +@dataclass(frozen=True) +class TokenScope: + """What a caller may do; ``admin`` implies ``read`` and ``write``.""" + + read: bool = False + write: bool = False + admin: bool = False + + @classmethod + def parse(cls, values: Iterable[str]) -> "TokenScope": + if isinstance(values, (str, bytes)): + raise ValueError("scopes must be a list of scope names, not a string") + names = [str(value) for value in values] + if not names: + raise ValueError( + "scopes must name at least one of " + ", ".join(SCOPES) + ) + unknown = sorted(set(names) - set(SCOPES)) + if unknown: + raise ValueError("unknown scope(s): " + ", ".join(unknown)) + return cls( + read="read" in names, + write="write" in names, + admin="admin" in names, + ) + + def allows(self, required: str) -> bool: + if required not in SCOPES: + raise ValueError(f"required scope must be one of {', '.join(SCOPES)}") + if self.admin: + return True + return bool(getattr(self, required)) + + +@dataclass(frozen=True) +class TokenRecord: + """One caller: a name, its scopes and its per-minute budget.""" + + token_id: str + scopes: TokenScope + rate_limit_per_min: int = DEFAULT_RATE_LIMIT_PER_MIN + + +@dataclass(frozen=True) +class Principal: + """Who made an authorized call; ``token_id`` and its scopes are the whole record.""" + + token_id: str + scopes: TokenScope + + +class AuthError(Exception): + """A refusal that carries the HTTP status, reason and headers to send.""" + + def __init__( + self, + status: int, + reason: str, + *, + required: Optional[str] = None, + retry_after: Optional[int] = None, + ) -> None: + super().__init__(reason) + self.status = status + self.reason = reason + self.required = required + self.retry_after = retry_after + + def headers(self) -> dict[str, str]: + if self.status == 401: + return {"WWW-Authenticate": 'Bearer realm="janus"'} + if self.status == 403: + return { + "WWW-Authenticate": ( + f'Bearer error="insufficient_scope", scope="{self.required}"' + ) + } + if self.status == 429 and self.retry_after is not None: + return {"Retry-After": str(max(1, self.retry_after))} + return {} + + +class DenialAudit: + """Append-only JSONL of refusals; ``path=None`` keeps lines in memory. + + A line is ``{"at", "event", "token_hash_prefix", "route", "reason", + "status"}``. The prefix is the first eight hex characters of sha256(token), + which identifies a caller without being usable as a credential, and a missing + or malformed header is recorded with an empty prefix. + """ + + def __init__(self, path: Optional[Path | str] = None) -> None: + self.path: Optional[Path] = Path(path) if path is not None else None + self._lines: list[dict[str, Any]] = [] + self._lock = threading.Lock() + + def record( + self, + *, + token_hash_prefix: str, + route: str, + reason: str, + status: int, + ) -> dict[str, Any]: + line = { + "at": datetime.now(timezone.utc).isoformat(), + "event": "denied", + "token_hash_prefix": token_hash_prefix, + "route": route, + "reason": reason, + "status": status, + } + with self._lock: + self._lines.append(line) + if self.path is not None: + self.path.parent.mkdir(parents=True, exist_ok=True) + with self.path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(line, sort_keys=True) + "\n") + return line + + def entries(self) -> list[dict[str, Any]]: + with self._lock: + return [dict(line) for line in self._lines] + + +class TeamAuth: + """Token table with scopes, per-token rate limits and a denial audit.""" + + def __init__( + self, + tokens: Mapping[str, TokenRecord], + *, + audit: Optional[DenialAudit] = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if not tokens: + raise ValueError("no team tokens configured; refusing to start") + records: dict[str, TokenRecord] = {} + seen_ids: set[str] = set() + for raw, record in tokens.items(): + if not isinstance(raw, str) or not raw: + raise ValueError( + f"token for {record.token_id!r} must be a non-empty string" + ) + if not record.token_id: + raise ValueError("token_id must not be empty") + if record.token_id in seen_ids: + raise ValueError( + f"duplicate token_id {record.token_id!r}; each caller needs its own" + ) + seen_ids.add(record.token_id) + digest = hashlib.sha256(raw.encode("utf-8")).hexdigest() + if digest in records: + raise ValueError( + f"duplicate token for {record.token_id!r}; each caller needs its own" + ) + records[digest] = record + self._records = records + # Keyed by digest, not token_id: two entries that declare the same id + # would otherwise share one deque and one budget. + self._windows: dict[str, deque[float]] = { + digest: deque() for digest in records + } + self._lock = threading.Lock() + self.audit = audit if audit is not None else DenialAudit() + self._clock = clock + + @classmethod + def from_config( + cls, + config: Mapping[str, Any], + *, + audit: Optional[DenialAudit] = None, + clock: Callable[[], float] = time.monotonic, + ) -> "TeamAuth": + """Build from ``{"tokens": {token_id: {"token", "scopes", ...}}}``. + + Every malformed entry names its token id, and an absent or empty table is + a startup error rather than an open server. + """ + + if not isinstance(config, Mapping): + raise ValueError("team token config must be a JSON object") + entries = config.get("tokens", config) + if not isinstance(entries, Mapping): + raise ValueError("'tokens' must be an object keyed by token id") + if not entries: + raise ValueError("no team tokens configured; refusing to start") + tokens: dict[str, TokenRecord] = {} + secret_owner: dict[str, str] = {} + for token_id, entry in entries.items(): + if not isinstance(token_id, str) or not token_id: + raise ValueError("token ids must be non-empty strings") + if not isinstance(entry, Mapping): + raise ValueError(f"token {token_id!r} must be an object") + missing = sorted( + field for field in ("token", "scopes") if field not in entry + ) + if missing: + raise ValueError( + f"token {token_id!r} is missing " + ", ".join(missing) + ) + try: + scopes = TokenScope.parse(entry["scopes"]) + except ValueError as exc: + raise ValueError(f"token {token_id!r}: {exc}") from exc + limit = entry.get("rate_limit_per_min", DEFAULT_RATE_LIMIT_PER_MIN) + if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1: + raise ValueError( + f"token {token_id!r} rate_limit_per_min must be an integer >= 1" + ) + raw = entry["token"] + if not isinstance(raw, str) or not raw: + raise ValueError(f"token {token_id!r} token must be a non-empty string") + first = secret_owner.setdefault(raw, token_id) + if first != token_id: + raise ValueError( + f"tokens {first!r} and {token_id!r} share one token; " + "each caller needs its own" + ) + tokens[raw] = TokenRecord( + token_id=token_id, scopes=scopes, rate_limit_per_min=limit + ) + return cls(tokens, audit=audit, clock=clock) + + def _prefix(self, supplied: Optional[str]) -> str: + if not supplied: + return "" + return hashlib.sha256(supplied.encode("utf-8")).hexdigest()[:8] + + def _deny( + self, + status: int, + reason: str, + *, + route: str, + supplied: Optional[str], + required: Optional[str] = None, + retry_after: Optional[int] = None, + ) -> AuthError: + self.audit.record( + token_hash_prefix=self._prefix(supplied), + route=route, + reason=reason, + status=status, + ) + return AuthError( + status, reason, required=required, retry_after=retry_after + ) + + def _check_rate(self, digest: str, record: TokenRecord) -> Optional[int]: + now = self._clock() + window = self._windows[digest] + while window and window[0] <= now - WINDOW_SECONDS: + window.popleft() + if len(window) >= record.rate_limit_per_min: + retry_after = math.ceil(window[0] + WINDOW_SECONDS - now) + return max(1, retry_after) + window.append(now) + return None + + def authorize( + self, + headers: Mapping[str, str], + *, + required: str = "read", + route: str = "/", + ) -> Principal: + """Return the caller or raise :class:`AuthError`; every refusal is audited.""" + + if required not in SCOPES: + raise ValueError(f"required scope must be one of {', '.join(SCOPES)}") + supplied = headers.get("Authorization") if hasattr(headers, "get") else None + if not supplied: + raise self._deny( + 401, "missing_token", route=route, supplied=None, required=required + ) + parts = supplied.split() + if len(parts) != 2 or parts[0].lower() != "bearer": + raise self._deny( + 401, "malformed_token", route=route, supplied=None, required=required + ) + token = parts[1] + digest = hashlib.sha256(token.encode("utf-8")).hexdigest() + record = self._records.get(digest) + if record is None: + raise self._deny( + 401, "unknown_token", route=route, supplied=token, required=required + ) + if not record.scopes.allows(required): + raise self._deny( + 403, + "insufficient_scope", + route=route, + supplied=token, + required=required, + ) + with self._lock: + retry_after = self._check_rate(digest, record) + if retry_after is not None: + raise self._deny( + 429, + "rate_limited", + route=route, + supplied=token, + required=required, + retry_after=retry_after, + ) + return Principal(token_id=record.token_id, scopes=record.scopes) diff --git a/core/janus/server.py b/core/janus/server.py index d5aeb8f..33b0590 100644 --- a/core/janus/server.py +++ b/core/janus/server.py @@ -7,7 +7,7 @@ from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from typing import Any, Optional +from typing import Any, Mapping, Optional, cast from urllib.parse import parse_qs, urlparse from uuid import uuid4 @@ -16,6 +16,7 @@ from .config import load_settings from .contracts import SCHEMA_VERSION from .mcp.service import JanusService +from .mcp.team_auth import AuthError, TeamAuth from .memory.store import JanusStore, open_store WEB_DIR = Path(__file__).resolve().with_name("web") @@ -130,8 +131,10 @@ def snapshot(self) -> dict[str, Any]: class JanusHandler(BaseHTTPRequestHandler): service: JanusService token: Optional[str] = None + team_auth: Optional[TeamAuth] = None metrics: _Metrics = _Metrics() request_id: str = "" + principal: Optional[str] = None def do_OPTIONS(self) -> None: # noqa: N802 self.send_response(204) @@ -147,6 +150,47 @@ def _authorized(self) -> bool: expected = f"Bearer {self.token}" return hmac.compare_digest(supplied, expected) + def _authorize(self, route: str) -> bool: + """Check the shared token or, in team mode, the scoped token table. + + A refusal answers here: the reason and headers come from the auth layer, so + the handler never invents a status, and a denial is already audited there. + """ + + if self.team_auth is not None: + try: + # ``http.client.HTTPMessage`` is mapping-like but not a + # ``Mapping`` subclass; the auth layer only calls ``.get``. + headers = cast(Mapping[str, str], self.headers) + principal = self.team_auth.authorize( + headers, required="read", route=route + ) + except AuthError as exc: + if exc.status == 401: + # One body for missing, malformed and unknown tokens: the + # detailed reason lives in the audit line, not in the reply. + body = { + "error": "unauthorized", + "message": "request denied: authentication required", + } + else: + body = { + "error": exc.reason, + "message": f"request denied: {exc.reason}", + } + if exc.status != 401 and exc.required is not None: + body["required_scope"] = exc.required + self.metrics.record_error() + self._json(exc.status, body, headers=exc.headers()) + return False + self.principal = principal.token_id + return True + if not self._authorized(): + self.metrics.record_error() + self._json(401, {"error": "unauthorized"}) + return False + return True + @staticmethod def _static_name(path: str) -> Optional[str]: if path in ("/", "/index.html"): @@ -215,8 +259,7 @@ def do_GET(self) -> None: # noqa: N802 if parsed.path.startswith("/assets/"): self._json(404, {"error": "not_found", "path": parsed.path}) return - if not self._authorized(): - self._json(401, {"error": "unauthorized"}) + if not self._authorize(parsed.path): return if parsed.path == "/api/panels": self._json( @@ -299,12 +342,22 @@ def do_GET(self) -> None: # noqa: N802 self.metrics.record_error() self._json(400, {"error": type(exc).__name__, "message": str(exc)}) - def _json(self, status: int, payload: Any) -> None: + def _json( + self, + status: int, + payload: Any, + *, + headers: Optional[dict[str, str]] = None, + ) -> None: body = json.dumps(payload, default=str).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Content-Length", str(len(body))) + for name, value in (headers or {}).items(): + self.send_header(name, value) + if self.principal: + self.send_header("X-Janus-Principal", self.principal) if self.request_id: self.send_header("X-Request-ID", self.request_id) self.end_headers() @@ -320,12 +373,20 @@ def make_server( host: str = "127.0.0.1", port: int = 8766, token: Optional[str] = None, + team_auth: Optional[TeamAuth] = None, ) -> ThreadingHTTPServer: + if token is not None and team_auth is not None: + raise ValueError("pass either token or team_auth, not both") service = JanusService(store or open_store(load_settings().database)) handler = type( "BoundJanusHandler", (JanusHandler,), - {"service": service, "token": token, "metrics": _Metrics()}, + { + "service": service, + "token": token, + "team_auth": team_auth, + "metrics": _Metrics(), + }, ) return ThreadingHTTPServer((host, port), handler) @@ -336,8 +397,11 @@ def serve( host: str = "127.0.0.1", port: int = 8766, token: Optional[str] = None, + team_auth: Optional[TeamAuth] = None, ) -> None: - server = make_server(store, host=host, port=port, token=token) + server = make_server( + store, host=host, port=port, token=token, team_auth=team_auth + ) try: server.serve_forever() finally: diff --git a/docs/MCP.md b/docs/MCP.md index cc2f5d2..8064ccb 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -159,6 +159,33 @@ plugin. It is read-only: When `JANUS_API_TOKEN` is set for `janus serve`, every `/api/*` route requires `Authorization: Bearer `; `/health` remains open for readiness checks. +`--team-tokens FILE` replaces that one shared secret with a scoped table +(`core/janus/mcp/team_auth.py`): + +```json +{ + "tokens": { + "dash": {"token": "…", "scopes": ["read"], "rate_limit_per_min": 120}, + "agent": {"token": "…", "scopes": ["read", "write"], "rate_limit_per_min": 30}, + "ops": {"token": "…", "scopes": ["admin"], "rate_limit_per_min": 10} + } +} +``` + +Each caller gets its own sliding-window counter, so one client cannot spend +another's budget; `admin` implies `read` and `write`. Only the sha256 of a token +is kept after startup, and refusals answer `401` (missing, malformed or unknown +token — one status, so a caller cannot enumerate valid tokens), `403` with the +required scope in `WWW-Authenticate`, or `429` with a positive `Retry-After`. +`--audit-log FILE` appends one JSON line per refusal carrying the first eight +hex characters of the token hash, the route and the reason, never the token. +An empty or malformed token table refuses to start instead of falling back to +open access, and two token ids may not share one secret. The panel exposes only +`GET` routes today, so `read` is the only scope any route demands: a `write` or +`admin` token can read, and `write` alone is refused everywhere until a writing +route exists. `--audit-log` requires `--team-tokens`, because the legacy shared +token is not audited. + Panel routes accept `fixture=1` for contract-shaped sample data. The stock route requires `entity_id` and reads the latest feature materialization at or before `as_of`; market and sector routes return an explicit `not_materialized` payload diff --git a/tests/test_team_auth.py b/tests/test_team_auth.py new file mode 100644 index 0000000..1e0faaa --- /dev/null +++ b/tests/test_team_auth.py @@ -0,0 +1,313 @@ +from __future__ import annotations + +import json +import threading +import urllib.error +import urllib.request + +import pytest + +from janus.mcp.team_auth import ( + AuthError, + DenialAudit, + TeamAuth, + TokenRecord, + TokenScope, +) +from janus.memory.store import JanusStore +from janus.server import make_server + + +class Clock: + """Injected monotonic clock; tests never sleep.""" + + def __init__(self, start: float = 1000.0) -> None: + self.now = start + + def __call__(self) -> float: + return self.now + + def advance(self, seconds: float) -> None: + self.now += seconds + + +def _auth( + *, + read_token: str = "read-token", + read_limit: int = 60, + write_token: str = "write-token", + admin_token: str = "admin-token", + clock: Clock | None = None, +) -> TeamAuth: + auth = TeamAuth( + { + read_token: TokenRecord("reader", TokenScope(read=True), read_limit), + write_token: TokenRecord("writer", TokenScope(write=True), 60), + admin_token: TokenRecord("admin", TokenScope(admin=True), 60), + }, + audit=DenialAudit(), + clock=clock or Clock(), + ) + return auth + + +def _headers(token: str | None) -> dict[str, str]: + return {} if token is None else {"Authorization": f"Bearer {token}"} + + +def test_config_names_the_token_and_the_bad_field() -> None: + with pytest.raises(ValueError, match="no team tokens configured"): + TeamAuth.from_config({"tokens": {}}) + with pytest.raises(ValueError, match="token 'ops' is missing token"): + TeamAuth.from_config({"tokens": {"ops": {"scopes": ["read"]}}}) + with pytest.raises(ValueError, match="token 'ops' is missing scopes"): + TeamAuth.from_config({"tokens": {"ops": {"token": "secret"}}}) + with pytest.raises(ValueError, match="token 'ops': unknown scope\\(s\\): root"): + TeamAuth.from_config( + {"tokens": {"ops": {"token": "secret", "scopes": ["read", "root"]}}} + ) + with pytest.raises(ValueError, match="token 'ops': scopes must name at least one"): + TeamAuth.from_config({"tokens": {"ops": {"token": "secret", "scopes": []}}}) + with pytest.raises(ValueError, match="token 'ops' rate_limit_per_min"): + TeamAuth.from_config( + { + "tokens": { + "ops": {"token": "secret", "scopes": ["read"], "rate_limit_per_min": 0} + } + } + ) + with pytest.raises(ValueError, match="no team tokens configured"): + TeamAuth({}) + + +def test_missing_malformed_and_unknown_tokens_are_one_indistinct_401() -> None: + auth = _auth() + for supplied, reason in ( + (None, "missing_token"), + ({"Authorization": "Basic abc"}, "malformed_token"), + ({"Authorization": "Bearer nope"}, "unknown_token"), + ): + with pytest.raises(AuthError) as excinfo: + auth.authorize(supplied or {}, route="/api/theses") + assert excinfo.value.status == 401 + assert excinfo.value.reason == reason + assert "nope" not in str(excinfo.value) + audit = auth.audit.entries() + assert [line["reason"] for line in audit] == [ + "missing_token", + "malformed_token", + "unknown_token", + ] + assert audit[0]["token_hash_prefix"] == "" + assert len(audit[2]["token_hash_prefix"]) == 8 + assert {line["route"] for line in audit} == {"/api/theses"} + + +def test_scope_denial_names_the_required_scope_and_admin_implies_all() -> None: + auth = _auth() + with pytest.raises(AuthError) as excinfo: + auth.authorize(_headers("write-token"), required="read", route="/api/as_of") + assert excinfo.value.status == 403 + assert excinfo.value.headers()["WWW-Authenticate"] == ( + 'Bearer error="insufficient_scope", scope="read"' + ) + assert auth.authorize(_headers("read-token")).token_id == "reader" + for required in ("read", "write"): + assert auth.authorize(_headers("admin-token"), required=required).token_id == "admin" + with pytest.raises(AuthError) as excinfo: + auth.authorize(_headers("read-token"), required="admin") + assert excinfo.value.status == 403 + + +def test_rate_limit_boundary_retry_after_and_recovery() -> None: + clock = Clock() + auth = _auth(read_limit=2, clock=clock) + assert auth.authorize(_headers("read-token")).token_id == "reader" + assert auth.authorize(_headers("read-token")).token_id == "reader" + with pytest.raises(AuthError) as excinfo: + auth.authorize(_headers("read-token")) + assert excinfo.value.status == 429 + assert excinfo.value.headers()["Retry-After"] == "60" + clock.advance(30) + with pytest.raises(AuthError) as excinfo: + auth.authorize(_headers("read-token")) + assert excinfo.value.headers()["Retry-After"] == "30" + clock.advance(31) + assert auth.authorize(_headers("read-token")).token_id == "reader" + assert [line["status"] for line in auth.audit.entries()] == [429, 429] + + +def test_each_token_has_its_own_quota() -> None: + auth = _auth(read_limit=1) + assert auth.authorize(_headers("read-token")).token_id == "reader" + with pytest.raises(AuthError): + auth.authorize(_headers("read-token")) + assert auth.authorize(_headers("write-token"), required="write").token_id == "writer" + assert auth.authorize(_headers("admin-token"), required="admin").token_id == "admin" + + +def test_audit_file_gets_one_named_line_per_denial_without_the_token(tmp_path) -> None: + path = tmp_path / "audit" / "denials.jsonl" + auth = TeamAuth( + {"read-token": TokenRecord("reader", TokenScope(read=True), 1)}, + audit=DenialAudit(path), + clock=Clock(), + ) + assert auth.authorize(_headers("read-token")).token_id == "reader" + with pytest.raises(AuthError): + auth.authorize(_headers("read-token"), route="/api/brief") + with pytest.raises(AuthError): + auth.authorize(_headers("read-token"), required="write", route="/api/brief") + lines = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + assert [line["reason"] for line in lines] == ["rate_limited", "insufficient_scope"] + assert [line["status"] for line in lines] == [429, 403] + assert all(line["event"] == "denied" and line["route"] == "/api/brief" for line in lines) + text = path.read_text(encoding="utf-8") + assert "read-token" not in text + assert all(line["token_hash_prefix"] for line in lines) + + +def test_two_token_ids_may_not_share_one_secret() -> None: + with pytest.raises(ValueError, match="tokens 'alice' and 'bob' share one token"): + TeamAuth.from_config( + { + "tokens": { + "alice": {"token": "same", "scopes": ["read"]}, + "bob": {"token": "same", "scopes": ["admin"]}, + } + } + ) + with pytest.raises(ValueError, match="duplicate token_id 'ops'"): + TeamAuth( + { + "first": TokenRecord("ops", TokenScope(read=True)), + "second": TokenRecord("ops", TokenScope(read=True)), + } + ) + + +def test_independent_quotas_hold_under_concurrent_calls() -> None: + auth = TeamAuth( + { + "alpha": TokenRecord("alpha", TokenScope(read=True), 2), + "beta": TokenRecord("beta", TokenScope(read=True), 2), + }, + audit=DenialAudit(), + clock=Clock(), + ) + results: dict[str, list[object]] = {"alpha": [], "beta": []} + barrier = threading.Barrier(2) + + def worker(token: str) -> None: + barrier.wait() + for _ in range(4): + try: + results[token].append(auth.authorize(_headers(token)).token_id) + except AuthError as error: + results[token].append(error.status) + + threads = [threading.Thread(target=worker, args=(token,)) for token in results] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=5) + assert results["alpha"].count("alpha") == 2 + assert results["beta"].count("beta") == 2 + assert results["alpha"].count(429) == 2 + assert results["beta"].count(429) == 2 + + +def test_cli_refuses_an_audit_log_without_team_tokens(tmp_path) -> None: + """The option pair is validated before any server binds its port.""" + + import typer + + from janus.cli import serve + + with pytest.raises(typer.BadParameter, match="needs --team-tokens"): + serve(host="127.0.0.1", port=0, db=None, team_tokens=None, + audit_log=tmp_path / "audit.jsonl") + + +def test_cli_names_a_bad_token_table_instead_of_a_traceback(tmp_path) -> None: + import typer + + from janus.cli import serve + + config = tmp_path / "tokens.json" + config.write_text( + json.dumps({"tokens": {"ops": {"token": "s", "scopes": ["root"]}}}), + encoding="utf-8", + ) + with pytest.raises(typer.BadParameter, match="token 'ops'"): + serve(host="127.0.0.1", port=0, db=None, team_tokens=config, + audit_log=None) + + +def _start(server) -> str: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return f"http://127.0.0.1:{server.server_address[1]}" + + +def _request(url: str, token: str | None, *, bearer: str | None = None) -> tuple[int, dict, dict]: + request = urllib.request.Request(url) + if token is not None: + request.add_header("Authorization", f"Bearer {token}") + if bearer is not None: + request.add_header("Authorization", bearer) + try: + with urllib.request.urlopen(request, timeout=5) as response: + return response.status, json.loads(response.read().decode()), dict(response.headers) + except urllib.error.HTTPError as error: + return error.code, json.loads(error.read().decode()), dict(error.headers) + + +def test_server_team_mode_401_403_and_429_with_audit_and_no_token_leak(tmp_path) -> None: + log = tmp_path / "denials.jsonl" + auth = TeamAuth( + { + "reader-token": TokenRecord("reader", TokenScope(read=True), 1), + "writer-token": TokenRecord("writer", TokenScope(write=True), 10), + }, + audit=DenialAudit(log), + clock=Clock(), + ) + server = make_server(JanusStore(":memory:"), port=0, team_auth=auth) + url = _start(server) + try: + status, body, _ = _request(f"{url}/api/theses", None) + assert status == 401 and body["error"] == "unauthorized" + status, body, headers = _request(f"{url}/api/theses", None, bearer="Bearer reader-token") + assert status == 200 and body == [] + assert headers["X-Request-ID"] + status, body, headers = _request(f"{url}/api/theses", "reader-token") + assert status == 429 + assert int(headers["Retry-After"]) >= 1 + status, body, _ = _request(f"{url}/api/theses", "writer-token") + assert status == 403 + assert body["required_scope"] == "read" + assert "reader-token" not in json.dumps(body) + assert _request(f"{url}/health", None)[0] == 200 + finally: + server.shutdown() + server.server_close() + records = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + assert [record["reason"] for record in records] == [ + "missing_token", + "rate_limited", + "insufficient_scope", + ] + assert "reader-token" not in log.read_text(encoding="utf-8") + + +def test_team_mode_refuses_ambiguous_or_empty_configuration() -> None: + with pytest.raises(ValueError, match="not both"): + make_server( + JanusStore(":memory:"), + port=0, + token="secret", + team_auth=_auth(), + ) + with pytest.raises(ValueError, match="refusing to start"): + TeamAuth.from_config({"tokens": {}})