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/api/app.py ADDED
@@ -0,0 +1,1574 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The REST door's routes (spec/contracts/rest.md §1–§4.1): who may call, the one refusal, CORS for
5
+ the browser origins, and the reads and writes that need no confirm.
6
+
7
+ Every request passes the door in one order: CORS preflight, the throttle (§2 item 7), the credential
8
+ (a container `Token` or a provider token, `identity.md` §3), then the route. Every answer is JSON
9
+ under the same three headers, and every refusal that turns on what exists or what the token may do
10
+ is §3's one `404`, byte for byte. Nothing here renders an item: a body is a JSON string, and data.
11
+
12
+ The acts the confirm gates (§4.2) — a move or copy that widens an audience, and approve, deny and
13
+ promote — answer in two legs on one route: the first issues a challenge and says who would newly
14
+ see the item, the second spends it with a proof, and the act lands in the same transaction. An
15
+ artifact arrives through an upload (§4.4): open, bytes, item, and leaves through a `BlobGrant`
16
+ (§6): `GET /v1/fetch` and `GET /v1/items/{id}` carry one beside an artifact whose bytes do not ride
17
+ inline, and `GET /v1/blobs/{sha256}` redeems it, by the descriptor alone, never a bearer. An admin
18
+ lists the grants, grants access with the confirm, and ends one (§4.3), with the confirm where it is
19
+ someone else's. A person lists the agents serving them, registers one with the confirm, ends one,
20
+ and reads what one did for them (§4.3): an admin ends one serving someone else with the confirm.
21
+ A person registers a terminal of theirs with the confirm, lists their terminals, live or ended,
22
+ ends one and reads what was done through it, as for an agent (§4.3); each family of routes reads
23
+ its own kind only. A terminal's token is its person, but it gives no one access and concludes no
24
+ confirm: the routes that give access refuse it before any leg (§4.3).
25
+
26
+ MCP over Streamable HTTP (identity.md §7) is `POST /mcp`, past the same credential and throttle:
27
+ its `401` alone names the protected-resource metadata, which is served to anyone, unthrottled.
28
+
29
+ A person tombstones an item (§4): at once, or with the confirm where a person promoted it; never an
30
+ agent.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import asyncio
36
+ import calendar
37
+ import contextlib
38
+ import json
39
+ import re
40
+ import time
41
+ from collections.abc import AsyncIterator
42
+ from typing import Any
43
+
44
+ from fastapi import FastAPI, Request
45
+ from starlette.responses import Response, StreamingResponse
46
+
47
+ from egzos._types import StorageBusy
48
+ from egzos.api.blobs import PULL_HEADERS, redeem
49
+ from egzos.api.throttle import Throttle, throttle_key
50
+ from egzos.backends.base import holds_nul
51
+ from egzos.confirm import CREDENTIAL_NAME_MAX, REMOVE_REASONS, person_of, terminal_of
52
+ from egzos.container import Container
53
+ from egzos.identity import (
54
+ GrantToken,
55
+ LastAdmin,
56
+ TooManyAgents,
57
+ TooManyTerminals,
58
+ display_name,
59
+ principal_id,
60
+ provider_id,
61
+ )
62
+ from egzos.ledger import attributed
63
+ from egzos.mcp.http import StreamableHttp
64
+ from egzos.model import CONTAINER_TYPES, KINDS, VERIFIED_ONLY_KINDS, ContextItem, Node, Token
65
+ from egzos.store.blobs import grant_url
66
+ from egzos.store.find import QueryError, find, parse, shown
67
+ from egzos.store.items import StoreError
68
+ from egzos.store.nodes import AmbiguousRef, StructureError
69
+ from egzos.store.uploads import TooManyUploads, valid_open
70
+ from egzos.store.uploads import person_of as opener_of
71
+ from egzos.trust import HumanOnly, TrustError
72
+
73
+ #: §3: the four lines every answer of this door carries (Content-Type is the response's own).
74
+ HEADERS = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"}
75
+ METHODS = "GET, POST, PUT, DELETE"
76
+ #: identity.md §6: the same CORS headers on every answer to an allowed origin, whatever it is.
77
+ CORS_ALLOW_HEADERS = "Authorization, Content-Type"
78
+ #: A request body larger than this is not one this door reads (the upload route has its own).
79
+ BODY_MAX_BYTES = 256 * 1024
80
+ #: How often the door closes throttle windows (§2 item 7's release and tally).
81
+ CLOSE_EVERY_SECONDS = 15
82
+
83
+ _CREATABLE = tuple(t for t in CONTAINER_TYPES if t not in ("inbox", "global", "uxo"))
84
+ #: §4.4: what `GET /v1/pending` says of an orphaned upload, beside its id.
85
+ ORPHAN_KEYS = ("name", "size", "sha256", "scope", "opened_at")
86
+ #: identity.md §7: MCP's endpoint, and where its protected-resource metadata (RFC 9728) lives.
87
+ MCP_PATH = "/mcp"
88
+ METADATA_PATH = "/.well-known/oauth-protected-resource"
89
+ #: rest.md §6: the one route no bearer is read on, for GET only.
90
+ PULL_PATH = re.compile(r"/v1/blobs/[^/]+")
91
+
92
+
93
+ def _json(status: int, payload: Any, extra: dict[str, str] | None = None) -> Response:
94
+ body = json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode()
95
+ return Response(body, status_code=status, media_type="application/json",
96
+ headers={**HEADERS, **(extra or {})})
97
+
98
+
99
+ def refusal() -> Response:
100
+ """§3's one refusal: absent, uncovered, lacking the capability, unserved, undeclared."""
101
+ return _json(404, {"error": "not_found"})
102
+
103
+
104
+ def unauthorized(metadata: str | None = None) -> Response:
105
+ """§2 item 5: every unauthenticated case, byte-identical. At `/mcp` the challenge names the
106
+ protected-resource metadata (identity.md §7); on `/v1/` it carries no parameter."""
107
+ challenge = f'Bearer resource_metadata="{metadata}"' if metadata else "Bearer"
108
+ return _json(401, {"error": "unauthorized"}, {"WWW-Authenticate": challenge})
109
+
110
+
111
+ def invalid() -> Response:
112
+ """§3: a request that fails on a fact identical for every container."""
113
+ return _json(400, {"error": "invalid_request"})
114
+
115
+
116
+ def busy() -> Response:
117
+ """§3: the store raised `StorageBusy`, so nothing was written; it names nothing requested."""
118
+ return _json(503, {"error": "busy"}, {"Retry-After": "1"})
119
+
120
+
121
+ def ambiguous(paths: list[str]) -> Response:
122
+ return _json(409, {"error": "ambiguous", "matches": sorted(paths)})
123
+
124
+
125
+ class Invalid(Exception):
126
+ """The request's shape is wrong: answered `400` before any lookup."""
127
+
128
+
129
+ def _only(params: Any, allowed: set[str]) -> None:
130
+ if set(params) - allowed or any(len(params.getlist(k)) > 1 for k in params):
131
+ raise Invalid
132
+
133
+
134
+ async def _bounded(request: Request, limit: int) -> bytes:
135
+ """The request body, read only up to `limit` bytes: a declared or actual length beyond it is
136
+ refused before the rest is read, so no caller makes the door hold a body it will not take."""
137
+ declared = request.headers.get("content-length")
138
+ if declared is not None and (not declared.isdigit() or int(declared) > limit):
139
+ raise Invalid
140
+ chunks, size = [], 0
141
+ async for chunk in request.stream():
142
+ size += len(chunk)
143
+ if size > limit:
144
+ raise Invalid
145
+ chunks.append(chunk)
146
+ return b"".join(chunks)
147
+
148
+
149
+ async def _exactly(request: Request, size: int) -> bytes | None:
150
+ """An upload's bytes (rest.md §4.4 item 2): exactly `size` of them, or None. The door reads at
151
+ most `size` bytes, and none at all when the declared length already says otherwise."""
152
+ declared = request.headers.get("content-length")
153
+ if declared is not None and (not declared.isdigit() or int(declared) != size):
154
+ return None
155
+ chunks, got = [], 0
156
+ async for chunk in request.stream():
157
+ got += len(chunk)
158
+ if got > size:
159
+ return None
160
+ chunks.append(chunk)
161
+ return b"".join(chunks) if got == size else None
162
+
163
+
164
+ async def _object(request: Request, allowed: set[str], required: set[str]) -> dict[str, Any]:
165
+ raw = await _bounded(request, BODY_MAX_BYTES)
166
+ try:
167
+ body = json.loads(raw)
168
+ except ValueError as e:
169
+ raise Invalid from e
170
+ if not isinstance(body, dict) or set(body) - allowed or required - set(body) or holds_nul(body):
171
+ raise Invalid # U+0000 included, in a key or a value at any depth (§3)
172
+ return body
173
+
174
+
175
+ def _str(value: Any, *, optional: bool = False, limit: int = 1024) -> str | None:
176
+ if value is None and optional:
177
+ return None
178
+ if not isinstance(value, str) or not value or len(value) > limit:
179
+ raise Invalid
180
+ return value
181
+
182
+
183
+ class Door:
184
+ """The door over one container: the credential, the throttle and the routes' shared reads."""
185
+
186
+ def __init__(self, container: Container, throttle: Throttle | None = None):
187
+ self.c = container
188
+ self.throttle = throttle or Throttle(
189
+ container.backend, container.ledger, throttle_key(container.home),
190
+ atomic=container.backend.atomic,
191
+ )
192
+
193
+ def origins(self) -> set[str]:
194
+ return set((self.c.config_value("identity.browser_origins") or "").split())
195
+
196
+ def caller(self, header: str | None) -> Token | None:
197
+ """The live caller a bearer value proves, or None (`rest.md` §2): a container `Token`,
198
+ else a provider token through all seven checks. Only the `Authorization` header is read."""
199
+ if not header or not header.startswith("Bearer "):
200
+ return None
201
+ value = header[len("Bearer "):]
202
+ if not value or value != value.strip():
203
+ return None
204
+ token = self.c.auth.use(value)
205
+ if token is not None:
206
+ return token
207
+ return self.c.identity.verify(value)
208
+
209
+ # -- shared reads ---------------------------------------------------------------------------
210
+ def probe(self, token: Token, ref: str | None) -> None:
211
+ """§4: a refusal appends a read, identical for every case."""
212
+ self.c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
213
+ client=token.client, ref=ref, items=[], layers=[], withheld=0)
214
+
215
+ def start(self, token: Token) -> Node | None:
216
+ """Where a scope defaults to: the token's first grant, or the personal root."""
217
+ if token.scopes and token.scopes[0] != "*":
218
+ node = self.c.backend.get_node(token.scopes[0])
219
+ return node if node and self.c.trust.covers(token, node) else None
220
+ return self.c.nodes.user_root()
221
+
222
+ def scope(self, token: Token, ref: str | None) -> Node | None:
223
+ """A covered node, or None for absent and uncovered alike. Raises `AmbiguousRef` to a
224
+ token holding `fetch`: the matches are named only to one that could list them, and to
225
+ any other an ambiguous tail is an absent one (§3)."""
226
+ if ref is None:
227
+ return self.start(token)
228
+ try:
229
+ node = self.c.nodes.resolve_ref(ref, token)
230
+ except AmbiguousRef:
231
+ if token.has("fetch"):
232
+ raise
233
+ return None
234
+ return node if node and self.c.trust.covers(token, node) else None
235
+
236
+ def node(self, node: Node) -> dict[str, Any]:
237
+ return {**node.to_dict(), "path": self.c.nodes.path(node)}
238
+
239
+ def entry(self, item: dict[str, Any], node: Node, shadowed_by: str | None = None) -> dict:
240
+ return {"item": item, "layer": self.c.nodes.path(node), "layer_type": node.type,
241
+ "shadowed_by": shadowed_by}
242
+
243
+ def readable(self, token: Token, item, node: Node) -> bool:
244
+ """Whether `GET /v1/items/{id}` serves the item to this token (§3's list)."""
245
+ if item.status == "quarantined":
246
+ return False
247
+ if item.kind in VERIFIED_ONLY_KINDS and item.status != "verified":
248
+ return False
249
+ return token.has("fetch") and self.c.trust.covers(token, node) and shown(
250
+ self.c, token, item, node
251
+ )
252
+
253
+
254
+ def create_app(
255
+ container: Container, *, door: Door | None = None, origin: str = "http://127.0.0.1:7426"
256
+ ) -> FastAPI:
257
+ """The door, served from `origin`: the door's own, as `serve` binds it (`bound_origin`). The
258
+ default is `serve`'s default bind; only tests rely on it. Where `identity.origin` is set, that
259
+ is the origin clients reach, and `/mcp`'s metadata and challenge name it (identity.md §2)."""
260
+ d = door or Door(container)
261
+ c = container
262
+ own = origin # the middleware's `origin` is the request's header
263
+ mcp = StreamableHttp(container, max_body=BODY_MAX_BYTES)
264
+
265
+ @contextlib.asynccontextmanager
266
+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
267
+ async def closer() -> None:
268
+ while True:
269
+ await asyncio.sleep(CLOSE_EVERY_SECONDS)
270
+ with contextlib.suppress(Exception): # a closer that fails tries next round
271
+ d.throttle.close()
272
+
273
+ task = asyncio.create_task(closer())
274
+ try:
275
+ async with mcp.running():
276
+ yield
277
+ finally:
278
+ task.cancel()
279
+
280
+ def public() -> str:
281
+ """The container's public origin (identity.md §2), read on every request so that a
282
+ `config set` reaches a running door; absent, the origin `serve` binds."""
283
+ named = c.config_value("identity.origin")
284
+ return own if named is None else named
285
+
286
+ def resource_metadata() -> Response:
287
+ """RFC 9728's document for `/mcp` (identity.md §7): the public origin, and the provider that
288
+ issues its tokens. A container with no provider has none to name (§1), so the key is left
289
+ out, as RFC 9728 allows."""
290
+ issuer = c.config_value("identity.issuer")
291
+ doc: dict[str, Any] = {"resource": public()}
292
+ if issuer is not None:
293
+ doc["authorization_servers"] = [issuer]
294
+ return _json(200, doc)
295
+
296
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
297
+
298
+ @app.middleware("http")
299
+ async def the_door(request: Request, call_next):
300
+ origin = request.headers.get("origin")
301
+ cors: dict[str, str] = {}
302
+ if origin is not None and origin in d.origins():
303
+ cors = {
304
+ "Access-Control-Allow-Origin": origin,
305
+ "Access-Control-Allow-Headers": CORS_ALLOW_HEADERS,
306
+ "Access-Control-Allow-Methods": METHODS,
307
+ "Vary": "Origin",
308
+ }
309
+
310
+ def out(response: Response) -> Response:
311
+ for key, value in HEADERS.items(): # §4.1's headers on MCP's answers too
312
+ response.headers.setdefault(key, value)
313
+ response.headers.update(cors)
314
+ return response
315
+
316
+ try:
317
+ return await admit(request, call_next, out, cors)
318
+ except StorageBusy: # §3: the write lock was not taken in time, the token check's included
319
+ return out(busy())
320
+ except Exception: # noqa: BLE001 — never a stack, a path or an exception's text
321
+ return out(_json(500, {"error": "internal"}))
322
+
323
+ async def admit(request: Request, call_next, out, cors: dict[str, str]) -> Response:
324
+ """Past CORS: the preflight, the metadata, the throttle, the credential, then the route."""
325
+ path = request.url.path
326
+ if request.method == "OPTIONS":
327
+ # identity.md §6: a preflight from an allowed origin gets 204 on every /v1/ path,
328
+ # declared or not, and at /mcp; from any other origin, §3's refusal and no CORS header.
329
+ if cors and (path.startswith("/v1/") or path == MCP_PATH):
330
+ return out(Response(status_code=204, headers=HEADERS))
331
+ return refusal()
332
+ if path == METADATA_PATH:
333
+ # Public and the same for every caller, so it needs no credential and is never held:
334
+ # a client reads it to learn where to get one (identity.md §7).
335
+ return out(resource_metadata() if request.method == "GET" else refusal())
336
+ metadata = public() + METADATA_PATH if path == MCP_PATH else None
337
+ address = request.client.host if request.client else None
338
+ # §6: a redemption is the descriptor's alone, so no Authorization header is read on it.
339
+ # Decided on the path the router matches, so no other route is reached without a caller.
340
+ pull = request.method == "GET" and PULL_PATH.fullmatch(request.scope["path"]) is not None
341
+ if d.throttle.holds(address):
342
+ d.throttle.count(address, refused=True)
343
+ return out(refusal() if pull else unauthorized(metadata))
344
+ token = None if pull else d.caller(request.headers.get("authorization"))
345
+ if token is None and not pull:
346
+ d.throttle.count(address, refused=False)
347
+ return out(unauthorized(metadata))
348
+ if path == MCP_PATH and token.principal == "interactive" and not isinstance(
349
+ token, GrantToken):
350
+ # identity.md §7 (the Chief, on #310): the owner's container Token, interactive and
351
+ # never expiring, is no credential at /mcp, so an MCP client is never handed it.
352
+ d.throttle.count(address, refused=False)
353
+ return out(unauthorized(metadata))
354
+ if path == MCP_PATH and request.method in ("GET", "DELETE"):
355
+ # identity.md §7: a stateless /mcp opens no stream and has no session to end. The
356
+ # transport's 405, the same for every verified caller; the 401 above came first.
357
+ return out(_json(405, {"error": "method_not_allowed"}, {"Allow": "POST"}))
358
+ if holds_nul([request.scope["path"], *request.query_params.multi_items()]):
359
+ return out(invalid()) # §3: a malformed request, answered before any lookup
360
+ request.state.token = token
361
+ # identity.md §3a: every entry the request appends names an agent's person
362
+ # (`details.for`) or the terminal a person's request came through (`details.terminal`).
363
+ with attributed(token):
364
+ return out(await call_next(request))
365
+
366
+ @app.exception_handler(Invalid)
367
+ async def on_invalid(request: Request, exc: Invalid):
368
+ return invalid()
369
+
370
+ @app.exception_handler(AmbiguousRef)
371
+ async def on_ambiguous(request: Request, exc: AmbiguousRef):
372
+ # §3: the matches named are only nodes the token covers; the refusal is a read too.
373
+ d.probe(request.state.token, None)
374
+ return ambiguous(exc.paths)
375
+
376
+ # -- reads ----------------------------------------------------------------------------------
377
+ def with_pull(token: Token, entry: dict[str, Any]) -> dict[str, Any]:
378
+ """§6: an artifact whose bytes do not ride inline carries Trust's grant and its URL beside
379
+ the item (§4.1), or nothing. Decided on the item as served: one small and `text/*` enough
380
+ to ride inline that does not (an agent's, promoted after its write) is asked about too."""
381
+ item = entry["item"]
382
+ if item["kind"] != "artifact" or "inline" in item["content"]:
383
+ return entry
384
+ grant = c.trust.authorize_pull(token, ContextItem.from_dict(item))
385
+ return {**entry, "grant": grant, "grant_url": grant_url(grant)} if grant else entry
386
+
387
+ @app.get("/v1/fetch")
388
+ async def fetch(request: Request):
389
+ token: Token = request.state.token
390
+ params = request.query_params
391
+ _only(params, {"scope", "query", "kind"})
392
+ kinds = None
393
+ if params.get("kind"):
394
+ kinds = params["kind"].split(",")
395
+ if any(k not in KINDS for k in kinds):
396
+ raise Invalid
397
+ query = params.get("query") or None
398
+ ref = params.get("scope") or None
399
+ node = d.scope(token, ref)
400
+ if node is None:
401
+ d.probe(token, ref)
402
+ return refusal()
403
+ result = c.resolver.resolve(node, token=token, actor=token.owner, kinds=kinds, text=query)
404
+ if result["scope"] is None:
405
+ return refusal() # the resolver appended the probe
406
+ return _json(200, {
407
+ "scope": result["scope"],
408
+ "chain": result["chain"],
409
+ "items": [
410
+ with_pull(token, {k: e[k] for k in ("item", "layer", "layer_type", "shadowed_by")})
411
+ for e in result["items"]
412
+ ],
413
+ })
414
+
415
+ @app.get("/v1/find")
416
+ async def find_items(request: Request):
417
+ token: Token = request.state.token
418
+ params = request.query_params
419
+ _only(params, {"q"})
420
+ q = params.get("q", "")
421
+ try:
422
+ query = parse(q)
423
+ except QueryError as e:
424
+ raise Invalid from e
425
+ if not token.has("fetch"):
426
+ d.probe(token, None)
427
+ return refusal()
428
+ hits = find(c, token, query)
429
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
430
+ subject=None, scope=None, client=token.client, query=q,
431
+ items=[i.id for _, i in hits], layers=[], withheld=0)
432
+ return _json(200, {"items": [d.entry(i.to_dict(), n) for n, i in hits]})
433
+
434
+ @app.get("/v1/items/{item_id}")
435
+ async def item(request: Request, item_id: str):
436
+ token: Token = request.state.token
437
+ _only(request.query_params, set())
438
+ found = c.store.get(item_id)
439
+ node = c.backend.get_node(found.scope) if found else None
440
+ if found is None or node is None or not d.readable(token, found, node):
441
+ d.probe(token, item_id)
442
+ return refusal()
443
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
444
+ subject=found.id, scope=node.id, client=token.client,
445
+ items=[found.id], layers=[node.id], withheld=0)
446
+ return _json(200, with_pull(token, d.entry(found.to_dict(), node)))
447
+
448
+ @app.get("/v1/inbox")
449
+ async def inbox(request: Request):
450
+ token: Token = request.state.token
451
+ _only(request.query_params, set())
452
+ box = c.nodes.inbox()
453
+ if box is None or not token.has("fetch") or not c.trust.covers(token, box):
454
+ d.probe(token, "inbox")
455
+ return refusal()
456
+ held = c.store.inbox_items()
457
+ rows = [(n, i) for n, i in held if c.resolver.serve(i, n)]
458
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
459
+ subject=box.id, scope=box.id, client=token.client, layers=["inbox"],
460
+ items=[i.id for _, i in rows], withheld=len(held) - len(rows))
461
+ return _json(200, {"items": [d.entry(i.to_dict(), n) for n, i in rows]})
462
+
463
+ @app.get("/v1/scopes")
464
+ async def scopes(request: Request):
465
+ token: Token = request.state.token
466
+ _only(request.query_params, {"under"})
467
+ ref = request.query_params.get("under") or None
468
+ node = d.scope(token, ref)
469
+ if node is None or not token.has("fetch"):
470
+ d.probe(token, ref)
471
+ return refusal()
472
+ children = [n for n in c.backend.list_nodes(parent=node.id) if c.trust.covers(token, n)]
473
+ out = sorted((d.node(n) for n in children), key=lambda n: n["path"])
474
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
475
+ subject=node.id, scope=node.id, client=token.client, items=[],
476
+ layers=[], nodes=[n["id"] for n in out], withheld=0)
477
+ return _json(200, {"nodes": out})
478
+
479
+ @app.get("/v1/pending")
480
+ async def pending(request: Request):
481
+ token: Token = request.state.token
482
+ _only(request.query_params, set())
483
+ if token.principal != "interactive":
484
+ d.probe(token, "pending")
485
+ return refusal()
486
+ queue = c.trust.pending()
487
+ # §4.4: an artifact still staged past the retention days is asked about under `staged`,
488
+ # instead of under `items`, until a person promotes or tombstones it.
489
+ days = c.config_value("blobs.staging_retention_days")
490
+ cutoff = c.uploads.clock() - days * 86400
491
+ waiting = c.uploads.staged_items()
492
+ items, staged = [], []
493
+ for i in queue["items"]:
494
+ n = c.backend.get_node(i.scope)
495
+ if n is not None and i.status == "unverified" and c.trust.covers(token, n):
496
+ created = calendar.timegm(time.strptime(i.lifecycle["created_at"],
497
+ "%Y-%m-%dT%H:%M:%SZ"))
498
+ old = i.id in waiting and created <= cutoff
499
+ (staged if old else items).append(i.to_dict())
500
+ proposals = [p for p in queue["proposals"] if c.trust.decides_over(token, p)]
501
+ wire = [{("from" if k == "from_" else k): v for k, v in p.items()} for p in proposals]
502
+ orphans = c.uploads.orphans(token, admin=token.has("admin") and "*" in token.scopes)
503
+ uploads = [{"upload": r["id"], **{k: r[k] for k in ORPHAN_KEYS}} for r in orphans]
504
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
505
+ client=token.client, view="pending", items=[i["id"] for i in items],
506
+ staged=[i["id"] for i in staged], uploads=[u["upload"] for u in uploads],
507
+ proposals=[p["id"] for p in proposals], layers=[], withheld=0)
508
+ return _json(200, {"items": items, "proposals": wire, "uploads": uploads,
509
+ "staged": staged})
510
+
511
+ # -- writes without a confirm ---------------------------------------------------------------
512
+ @app.post("/v1/items")
513
+ async def add(request: Request):
514
+ token: Token = request.state.token
515
+ _only(request.query_params, set())
516
+ if not token.has("remember"):
517
+ # The capability first: a token that may not write never makes the door read a body.
518
+ d.probe(token, None)
519
+ return refusal()
520
+ body = await _object(request, {"body", "kind", "scope", "key", "tags", "upload"}, set())
521
+ kind = _str(body.get("kind"), optional=True, limit=32) or "memory"
522
+ # Text in its body, or an artifact through an upload (§4.4): one or the other.
523
+ if kind not in KINDS or (kind == "artifact") != ("upload" in body) or (
524
+ ("body" in body) == ("upload" in body)):
525
+ raise Invalid
526
+ text = _str(body["body"], limit=BODY_MAX_BYTES) if "body" in body else None
527
+ upload = _str(body["upload"], limit=64) if "upload" in body else None
528
+ ref = _str(body.get("scope"), optional=True)
529
+ key = _str(body.get("key"), optional=True, limit=255)
530
+ tags = body.get("tags") or []
531
+ if not isinstance(tags, list) or not all(isinstance(t, str) and t for t in tags):
532
+ raise Invalid
533
+ node = None
534
+ if ref is not None:
535
+ node = d.scope(token, ref)
536
+ if node is None:
537
+ d.probe(token, ref)
538
+ return refusal()
539
+ try:
540
+ if upload is not None:
541
+ written = c.uploads.item(token, upload, scope=node, key=key, tags=tags)
542
+ else:
543
+ written = c.store.add(body=text, kind=kind, scope=node, key=key, tags=tags,
544
+ token=token, actor=token.owner, principal=token.principal)
545
+ except StoreError:
546
+ written = None
547
+ if written is None:
548
+ d.probe(token, upload or ref)
549
+ return refusal()
550
+ return _json(200, {"item": written.to_dict()})
551
+
552
+ # -- artifact upload (§4.4) -----------------------------------------------------------------
553
+ @app.post("/v1/uploads")
554
+ async def open_upload(request: Request):
555
+ token: Token = request.state.token
556
+ _only(request.query_params, set())
557
+ if not token.has("remember"):
558
+ d.probe(token, None)
559
+ return refusal()
560
+ fields = {"scope", "name", "mime", "size", "sha256"}
561
+ body = await _object(request, fields, fields)
562
+ ref = _str(body["scope"])
563
+ if not valid_open(body["name"], body["mime"], body["size"], body["sha256"],
564
+ limit=c.config_value("blobs.upload_max_bytes")):
565
+ raise Invalid
566
+ node = d.scope(token, ref)
567
+ if node is None:
568
+ d.probe(token, ref)
569
+ return refusal()
570
+ try:
571
+ record = c.uploads.open(token, scope=node, name=body["name"], mime=body["mime"],
572
+ size=body["size"], sha256=body["sha256"])
573
+ except TooManyUploads:
574
+ return _json(429, {"error": "too_many_uploads"})
575
+ return _json(200, {"upload": record["id"], "expires_at": record["expires_at"]})
576
+
577
+ @app.put("/v1/uploads/{upload_id}")
578
+ async def upload_bytes(request: Request, upload_id: str):
579
+ token: Token = request.state.token
580
+ _only(request.query_params, set())
581
+ record = c.uploads.live(token, upload_id)
582
+ if record is None:
583
+ # Unknown, expired, discarded and another principal's alike; no byte is read.
584
+ d.probe(token, upload_id)
585
+ return refusal()
586
+ outcome = c.uploads.put(token, upload_id, await _exactly(request, record["size"]))
587
+ if outcome is None:
588
+ d.probe(token, upload_id)
589
+ return refusal()
590
+ if outcome != "staged":
591
+ return invalid()
592
+ return _json(200, {"upload": upload_id, "sha256": record["sha256"]})
593
+
594
+ @app.delete("/v1/uploads/{upload_id}")
595
+ async def discard_upload(request: Request, upload_id: str):
596
+ token: Token = request.state.token
597
+ _only(request.query_params, set())
598
+ admin = token.principal == "interactive" and token.has("admin") and "*" in token.scopes
599
+ if not c.uploads.discard(token, upload_id, admin=admin):
600
+ d.probe(token, upload_id)
601
+ return refusal()
602
+ return _json(200, {"result": "discarded"})
603
+
604
+ @app.post("/v1/scopes")
605
+ async def make(request: Request):
606
+ token: Token = request.state.token
607
+ _only(request.query_params, set())
608
+ body = await _object(request, {"type", "name", "parent"}, {"type", "name"})
609
+ kind = _str(body["type"], limit=32)
610
+ name = _str(body["name"], limit=255)
611
+ if kind not in _CREATABLE:
612
+ raise Invalid
613
+ ref = _str(body.get("parent"), optional=True)
614
+ parent = d.scope(token, ref) if ref is not None else c.nodes.user_root()
615
+ if parent is None or not c.trust.covers(token, parent):
616
+ d.probe(token, ref)
617
+ return refusal()
618
+ try:
619
+ node = c.nodes.create(kind, name, parent, token=token, actor=token.owner,
620
+ principal=token.principal)
621
+ except StructureError:
622
+ d.probe(token, ref)
623
+ return refusal()
624
+ made = d.node(node)
625
+ if not token.has("fetch"):
626
+ made["path"] = None # §4.1 item 8: a computed path names ancestors; only `fetch` reads
627
+ return _json(200, {"node": made})
628
+
629
+ # -- the confirm (§4.2) ---------------------------------------------------------------------
630
+ def names(delta: list[dict[str, Any]]) -> list[str]:
631
+ """Who would newly see it: each grant's or registration's display name, a token's client."""
632
+ granted = {t.id: t for t in c.identity.audience_tokens()}
633
+ return [granted[m["token"]].name if m["token"] in granted else m["client"] for m in delta]
634
+
635
+ def origin_of(request: Request) -> str | None:
636
+ """The request's browser origin, when it is one this container answers (identity.md §6):
637
+ the relying party a WebAuthn credential belongs to. Any other origin is no origin."""
638
+ origin = request.headers.get("origin")
639
+ return origin if origin in d.origins() else None
640
+
641
+ def first_leg(token: Token, *, act: str, subject: str, destination: str | None,
642
+ delta: list[dict[str, Any]], origin: str | None, **extra: Any) -> Response:
643
+ newly = names(delta)
644
+ # Showing who would newly see an item is a read of credential metadata (§4.2 item 2).
645
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
646
+ client=token.client, subject=subject, items=[], layers=[], withheld=0,
647
+ confirm_for=act, newly=newly, **extra)
648
+ return _json(200, {**c.confirm.issue(token, act=act, subject=subject,
649
+ destination=destination,
650
+ delta=[m["token"] for m in delta], newly=newly,
651
+ origin=origin), **extra})
652
+
653
+ def presented(body: dict[str, Any]) -> dict[str, Any] | None:
654
+ value = body.get("confirm")
655
+ if value is None:
656
+ return None
657
+ if (not isinstance(value, dict) or set(value) - {"challenge", "proof", "assertion"}
658
+ or value.get("proof") not in ("biometric", "button")):
659
+ raise Invalid
660
+ _str(value.get("challenge"), limit=128) # a challenge id, never empty (§3: a 400)
661
+ return value
662
+
663
+ class Refused(Exception):
664
+ """The act the confirm was for cannot land: everything rolls back, the answer is §3's."""
665
+
666
+ async def move_or_copy(request: Request, item_id: str, act: str) -> Response:
667
+ token: Token = request.state.token
668
+ origin = origin_of(request)
669
+ _only(request.query_params, set())
670
+ body = await _object(request, {"to", "confirm"}, {"to"})
671
+ ref = _str(body["to"])
672
+ proof = presented(body)
673
+ item = c.store.get(item_id)
674
+ to = d.scope(token, ref)
675
+ if item is None or to is None:
676
+ d.probe(token, item_id)
677
+ return refusal()
678
+ try:
679
+ _frm, delta = c.trust.gate(item, to, token=token, act=act)
680
+ except TrustError:
681
+ d.probe(token, item_id)
682
+ return refusal()
683
+ if not delta or token.principal != "interactive":
684
+ # Nobody new would see it: the silent pass. Or a client principal, whose widening act
685
+ # parks for a person to decide, and whose `confirm` is ignored (§4.2 item 6).
686
+ r = (c.trust.move if act == "move" else c.trust.copy)(
687
+ item, to, token=token, actor=token.owner)
688
+ if r.get("gate") == "pending":
689
+ return _json(200, {"result": "pending", "proposal": r["proposal"]["id"]})
690
+ landed = c.store.get(item.id) if act == "move" else r["item"]
691
+ return _json(200, {"result": "moved" if act == "move" else "copied",
692
+ "item": landed.to_dict()})
693
+ if proof is None:
694
+ return first_leg(
695
+ token, act=act, subject=item.id, destination=to.id, delta=delta, origin=origin
696
+ )
697
+ try:
698
+ with c.backend.atomic():
699
+ # Recomputed under the lock: the confirm binds the delta as it stands now.
700
+ _frm, delta = c.trust.gate(item, to, token=token, act=act)
701
+ landed = None
702
+ if not delta:
703
+ # Nobody new would see it any more: the silent pass that is now due, with
704
+ # nothing to confirm (a1r on #289).
705
+ r = (c.trust.move if act == "move" else c.trust.copy)(
706
+ item, to, token=token, actor=token.owner)
707
+ landed = c.store.get(item.id) if act == "move" else r["item"]
708
+ else:
709
+ reason = c.confirm.conclude(token, proof, act=act, subject=item.id,
710
+ destination=to.id,
711
+ delta=[m["token"] for m in delta], origin=origin)
712
+ if reason is None:
713
+ landed = c.trust.confirmed(item, to, token=token, actor=token.owner,
714
+ act=act, delta=delta,
715
+ step_up=c.confirm.last_step_up_seq())
716
+ except (TrustError, HumanOnly):
717
+ d.probe(token, item_id)
718
+ return refusal()
719
+ if landed is None:
720
+ return first_leg(
721
+ token, act=act, subject=item.id, destination=to.id, delta=delta, origin=origin
722
+ )
723
+ return _json(200, {"result": "moved" if act == "move" else "copied",
724
+ "item": landed.to_dict()})
725
+
726
+ @app.post("/v1/items/{item_id}/move")
727
+ async def move(request: Request, item_id: str):
728
+ return await move_or_copy(request, item_id, "move")
729
+
730
+ @app.post("/v1/items/{item_id}/copy")
731
+ async def copy(request: Request, item_id: str):
732
+ return await move_or_copy(request, item_id, "copy")
733
+
734
+ async def optional_body(request: Request) -> dict[str, Any]:
735
+ if not await request.body():
736
+ return {}
737
+ return await _object(request, {"confirm"}, set())
738
+
739
+ async def decide(request: Request, proposal_id: str, act: str) -> Response:
740
+ token: Token = request.state.token
741
+ origin = origin_of(request)
742
+ _only(request.query_params, set())
743
+ proof = presented(await optional_body(request))
744
+ p = c.backend.get_proposal(proposal_id)
745
+ if (token.principal != "interactive" or p is None or p["status"] != "open"
746
+ or not c.trust.decides_over(token, p)):
747
+ d.probe(token, proposal_id)
748
+ return refusal()
749
+ # Approving a parked widening act shows who would newly see it, and the confirm binds that
750
+ # delta; a denial changes nobody's view (§4.2 item 1; a1r on #289).
751
+ widens = list(p.get("audience_delta") or []) if act == "approve" else []
752
+ if proof is None:
753
+ return first_leg(
754
+ token, act=act, subject=proposal_id, destination=None, delta=widens, origin=origin
755
+ )
756
+ outcome: str | None = None
757
+ result: dict[str, Any] = {}
758
+ try:
759
+ with c.backend.atomic():
760
+ reason = c.confirm.conclude(token, proof, act=act, subject=proposal_id,
761
+ destination=None,
762
+ delta=[m["token"] for m in widens], origin=origin)
763
+ if reason is None:
764
+ try:
765
+ if act == "approve":
766
+ result = c.trust.execute(proposal_id, token=token, actor=token.owner)
767
+ outcome = "executed"
768
+ else:
769
+ c.trust.deny(proposal_id, token=token, actor=token.owner)
770
+ outcome = "denied"
771
+ except TrustError as e:
772
+ current = c.backend.get_proposal(proposal_id)
773
+ if current is None or current["status"] != "stale":
774
+ raise Refused from e
775
+ outcome = "stale" # kept: the stale status and its event commit
776
+ except (Refused, HumanOnly):
777
+ d.probe(token, proposal_id)
778
+ return refusal()
779
+ if outcome is None:
780
+ return first_leg(
781
+ token, act=act, subject=proposal_id, destination=None, delta=widens, origin=origin
782
+ )
783
+ if outcome == "executed":
784
+ # A move's item is where it went; a copy's is the new one, not its source.
785
+ made = result.get("copies") or p["items"]
786
+ landed = c.store.get(made[0])
787
+ return _json(200, {"result": "executed", "item": landed.to_dict() if landed else None})
788
+ return _json(200, {"result": outcome})
789
+
790
+ @app.post("/v1/pending/{proposal_id}/approve")
791
+ async def approve(request: Request, proposal_id: str):
792
+ return await decide(request, proposal_id, "approve")
793
+
794
+ @app.post("/v1/pending/{proposal_id}/deny")
795
+ async def deny(request: Request, proposal_id: str):
796
+ return await decide(request, proposal_id, "deny")
797
+
798
+ # -- tombstone (§4): a person's, at once, or with the confirm where a person promoted it -----
799
+ def tombstone_leg(token: Token, item: Any, origin: str | None) -> Response:
800
+ """A promoted item's first leg: nobody newly sees anything, and it names what it removes,
801
+ a read audited as every first leg is (§4.2 item 2)."""
802
+ named = {"item": item.id, "kind": item.kind, "auto_title": item.content.get("auto_title")}
803
+ return first_leg(token, act="tombstone", subject=item.id, destination=None, delta=[],
804
+ origin=origin, tombstones=named)
805
+
806
+ @app.delete("/v1/items/{item_id}")
807
+ async def tombstone(request: Request, item_id: str):
808
+ token: Token = request.state.token
809
+ origin = origin_of(request)
810
+ _only(request.query_params, set())
811
+ if token.principal != "interactive" or not token.has("organize"):
812
+ d.probe(token, item_id) # one who may not act here never makes the door read a body
813
+ return refusal()
814
+ proof = presented(await optional_body(request))
815
+ leg, gone = None, None
816
+ with c.backend.atomic():
817
+ item = c.store.get(item_id) # as it stands under the lock (a6 on #289)
818
+ # A verified item, or one a person promoted whatever its status now, takes the
819
+ # confirm. A refused proof's `step_up` commits; a fresh first leg follows (§4.2 item 4).
820
+ if (item is not None and c.uploads.tombstonable(token, item)
821
+ and c.uploads.promoted(item)
822
+ and (proof is None or c.confirm.conclude(
823
+ token, proof, act="tombstone", subject=item.id, destination=None,
824
+ delta=[], origin=origin) is not None)):
825
+ leg = item
826
+ else: # never promoted, a `confirm` with it ignored; or confirmed
827
+ gone = c.uploads.tombstone(token, item_id)
828
+ if leg is not None:
829
+ return tombstone_leg(token, leg, origin)
830
+ if gone is None:
831
+ d.probe(token, item_id)
832
+ return refusal()
833
+ return _json(200, {"result": "tombstoned"})
834
+
835
+ @app.post("/v1/items/{item_id}/promote")
836
+ async def promote(request: Request, item_id: str):
837
+ token: Token = request.state.token
838
+ origin = origin_of(request)
839
+ _only(request.query_params, set())
840
+ proof = presented(await optional_body(request))
841
+ item = c.store.get(item_id)
842
+ node = c.backend.get_node(item.scope) if item else None
843
+ if (token.principal != "interactive" or item is None or node is None
844
+ or item.status != "unverified" or not c.trust.covers(token, node)):
845
+ d.probe(token, item_id)
846
+ return refusal()
847
+ if proof is None:
848
+ return first_leg(
849
+ token, act="promote", subject=item.id, destination=None, delta=[], origin=origin
850
+ )
851
+ promoted = None
852
+ try:
853
+ with c.backend.atomic():
854
+ reason = c.confirm.conclude(token, proof, act="promote", subject=item.id,
855
+ destination=None, delta=[], origin=origin)
856
+ if reason is None:
857
+ promoted = c.trust.promote(item, token=token, actor=token.owner)
858
+ except (TrustError, HumanOnly):
859
+ d.probe(token, item_id)
860
+ return refusal()
861
+ if promoted is None:
862
+ return first_leg(
863
+ token, act="promote", subject=item.id, destination=None, delta=[], origin=origin
864
+ )
865
+ return _json(200, {"result": "promoted", "item": promoted.to_dict()})
866
+
867
+ # -- grants (§4.3) --------------------------------------------------------------------------
868
+ def at_terminal(token: Token) -> bool:
869
+ """A person's token issued to a terminal's own client (identity.md §3a). It is its person,
870
+ but it gives no one access: the routes that give access, or keep or remove a confirm
871
+ credential, are §3's refusal to it before any leg and before its body is read (§4.3)."""
872
+ return terminal_of(token) is not None
873
+
874
+ def grantor(token: Token | None) -> bool:
875
+ """A person signed in at the provider, with `admin` over the whole container. A container
876
+ `Token` names no `sub`; an agent is never served who else holds access."""
877
+ return (isinstance(token, GrantToken) and token.principal == "interactive"
878
+ and token.has("admin") and "*" in token.scopes)
879
+
880
+ def granted(g: dict[str, Any]) -> dict[str, Any]:
881
+ """§4.3's `<grant>`."""
882
+ return {k: g[k] for k in ("sub", "name", "capabilities", "scopes", "created_at")}
883
+
884
+ scopes_max = 64 # the most scope refs a grant names: each is a lookup, made before any leg
885
+
886
+ def ask(token: Token, *, subject: str, destination: str, opens: list[tuple[str, str]],
887
+ origin: str | None) -> Response:
888
+ """§4.2's first leg for a grant: as `first_leg`, but naming whom it opens to as
889
+ `Identity.opens` does, since a person not yet granted is in no audience to name."""
890
+ newly = [name for _, name in opens]
891
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
892
+ client=token.client, subject=subject, items=[], layers=[], withheld=0,
893
+ confirm_for="grant.add", newly=newly)
894
+ return _json(200, c.confirm.issue(token, act="grant.add", subject=subject,
895
+ destination=destination,
896
+ delta=[member for member, _ in opens], newly=newly,
897
+ origin=origin))
898
+
899
+ @app.get("/v1/grants")
900
+ async def list_grants(request: Request):
901
+ token: Token = request.state.token
902
+ _only(request.query_params, set())
903
+ if not grantor(token):
904
+ d.probe(token, "grants")
905
+ return refusal()
906
+ live = [granted(g) for g in c.backend.list_user_grants() if not g["revoked"]]
907
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
908
+ client=token.client, read="grants", items=[], layers=[], withheld=0,
909
+ grants=[g["sub"] for g in live])
910
+ return _json(200, {"grants": live})
911
+
912
+ @app.post("/v1/grants")
913
+ async def add_grant(request: Request):
914
+ token: Token = request.state.token
915
+ origin = origin_of(request)
916
+ _only(request.query_params, set())
917
+ if not grantor(token) or at_terminal(token): # the door never reads this caller's body
918
+ d.probe(token, "grants")
919
+ return refusal()
920
+ body = await _object(request, {"sub", "name", "role", "capabilities", "scopes", "confirm"},
921
+ {"sub", "name", "scopes"})
922
+ proof = presented(body)
923
+ refs = body["scopes"]
924
+ try: # as `grant_user` checks them, so it never refuses one under the lock
925
+ sub = c.identity.user_id(body["sub"])
926
+ name = display_name(body["name"])
927
+ caps = c.identity.expand(body.get("role"), body.get("capabilities"))
928
+ except ValueError as e:
929
+ raise Invalid from e
930
+ if not isinstance(refs, list) or not 0 < len(refs) <= scopes_max:
931
+ raise Invalid
932
+ refs = [_str(r) for r in refs]
933
+ # The lookups, after every shape check (§3): a ref resolves as §3's do (an ambiguous tail
934
+ # is its 409), and the grant holds the node ids, never the refs.
935
+ nodes = [d.scope(token, r) for r in refs if r != "*"]
936
+ scopes = ["*"] if "*" in refs else sorted({n.id for n in nodes if n is not None})
937
+ # No grant exceeds the caller's own: wider capabilities or scopes are §3's refusal.
938
+ if None in nodes or c.identity.exceeds(token, caps, scopes):
939
+ d.probe(token, sub)
940
+ return refusal()
941
+ kw = {"actor": token.owner, "principal": token.principal}
942
+ if c.identity.refuse_narrowing(sub, caps, scopes, **kw): # before any leg (§4.3)
943
+ return _json(409, {"error": "last_admin"})
944
+ # The challenge binds the grant as it would land, beside its `sub` (the subject).
945
+ terms = json.dumps({"name": name, "capabilities": caps, "scopes": scopes}, sort_keys=True)
946
+ if proof is None:
947
+ return ask(token, subject=sub, destination=terms,
948
+ opens=c.identity.opens(sub, name, caps, scopes), origin=origin)
949
+ made, reason, opens = None, None, []
950
+ with c.backend.atomic():
951
+ # As on DELETE: the caller as their grant stands now, so a revoke or a narrowing since
952
+ # the door counts; the door's token concludes, as only it carries the sign-in time.
953
+ now = c.identity.refresh(token)
954
+ if grantor(now) and not c.identity.exceeds(now, caps, scopes):
955
+ opens = c.identity.opens(sub, name, caps, scopes) # the delta as it stands now
956
+ reason = c.confirm.conclude(token, proof, act="grant.add", subject=sub,
957
+ destination=terms, delta=[m for m, _ in opens],
958
+ origin=origin, fresh_sign_in=True)
959
+ if reason is None:
960
+ try:
961
+ made = c.identity.grant_user(sub, name=name, capabilities=caps,
962
+ scopes=scopes, **kw)
963
+ except LastAdmin:
964
+ return _json(409, {"error": "last_admin"}) # its refusal commits
965
+ if reason is not None:
966
+ return ask(token, subject=sub, destination=terms, opens=opens, origin=origin)
967
+ if made is None: # the caller's own grant changed since the door
968
+ d.probe(token, sub)
969
+ return refusal()
970
+ return _json(200, {"grant": granted(made)})
971
+
972
+ @app.delete("/v1/grants/{sub}")
973
+ async def revoke_grant(request: Request, sub: str):
974
+ token: Token = request.state.token
975
+ origin = origin_of(request)
976
+ _only(request.query_params, set())
977
+ if not grantor(token): # a caller who may not act here never makes the door read a body
978
+ d.probe(token, sub)
979
+ return refusal()
980
+ proof = presented(await optional_body(request))
981
+ grant = c.backend.get_user_grant(sub)
982
+ if grant is None or grant["revoked"]:
983
+ d.probe(token, sub)
984
+ return refusal()
985
+
986
+ def first() -> Response: # whose access it ends, and every registration it takes with it
987
+ ends: dict[str, Any] = {"grant": {"sub": sub, "name": grant["name"]}}
988
+ for kind, key in (("agent", "agents"), ("terminal", "terminals")):
989
+ named = [{"client_id": r["client_id"], "name": r["name"]}
990
+ for r in c.identity.serving(sub, kind)]
991
+ if named or kind == "agent": # `terminals` only where it ends one
992
+ ends[key] = named
993
+ return first_leg(token, act="grant.revoke", subject=sub, destination=None, delta=[],
994
+ origin=origin, revokes=ends)
995
+
996
+ # Narrowing your own access is never gated; ending someone else's is. `last_admin` is
997
+ # `revoke_user`'s, under the lock: your own revoke has no leg to come before, and another
998
+ # person's grant is never the last while the caller, re-read there, holds one.
999
+ gated = f"user:{sub}" != person_of(token)
1000
+ if gated and proof is None:
1001
+ return first()
1002
+ revoked, reason = False, None
1003
+ with c.backend.atomic():
1004
+ # The caller as their grant stands now, as approve re-reads its decider (#118): a
1005
+ # revoke or a narrowing since the door verified them counts. The token the door
1006
+ # verified is the one that concludes, since only it carries the sign-in time.
1007
+ if grantor(c.identity.refresh(token)):
1008
+ if gated:
1009
+ reason = c.confirm.conclude(token, proof, act="grant.revoke", subject=sub,
1010
+ destination=None, delta=[], origin=origin,
1011
+ fresh_sign_in=True)
1012
+ if reason is None:
1013
+ try:
1014
+ revoked = c.identity.revoke_user(sub, actor=token.owner,
1015
+ principal=token.principal)
1016
+ except LastAdmin:
1017
+ return _json(409, {"error": "last_admin"}) # its refusal commits
1018
+ if reason is not None:
1019
+ return first()
1020
+ if not revoked: # the caller's grant or the target's changed since the door
1021
+ d.probe(token, sub)
1022
+ return refusal()
1023
+ return _json(200, {"result": "revoked"})
1024
+
1025
+ # -- agents (§4.3) --------------------------------------------------------------------------
1026
+ def registrant(token: Token | None) -> bool:
1027
+ """A person signed in at the provider, on any live grant: whose agents these are. A
1028
+ container `Token` names no `sub`; an agent is never served who else holds access."""
1029
+ return isinstance(token, GrantToken) and token.principal == "interactive"
1030
+
1031
+ def agent(r: dict[str, Any], seen: dict[tuple[str, str], str]) -> dict[str, Any]:
1032
+ """§4.3's `<agent>`, `last_seen` read from the chain: null for an agent never seen."""
1033
+ keys = ("client_id", "name", "sub", "capabilities", "scopes", "created_at")
1034
+ return {**{k: r[k] for k in keys}, "last_seen": seen.get((r["client_id"], r["sub"]))}
1035
+
1036
+ @app.get("/v1/agents")
1037
+ async def list_agents(request: Request):
1038
+ token: Token = request.state.token
1039
+ _only(request.query_params, set())
1040
+ if not registrant(token):
1041
+ d.probe(token, "agents")
1042
+ return refusal()
1043
+ # The registrations serving this person; for an admin over everything, everyone's.
1044
+ live = ([r for r in c.identity.registrations("agent") if not r["revoked"]]
1045
+ if grantor(token) else c.identity.serving(token.sub, "agent"))
1046
+ seen = c.identity.last_seen(live)
1047
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
1048
+ client=token.client, read="agents", items=[], layers=[], withheld=0,
1049
+ agents=[{"client_id": r["client_id"], "sub": r["sub"]} for r in live])
1050
+ return _json(200, {"agents": [agent(r, seen) for r in live]})
1051
+
1052
+ @app.post("/v1/agents")
1053
+ async def add_agent(request: Request):
1054
+ token: Token = request.state.token
1055
+ origin = origin_of(request)
1056
+ _only(request.query_params, set())
1057
+ if not registrant(token) or at_terminal(token): # the door never reads this body
1058
+ d.probe(token, "agents")
1059
+ return refusal()
1060
+ body = await _object(
1061
+ request, {"authorization_id", "client_id", "name", "role", "capabilities", "scopes",
1062
+ "confirm"}, {"authorization_id", "client_id", "name", "scopes"})
1063
+ proof = presented(body)
1064
+ refs = body["scopes"]
1065
+ try: # what the consent page relays; the name is the agent's own claim
1066
+ authorization = provider_id(body["authorization_id"])
1067
+ client_id = provider_id(body["client_id"])
1068
+ name = display_name(body["name"])
1069
+ caps = c.identity.expand(body.get("role"), body.get("capabilities"))
1070
+ except ValueError as e:
1071
+ raise Invalid from e
1072
+ if not isinstance(refs, list) or not 0 < len(refs) <= scopes_max:
1073
+ raise Invalid
1074
+ refs = [_str(r) for r in refs]
1075
+ # The lookups, after every shape check, resolved as a grant's are: node ids, never refs.
1076
+ nodes = [d.scope(token, r) for r in refs if r != "*"]
1077
+ scopes = ["*"] if "*" in refs else sorted({n.id for n in nodes if n is not None})
1078
+ # This container's own client names a person, never an agent; a registration never
1079
+ # exceeds the caller's own grant, and needs no `publish`; an authorization registers once.
1080
+ head = c.ledger.tail(1)[-1]["seq"] # the door reads the chain to here; the lock, past it
1081
+ if (client_id == c.config_value("identity.client_id") or None in nodes
1082
+ or c.identity.exceeds(token, caps, scopes) or c.identity.claimed(authorization)):
1083
+ d.probe(token, client_id)
1084
+ return refusal()
1085
+ if c.identity.full(token.sub, client_id): # a fact about the caller's own, before any leg
1086
+ return _json(429, {"error": "too_many_agents"})
1087
+ # The challenge binds the registration as it would land, beside its client (the subject):
1088
+ # what the person is shown is what lands.
1089
+ terms = json.dumps({"authorization_id": authorization, "name": name,
1090
+ "capabilities": caps, "scopes": scopes}, sort_keys=True)
1091
+
1092
+ def first() -> Response: # nobody newly sees anything: the agent is named apart, as itself
1093
+ return first_leg(token, act="agent.add", subject=client_id, destination=terms,
1094
+ delta=[], origin=origin,
1095
+ registers={"client_id": client_id, "name": name})
1096
+
1097
+ if proof is None:
1098
+ return first()
1099
+ made, reason = None, None
1100
+ with c.backend.atomic():
1101
+ # As on the grant routes: the caller as their grant stands now, still covering the
1102
+ # registration, so a revoke since the door leaves no agent for a later grant to find;
1103
+ # the door's token concludes, as only it carries the sign-in time.
1104
+ # A client id a terminal's registration names is never an agent's: a proof that
1105
+ # would confirm concludes refused, `registered`, and the answer is a fresh first leg,
1106
+ # as for every refused proof, so no leg says the id was taken (§4.3).
1107
+ now = c.identity.refresh(token)
1108
+ if registrant(now) and not c.identity.exceeds(now, caps, scopes):
1109
+ taken = c.identity.taken(client_id, "agent")
1110
+ reason = c.confirm.conclude(token, proof, act="agent.add", subject=client_id,
1111
+ destination=terms, delta=[], origin=origin,
1112
+ fresh_sign_in=True,
1113
+ refusal="registered" if taken else None)
1114
+ if reason is None:
1115
+ try:
1116
+ made = c.identity.register_agent(
1117
+ token, client_id, authorization_id=authorization, name=name,
1118
+ capabilities=caps, scopes=scopes, after=head)
1119
+ except TooManyAgents: # a 16th landed since the door; its step_up commits
1120
+ return _json(429, {"error": "too_many_agents"})
1121
+ if reason is not None:
1122
+ return first()
1123
+ if made is None: # the caller's grant changed since the door, or the authorization is spent
1124
+ d.probe(token, client_id)
1125
+ return refusal()
1126
+ return _json(200, {"agent": agent(made, c.identity.last_seen([made]))})
1127
+
1128
+ def served(token: Token, sub: str | None) -> str | None:
1129
+ """The person whose registration a route names (`sub`, §4.3): the caller, or another
1130
+ person only for an admin over the whole container. None is §3's refusal, as it is for a
1131
+ client principal and a container `Token`."""
1132
+ if not registrant(token):
1133
+ return None
1134
+ if sub is None or sub == token.sub:
1135
+ return token.sub
1136
+ return sub if grantor(token) else None
1137
+
1138
+ @app.delete("/v1/agents/{client_id}")
1139
+ async def end_agent(request: Request, client_id: str):
1140
+ token: Token = request.state.token
1141
+ origin = origin_of(request)
1142
+ _only(request.query_params, {"sub"})
1143
+ sub = served(token, request.query_params.get("sub"))
1144
+ # As on the grant routes, a caller who may not act here never makes the door read a body.
1145
+ if sub is None:
1146
+ d.probe(token, client_id)
1147
+ return refusal()
1148
+ proof = presented(await optional_body(request))
1149
+ found = c.identity.registration(client_id, sub, "agent") # a terminal's is not one
1150
+ if found is None or found["revoked"]:
1151
+ d.probe(token, client_id)
1152
+ return refusal()
1153
+ # Ending your own agent narrows only your own access, so it is never gated, and a confirm
1154
+ # sent with it concludes nothing; ending one that serves someone else is gated as
1155
+ # registering it was, the challenge bound to the pair (GHSA-c3gg-hwx9-473g).
1156
+ gated = sub != token.sub
1157
+ binding = {"act": "agent.revoke", "subject": client_id, "destination": sub, "delta": [],
1158
+ "origin": origin}
1159
+
1160
+ def first() -> Response: # the registration it ends; the name is the agent's own claim
1161
+ return first_leg(token, **binding, revokes={"agent": {
1162
+ "client_id": client_id, "name": found["name"], "sub": sub}})
1163
+
1164
+ if gated and proof is None:
1165
+ return first()
1166
+ revoked, reason = False, None
1167
+ with c.backend.atomic():
1168
+ # Gated, as on the grant routes: the caller as their grant stands now, still an admin
1169
+ # over everything; the door's token concludes, as only it carries the sign-in time.
1170
+ # Your own: a revoke of your grant since the door ended this registration with it.
1171
+ if not gated or grantor(c.identity.refresh(token)):
1172
+ if gated:
1173
+ reason = c.confirm.conclude(token, proof, **binding, fresh_sign_in=True)
1174
+ if reason is None:
1175
+ revoked = c.identity.revoke_agent(client_id, sub, actor=token.owner,
1176
+ principal=token.principal)
1177
+ if reason is not None:
1178
+ return first()
1179
+ if not revoked: # the caller's grant or the registration changed since the door
1180
+ d.probe(token, client_id)
1181
+ return refusal()
1182
+ return _json(200, {"result": "revoked"})
1183
+
1184
+ def log_limit(params: Any) -> int:
1185
+ """§4.3: a log's `limit`, 1 to 200 and 50 when absent; any other value is §3's `400`."""
1186
+ raw = params.get("limit", "50")
1187
+ limit = int(raw) if re.fullmatch(r"[0-9]{1,3}", raw) else 0
1188
+ if not 0 < limit <= 200:
1189
+ raise Invalid
1190
+ return limit
1191
+
1192
+ def log_of(token: Token, entries: list[dict[str, Any]], limit: int,
1193
+ own: Any = None) -> tuple[list[dict[str, Any]], list[int], int]:
1194
+ """§4.3's log reader, newest first, over `entries`: the lines served, their chain
1195
+ positions and how many were passed over to serve them. It omits, with no marker and no
1196
+ count, a refused act, a probe (§4's names no subject), and a line whose subject, or scope
1197
+ where it names one, the reader does not cover today; `own` names the further subjects a
1198
+ terminal's log serves."""
1199
+ sight: dict[str, bool] = {}
1200
+
1201
+ def sees(ref: str | None) -> bool:
1202
+ # Covered today: an item by the node it sits in now, a node by itself, and anything
1203
+ # else (a proposal, an upload, a client id) never, but what `own` serves. A
1204
+ # tombstoned or quarantined item reads as absent, as at every item route (§3).
1205
+ if ref is None:
1206
+ return False
1207
+ if ref not in sight:
1208
+ item = c.store.get(ref) # None for a tombstoned item
1209
+ node = c.backend.get_node(item.scope if item else ref)
1210
+ sight[ref] = (node is not None and c.trust.covers(token, node)
1211
+ and (item is None or item.status != "quarantined"))
1212
+ return sight[ref]
1213
+
1214
+ lines: list[dict[str, Any]] = []
1215
+ positions: list[int] = [] # their chain positions, on the record only: served, a position
1216
+ withheld = 0 # would count what the reader cannot see (§4.3, "no count")
1217
+ for e in reversed(entries):
1218
+ if len(lines) == limit:
1219
+ break
1220
+ subject = e["subject"]
1221
+ if (e["details"].get("outcome") != "refused"
1222
+ and (sees(subject) or (own is not None and own(subject)))
1223
+ and (e["scope"] is None or sees(e["scope"]))):
1224
+ lines.append({k: e[k] for k in ("ts", "event", "subject", "scope")})
1225
+ positions.append(e["seq"])
1226
+ else:
1227
+ withheld += 1
1228
+ return lines, positions, withheld
1229
+
1230
+ @app.get("/v1/agents/{client_id}/log")
1231
+ async def agent_log(request: Request, client_id: str):
1232
+ token: Token = request.state.token
1233
+ params = request.query_params
1234
+ _only(params, {"sub", "limit"})
1235
+ limit = log_limit(params)
1236
+ sub = served(token, params.get("sub"))
1237
+ # A revoked registration's log is still its history, there to review after ending it. A
1238
+ # terminal's client id names no agent here (§4.3).
1239
+ if sub is None or c.identity.registration(client_id, sub, "agent") is None:
1240
+ d.probe(token, client_id)
1241
+ return refusal()
1242
+ lines, positions, withheld = log_of(token, c.identity.acted(client_id, sub), limit)
1243
+ # `withheld`, on the record only: the lines passed over to serve these.
1244
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
1245
+ client=token.client, subject=client_id, read="agent_log", items=[],
1246
+ layers=[], withheld=withheld, agent={"client_id": client_id, "sub": sub},
1247
+ entries=positions)
1248
+ return _json(200, {"entries": lines})
1249
+
1250
+ # -- terminals (§4.3) -----------------------------------------------------------------------
1251
+ def terminal(r: dict[str, Any], seen: dict[tuple[str, str], str],
1252
+ ended: dict[tuple[str, str], str] | None = None) -> dict[str, Any]:
1253
+ """§4.3's `<terminal>`, `last_seen` read from the chain, null for one not used yet; an
1254
+ ended one also carries `ended_at`, read from its `identity.revoke`."""
1255
+ pair = (r["client_id"], r["sub"])
1256
+ out = {**{k: r[k] for k in ("client_id", "name", "sub", "created_at")},
1257
+ "last_seen": seen.get(pair)}
1258
+ if ended is not None:
1259
+ out["ended_at"] = ended.get(pair)
1260
+ return out
1261
+
1262
+ @app.get("/v1/terminals")
1263
+ async def list_terminals(request: Request):
1264
+ token: Token = request.state.token
1265
+ params = request.query_params
1266
+ _only(params, {"ended"})
1267
+ if params.get("ended", "1") != "1": # absent, or exactly `1`: anything else is a 400
1268
+ raise Invalid
1269
+ ended = "ended" in params
1270
+ if not registrant(token):
1271
+ d.probe(token, "terminals")
1272
+ return refusal()
1273
+ # The live terminals signed in as this person, or with `ended=1` the ended ones; for an
1274
+ # admin over everything, everyone's. Never an agent (§4.3).
1275
+ mine = c.identity.registrations("terminal", sub=None if grantor(token) else token.sub)
1276
+ listed = [r for r in mine if bool(r["revoked"]) == ended]
1277
+ seen = c.identity.terminal_last_seen(listed)
1278
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
1279
+ client=token.client, read="terminals", items=[], layers=[], withheld=0,
1280
+ terminals=[{"client_id": r["client_id"], "sub": r["sub"]} for r in listed])
1281
+ gone = c.identity.terminal_ended(listed) if ended else None
1282
+ return _json(200, {"terminals": [terminal(r, seen, gone) for r in listed]})
1283
+
1284
+ @app.post("/v1/terminals")
1285
+ async def add_terminal(request: Request):
1286
+ token: Token = request.state.token
1287
+ origin = origin_of(request)
1288
+ _only(request.query_params, set())
1289
+ # A person's own, from a browser: a terminal's token registers nothing, and the door never
1290
+ # reads its body, nor that of a caller who may not act here.
1291
+ if not registrant(token) or at_terminal(token):
1292
+ d.probe(token, "terminals")
1293
+ return refusal()
1294
+ body = await _object(request, {"authorization_id", "client_id", "name", "confirm"},
1295
+ {"authorization_id", "client_id", "name"})
1296
+ proof = presented(body)
1297
+ try: # what the hand-off's page relays; the name is the terminal's own claim
1298
+ authorization = provider_id(body["authorization_id"])
1299
+ client_id = provider_id(body["client_id"])
1300
+ name = display_name(body["name"])
1301
+ except ValueError as e:
1302
+ raise Invalid from e
1303
+ # This container's own client names a person, and that id is no secret; an authorization
1304
+ # registers once. Whether this client id was registered here is said by no leg (below).
1305
+ head = c.ledger.tail(1)[-1]["seq"] # the door reads the chain to here; the lock, past it
1306
+ if client_id == c.config_value("identity.client_id") or c.identity.claimed(authorization):
1307
+ d.probe(token, client_id)
1308
+ return refusal()
1309
+ if c.identity.terminals_full(token.sub): # the caller's own fact, before any leg
1310
+ return _json(429, {"error": "too_many_terminals"})
1311
+ # The challenge binds the registration as it would land, beside its client (the subject).
1312
+ terms = json.dumps({"authorization_id": authorization, "name": name}, sort_keys=True)
1313
+
1314
+ def first() -> Response: # nobody newly sees anything: the terminal is named apart
1315
+ return first_leg(token, act="terminal.add", subject=client_id, destination=terms,
1316
+ delta=[], origin=origin,
1317
+ signs_in={"client_id": client_id, "name": name})
1318
+
1319
+ if proof is None:
1320
+ return first()
1321
+ made, reason = None, None
1322
+ with c.backend.atomic():
1323
+ # As on POST /v1/agents: the caller as their grant stands now. A client id any
1324
+ # registration here names, of either kind, live or ended, for anyone, is never a
1325
+ # terminal's: a proof that would confirm concludes refused, `registered`, answered with
1326
+ # a fresh first leg as every refused proof is, so a terminal ended never returns.
1327
+ now = c.identity.refresh(token)
1328
+ if registrant(now):
1329
+ taken = c.identity.taken(client_id, "terminal")
1330
+ reason = c.confirm.conclude(token, proof, act="terminal.add", subject=client_id,
1331
+ destination=terms, delta=[], origin=origin,
1332
+ fresh_sign_in=True,
1333
+ refusal="registered" if taken else None)
1334
+ if reason is None:
1335
+ try:
1336
+ made = c.identity.register_terminal(
1337
+ token, client_id, authorization_id=authorization, name=name,
1338
+ after=head)
1339
+ except TooManyTerminals: # a 16th landed since the door; its step_up commits
1340
+ return _json(429, {"error": "too_many_terminals"})
1341
+ if reason is not None:
1342
+ return first()
1343
+ if made is None: # the caller's grant changed since the door, or the authorization is spent
1344
+ d.probe(token, client_id)
1345
+ return refusal()
1346
+ return _json(200, {"terminal": terminal(made, c.identity.terminal_last_seen([made]))})
1347
+
1348
+ @app.delete("/v1/terminals/{client_id}")
1349
+ async def end_terminal(request: Request, client_id: str):
1350
+ token: Token = request.state.token
1351
+ origin = origin_of(request)
1352
+ _only(request.query_params, {"sub"})
1353
+ sub = served(token, request.query_params.get("sub"))
1354
+ if sub is None: # a caller who may not act here never makes the door read a body
1355
+ d.probe(token, client_id)
1356
+ return refusal()
1357
+ proof = presented(await optional_body(request))
1358
+ found = c.identity.registration(client_id, sub, "terminal") # an agent's is not one
1359
+ if found is None or found["revoked"]:
1360
+ d.probe(token, client_id)
1361
+ return refusal()
1362
+ # As for an agent: ending your own terminal, or the terminal ending itself with its
1363
+ # person's token, is never gated; ending one that serves someone else is, bound to the
1364
+ # pair, and a terminal's token concludes no second leg (identity.md §5).
1365
+ gated = sub != token.sub
1366
+ binding = {"act": "terminal.revoke", "subject": client_id, "destination": sub,
1367
+ "delta": [], "origin": origin}
1368
+
1369
+ def first() -> Response: # the terminal it ends; the name is the terminal's own claim
1370
+ return first_leg(token, **binding, revokes={"terminal": {
1371
+ "client_id": client_id, "name": found["name"], "sub": sub}})
1372
+
1373
+ if gated and proof is None:
1374
+ return first()
1375
+ revoked, reason = False, None
1376
+ with c.backend.atomic():
1377
+ if not gated or grantor(c.identity.refresh(token)):
1378
+ if gated:
1379
+ reason = c.confirm.conclude(token, proof, **binding, fresh_sign_in=True)
1380
+ if reason is None:
1381
+ revoked = c.identity.revoke_terminal(client_id, sub, actor=token.owner,
1382
+ principal=token.principal)
1383
+ if reason is not None:
1384
+ return first()
1385
+ if not revoked: # the caller's grant or the registration changed since the door
1386
+ d.probe(token, client_id)
1387
+ return refusal()
1388
+ return _json(200, {"result": "revoked"})
1389
+
1390
+ @app.get("/v1/terminals/{client_id}/log")
1391
+ async def terminal_log(request: Request, client_id: str):
1392
+ token: Token = request.state.token
1393
+ params = request.query_params
1394
+ _only(params, {"sub", "limit"})
1395
+ limit = log_limit(params)
1396
+ sub = served(token, params.get("sub"))
1397
+ # An ended terminal's log stays readable; an agent's client id names no terminal here.
1398
+ if sub is None or c.identity.registration(client_id, sub, "terminal") is None:
1399
+ d.probe(token, client_id)
1400
+ return refusal()
1401
+ person = principal_id(None, sub)
1402
+
1403
+ def own(ref: str | None) -> bool:
1404
+ # §4.3: what a terminal did to its person's other access shows in its log, judged
1405
+ # against the person it serves: their own `sub`, a registration serving them, of
1406
+ # either kind, live or ended, or an upload of theirs.
1407
+ if ref is None:
1408
+ return False
1409
+ if ref == sub or c.backend.get_agent_registration(ref, sub) is not None:
1410
+ return True
1411
+ upload = c.backend.get_upload(ref)
1412
+ return upload is not None and opener_of(upload["principal"], upload["actor"]) == person
1413
+
1414
+ lines, positions, withheld = log_of(token, c.identity.terminal_acted(client_id, sub),
1415
+ limit, own)
1416
+ # `withheld`, on the record only. The terminal is named under its own key: `terminal`
1417
+ # here would read as this read having come through it (identity.md §3a).
1418
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
1419
+ client=token.client, subject=client_id, read="terminal_log", items=[],
1420
+ layers=[], withheld=withheld,
1421
+ registration={"client_id": client_id, "sub": sub}, entries=positions)
1422
+ return _json(200, {"entries": lines})
1423
+
1424
+ # -- confirm credentials (§4.3) -------------------------------------------------------------
1425
+ def whose(token: Token, sub: str | None) -> str | None:
1426
+ """The person a credential route acts on: the caller, or with `sub` another person, which
1427
+ only an admin over the whole container may name. None is §3's refusal."""
1428
+ if sub is None or f"user:{sub}" == person_of(token):
1429
+ return person_of(token)
1430
+ if token.has("admin") and "*" in token.scopes:
1431
+ return f"user:{sub}"
1432
+ return None
1433
+
1434
+ def wire(cred: dict[str, Any]) -> dict[str, Any]:
1435
+ return {k: cred[k] for k in ("id", "name", "created_at", "last_used")}
1436
+
1437
+ @app.get("/v1/credentials")
1438
+ async def credentials(request: Request):
1439
+ token: Token = request.state.token
1440
+ _only(request.query_params, {"sub"})
1441
+ person = whose(token, request.query_params.get("sub")) if (
1442
+ token.principal == "interactive") else None
1443
+ if person is None:
1444
+ d.probe(token, "credentials")
1445
+ return refusal()
1446
+ creds = c.confirm.credentials(person)
1447
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
1448
+ client=token.client, read="credentials", items=[], layers=[],
1449
+ withheld=0)
1450
+ return _json(200, {"credentials": [wire(x) for x in creds]})
1451
+
1452
+ @app.post("/v1/credentials")
1453
+ async def register(request: Request):
1454
+ token: Token = request.state.token
1455
+ _only(request.query_params, set())
1456
+ origin = origin_of(request)
1457
+ if at_terminal(token): # kept from a browser, so never a body read from a terminal
1458
+ d.probe(token, "credentials")
1459
+ return refusal()
1460
+ body = await optional_body_of(request, {"challenge", "attestation", "confirm", "name"})
1461
+ if token.principal != "interactive" or origin is None:
1462
+ d.probe(token, "credentials")
1463
+ return refusal()
1464
+ raw = _str(body.get("name"), optional=True, limit=CREDENTIAL_NAME_MAX)
1465
+ try:
1466
+ name = display_name(raw, limit=CREDENTIAL_NAME_MAX) if raw else "this device"
1467
+ except ValueError as e:
1468
+ raise Invalid from e
1469
+ if "challenge" not in body:
1470
+ if "attestation" in body or "confirm" in body:
1471
+ raise Invalid
1472
+ return registration(token, origin, name)
1473
+ challenge = _str(body["challenge"])
1474
+ proof = presented(body)
1475
+ # A fresh sign-in is a provider token's, from its `amr`: a container `Token` carries none,
1476
+ # and this door is never the owner's own surface (rest.md §4.3; a1r on #290).
1477
+ fresh = c.confirm.fresh(token)
1478
+ with c.backend.atomic():
1479
+ cred, reason = c.confirm.finish_registration(
1480
+ token, origin=origin, challenge_id=challenge, attestation=body.get("attestation"),
1481
+ presented=proof, name=name, fresh=fresh, owner_surface=False)
1482
+ if reason is not None:
1483
+ return registration(token, origin, name)
1484
+ return _json(200, {"credential": wire(cred)})
1485
+
1486
+ def registration(token: Token, origin: str, name: str) -> Response:
1487
+ """A registration's first leg, fresh after a refusal too. Where its assertion options list
1488
+ the person's credentials, that is a read, and appends one (rest.md §4.3)."""
1489
+ out = c.confirm.begin_registration(token, origin=origin, name=name)
1490
+ if out["confirm"]["webauthn"] is not None:
1491
+ c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
1492
+ client=token.client, read="credentials", items=[], layers=[],
1493
+ withheld=0)
1494
+ return _json(200, out)
1495
+
1496
+ async def optional_body_of(request: Request, allowed: set[str]) -> dict[str, Any]:
1497
+ if not await request.body():
1498
+ return {}
1499
+ return await _object(request, allowed, set())
1500
+
1501
+ @app.delete("/v1/credentials/{credential_id}")
1502
+ async def remove(request: Request, credential_id: str):
1503
+ token: Token = request.state.token
1504
+ _only(request.query_params, {"sub"})
1505
+ origin = origin_of(request)
1506
+ if at_terminal(token): # removed from a browser, so never a body read from a terminal
1507
+ d.probe(token, credential_id)
1508
+ return refusal()
1509
+ proof = presented(await optional_body_of(request, {"confirm"}))
1510
+ person = whose(token, request.query_params.get("sub")) if (
1511
+ token.principal == "interactive") else None
1512
+ cred = c.backend.get_credential(credential_id)
1513
+ if person is None or cred is None or cred["removed"] or cred["person"] != person:
1514
+ d.probe(token, credential_id)
1515
+ return refusal()
1516
+ if proof is None:
1517
+ return first_leg(
1518
+ token, act="credential.remove", subject=credential_id, destination=None,
1519
+ delta=[], origin=origin
1520
+ )
1521
+ removed = False
1522
+ with c.backend.atomic():
1523
+ # A biometric proof only, never the button: the caller's own (rest.md §4.3).
1524
+ reason = c.confirm.conclude(token, proof, act="credential.remove",
1525
+ subject=credential_id, destination=None, delta=[],
1526
+ origin=origin, biometric_only=True)
1527
+ # Removed as it stands under the lock, never a snapshot read before it (a6 on #290).
1528
+ current = c.backend.get_credential(credential_id)
1529
+ if reason is None and current is not None and not current["removed"]:
1530
+ c.confirm.remove(token, current)
1531
+ removed = True
1532
+ else:
1533
+ # §4.3's closed set for a removal: the confirm's own reasons, mapped onto it.
1534
+ c.ledger.append("identity.credential", actor=token.owner,
1535
+ principal=token.principal, subject=cred["person"], op="remove",
1536
+ outcome="refused", reason=REMOVE_REASONS.get(reason, "stale"),
1537
+ credential=credential_id)
1538
+ if not removed:
1539
+ return first_leg(
1540
+ token, act="credential.remove", subject=credential_id, destination=None,
1541
+ delta=[], origin=origin
1542
+ )
1543
+ return _json(200, {"result": "removed"})
1544
+
1545
+ # -- BlobGrant redemption (§6): the descriptor is the credential ------------------------------
1546
+ @app.get("/v1/blobs/{sha256}")
1547
+ async def pull(request: Request, sha256: str):
1548
+ address = request.client.host if request.client else None
1549
+ data = redeem(c, d.throttle, address, sha256, request.query_params)
1550
+ # One chunk, read whole by `BlobStore.get`; streamed so that no Content-Length joins §6's
1551
+ # six headers.
1552
+ return refusal() if data is None else StreamingResponse(iter((data,)), headers=PULL_HEADERS)
1553
+
1554
+ # -- MCP over Streamable HTTP (identity.md §7): stateless, so POST is all it declares ---------
1555
+ app.add_route(MCP_PATH, mcp, methods=["POST"], include_in_schema=False)
1556
+
1557
+ # -- everything else ------------------------------------------------------------------------
1558
+ @app.api_route("/{rest:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"],
1559
+ include_in_schema=False)
1560
+ async def undeclared(request: Request, rest: str):
1561
+ return refusal()
1562
+
1563
+ from fastapi.exceptions import RequestValidationError
1564
+ from starlette.exceptions import HTTPException
1565
+
1566
+ @app.exception_handler(HTTPException)
1567
+ async def no_framework_shape(request: Request, exc: HTTPException):
1568
+ return refusal() # a 405 would confirm the path exists (§3)
1569
+
1570
+ @app.exception_handler(RequestValidationError)
1571
+ async def no_validation_shape(request: Request, exc: RequestValidationError):
1572
+ return invalid()
1573
+
1574
+ return app