From e7690b2014378077ef12baeca997082ec5e3b3e5 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Wed, 2 Dec 2026 20:16:15 +0800 Subject: [PATCH 1/3] feat(server): scoped team tokens, per-token rate limits and denial audit (#153) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `janus serve` had one shared `JANUS_API_TOKEN`: it could not say who called, could not stop one caller from spending every other caller's budget, and wrote nothing when it refused. `--team-tokens FILE` now maps each caller to a name, a `read`/`write`/`admin` scope and a per-minute quota; `admin` implies the other two. Only sha256(token) is kept, each token gets its own sliding window (injected clock, no sleeps), and refusals answer 401 for missing, malformed and unknown tokens alike so a caller cannot enumerate them, 403 with the required scope in `WWW-Authenticate`, or 429 with a positive `Retry-After`. `--audit-log FILE` appends one JSON line per refusal with the first eight hex characters of the token hash, the route and the reason — never the token. An empty or malformed table raises at startup, and passing both the legacy token and a team table is an error, so the server fails closed instead of guessing. --- core/janus/cli.py | 25 ++- core/janus/mcp/team_auth.py | 330 ++++++++++++++++++++++++++++++++++++ core/janus/server.py | 66 +++++++- docs/MCP.md | 23 +++ tests/test_team_auth.py | 236 ++++++++++++++++++++++++++ 5 files changed, 673 insertions(+), 7 deletions(-) create mode 100644 core/janus/mcp/team_auth.py create mode 100644 tests/test_team_auth.py diff --git a/core/janus/cli.py b/core/janus/cli.py index 0d7335d..a700747 100644 --- a/core/janus/cli.py +++ b/core/janus/cli.py @@ -638,17 +638,40 @@ 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() + 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 + team_auth = TeamAuth.from_config( + config, audit=DenialAudit(audit_log) + ) 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..153bba0 --- /dev/null +++ b/core/janus/mcp/team_auth.py @@ -0,0 +1,330 @@ +"""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, for handlers and audit lines.""" + + 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] = {} + 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") + 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 + self._windows: dict[str, deque[float]] = { + record.token_id: deque() for record in records.values() + } + 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] = {} + 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") + 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, record: TokenRecord) -> Optional[int]: + now = self._clock() + window = self._windows[record.token_id] + 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] + record = self._records.get(hashlib.sha256(token.encode("utf-8")).hexdigest()) + 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(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..af00129 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,39 @@ 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: + body = { + "error": exc.reason, + "message": f"request denied: {exc.reason}", + } + if 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 +251,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 +334,20 @@ 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.request_id: self.send_header("X-Request-ID", self.request_id) self.end_headers() @@ -320,12 +363,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 +387,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..d9edcd3 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -159,6 +159,29 @@ 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. + 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..a47d79a --- /dev/null +++ b/tests/test_team_auth.py @@ -0,0 +1,236 @@ +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 _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"] == "missing_token" + 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": {}}) From fdb4608968f6f28d3db756b783c0367253610660 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Wed, 2 Dec 2026 20:43:56 +0800 Subject: [PATCH 2/3] fix(server): refuse a shared token secret and audit only in team mode (#153) The review's blocking item was real: `from_config` keyed its table by the raw secret, so two token ids sharing one secret collapsed to the last entry before `__init__` could see the collision. Alice's calls were attributed to Bob and her token carried Bob's scopes. `from_config` now refuses `tokens 'alice' and 'bob' share one token`, `__init__` refuses a duplicate `token_id`, and the rate-limit windows are keyed by digest instead of by name, so two records can never share one budget. Also from the review: 401 answers carry only `unauthorized` (the detail stays in the audit line), `--audit-log` without `--team-tokens` is a usage error rather than a silently dropped flag, a bad token table is a one-line `BadParameter` instead of a traceback, the authorized caller is sent back in `X-Janus-Principal`, and `docs/MCP.md` says plainly that `read` is the only scope any current route demands. --- core/janus/cli.py | 13 ++++-- core/janus/mcp/team_auth.py | 28 ++++++++++--- core/janus/server.py | 20 +++++++--- docs/MCP.md | 6 ++- tests/test_team_auth.py | 79 ++++++++++++++++++++++++++++++++++++- 5 files changed, 130 insertions(+), 16 deletions(-) diff --git a/core/janus/cli.py b/core/janus/cli.py index a700747..87d9d07 100644 --- a/core/janus/cli.py +++ b/core/janus/cli.py @@ -651,6 +651,10 @@ def serve( 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: @@ -663,9 +667,12 @@ def serve( raise typer.BadParameter( f"--team-tokens {team_tokens} is not valid JSON: {exc}" ) from exc - team_auth = TeamAuth.from_config( - config, audit=DenialAudit(audit_log) - ) + 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, diff --git a/core/janus/mcp/team_auth.py b/core/janus/mcp/team_auth.py index 153bba0..f826e33 100644 --- a/core/janus/mcp/team_auth.py +++ b/core/janus/mcp/team_auth.py @@ -80,7 +80,7 @@ class TokenRecord: @dataclass(frozen=True) class Principal: - """Who made an authorized call, for handlers and audit lines.""" + """Who made an authorized call; ``token_id`` and its scopes are the whole record.""" token_id: str scopes: TokenScope @@ -173,6 +173,7 @@ def __init__( 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( @@ -180,6 +181,11 @@ def __init__( ) 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( @@ -187,8 +193,10 @@ def __init__( ) 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]] = { - record.token_id: deque() for record in records.values() + digest: deque() for digest in records } self._lock = threading.Lock() self.audit = audit if audit is not None else DenialAudit() @@ -216,6 +224,7 @@ def from_config( 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") @@ -240,6 +249,12 @@ def from_config( 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 ) @@ -270,9 +285,9 @@ def _deny( status, reason, required=required, retry_after=retry_after ) - def _check_rate(self, record: TokenRecord) -> Optional[int]: + def _check_rate(self, digest: str, record: TokenRecord) -> Optional[int]: now = self._clock() - window = self._windows[record.token_id] + window = self._windows[digest] while window and window[0] <= now - WINDOW_SECONDS: window.popleft() if len(window) >= record.rate_limit_per_min: @@ -303,7 +318,8 @@ def authorize( 401, "malformed_token", route=route, supplied=None, required=required ) token = parts[1] - record = self._records.get(hashlib.sha256(token.encode("utf-8")).hexdigest()) + 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 @@ -317,7 +333,7 @@ def authorize( required=required, ) with self._lock: - retry_after = self._check_rate(record) + retry_after = self._check_rate(digest, record) if retry_after is not None: raise self._deny( 429, diff --git a/core/janus/server.py b/core/janus/server.py index af00129..33b0590 100644 --- a/core/janus/server.py +++ b/core/janus/server.py @@ -166,11 +166,19 @@ def _authorize(self, route: str) -> bool: headers, required="read", route=route ) except AuthError as exc: - body = { - "error": exc.reason, - "message": f"request denied: {exc.reason}", - } - if exc.required is not None: + 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()) @@ -348,6 +356,8 @@ def _json( 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() diff --git a/docs/MCP.md b/docs/MCP.md index d9edcd3..8064ccb 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -180,7 +180,11 @@ 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. +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 diff --git a/tests/test_team_auth.py b/tests/test_team_auth.py index a47d79a..c354031 100644 --- a/tests/test_team_auth.py +++ b/tests/test_team_auth.py @@ -167,6 +167,83 @@ def test_audit_file_gets_one_named_line_per_denial_without_the_token(tmp_path) - 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: + from typer.testing import CliRunner + + from janus.cli import app + + result = CliRunner().invoke( + app, ["serve", "--audit-log", str(tmp_path / "audit.jsonl")] + ) + assert result.exit_code == 2 + assert "team-tokens" in result.output + + +def test_cli_names_a_bad_token_table_instead_of_a_traceback(tmp_path) -> None: + from typer.testing import CliRunner + + from janus.cli import app + + config = tmp_path / "tokens.json" + config.write_text( + json.dumps({"tokens": {"ops": {"token": "s", "scopes": ["root"]}}}), + encoding="utf-8", + ) + result = CliRunner().invoke(app, ["serve", "--team-tokens", str(config)]) + assert result.exit_code == 2 + assert "token 'ops'" in result.output + + def _start(server) -> str: thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() @@ -200,7 +277,7 @@ def test_server_team_mode_401_403_and_429_with_audit_and_no_token_leak(tmp_path) url = _start(server) try: status, body, _ = _request(f"{url}/api/theses", None) - assert status == 401 and body["error"] == "missing_token" + 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"] From 54791cb43cb2afda0f3ea97d78c6bce4d0daa702 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Wed, 2 Dec 2026 20:47:31 +0800 Subject: [PATCH 3/3] test(server): assert the CLI refusals on the function, not on rich output --- tests/test_team_auth.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/test_team_auth.py b/tests/test_team_auth.py index c354031..1e0faaa 100644 --- a/tests/test_team_auth.py +++ b/tests/test_team_auth.py @@ -218,30 +218,30 @@ def worker(token: str) -> None: def test_cli_refuses_an_audit_log_without_team_tokens(tmp_path) -> None: - from typer.testing import CliRunner + """The option pair is validated before any server binds its port.""" - from janus.cli import app + import typer - result = CliRunner().invoke( - app, ["serve", "--audit-log", str(tmp_path / "audit.jsonl")] - ) - assert result.exit_code == 2 - assert "team-tokens" in result.output + 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: - from typer.testing import CliRunner + import typer - from janus.cli import app + from janus.cli import serve config = tmp_path / "tokens.json" config.write_text( json.dumps({"tokens": {"ops": {"token": "s", "scopes": ["root"]}}}), encoding="utf-8", ) - result = CliRunner().invoke(app, ["serve", "--team-tokens", str(config)]) - assert result.exit_code == 2 - assert "token 'ops'" in result.output + 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: