Coverage for src/governed_harness/configuration/api.py: 100%
92 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"""Authentication and roles of the local API and dashboard (since 2.0, issue #18).
3``harness api serve`` of 1.0.0 had no authentication: any process that reached the port could
4read every run and record a decision under any actor id. The ``api`` section turns on a local
5bearer-token check for every route and three roles:
7* ``viewer``: every ``GET`` (the dashboard, runs, briefs, traces, evidence);
8* ``reviewer``: a viewer that may also decide (``POST /api/runs/ID/decision``);
9* ``admin``: a reviewer that may also read the effective configuration (``GET /api/config``).
11Tokens never appear in ``project.yaml``: the section names the environment variable that holds
12each one. The token of the person who starts the server comes from ``tokenEnv`` or, when that
13variable is not set, is generated at start and shown once on the terminal.
15Every key is optional. A project without the section keeps the 1.0.0 behaviour (no
16authentication) and its configuration digest, because the section is left out of the
17serialized configuration. With the section present and ``auth`` absent, authentication is on.
18"""
20from __future__ import annotations
22import re
23from typing import Any, Literal
25from pydantic import (
26 BaseModel,
27 ConfigDict,
28 Field,
29 SerializerFunctionWrapHandler,
30 field_validator,
31 model_serializer,
32 model_validator,
33)
35from governed_harness.configuration.agent_results import off_from_yaml
36from governed_harness.domain.actors import DEFAULT_API_ACTOR, is_non_human_actor_id
38ApiRole = Literal["viewer", "reviewer", "admin"]
39API_ROLES: tuple[ApiRole, ...] = ("viewer", "reviewer", "admin")
40"""The roles from the least to the most privileged; each one includes the ones before it."""
42DEFAULT_API_TOKEN_ENV = "HARNESS_API_TOKEN" # nosec B105 - an environment variable name, not a token
43DEFAULT_API_TOKEN_ROLE: ApiRole = "admin"
44MIN_API_TOKEN_LENGTH = 16
45"""Shorter tokens taken from the environment are refused at start (fail closed)."""
47_ENV_NAME = re.compile(r"^[A-Za-z_]\w{0,127}$", re.ASCII)
48_USER_ID = re.compile(r"^[a-z][a-z0-9_.-]{1,127}$")
51def role_allows(role: ApiRole, required: ApiRole) -> bool:
52 """Whether ``role`` includes the permissions of ``required``."""
53 return API_ROLES.index(role) >= API_ROLES.index(required)
56def _env_name(value: str) -> str:
57 if not _ENV_NAME.match(value):
58 raise ValueError(f"not an environment variable name: {value!r}")
59 return value
62def _user_id(value: str) -> str:
63 if not _USER_ID.match(value):
64 raise ValueError(
65 f"user id {value!r} must be an actor id: lower case, starting with a letter, "
66 "then letters, digits, '_', '.' or '-' (2 to 128 characters)"
67 )
68 if is_non_human_actor_id(value):
69 raise ValueError(
70 f"user id {value!r} belongs to the agent, validator or harness namespace; "
71 "API users are people"
72 )
73 return value
76class _Section(BaseModel):
77 """A section whose unset (``None``) keys are left out of the serialized configuration."""
79 model_config = ConfigDict(extra="forbid", populate_by_name=True, frozen=True)
81 @model_serializer(mode="wrap")
82 def _omit_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
83 data: dict[str, Any] = handler(self)
84 for name, field in type(self).model_fields.items():
85 if getattr(self, name) is None:
86 data.pop(name, None)
87 data.pop(field.alias or name, None)
88 return data
91class ApiUser(_Section):
92 """A person who may use the API: the actor id recorded on their decisions, their role and
93 the NAME of the environment variable that holds their token (never the token itself)."""
95 user_id: str = Field(alias="id")
96 role: ApiRole
97 token_env: str = Field(alias="tokenEnv")
99 @field_validator("user_id")
100 @classmethod
101 def _valid_user(cls, value: str) -> str:
102 return _user_id(value)
104 @field_validator("token_env")
105 @classmethod
106 def _valid_env(cls, value: str) -> str:
107 return _env_name(value)
110class ApiConfig(_Section):
111 """``harness api serve`` authentication (#18). ``auth: token`` (the default when the
112 section is present) requires ``Authorization: Bearer TOKEN`` on every route; ``off`` keeps
113 the 1.0.0 behaviour. ``tokenEnv`` names the variable holding the token of the person who
114 starts the server (generated and shown once when it is not set), ``tokenUser`` the actor
115 id recorded on that person's decisions and ``tokenRole`` their role. ``users`` declares
116 further people, each with an id, a role and the variable of their token."""
118 auth: Literal["token", "off"] | None = None
119 token_env: str | None = Field(default=None, alias="tokenEnv")
120 token_user: str | None = Field(default=None, alias="tokenUser")
121 token_role: ApiRole | None = Field(default=None, alias="tokenRole")
122 users: tuple[ApiUser, ...] | None = None
124 @field_validator("auth", mode="before")
125 @classmethod
126 def _bare_off(cls, value: Any) -> Any:
127 return off_from_yaml(value)
129 @field_validator("token_env")
130 @classmethod
131 def _valid_env(cls, value: str | None) -> str | None:
132 return None if value is None else _env_name(value)
134 @field_validator("token_user")
135 @classmethod
136 def _valid_user(cls, value: str | None) -> str | None:
137 return None if value is None else _user_id(value)
139 @model_validator(mode="after")
140 def _distinct_users(self) -> ApiConfig:
141 ids = [self.start_user, *(user.user_id for user in self.users or ())]
142 envs = [self.start_token_env, *(user.token_env for user in self.users or ())]
143 for label, values in (("user id", ids), ("tokenEnv", envs)):
144 repeated = sorted({value for value in values if values.count(value) > 1})
145 if repeated:
146 raise ValueError(
147 f"api: each {label} must be distinct (the start token counts as "
148 f"{self.start_user} with {self.start_token_env}): {', '.join(repeated)}"
149 )
150 return self
152 @property
153 def enabled(self) -> bool:
154 """Whether the API requires a token (the section is present and ``auth`` is not
155 ``off``)."""
156 return self.auth != "off"
158 @property
159 def start_token_env(self) -> str:
160 return self.token_env or DEFAULT_API_TOKEN_ENV
162 @property
163 def start_user(self) -> str:
164 return self.token_user or DEFAULT_API_ACTOR
166 @property
167 def start_role(self) -> ApiRole:
168 return self.token_role or DEFAULT_API_TOKEN_ROLE
170 @property
171 def token_env_names(self) -> tuple[str, ...]:
172 """Every variable that may hold an API token (their values are redacted from the
173 artifacts like any other secret of the environment)."""
174 return (self.start_token_env, *(user.token_env for user in self.users or ()))
177__all__ = [
178 "API_ROLES",
179 "DEFAULT_API_TOKEN_ENV",
180 "DEFAULT_API_TOKEN_ROLE",
181 "MIN_API_TOKEN_LENGTH",
182 "ApiConfig",
183 "ApiRole",
184 "ApiUser",
185 "role_allows",
186]