egzoscore 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. egzos/__init__.py +11 -0
  2. egzos/_ids.py +29 -0
  3. egzos/_signals.py +39 -0
  4. egzos/_term.py +33 -0
  5. egzos/_types.py +1023 -0
  6. egzos/api/__init__.py +150 -0
  7. egzos/api/app.py +1574 -0
  8. egzos/api/blobs.py +92 -0
  9. egzos/api/throttle.py +190 -0
  10. egzos/auth.py +176 -0
  11. egzos/authz/__init__.py +5 -0
  12. egzos/authz/presence.py +778 -0
  13. egzos/authz/values.py +32 -0
  14. egzos/backends/__init__.py +8 -0
  15. egzos/backends/base.py +91 -0
  16. egzos/backends/postgres.py +490 -0
  17. egzos/backends/sqlite.py +524 -0
  18. egzos/binding.py +309 -0
  19. egzos/cli/__init__.py +1092 -0
  20. egzos/cli/__main__.py +11 -0
  21. egzos/confirm.py +455 -0
  22. egzos/container.py +222 -0
  23. egzos/identity.py +1104 -0
  24. egzos/ledger.py +167 -0
  25. egzos/mcp/__init__.py +3 -0
  26. egzos/mcp/http.py +90 -0
  27. egzos/mcp/server.py +287 -0
  28. egzos/model.py +242 -0
  29. egzos/py.typed +0 -0
  30. egzos/resolver.py +115 -0
  31. egzos/store/__init__.py +10 -0
  32. egzos/store/autotitle.py +31 -0
  33. egzos/store/blobs.py +120 -0
  34. egzos/store/find.py +120 -0
  35. egzos/store/items.py +233 -0
  36. egzos/store/nodes.py +193 -0
  37. egzos/store/objects.py +143 -0
  38. egzos/store/uploads.py +369 -0
  39. egzos/trust.py +675 -0
  40. egzos/web/__init__.py +88 -0
  41. egzos/web/app.py +965 -0
  42. egzos/web/static/htmx.LICENSE +13 -0
  43. egzos/web/static/htmx.min.js +1 -0
  44. egzos/web/static/lifeboat.css +140 -0
  45. egzos/web/static/lifeboat.js +12 -0
  46. egzos/web/strings.py +133 -0
  47. egzos/web/templates/_manifest_row.html +3 -0
  48. egzos/web/templates/_shell.html +29 -0
  49. egzos/web/templates/_window.html +7 -0
  50. egzos/web/templates/base.html +24 -0
  51. egzos/web/templates/error.html +10 -0
  52. egzos/web/templates/home.html +39 -0
  53. egzos/web/templates/item.html +91 -0
  54. egzos/web/templates/notfound.html +6 -0
  55. egzos/web/templates/pending.html +107 -0
  56. egzos/web/tokens.css +294 -0
  57. egzoscore-0.2.0.dist-info/METADATA +135 -0
  58. egzoscore-0.2.0.dist-info/RECORD +62 -0
  59. egzoscore-0.2.0.dist-info/WHEEL +4 -0
  60. egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
  61. egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
  62. egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/identity.py ADDED
@@ -0,0 +1,1104 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The container as a resource server (spec/contracts/identity.md).
5
+
6
+ A request may carry an access token signed by the container's identity provider (Supabase Auth):
7
+ a person's, issued to this container's own OAuth client or to a terminal's own client that the
8
+ person registered here (§4, v0.7 §AJ), or an agent's, issued to a client that the person it serves
9
+ registered here (§4: each person registers their own, v0.7 §AB). Both registrations are kept in
10
+ one store, told apart by `kind`, and every reader here names the kind it wants.
11
+ `Identity.verify` runs §3's seven checks in order, on every request, and answers
12
+ with the principal the token maps to, or `None`: every failure is the same answer, whichever check
13
+ failed. The JWT work is PyJWT's (buy, don't build). What is here is what egzos is: the order, the
14
+ binding to this one container, and the grants that decide what a verified caller may do (§4).
15
+
16
+ A verified caller reaches the engine as a `GrantToken`: a `Token` built per request from the grant
17
+ (and, for an agent, the registration intersected with it), never stored, so coverage, the gate and
18
+ the audience treat a granted person exactly as they treat a minted token. A person at a terminal is
19
+ that person, with the grant as it stands, under the terminal's own id and marked with its client.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import ipaddress
25
+ import json
26
+ import re
27
+ import threading
28
+ import time
29
+ import unicodedata
30
+ import urllib.request
31
+ from collections.abc import Callable, Iterable
32
+ from contextlib import AbstractContextManager, nullcontext
33
+ from dataclasses import dataclass, field
34
+ from typing import Any
35
+ from urllib.parse import unquote, urlsplit
36
+
37
+ import jwt
38
+
39
+ from egzos._types import (
40
+ REGISTRATION_KINDS,
41
+ AgentRegistration,
42
+ IdentityState,
43
+ Registration,
44
+ RegistrationKind,
45
+ TerminalRegistration,
46
+ UserGrant,
47
+ )
48
+ from egzos.ledger import Ledger
49
+ from egzos.model import CAPABILITIES, ROLE_BUNDLES, Node, Token, now_iso
50
+
51
+ #: §2: never `none`, never a symmetric `HS*`. The asymmetric algorithms PyJWT verifies.
52
+ ASYMMETRIC_ALGORITHMS = frozenset(
53
+ {"ES256", "ES384", "ES512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "EdDSA"}
54
+ )
55
+ #: §3 check 4: `exp` and `iat` each get at most this much clock skew.
56
+ SKEW_SECONDS = 60
57
+ #: §3 check 1: an unknown `kid` re-fetches the key set at most once a minute.
58
+ JWKS_REFETCH_SECONDS = 60
59
+ #: A key set is a handful of public keys; anything larger is not one.
60
+ JWKS_MAX_BYTES = 64 * 1024
61
+ #: A bearer value longer than this is not a provider token, and is refused before any parsing.
62
+ TOKEN_MAX_CHARS = 16 * 1024
63
+
64
+ #: §2's keys this module reads, wire spelling.
65
+ IDENTITY_KEYS = (
66
+ "identity.issuer",
67
+ "identity.client_id",
68
+ "identity.audience",
69
+ "identity.algorithms",
70
+ "identity.browser_origins",
71
+ )
72
+ #: The keys some code reads, so the only keys `config set` takes: §2's seven (`identity.origin` is
73
+ #: the door's, `egzos.api`; `confirm.allow_button` the confirm's, `egzos.confirm`), and the two the
74
+ #: upload reads (`rest.md` §4.4).
75
+ SETTABLE_KEYS = (
76
+ *IDENTITY_KEYS, "identity.origin", "confirm.allow_button", "blobs.upload_max_bytes",
77
+ "blobs.staging_retention_days",
78
+ )
79
+ #: The bounds of the two numeric keys: an upload of 1 byte to 1 TiB; 0 days to a century.
80
+ _NUMBERS = {"blobs.upload_max_bytes": (1, 1 << 40), "blobs.staging_retention_days": (0, 36500)}
81
+
82
+ _NO_CLAIM_CHECKS = {
83
+ # PyJWT verifies the signature; the claims are checked below, in §3's order, by this module.
84
+ "verify_signature": True,
85
+ "verify_exp": False,
86
+ "verify_nbf": False,
87
+ "verify_iat": False,
88
+ "verify_aud": False,
89
+ "verify_iss": False,
90
+ "verify_sub": False,
91
+ "verify_jti": False,
92
+ "require": [],
93
+ }
94
+
95
+
96
+ class ConfigError(ValueError):
97
+ """A config value this container will not hold. The message names the key, never a caller."""
98
+
99
+
100
+ class LastAdmin(Exception):
101
+ """§4: the last live grant holding `admin` over `["*"]` is never revoked."""
102
+
103
+
104
+ #: rest.md §4.3: the live agent registrations one person holds at most, so the audience the gate
105
+ #: computes over registrations (§4) stays bounded.
106
+ MAX_AGENTS = 16
107
+ #: rest.md §4.3: the live terminal registrations one person holds at most, counted apart from
108
+ #: their agents, which bounds what one person's tokens spend together (rest.md §6).
109
+ MAX_TERMINALS = 16
110
+
111
+
112
+ class TooManyAgents(Exception):
113
+ """rest.md §4.3: the person already holds `MAX_AGENTS` live agent registrations. Their own
114
+ fact."""
115
+
116
+
117
+ class TooManyTerminals(Exception):
118
+ """rest.md §4.3: the person already holds `MAX_TERMINALS` live terminal registrations. Their
119
+ own fact."""
120
+
121
+
122
+ class Registered(Exception):
123
+ """identity.md §4, rest.md §4.3: a `client_id` is registered as a terminal once. One that
124
+ names any registration here is never registered as a terminal, and one that names a
125
+ terminal's is never registered as an agent. The door concludes the confirm refused,
126
+ `registered`, never a refusal that says so before a leg."""
127
+
128
+
129
+ #: A name shown to a person deciding something — who would newly see an item, an agent's own
130
+ #: claim, a device — is at most this long.
131
+ DISPLAY_NAME_MAX = 128
132
+ #: Characters a display name never holds: controls, and the formatting characters (bidi
133
+ #: overrides among them) that make text read other than it is (a6 on #289).
134
+ _HIDDEN = frozenset({"Cc", "Cf", "Zl", "Zp"})
135
+
136
+
137
+ def display_name(value: Any, *, limit: int = DISPLAY_NAME_MAX) -> str:
138
+ """A display name as given, or `ValueError`. Untrusted display data every surface escapes;
139
+ this keeps it short and free of characters that hide what it says."""
140
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
141
+ raise ValueError(f"a name of 1 to {limit} characters")
142
+ if any(unicodedata.category(ch) in _HIDDEN for ch in value):
143
+ raise ValueError("a name holds no control or formatting characters")
144
+ return value
145
+
146
+
147
+ def provider_id(value: Any, what: str = "an id the provider issued") -> str:
148
+ """An id the provider issued — a user's, an OAuth client's, an authorization's — as given, or
149
+ `ValueError(what)`: 1 to 255 characters, with no whitespace and, as in a display name, no
150
+ control or formatting character, so it reads as what it is wherever it is listed."""
151
+ if not isinstance(value, str) or not value or len(value) > 255 or any(
152
+ ch.isspace() or unicodedata.category(ch) in _HIDDEN for ch in value
153
+ ):
154
+ raise ValueError(what)
155
+ return value
156
+
157
+
158
+ def principal_id(client_id: str | None, sub: str, kind: RegistrationKind = "agent") -> str:
159
+ """A provider principal's `Token.id`, naming exactly one `(client_id, sub)` pair of one kind
160
+ (GHSA-9g46-638p-v4xm, rest.md §6): `user:<sub>` for a person, `agent:<client_id>:<sub>` for an
161
+ agent, as ever, and `terminal:<client_id>:<sub>` for a person at a terminal (v0.7 §AJ), where
162
+ no part holds `%` or `:`, a UUID among them. Otherwise the kind is `user%`, `agent%` or
163
+ `terminal%`, which no id written before held, and each part has `%` written `%25` and `:`
164
+ `%3A`. `kind` is read only with a `client_id`. The owner and `acting_for` are attribution, not
165
+ ids: one part each, raw (identity.md §3a)."""
166
+ name, parts = ("user", [sub]) if client_id is None else (kind, [client_id, sub])
167
+ if any("%" in p or ":" in p for p in parts):
168
+ name, parts = name + "%", [p.replace("%", "%25").replace(":", "%3A") for p in parts]
169
+ return ":".join([name, *parts])
170
+
171
+
172
+ def principal_of(token_id: str) -> tuple[str, str | None, str] | None:
173
+ """`(kind, client_id, sub)` for the provider principal an id names, `kind` one of `user`,
174
+ `agent` and `terminal`, and `client_id` None for a person: `principal_id` read back. None for
175
+ any string `principal_id` would not write, a container `Token`'s ULID among them, so no other
176
+ spelling names a pair, and an id names one kind."""
177
+ parts = [unquote(p) for p in token_id.split(":")[1:]]
178
+ if not 1 <= len(parts) <= 2 or not all(parts):
179
+ return None
180
+ if len(parts) == 1:
181
+ return ("user", None, parts[0]) if principal_id(None, parts[0]) == token_id else None
182
+ # The kind is never parsed: this round trip is what refuses a foreign or mismatched one.
183
+ for kind in REGISTRATION_KINDS:
184
+ if principal_id(parts[0], parts[1], kind) == token_id:
185
+ return kind, parts[0], parts[1]
186
+ return None
187
+
188
+
189
+ def principal_parts(token_id: str) -> tuple[str | None, str] | None:
190
+ """The `(client_id, sub)` pair a person's or an agent's id names, `client_id` None for a
191
+ person. None for a terminal's id, which `principal_of` reads with its kind, so a reader of
192
+ this pair never takes a terminal for an agent, and None for any string `principal_id` would
193
+ not write."""
194
+ read = principal_of(token_id)
195
+ if read is None or read[0] == "terminal":
196
+ return None
197
+ return read[1], read[2]
198
+
199
+
200
+ # -- configuration (§2) --------------------------------------------------------------------------
201
+ def _loopback(host: str | None) -> bool:
202
+ if host is None:
203
+ return False
204
+ if host == "localhost":
205
+ return True
206
+ try:
207
+ return ipaddress.ip_address(host).is_loopback
208
+ except ValueError:
209
+ return False
210
+
211
+
212
+ _LABEL = r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
213
+ #: An origin as a browser sends one (RFC 6454 §6.2): a scheme, a lowercase ASCII host or a
214
+ #: bracketed IPv6 address, and a port, with nothing around them.
215
+ _ORIGIN = re.compile(rf"(https?)://({_LABEL}(?:\.{_LABEL})*|\[[0-9a-f:]+\])(?::([1-9][0-9]*))?")
216
+ _DEFAULT_PORT = {"https": 443, "http": 80}
217
+
218
+
219
+ def _origin(value: str, *, key: str) -> str:
220
+ """An origin, exactly as a browser sends it: `https://host[:port]`, or `http://` on a loopback
221
+ host only, with no default port and nothing else. Only such a value can match an `Origin`
222
+ header, and only such a value is published (§7) as it is held."""
223
+ match = _ORIGIN.fullmatch(value)
224
+ scheme, host, port = match.groups() if match else ("", "", None)
225
+ if host.startswith("["): # an IPv6 address, written as a browser writes it, or nothing
226
+ try:
227
+ host = host[1:-1] if ipaddress.IPv6Address(host[1:-1]).compressed == host[1:-1] else ""
228
+ except ValueError:
229
+ host = ""
230
+ if not host or port is not None and (
231
+ len(port) > 5 or int(port) > 65535 or int(port) == _DEFAULT_PORT[scheme]):
232
+ raise ConfigError(f"{key}: {value!r} is not an origin")
233
+ if scheme == "http" and not _loopback(host):
234
+ raise ConfigError(f"{key}: plain http is for a loopback host only")
235
+ return value
236
+
237
+
238
+ def validate(key: str, value: Any) -> Any:
239
+ """The value `key` may hold, normalised, or `ConfigError`. None of these is a secret (§2)."""
240
+ if key == "identity.issuer":
241
+ if value is None:
242
+ return None
243
+ if not isinstance(value, str):
244
+ raise ConfigError(f"{key}: a URL, or nothing")
245
+ parts = urlsplit(value)
246
+ if parts.scheme not in ("https", "http") or not parts.hostname:
247
+ raise ConfigError(f"{key}: {value!r} is not a URL")
248
+ if parts.scheme == "http" and not _loopback(parts.hostname):
249
+ raise ConfigError(f"{key}: plain http is for a loopback host only")
250
+ if parts.query or parts.fragment or parts.username or parts.password:
251
+ raise ConfigError(f"{key}: an issuer has no query, fragment or credentials")
252
+ return value
253
+ if key == "identity.client_id":
254
+ if value is None:
255
+ return None
256
+ if not isinstance(value, str) or not value or len(value) > 255 or value != value.strip():
257
+ raise ConfigError(f"{key}: a client id, or nothing")
258
+ if any(c.isspace() for c in value):
259
+ raise ConfigError(f"{key}: a client id holds no whitespace")
260
+ return value
261
+ if key == "identity.audience":
262
+ if not isinstance(value, str) or not value.strip() or len(value) > 255:
263
+ raise ConfigError(f"{key}: an audience value")
264
+ return value.strip()
265
+ if key == "identity.algorithms":
266
+ names = value.split() if isinstance(value, str) else []
267
+ if not names:
268
+ raise ConfigError(f"{key}: one or more of {' '.join(sorted(ASYMMETRIC_ALGORITHMS))}")
269
+ refused = [n for n in names if n not in ASYMMETRIC_ALGORITHMS]
270
+ if refused:
271
+ raise ConfigError(f"{key}: {' '.join(refused)} refused; asymmetric algorithms only")
272
+ return " ".join(dict.fromkeys(names))
273
+ if key == "identity.browser_origins":
274
+ if not isinstance(value, str):
275
+ raise ConfigError(f"{key}: origins, separated by spaces")
276
+ return " ".join(dict.fromkeys(_origin(o, key=key) for o in value.split()))
277
+ if key == "identity.origin":
278
+ if value is None:
279
+ return None
280
+ if not isinstance(value, str):
281
+ raise ConfigError(f"{key}: an origin, or nothing")
282
+ return _origin(value, key=key) # one origin, held as a browser origin is
283
+ if key == "confirm.allow_button":
284
+ if isinstance(value, bool):
285
+ return value
286
+ if value in ("true", "false"):
287
+ return value == "true"
288
+ raise ConfigError(f"{key}: true or false")
289
+ if key in _NUMBERS:
290
+ low, high = _NUMBERS[key]
291
+ if isinstance(value, str) and value.isdigit() and value.isascii():
292
+ value = int(value)
293
+ if not isinstance(value, int) or isinstance(value, bool) or not low <= value <= high:
294
+ raise ConfigError(f"{key}: a whole number from {low} to {high}")
295
+ return value
296
+ raise ConfigError(f"{key}: not a key this container sets")
297
+
298
+
299
+ @dataclass(frozen=True)
300
+ class Provider:
301
+ """The provider this container trusts, read from config on every request (§2)."""
302
+
303
+ issuer: str
304
+ client_id: str
305
+ audience: str
306
+ algorithms: frozenset[str]
307
+
308
+ @property
309
+ def jwks_url(self) -> str:
310
+ return self.issuer.rstrip("/") + "/.well-known/jwks.json"
311
+
312
+
313
+ # -- the key set (§3 check 1) --------------------------------------------------------------------
314
+ def _fetch_json(url: str) -> Any:
315
+ with urllib.request.urlopen(url, timeout=5) as response: # noqa: S310 — the configured issuer
316
+ body = response.read(JWKS_MAX_BYTES + 1)
317
+ if len(body) > JWKS_MAX_BYTES:
318
+ raise ValueError("key set too large")
319
+ return json.loads(body)
320
+
321
+
322
+ def _keys(data: Any) -> dict[str, jwt.PyJWK]:
323
+ """The asymmetric keys of a JWKS, by `kid`. A symmetric or unparseable key is skipped: it can
324
+ never verify here, so it is as if the provider had not published it."""
325
+ out: dict[str, jwt.PyJWK] = {}
326
+ for jwk in (data.get("keys") if isinstance(data, dict) else None) or []:
327
+ if not isinstance(jwk, dict) or not isinstance(jwk.get("kid"), str):
328
+ continue
329
+ if jwk.get("kty") == "oct":
330
+ continue
331
+ try:
332
+ key = jwt.PyJWK(jwk)
333
+ except (jwt.PyJWTError, ValueError, TypeError, KeyError):
334
+ continue
335
+ out.setdefault(jwk["kid"], key)
336
+ return out
337
+
338
+
339
+ class Jwks:
340
+ """The provider's public keys, cached. An unknown `kid` re-fetches the set at most once a
341
+ minute, so a stream of tokens naming made-up keys costs the provider one request a minute."""
342
+
343
+ def __init__(
344
+ self,
345
+ url: str,
346
+ *,
347
+ fetch: Callable[[str], Any] = _fetch_json,
348
+ clock: Callable[[], float] = time.monotonic,
349
+ ):
350
+ self.url = url
351
+ self._fetch = fetch
352
+ self._clock = clock
353
+ self._keys: dict[str, jwt.PyJWK] = {}
354
+ self._fetched_at: float | None = None
355
+ self._lock = threading.Lock()
356
+
357
+ def key(self, kid: str) -> jwt.PyJWK | None:
358
+ with self._lock:
359
+ key = self._keys.get(kid)
360
+ if key is not None:
361
+ return key
362
+ now = self._clock()
363
+ if self._fetched_at is not None and now - self._fetched_at < JWKS_REFETCH_SECONDS:
364
+ return None
365
+ self._fetched_at = now
366
+ try:
367
+ self._keys = _keys(self._fetch(self.url))
368
+ except Exception: # an unreachable or malformed provider fails closed, as one answer
369
+ return None
370
+ return self._keys.get(kid)
371
+
372
+
373
+ # -- the principal a verified token maps to (§4) --------------------------------------------------
374
+ @dataclass
375
+ class GrantToken(Token):
376
+ """A `Token` built per request from a grant: never stored, never minted, never a bearer value.
377
+ `sub` is the provider's user id; `client_id` is this container's own (a person), a registered
378
+ terminal's (the person at that terminal) or a registered agent's. `acting_for` is the user an
379
+ agent acts for (`details.for`, §3a); `terminal` is the client id of the terminal a person's
380
+ token came through (`details.terminal`, §3a), None for every other token."""
381
+
382
+ sub: str = ""
383
+ client_id: str = ""
384
+ acting_for: str | None = field(default=None, compare=False)
385
+ terminal: str | None = field(default=None, compare=False)
386
+ #: The grant's or registration's display name: untrusted display data (rest.md §4.3).
387
+ name: str = field(default="", compare=False)
388
+ #: When the person last signed in at the provider (the newest `amr` timestamp), for the acts
389
+ #: that need a fresh sign-in (rest.md §4.3). None when the token says nothing.
390
+ auth_time: int | None = field(default=None, compare=False)
391
+
392
+
393
+ def _number(value: Any) -> bool:
394
+ return isinstance(value, int | float) and not isinstance(value, bool)
395
+
396
+
397
+ def _auth_time(amr: Any) -> int | None:
398
+ """The newest authentication time in Supabase's `amr` claim: `[{method, timestamp}, …]`."""
399
+ times = [
400
+ int(entry["timestamp"]) for entry in amr or ()
401
+ if isinstance(entry, dict) and _number(entry.get("timestamp"))
402
+ ] if isinstance(amr, list) else []
403
+ return max(times) if times else None
404
+
405
+
406
+ def _live(record: UserGrant | Registration | None) -> bool:
407
+ return bool(record) and not record.get("revoked")
408
+
409
+
410
+ def kind_of(registration: Registration) -> str:
411
+ """A registration's kind (storage.md §3.2): a record with none is an agent's. Any other value
412
+ is returned as it is, so it reads as neither kind."""
413
+ return registration.get("kind", "agent")
414
+
415
+
416
+ def of_kind(registration: Registration | None, kind: RegistrationKind) -> bool:
417
+ return registration is not None and kind_of(registration) == kind
418
+
419
+
420
+ class Identity:
421
+ """§3's verification and §4's grants, over the container's `IdentityState`."""
422
+
423
+ def __init__(
424
+ self,
425
+ state: IdentityState,
426
+ ledger: Ledger,
427
+ config: Callable[[str], Any],
428
+ *,
429
+ ancestors: Callable[[str], list[str] | None],
430
+ jwks: Callable[[str], Jwks] | None = None,
431
+ atomic: Callable[[], AbstractContextManager[Any]] = nullcontext,
432
+ ):
433
+ self.state = state
434
+ self.ledger = ledger
435
+ self.config = config
436
+ # One transaction on the container's store: a grant's check, its write and its entry land
437
+ # together, and two concurrent revokes are serialised (BEGIN IMMEDIATE on sqlite).
438
+ self.atomic = atomic
439
+ # Node id -> the ids of its ancestors, itself included; None for a node that is absent.
440
+ self.ancestors = ancestors
441
+ self._jwks_for = jwks or self._jwks
442
+ self._jwks_cache: dict[str, Jwks] = {}
443
+
444
+ def _jwks(self, url: str) -> Jwks:
445
+ cached = self._jwks_cache.get(url)
446
+ if cached is None:
447
+ cached = self._jwks_cache[url] = Jwks(url)
448
+ return cached
449
+
450
+ def provider(self) -> Provider | None:
451
+ """The configured provider, or None: a container with none accepts only its own `Token`
452
+ (§1), and is exactly the container that ran before v1.1."""
453
+ issuer, client_id = self.config("identity.issuer"), self.config("identity.client_id")
454
+ if not issuer or not client_id:
455
+ return None
456
+ return Provider(
457
+ issuer=issuer,
458
+ client_id=client_id,
459
+ audience=self.config("identity.audience"),
460
+ algorithms=frozenset(self.config("identity.algorithms").split())
461
+ & ASYMMETRIC_ALGORITHMS,
462
+ )
463
+
464
+ # -- §3 ------------------------------------------------------------------------------------
465
+ def verify(self, value: str, *, now: float | None = None) -> GrantToken | None:
466
+ """The seven checks, in order. `None` is the one answer for every failure (§3)."""
467
+ provider = self.provider()
468
+ if provider is None or not isinstance(value, str) or not value:
469
+ return None
470
+ if len(value) > TOKEN_MAX_CHARS:
471
+ return None
472
+ # 1 · Signature: the key named by `kid`, its algorithm from the key, never the header alone.
473
+ try:
474
+ header = jwt.get_unverified_header(value)
475
+ except jwt.PyJWTError:
476
+ return None
477
+ kid = header.get("kid")
478
+ if not isinstance(kid, str) or not kid:
479
+ return None
480
+ key = self._jwks_for(provider.jwks_url).key(kid)
481
+ if key is None:
482
+ return None
483
+ algorithm = key.algorithm_name
484
+ if algorithm not in provider.algorithms:
485
+ return None
486
+ try:
487
+ claims = jwt.decode(value, key.key, algorithms=[algorithm], options=_NO_CLAIM_CHECKS)
488
+ except (jwt.PyJWTError, ValueError, TypeError):
489
+ return None
490
+ # 2 · Issuer, byte for byte.
491
+ if claims.get("iss") != provider.issuer:
492
+ return None
493
+ # 3 · Audience: is, or contains.
494
+ aud = claims.get("aud")
495
+ if not (aud == provider.audience or (isinstance(aud, list) and provider.audience in aud)):
496
+ return None
497
+ # 4 · Time, with at most `SKEW_SECONDS` either way.
498
+ at = time.time() if now is None else now
499
+ exp, iat = claims.get("exp"), claims.get("iat")
500
+ if not _number(exp) or not _number(iat):
501
+ return None
502
+ if exp + SKEW_SECONDS <= at or iat - SKEW_SECONDS > at:
503
+ return None
504
+ # 5 · Subject.
505
+ sub = claims.get("sub")
506
+ if not isinstance(sub, str) or not sub:
507
+ return None
508
+ # 6 · Binding: this container's own client, or an agent or a terminal registered here
509
+ # (§3a).
510
+ client_id = claims.get("client_id")
511
+ if not isinstance(client_id, str) or not client_id:
512
+ return None
513
+ person = client_id == provider.client_id
514
+ if not person and not any(
515
+ _live(r) for r in self.state.list_agent_registrations(client_id=client_id)
516
+ ):
517
+ return None
518
+ # 7 · Grant: a live user grant, and for an agent or a terminal a live registration of
519
+ # that kind serving this `sub`.
520
+ who = self._person(sub, client_id) if person else self._registered(client_id, sub)
521
+ if who is not None:
522
+ who.auth_time = _auth_time(claims.get("amr"))
523
+ return who
524
+
525
+ def _registered(self, client_id: str, sub: str) -> GrantToken | None:
526
+ """Check 7 for a registered client: the agent or the terminal its record for `sub` is."""
527
+ registration = self.state.get_agent_registration(client_id, sub)
528
+ if of_kind(registration, "terminal"):
529
+ return self._terminal(client_id, sub)
530
+ return self._agent(client_id, sub)
531
+
532
+ # -- §4: what a verified caller may do ------------------------------------------------------
533
+ def _person(self, sub: str, client_id: str) -> GrantToken | None:
534
+ grant = self.state.get_user_grant(sub)
535
+ if not _live(grant):
536
+ return None
537
+ return GrantToken(
538
+ id=principal_id(None, sub),
539
+ principal="interactive",
540
+ owner=f"user:{sub}",
541
+ client=client_id,
542
+ capabilities=sorted(grant["capabilities"]),
543
+ scopes=list(grant["scopes"]),
544
+ created_at=grant["created_at"], # rest.md §6 check 5: a grant written since is new
545
+ sub=sub,
546
+ client_id=client_id,
547
+ name=grant.get("name", ""),
548
+ )
549
+
550
+ def _terminal(self, client_id: str, sub: str) -> GrantToken | None:
551
+ """A person at a terminal of theirs (§4): their live grant as it stands now, through a
552
+ live terminal registration serving them. The person, `interactive`, under the terminal's
553
+ own id (rest.md §6), so what is issued to it is not the browser's."""
554
+ grant = self.state.get_user_grant(sub)
555
+ registration = self.state.get_agent_registration(client_id, sub)
556
+ if not _live(grant) or not _live(registration) or not of_kind(registration, "terminal"):
557
+ return None
558
+ return GrantToken(
559
+ id=principal_id(client_id, sub, "terminal"),
560
+ principal="interactive",
561
+ owner=f"user:{sub}",
562
+ client=client_id,
563
+ capabilities=sorted(grant["capabilities"]),
564
+ scopes=list(grant["scopes"]),
565
+ # rest.md §6 check 5: a grant or a registration written since is new.
566
+ created_at=max(grant["created_at"], registration["created_at"]),
567
+ sub=sub,
568
+ client_id=client_id,
569
+ terminal=client_id,
570
+ name=grant.get("name", ""),
571
+ )
572
+
573
+ def _agent(self, client_id: str, sub: str) -> GrantToken | None:
574
+ grant = self.state.get_user_grant(sub)
575
+ registration = self.state.get_agent_registration(client_id, sub)
576
+ if not _live(grant) or not _live(registration) or not of_kind(registration, "agent"):
577
+ return None
578
+ capabilities = sorted(set(registration["capabilities"]) & set(grant["capabilities"]))
579
+ scopes = self.intersect(registration["scopes"], grant["scopes"])
580
+ if not capabilities or not scopes:
581
+ return None
582
+ return GrantToken(
583
+ id=principal_id(client_id, sub),
584
+ principal="client",
585
+ owner=f"agent:{client_id}",
586
+ client=client_id,
587
+ capabilities=capabilities,
588
+ scopes=scopes,
589
+ created_at=max(grant["created_at"], registration["created_at"]),
590
+ sub=sub,
591
+ client_id=client_id,
592
+ acting_for=f"user:{sub}",
593
+ name=registration.get("name", ""),
594
+ )
595
+
596
+ def intersect(self, left: Iterable[str], right: Iterable[str]) -> list[str]:
597
+ """Scopes covering exactly what both sides cover. Two scopes that both cover a node lie on
598
+ its path, so one is the other's ancestor and the deeper one covers just their overlap; a
599
+ pair on different branches covers nothing. Computed at check time, like coverage."""
600
+ out: set[str] = set()
601
+ right = list(right)
602
+ for a in left:
603
+ for b in right:
604
+ if a == "*":
605
+ out.add(b)
606
+ elif b == "*":
607
+ out.add(a)
608
+ elif a in (self.ancestors(b) or ()):
609
+ out.add(b)
610
+ elif b in (self.ancestors(a) or ()):
611
+ out.add(a)
612
+ return sorted(out)
613
+
614
+ def refresh(self, token: GrantToken) -> GrantToken | None:
615
+ """The same caller as the grants stand now: a revoke since the request began counts. A
616
+ terminal's token stays valid only while its registration and the grant are both live."""
617
+ if token.terminal is not None:
618
+ return self._terminal(token.terminal, token.sub)
619
+ if token.principal == "client":
620
+ return self._agent(token.client_id, token.sub)
621
+ return self._person(token.sub, token.client_id)
622
+
623
+ def named(self, token_id: str) -> GrantToken | None:
624
+ """The person, terminal or agent a `GrantToken` id names, as the grants stand now
625
+ (rest.md §6 check 5): the one pair and kind `principal_of` reads from it, and a
626
+ registration of that kind. Revoked since, a stand-in that is revoked and holds nothing, so
627
+ a refusal is still attributed to whom the grant named. None for an id that is not a
628
+ grant's."""
629
+ read = principal_of(token_id)
630
+ if read is None:
631
+ return None
632
+ kind, client_id, sub = read
633
+ if client_id is None:
634
+ own = self.config("identity.client_id") or ""
635
+ return self._person(sub, own) or GrantToken(
636
+ id=token_id, principal="interactive", owner=f"user:{sub}", client=own,
637
+ capabilities=[], scopes=[], revoked=True, sub=sub, client_id=own)
638
+ if not of_kind(self.state.get_agent_registration(client_id, sub), kind):
639
+ return None
640
+ if kind == "terminal":
641
+ return self._terminal(client_id, sub) or GrantToken(
642
+ id=token_id, principal="interactive", owner=f"user:{sub}", client=client_id,
643
+ capabilities=[], scopes=[], revoked=True, sub=sub, client_id=client_id,
644
+ terminal=client_id)
645
+ return self._agent(client_id, sub) or GrantToken(
646
+ id=token_id, principal="client", owner=f"agent:{client_id}", client=client_id,
647
+ capabilities=[], scopes=[], revoked=True, sub=sub, client_id=client_id,
648
+ acting_for=f"user:{sub}")
649
+
650
+ def audience_tokens(self) -> list[GrantToken]:
651
+ """Every live grant and agent registration, as the gate counts them (§4: audience is
652
+ every live `Token`, user grant and agent registration whose coverage reaches a container).
653
+ A terminal adds no one: it is its person, whose grant is already counted."""
654
+ own = self.config("identity.client_id") or ""
655
+ out: list[GrantToken] = []
656
+ for grant in self.state.list_user_grants():
657
+ person = self._person(grant["sub"], own) if _live(grant) else None
658
+ if person:
659
+ out.append(person)
660
+ for registration in self.registrations("agent"):
661
+ if _live(registration):
662
+ agent = self._agent(registration["client_id"], registration["sub"])
663
+ if agent:
664
+ out.append(agent)
665
+ return out
666
+
667
+ # -- registrations, by kind (§4: every reader names the kind it wants) ----------------------
668
+ def registrations(self, kind: RegistrationKind, *, sub: str | None = None,
669
+ client_id: str | None = None) -> list[Registration]:
670
+ """Every registration of `kind`, revoked ones included, optionally only those serving
671
+ `sub` or naming `client_id`. storage.md §3.2 lists by `client_id` only, so a filter by
672
+ `sub` scans them all."""
673
+ return [r for r in self.state.list_agent_registrations(client_id=client_id)
674
+ if of_kind(r, kind) and (sub is None or r["sub"] == sub)]
675
+
676
+ def registration(self, client_id: str, sub: str,
677
+ kind: RegistrationKind) -> Registration | None:
678
+ """The registration of `client_id` serving `sub`, revoked or not, when it is of `kind`;
679
+ None for none and for one of the other kind (rest.md §4.3: a `client_id` of the other
680
+ kind is §3's refusal on every agent and terminal route)."""
681
+ found = self.state.get_agent_registration(client_id, sub)
682
+ return found if of_kind(found, kind) else None
683
+
684
+ # -- grants (§4) ----------------------------------------------------------------------------
685
+ @staticmethod
686
+ def expand(role: Any, capabilities: Any) -> list[str]:
687
+ """A grant's capabilities, sorted: a role's bundle expanded at grant time, as at mint
688
+ (capabilities.md §2), or the capabilities named. It takes a request body's values as they
689
+ came, so anything else is a `ValueError`: both or neither, an unknown role, or other than
690
+ a non-empty list of known capabilities."""
691
+ if (role is None) == (capabilities is None):
692
+ raise ValueError("a grant names a role or capabilities, not both")
693
+ if role is not None:
694
+ if not isinstance(role, str) or role not in ROLE_BUNDLES:
695
+ raise ValueError("unknown role")
696
+ return sorted(ROLE_BUNDLES[role])
697
+ if not isinstance(capabilities, list) or not capabilities or any(
698
+ c not in CAPABILITIES for c in capabilities
699
+ ):
700
+ raise ValueError("unknown capability")
701
+ return sorted(set(capabilities))
702
+
703
+ @staticmethod
704
+ def user_id(value: Any) -> str:
705
+ """The provider's user id a grant names, read as `provider_id` reads any id the provider
706
+ issued. A provider's user id is a UUID."""
707
+ return provider_id(value, "a grant names the provider's user id")
708
+
709
+ def grant_user(
710
+ self,
711
+ sub: str,
712
+ *,
713
+ name: str,
714
+ role: str | None = None,
715
+ capabilities: list[str] | None = None,
716
+ scopes: list[str],
717
+ actor: str,
718
+ principal: str,
719
+ ) -> UserGrant:
720
+ """Write (or replace) a person's grant and append `identity.grant`. Whoever calls this has
721
+ already checked that the act is theirs: the owner `Token` at `link`, or an admin under
722
+ the confirm at the door (§4). `capabilities` is the names, which `expand` checks: a list,
723
+ never a lone string."""
724
+ if principal != "interactive":
725
+ raise PermissionError("granting access is a person's act")
726
+ sub = self.user_id(sub)
727
+ name = display_name(name)
728
+ caps = self.expand(role, capabilities)
729
+ if not scopes:
730
+ raise ValueError("a grant covers at least one scope")
731
+ grant: UserGrant = {
732
+ "sub": sub,
733
+ "name": name,
734
+ "capabilities": caps,
735
+ "scopes": list(scopes),
736
+ "created_at": now_iso(),
737
+ "revoked": False,
738
+ }
739
+ with self.atomic():
740
+ if not self._narrows(sub, caps, grant["scopes"]):
741
+ self.state.put_user_grant(grant)
742
+ self.ledger.append(
743
+ "identity.grant",
744
+ actor=actor,
745
+ principal=principal,
746
+ subject=sub,
747
+ kind="user",
748
+ outcome="granted",
749
+ capabilities=caps,
750
+ scopes=list(scopes),
751
+ )
752
+ return grant
753
+ self._refused("identity.grant", sub, actor=actor, principal=principal)
754
+ raise LastAdmin(sub)
755
+
756
+ def revoke_user(self, sub: str, *, actor: str, principal: str) -> bool:
757
+ """Revoke a person's grant and every live registration serving them, each with its own
758
+ `identity.revoke`, so a later grant to that `sub` starts with no agents and no terminals
759
+ (§4). The caller has judged the act: an admin narrowing their own access (never gated), an
760
+ admin ending someone else's under the confirm at the REST door, or the owner `Token` on the
761
+ CLI or the lifeboat, the recovery factor (§AD: no confirm, audited). `False` for no live
762
+ grant; the last live grant holding `admin` over `["*"]` raises `LastAdmin` and appends a
763
+ refusal.
764
+
765
+ The read, the last-admin check, the writes and the entries are one transaction, so two
766
+ concurrent revokes of the last two whole-container admins cannot both pass the check, and
767
+ a revoke never stands without its entries. The refusal is appended after it, not inside: a
768
+ refusal rolled back with the act it refused would leave no trace."""
769
+ with self.atomic():
770
+ grant = self.state.get_user_grant(sub)
771
+ if not _live(grant):
772
+ return False
773
+ if not self._last_admin(sub):
774
+ self.state.put_user_grant({**grant, "revoked": True})
775
+ self.ledger.append(
776
+ "identity.revoke",
777
+ actor=actor,
778
+ principal=principal,
779
+ subject=sub,
780
+ kind="user",
781
+ outcome="revoked",
782
+ capabilities=grant["capabilities"],
783
+ scopes=grant["scopes"],
784
+ )
785
+ for agent in self.serving(sub, "agent"):
786
+ self.revoke_agent(agent["client_id"], sub, actor=actor, principal=principal)
787
+ for terminal in self.serving(sub, "terminal"):
788
+ self.revoke_terminal(terminal["client_id"], sub, actor=actor,
789
+ principal=principal)
790
+ return True
791
+ self._refused("identity.revoke", sub, actor=actor, principal=principal)
792
+ raise LastAdmin(sub)
793
+
794
+ def revoke_agent(self, client_id: str, sub: str, *, actor: str, principal: str) -> bool:
795
+ """Revoke the live agent registration of `client_id` serving `sub` and append its
796
+ `identity.revoke` (`kind: agent`, `for` the person it served), as one transaction: of two
797
+ concurrent revokes of one registration, one ends it and the other finds nothing. The caller
798
+ has judged the act: the person it serves (never gated), an admin ending someone else's under
799
+ the confirm at the REST door, or a revoke of the grant it serves (§4). `False` for none,
800
+ and for a terminal's registration, which `revoke_terminal` ends."""
801
+ with self.atomic():
802
+ registration = self.state.get_agent_registration(client_id, sub)
803
+ if not _live(registration) or not of_kind(registration, "agent"):
804
+ return False
805
+ self.state.put_agent_registration({**registration, "revoked": True})
806
+ self.ledger.append(
807
+ "identity.revoke", actor=actor, principal=principal, subject=client_id,
808
+ kind="agent", outcome="revoked", capabilities=registration["capabilities"],
809
+ scopes=registration["scopes"], **{"for": f"user:{sub}"},
810
+ )
811
+ return True
812
+
813
+ def revoke_terminal(self, client_id: str, sub: str, *, actor: str, principal: str) -> bool:
814
+ """End the live terminal registration of `client_id` serving `sub` and append its
815
+ `identity.revoke` (`kind: terminal`, `for` the person it served, and no capabilities or
816
+ scopes, since it holds none), as one transaction. Its next request is refused at check 7,
817
+ and it never returns: its `client_id` is never registered again (§4). The caller has
818
+ judged the act: the person it serves, or the terminal itself with its person's token
819
+ (never gated), an admin ending someone else's under the confirm at the REST door, or a
820
+ revoke of the grant it serves (§4). `False` for none, and for an agent's registration."""
821
+ with self.atomic():
822
+ registration = self.state.get_agent_registration(client_id, sub)
823
+ if not _live(registration) or not of_kind(registration, "terminal"):
824
+ return False
825
+ self.state.put_agent_registration({**registration, "revoked": True})
826
+ self.ledger.append(
827
+ "identity.revoke", actor=actor, principal=principal, subject=client_id,
828
+ kind="terminal", outcome="revoked", **{"for": f"user:{sub}"},
829
+ )
830
+ return True
831
+
832
+ def serving(self, sub: str, kind: RegistrationKind = "agent") -> list[Registration]:
833
+ """Every live registration of `kind` serving `sub`: its agents, or its terminals."""
834
+ return [r for r in self.registrations(kind, sub=sub) if _live(r)]
835
+
836
+ def exceeds(self, caller: Token, capabilities: list[str], scopes: list[str]) -> bool:
837
+ """Whether a grant of these goes beyond `caller`'s own (rest.md §4.3): a capability the
838
+ caller lacks, or a scope their coverage does not reach. `*` is the whole container, which
839
+ only a caller holding `*` reaches."""
840
+ return not set(capabilities) <= set(caller.capabilities) or self._wider(
841
+ caller.scopes, scopes
842
+ )
843
+
844
+ def opens(
845
+ self, sub: str, name: str, capabilities: list[str], scopes: list[str]
846
+ ) -> list[tuple[str, str]]:
847
+ """Whom granting `sub` these would newly let see something, as sorted `(member, display
848
+ name)` pairs: rest.md §4.2's audience delta for a grant. The person, unless their live
849
+ grant already reaches all of it (a revoked one reaches nothing), and each agent serving
850
+ them whose reach, its registration intersected with the grant (§4), the grant widens."""
851
+ old = self.state.get_user_grant(sub)
852
+ had_caps, had_scopes = (old["capabilities"], old["scopes"]) if _live(old) else ([], [])
853
+ out = [(principal_id(None, sub), name)] if self._wider(had_scopes, scopes) else []
854
+ for agent in self.serving(sub, "agent"): # a terminal is its person, counted above
855
+ before = self._reach(agent, had_caps, had_scopes)
856
+ if self._wider(before, self._reach(agent, capabilities, scopes)):
857
+ out.append((principal_id(agent["client_id"], sub), agent["name"]))
858
+ return sorted(out)
859
+
860
+ def _reach(
861
+ self, agent: Registration, capabilities: list[str], scopes: list[str]
862
+ ) -> list[str]:
863
+ """What an agent covers under a grant of these, as at check time (`_agent`): nothing
864
+ without a capability in common, else its scopes intersected with the grant's."""
865
+ if not set(agent["capabilities"]) & set(capabilities):
866
+ return []
867
+ return self.intersect(agent["scopes"], scopes)
868
+
869
+ def _wider(self, before: list[str], after: list[str]) -> bool:
870
+ """Whether `after` reaches a node `before` does not. Coverage runs down the path, only
871
+ `*` reaches the whole container, and an absent node counts as one `before` misses."""
872
+ if "*" in before:
873
+ return False
874
+ return "*" in after or any(not set(before) & set(self.ancestors(s) or ()) for s in after)
875
+
876
+ def refuse_narrowing(
877
+ self, sub: str, capabilities: list[str], scopes: list[str], *, actor: str, principal: str
878
+ ) -> bool:
879
+ """rest.md §4.3's check before any leg of the confirm: where granting `sub` these would
880
+ narrow the last live grant holding `admin` over `["*"]`, append `identity.grant`'s
881
+ refusal and answer True. `grant_user` checks again under its lock."""
882
+ if not self._narrows(sub, capabilities, scopes):
883
+ return False
884
+ self._refused("identity.grant", sub, actor=actor, principal=principal)
885
+ return True
886
+
887
+ def _narrows(self, sub: str, capabilities: list[str], scopes: list[str]) -> bool:
888
+ """Whether granting `sub` anything short of `admin` over `["*"]` takes it from the last
889
+ grant holding it: that removes the last admin as surely as revoking it does (§4)."""
890
+ return not ("admin" in capabilities and "*" in scopes) and self._last_admin(sub)
891
+
892
+ def _refused(self, event: str, sub: str, *, actor: str, principal: str) -> None:
893
+ self.ledger.append(
894
+ event,
895
+ actor=actor,
896
+ principal=principal,
897
+ subject=sub,
898
+ kind="user",
899
+ outcome="refused",
900
+ reason="last_admin",
901
+ )
902
+
903
+ def _last_admin(self, sub: str) -> bool:
904
+ """Whether `sub` holds the only live grant with `admin` over the whole container."""
905
+ grants = self.state.list_user_grants()
906
+ mine = next((g for g in grants if g["sub"] == sub), None)
907
+ return bool(mine and _whole(mine)) and not any(
908
+ _whole(g) for g in grants if g["sub"] != sub
909
+ )
910
+
911
+ # -- agent registrations (§4, rest.md §4.3) -------------------------------------------------
912
+ def register_agent(self, person: GrantToken, client_id: str, *, authorization_id: str,
913
+ name: str, capabilities: list[str], scopes: list[str],
914
+ after: int | None = None) -> AgentRegistration | None:
915
+ """Write a registration serving `person` and append `identity.grant` attributed to them:
916
+ `kind: agent`, `for` the person, and `authorization_id` as the caller claimed it, never a
917
+ verified fact. Each person registers their own (v0.7 §AB). The caller has judged the act,
918
+ the confirm included, in the transaction this joins, and may have read the chain through
919
+ seq `after`. The rest of it and the cap are checked with the write, under one lock: of two
920
+ registrations naming one authorization at most one lands (None for the other and every
921
+ later one), and two at 15 never both take the 16th (`TooManyAgents`). A `client_id` that
922
+ names a terminal's registration is never an agent's (`Registered`), and this container's
923
+ own client names a person (`ValueError`). A terminal's token registers nothing."""
924
+ if (not isinstance(person, GrantToken) or person.principal != "interactive"
925
+ or person.terminal is not None):
926
+ raise PermissionError("registering an agent is a person's act, from a browser")
927
+ self._not_own(client_id)
928
+ registration: AgentRegistration = {
929
+ "client_id": client_id, "sub": person.sub, "kind": "agent", "name": name,
930
+ "capabilities": list(capabilities), "scopes": list(scopes), "created_at": now_iso(),
931
+ "revoked": False,
932
+ }
933
+ with self.atomic():
934
+ if self.claimed(authorization_id, after):
935
+ return None
936
+ if self.taken(client_id, "agent"):
937
+ raise Registered(client_id)
938
+ if self.full(person.sub, client_id):
939
+ raise TooManyAgents(person.sub)
940
+ self.state.put_agent_registration(registration)
941
+ self.ledger.append(
942
+ "identity.grant", actor=person.owner, principal=person.principal,
943
+ subject=client_id, kind="agent", outcome="granted",
944
+ capabilities=registration["capabilities"], scopes=registration["scopes"],
945
+ authorization_id=authorization_id, **{"for": f"user:{person.sub}"},
946
+ )
947
+ return registration
948
+
949
+ def full(self, sub: str, client_id: str) -> bool:
950
+ """Whether `sub` holds `MAX_AGENTS` live agent registrations besides one of `client_id`,
951
+ which registering it again replaces: a 17th is refused, never written (rest.md §4.3). Their
952
+ terminals are counted apart (`terminals_full`)."""
953
+ return sum(r["client_id"] != client_id
954
+ for r in self.serving(sub, "agent")) >= MAX_AGENTS
955
+
956
+ def terminals_full(self, sub: str) -> bool:
957
+ """Whether `sub` holds `MAX_TERMINALS` live terminal registrations: a 17th is refused,
958
+ never written (rest.md §4.3). A terminal's `client_id` is registered once, so none
959
+ replaces another. Their agents are counted apart (`full`)."""
960
+ return len(self.serving(sub, "terminal")) >= MAX_TERMINALS
961
+
962
+ def taken(self, client_id: str, kind: RegistrationKind) -> bool:
963
+ """Whether registering `client_id` as `kind` is refused because it was registered here
964
+ before (identity.md §4, rest.md §4.3): as a terminal, when any registration names it, an
965
+ agent's or a terminal's, live or revoked, for any person; as an agent, when a terminal's
966
+ does. The door asks this inside the registration's atomic step and concludes the confirm
967
+ refused, `registered`."""
968
+ named = self.state.list_agent_registrations(client_id=client_id)
969
+ return bool(named) if kind == "terminal" else any(
970
+ not of_kind(r, "agent") for r in named)
971
+
972
+ def _not_own(self, client_id: str) -> None:
973
+ """This container's own client names a person, never an agent or a terminal (§4)."""
974
+ if client_id == self.config("identity.client_id"):
975
+ raise ValueError("this container's own client names a person")
976
+
977
+ def claimed(self, authorization_id: str, after: int | None = None) -> bool:
978
+ """Whether a registration was ever written for this authorization, which keys one, as an
979
+ agent or as a terminal (rest.md §4.3). Its only record is `identity.grant`'s
980
+ `details.authorization_id`: neither identity.md §4's record nor storage.md §3.2 holds it,
981
+ so this reads the chain; with `after`, only its tail past that seq, so a lock never waits
982
+ on a read of all of it."""
983
+ return any(
984
+ e["event"] == "identity.grant" and e["details"].get("kind") in REGISTRATION_KINDS
985
+ and e["details"].get("authorization_id") == authorization_id
986
+ for e in (self.ledger.backend.audit_iter() if after is None
987
+ else self.ledger.tail(self.ledger.tail(1)[-1]["seq"] - after))
988
+ )
989
+
990
+ def acted(self, client_id: str, sub: str) -> list[dict[str, Any]]:
991
+ """What an agent did for one person, oldest first: every entry attributed to it that
992
+ names that person (`details.for`, §3a), its refusals included. Read from the chain in one
993
+ pass, as `last_seen` reads it (rest.md §4.3's log)."""
994
+ pair = (f"agent:{client_id}", f"user:{sub}")
995
+ return [e for e in self.ledger.backend.audit_iter()
996
+ if (e["actor"], e["details"].get("for")) == pair]
997
+
998
+ def last_seen(self, registrations: Iterable[Registration]) -> dict[tuple[str, str], str]:
999
+ """When each agent last acted for the person it serves, by `(client_id, sub)`: its newest
1000
+ entry attributed to it and naming that person (`details.for`, §3a). A pair never seen is
1001
+ absent, and so is every registration that is not an agent's. Read from the chain in one
1002
+ pass, as nothing else records it (rest.md §4.3)."""
1003
+ wanted = {(f"agent:{r['client_id']}", f"user:{r['sub']}"): (r["client_id"], r["sub"])
1004
+ for r in registrations if of_kind(r, "agent")}
1005
+ seen: dict[tuple[str, str], str] = {}
1006
+ if wanted:
1007
+ for entry in self.ledger.backend.audit_iter():
1008
+ pair = wanted.get((entry["actor"], entry["details"].get("for")))
1009
+ if pair is not None:
1010
+ seen[pair] = entry["ts"]
1011
+ return seen
1012
+
1013
+ # -- terminal registrations (§4, rest.md §4.3) ----------------------------------------------
1014
+ def register_terminal(self, person: GrantToken, client_id: str, *, authorization_id: str,
1015
+ name: str, after: int | None = None) -> TerminalRegistration | None:
1016
+ """Write a terminal registration serving `person` and append `identity.grant` attributed
1017
+ to them: `kind: terminal`, `for` the person, `authorization_id` as the caller claimed it,
1018
+ and no capabilities or scopes, since it holds none (§4). Each person registers their own,
1019
+ in a browser: a terminal's token registers nothing. The caller has judged the act, the
1020
+ confirm included, in the transaction this joins, and may have read the chain through seq
1021
+ `after`. Under one lock: an authorization registers once, as an agent or as a terminal
1022
+ (None for every later one); a `client_id` any registration here names is never a
1023
+ terminal's (`Registered`); and a 17th live terminal is refused before anything is written
1024
+ (`TooManyTerminals`). This container's own client names a person (`ValueError`)."""
1025
+ if (not isinstance(person, GrantToken) or person.principal != "interactive"
1026
+ or person.terminal is not None):
1027
+ raise PermissionError("registering a terminal is a person's act, from a browser")
1028
+ self._not_own(client_id)
1029
+ registration: TerminalRegistration = {
1030
+ "client_id": client_id, "sub": person.sub, "kind": "terminal", "name": name,
1031
+ "created_at": now_iso(), "revoked": False,
1032
+ }
1033
+ with self.atomic():
1034
+ if self.claimed(authorization_id, after):
1035
+ return None
1036
+ if self.taken(client_id, "terminal"):
1037
+ raise Registered(client_id)
1038
+ if self.terminals_full(person.sub):
1039
+ raise TooManyTerminals(person.sub)
1040
+ self.state.put_agent_registration(registration)
1041
+ self.ledger.append(
1042
+ "identity.grant", actor=person.owner, principal=person.principal,
1043
+ subject=client_id, kind="terminal", outcome="granted",
1044
+ authorization_id=authorization_id, **{"for": f"user:{person.sub}"},
1045
+ )
1046
+ return registration
1047
+
1048
+ def terminal_acted(self, client_id: str, sub: str) -> list[dict[str, Any]]:
1049
+ """What was done through one terminal, oldest first: every entry whose `actor` is the
1050
+ person it serves and whose `details.terminal` is its `client_id` (§3a), refusals
1051
+ included. Read from the chain in one pass (rest.md §4.3's terminal log)."""
1052
+ pair = (f"user:{sub}", client_id)
1053
+ return [e for e in self.ledger.backend.audit_iter()
1054
+ if (e["actor"], e["details"].get("terminal")) == pair]
1055
+
1056
+ def terminal_last_seen(
1057
+ self, registrations: Iterable[Registration]
1058
+ ) -> dict[tuple[str, str], str]:
1059
+ """When each terminal was last used, by `(client_id, sub)`: its newest entry whose `actor`
1060
+ is its person and whose `details.terminal` is its `client_id` (§3a). A terminal not used
1061
+ yet is absent, and so is every registration that is not a terminal's (rest.md §4.3)."""
1062
+ wanted = {(f"user:{r['sub']}", r["client_id"]): (r["client_id"], r["sub"])
1063
+ for r in registrations if of_kind(r, "terminal")}
1064
+ seen: dict[tuple[str, str], str] = {}
1065
+ if wanted:
1066
+ for entry in self.ledger.backend.audit_iter():
1067
+ pair = wanted.get((entry["actor"], entry["details"].get("terminal")))
1068
+ if pair is not None:
1069
+ seen[pair] = entry["ts"]
1070
+ return seen
1071
+
1072
+ def terminal_ended(
1073
+ self, registrations: Iterable[Registration]
1074
+ ) -> dict[tuple[str, str], str]:
1075
+ """When each terminal was ended, by `(client_id, sub)`: the time of its `identity.revoke`
1076
+ (`kind: terminal`, `for` its person), rest.md §4.3's `ended_at`. A live one is absent, and
1077
+ so is every registration that is not a terminal's."""
1078
+ wanted = {(r["client_id"], f"user:{r['sub']}"): (r["client_id"], r["sub"])
1079
+ for r in registrations if of_kind(r, "terminal")}
1080
+ ended: dict[tuple[str, str], str] = {}
1081
+ if wanted:
1082
+ for entry in self.ledger.backend.audit_iter():
1083
+ details = entry["details"]
1084
+ if (entry["event"] != "identity.revoke" or details.get("kind") != "terminal"
1085
+ or details.get("outcome") != "revoked"):
1086
+ continue
1087
+ pair = wanted.get((entry["subject"], details.get("for")))
1088
+ if pair is not None:
1089
+ ended[pair] = entry["ts"]
1090
+ return ended
1091
+
1092
+
1093
+ def _whole(grant: UserGrant) -> bool:
1094
+ return _live(grant) and "admin" in grant["capabilities"] and "*" in grant["scopes"]
1095
+
1096
+
1097
+ def node_ancestors(get_node: Callable[[str], Node | None], ancestors: Callable[[Node], list[Node]]):
1098
+ """`Identity`'s `ancestors` from the node service's own two reads."""
1099
+
1100
+ def lookup(node_id: str) -> list[str] | None:
1101
+ node = get_node(node_id)
1102
+ return [n.id for n in ancestors(node)] if node else None
1103
+
1104
+ return lookup