Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion core/janus/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
330 changes: 330 additions & 0 deletions core/janus/mcp/team_auth.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading