Coverage for src/governed_harness/api/auth.py: 96%
150 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Local bearer-token authentication, roles and the decision audit log of the API (#18).
3Without an ``api`` section in ``project.yaml`` (or with ``api.auth: off``) none of this runs
4and the API behaves as in 1.0.0. With it, every request (the dashboard page included) must
5carry ``Authorization: Bearer TOKEN``; the token identifies a person (an actor id) with a role.
7Tokens are compared in constant time, are never logged, never written to events, artifacts,
8the audit log or error messages, and are only accepted in the ``Authorization`` header (never
9in a query string, which servers log).
10"""
12from __future__ import annotations
14import hmac
15import json
16import os
17import secrets
18import threading
19from collections.abc import Awaitable, Callable, Mapping, MutableMapping
20from dataclasses import dataclass
21from pathlib import Path
22from typing import Any
24from pydantic import ValidationError
26from governed_harness.configuration.api import (
27 MIN_API_TOKEN_LENGTH,
28 ApiConfig,
29 ApiRole,
30 role_allows,
31)
32from governed_harness.configuration.loader import find_project_config, load_yaml
33from governed_harness.domain.errors import ConfigurationError
34from governed_harness.domain.models import utc_now
36PRINCIPAL_SCOPE_KEY = "governed_harness.principal"
37"""Where the middleware leaves the authenticated :class:`Principal` in the ASGI scope."""
39AUDIT_LOG = Path("audit") / "api-decisions.jsonl"
40"""The append-only audit log of API decisions, relative to ``.harness/``."""
42Scope = MutableMapping[str, Any]
43Message = MutableMapping[str, Any]
44Receive = Callable[[], Awaitable[Message]]
45Send = Callable[[Message], Awaitable[None]]
46ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
49@dataclass(frozen=True)
50class Principal:
51 """The person a request was authenticated as."""
53 user_id: str
54 role: ApiRole
56 def allows(self, required: ApiRole) -> bool:
57 return role_allows(self.role, required)
60@dataclass(frozen=True)
61class StartToken:
62 """The token of the person who starts the server; ``generated`` when it did not come
63 from the environment (and must be shown to that person once)."""
65 value: str
66 generated: bool
67 source: str
68 """The environment variable it came from, or ``generated``."""
71def api_settings(workspace: Path) -> ApiConfig:
72 """The ``api`` section of the project, authentication off (1.0.0) without it.
74 Fail closed: a ``project.yaml`` that cannot be read, or whose ``api`` section is invalid,
75 raises instead of serving without authentication. A workspace without ``project.yaml``
76 has nothing to configure and keeps the 1.0.0 behaviour."""
77 try:
78 config_path = find_project_config(workspace)
79 except (ConfigurationError, OSError):
80 return ApiConfig(auth="off")
81 raw = load_yaml(config_path)
82 section = raw.get("api")
83 if section is None:
84 return ApiConfig(auth="off")
85 try:
86 return ApiConfig.model_validate(section)
87 except ValidationError as error:
88 # Locations and messages only: a value (a token written in the file by mistake) is
89 # never echoed.
90 problems = "; ".join(
91 f"{'.'.join(str(part) for part in item['loc']) or 'api'}: {item['msg']}"
92 for item in error.errors(include_input=False, include_url=False)
93 )
94 raise ConfigurationError(f"invalid api section in {config_path}: {problems}") from None
97def start_token(settings: ApiConfig, environ: Mapping[str, str] | None = None) -> StartToken:
98 """The start token: the value of ``tokenEnv`` when it is set, else a new random one."""
99 source = os.environ if environ is None else environ
100 name = settings.start_token_env
101 value = source.get(name, "")
102 if value:
103 _check_length(value, f"{name} (the token of {settings.start_user})")
104 return StartToken(value=value, generated=False, source=name)
105 return StartToken(value=secrets.token_urlsafe(32), generated=True, source="generated")
108def _check_length(value: str, label: str) -> None:
109 if len(value) < MIN_API_TOKEN_LENGTH or value != value.strip():
110 # The message names the variable, never its value.
111 raise ConfigurationError(
112 f"the API token in {label} must have at least {MIN_API_TOKEN_LENGTH} characters "
113 "and no surrounding spaces"
114 )
117class TokenAuthenticator:
118 """Maps bearer tokens to people. Every comparison runs (no early exit) in constant time."""
120 def __init__(self, credentials: tuple[tuple[bytes, Principal], ...]) -> None:
121 values = [secret for secret, _ in credentials]
122 if len(set(values)) != len(values):
123 raise ConfigurationError(
124 "two API users share the same token; give each person their own token"
125 )
126 self._credentials = credentials
128 @property
129 def users(self) -> tuple[Principal, ...]:
130 return tuple(principal for _, principal in self._credentials)
132 @classmethod
133 def from_settings(
134 cls,
135 settings: ApiConfig,
136 start: StartToken | str | None,
137 environ: Mapping[str, str] | None = None,
138 notices: list[str] | None = None,
139 ) -> TokenAuthenticator:
140 """The start token (if any) plus each declared user whose variable is set. A user
141 whose variable is not set cannot sign in (a notice says so); a token that is too short
142 stops the server."""
143 source = os.environ if environ is None else environ
144 credentials: list[tuple[bytes, Principal]] = []
145 start_value = start.value if isinstance(start, StartToken) else start
146 if start_value:
147 _check_length(start_value, f"the token of {settings.start_user}")
148 credentials.append(
149 (start_value.encode("utf-8"), Principal(settings.start_user, settings.start_role))
150 )
151 for user in settings.users or ():
152 value = source.get(user.token_env, "")
153 if not value:
154 if notices is not None: 154 ↛ 158line 154 didn't jump to line 158 because the condition on line 154 was always true
155 notices.append(
156 f"API user {user.user_id} cannot sign in: {user.token_env} is not set"
157 )
158 continue
159 _check_length(value, f"{user.token_env} (the token of {user.user_id})")
160 credentials.append((value.encode("utf-8"), Principal(user.user_id, user.role)))
161 return cls(tuple(credentials))
163 def authenticate(self, authorization: str | None) -> Principal | None:
164 presented = bearer_token(authorization)
165 if presented is None:
166 return None
167 candidate = presented.encode("utf-8")
168 match: Principal | None = None
169 for secret, principal in self._credentials:
170 if hmac.compare_digest(secret, candidate):
171 match = principal
172 return match
175def bearer_token(authorization: str | None) -> str | None:
176 if not authorization:
177 return None
178 scheme, _, value = authorization.strip().partition(" ")
179 if scheme.lower() != "bearer" or not value.strip():
180 return None
181 return value.strip()
184_UNAUTHORIZED_DETAIL = "authentication required: send Authorization: Bearer TOKEN"
187class AuthenticationMiddleware:
188 """Requires a valid bearer token on every HTTP request and WebSocket connection; leaves
189 the :class:`Principal` in the scope. ``GET /`` without a token answers 401 with the sign-in
190 page, which asks for the token and keeps it in the tab's ``sessionStorage``."""
192 def __init__(self, app: ASGIApp, authenticator: TokenAuthenticator, sign_in_page: str):
193 self.app = app
194 self.authenticator = authenticator
195 self.sign_in_page = sign_in_page.encode("utf-8")
197 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
198 if scope["type"] not in {"http", "websocket"}:
199 await self.app(scope, receive, send)
200 return
201 principal = self.authenticator.authenticate(_header(scope, b"authorization"))
202 if principal is not None:
203 scope[PRINCIPAL_SCOPE_KEY] = principal
204 await self.app(scope, receive, send)
205 return
206 if scope["type"] == "websocket": 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true
207 await send({"type": "websocket.close", "code": 1008})
208 return
209 if scope.get("method") == "GET" and scope.get("path") == "/":
210 body, media = self.sign_in_page, b"text/html; charset=utf-8"
211 else:
212 body = json.dumps({"detail": _UNAUTHORIZED_DETAIL}).encode("utf-8")
213 media = b"application/json"
214 if scope.get("method") == "HEAD": 214 ↛ 215line 214 didn't jump to line 215 because the condition on line 214 was never true
215 body = b""
216 await send(
217 {
218 "type": "http.response.start",
219 "status": 401,
220 "headers": [
221 (b"content-type", media),
222 (b"content-length", str(len(body)).encode("ascii")),
223 (b"www-authenticate", b'Bearer realm="governed-harness"'),
224 (b"cache-control", b"no-store"),
225 ],
226 }
227 )
228 await send({"type": "http.response.body", "body": body})
231def _header(scope: Scope, name: bytes) -> str | None:
232 for key, value in scope.get("headers", ()):
233 if key.lower() == name:
234 return bytes(value).decode("latin-1")
235 return None
238class DecisionAuditLog:
239 """``.harness/audit/api-decisions.jsonl``: one JSON line per API decision attempt and one
240 per outcome, appended (never rewritten) with mode 0600. It records who (user id and
241 role), what (route, run, decision, ChangeSet digest), from where (client host) and the
242 result, never a token."""
244 def __init__(self, path: Path) -> None:
245 self.path = path
246 self._lock = threading.Lock()
248 @classmethod
249 def for_workspace(cls, workspace: Path) -> DecisionAuditLog:
250 return cls(find_project_config(workspace).parent / AUDIT_LOG)
252 def append(self, record: dict[str, Any]) -> None:
253 line = json.dumps({"time": utc_now().isoformat(), **record}, sort_keys=True)
254 with self._lock:
255 self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
256 descriptor = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
257 with os.fdopen(descriptor, "a", encoding="utf-8") as handle:
258 handle.write(line + "\n")
261__all__ = [
262 "AUDIT_LOG",
263 "PRINCIPAL_SCOPE_KEY",
264 "AuthenticationMiddleware",
265 "DecisionAuditLog",
266 "Principal",
267 "StartToken",
268 "TokenAuthenticator",
269 "api_settings",
270 "bearer_token",
271 "start_token",
272]