authzai 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 (148) hide show
  1. agentic_auth/__init__.py +8 -0
  2. agentic_auth/_extras.py +24 -0
  3. agentic_auth/api/__init__.py +0 -0
  4. agentic_auth/api/deps.py +112 -0
  5. agentic_auth/api/errors.py +51 -0
  6. agentic_auth/api/responses.py +38 -0
  7. agentic_auth/api/service_deps.py +113 -0
  8. agentic_auth/api/v1/__init__.py +0 -0
  9. agentic_auth/api/v1/agents.py +88 -0
  10. agentic_auth/api/v1/audit.py +67 -0
  11. agentic_auth/api/v1/authorize.py +439 -0
  12. agentic_auth/api/v1/consent.py +21 -0
  13. agentic_auth/api/v1/decisions.py +43 -0
  14. agentic_auth/api/v1/enrollment.py +48 -0
  15. agentic_auth/api/v1/identity.py +97 -0
  16. agentic_auth/api/v1/jwks.py +21 -0
  17. agentic_auth/api/v1/manifests.py +68 -0
  18. agentic_auth/api/v1/scopes.py +22 -0
  19. agentic_auth/api/v1/token.py +203 -0
  20. agentic_auth/api/v1/transaction.py +94 -0
  21. agentic_auth/boundary/__init__.py +26 -0
  22. agentic_auth/boundary/guarantee.py +96 -0
  23. agentic_auth/cli/__init__.py +27 -0
  24. agentic_auth/cli/audit.py +130 -0
  25. agentic_auth/cli/drift.py +164 -0
  26. agentic_auth/cli/drift_render.py +148 -0
  27. agentic_auth/cli/identity.py +63 -0
  28. agentic_auth/cli/manifest.py +275 -0
  29. agentic_auth/config.py +182 -0
  30. agentic_auth/db.py +49 -0
  31. agentic_auth/embedded/__init__.py +427 -0
  32. agentic_auth/embedded/_schema.py +8 -0
  33. agentic_auth/embedded/_transport.py +39 -0
  34. agentic_auth/embedded/capabilities.py +34 -0
  35. agentic_auth/embedded/export.py +86 -0
  36. agentic_auth/embedded/idp.py +78 -0
  37. agentic_auth/embedded/store.py +240 -0
  38. agentic_auth/errors.py +145 -0
  39. agentic_auth/main.py +141 -0
  40. agentic_auth/models/__init__.py +70 -0
  41. agentic_auth/models/agent.py +58 -0
  42. agentic_auth/models/audit_decision.py +199 -0
  43. agentic_auth/models/compiled_policy.py +28 -0
  44. agentic_auth/models/manifest.py +96 -0
  45. agentic_auth/models/reconciliation_report.py +27 -0
  46. agentic_auth/models/sandbox_run.py +93 -0
  47. agentic_auth/models/session.py +63 -0
  48. agentic_auth/models/step_up_grant.py +106 -0
  49. agentic_auth/models/transaction_token.py +73 -0
  50. agentic_auth/models/trust_anchor.py +59 -0
  51. agentic_auth/models/types.py +95 -0
  52. agentic_auth/observability/__init__.py +370 -0
  53. agentic_auth/observability/config.py +137 -0
  54. agentic_auth/observability/context.py +128 -0
  55. agentic_auth/observability/ids.py +122 -0
  56. agentic_auth/observability/logs.py +191 -0
  57. agentic_auth/observability/pep.py +169 -0
  58. agentic_auth/observability/spans.py +225 -0
  59. agentic_auth/observability/surface.py +286 -0
  60. agentic_auth/observability/tracing.py +167 -0
  61. agentic_auth/redis.py +27 -0
  62. agentic_auth/repositories/__init__.py +0 -0
  63. agentic_auth/repositories/agents.py +96 -0
  64. agentic_auth/repositories/audit_decisions.py +152 -0
  65. agentic_auth/repositories/compiled_policies.py +72 -0
  66. agentic_auth/repositories/manifests.py +149 -0
  67. agentic_auth/repositories/reconciliation_reports.py +40 -0
  68. agentic_auth/repositories/sessions.py +41 -0
  69. agentic_auth/repositories/transaction_tokens.py +60 -0
  70. agentic_auth/repositories/trust_anchors.py +150 -0
  71. agentic_auth/runtime.py +81 -0
  72. agentic_auth/schemas/__init__.py +0 -0
  73. agentic_auth/schemas/agent.py +58 -0
  74. agentic_auth/schemas/audit.py +207 -0
  75. agentic_auth/schemas/authorize.py +205 -0
  76. agentic_auth/schemas/common.py +40 -0
  77. agentic_auth/schemas/consent.py +74 -0
  78. agentic_auth/schemas/dag.py +39 -0
  79. agentic_auth/schemas/edge_trace.py +166 -0
  80. agentic_auth/schemas/identity.py +152 -0
  81. agentic_auth/schemas/manifest.py +117 -0
  82. agentic_auth/schemas/manifest_api.py +38 -0
  83. agentic_auth/schemas/reconciliation.py +49 -0
  84. agentic_auth/schemas/token.py +122 -0
  85. agentic_auth/schemas/transaction.py +28 -0
  86. agentic_auth/sdk/__init__.py +114 -0
  87. agentic_auth/sdk/client.py +677 -0
  88. agentic_auth/sdk/context.py +95 -0
  89. agentic_auth/sdk/drift.py +118 -0
  90. agentic_auth/sdk/errors.py +147 -0
  91. agentic_auth/sdk/identity.py +162 -0
  92. agentic_auth/sdk/planes.py +362 -0
  93. agentic_auth/sdk/provenance.py +63 -0
  94. agentic_auth/services/__init__.py +0 -0
  95. agentic_auth/services/anchors.py +81 -0
  96. agentic_auth/services/audit.py +222 -0
  97. agentic_auth/services/audit_chain.py +144 -0
  98. agentic_auth/services/audit_cursor.py +55 -0
  99. agentic_auth/services/catalog_service.py +58 -0
  100. agentic_auth/services/chain_query.py +152 -0
  101. agentic_auth/services/dag_compiler.py +199 -0
  102. agentic_auth/services/decision_cache.py +123 -0
  103. agentic_auth/services/decision_history.py +71 -0
  104. agentic_auth/services/discovery.py +95 -0
  105. agentic_auth/services/drift.py +330 -0
  106. agentic_auth/services/edge_rules.py +62 -0
  107. agentic_auth/services/edge_trace.py +198 -0
  108. agentic_auth/services/enrollment.py +310 -0
  109. agentic_auth/services/enrollment_rules.py +80 -0
  110. agentic_auth/services/manifest_service.py +166 -0
  111. agentic_auth/services/metrics.py +419 -0
  112. agentic_auth/services/pdp.py +312 -0
  113. agentic_auth/services/policy_loader.py +255 -0
  114. agentic_auth/services/principal.py +143 -0
  115. agentic_auth/services/reconciler.py +119 -0
  116. agentic_auth/services/revocation.py +149 -0
  117. agentic_auth/services/sessions.py +231 -0
  118. agentic_auth/services/taint.py +204 -0
  119. agentic_auth/services/tokens/__init__.py +11 -0
  120. agentic_auth/services/tokens/act_chain.py +76 -0
  121. agentic_auth/services/tokens/exchange.py +319 -0
  122. agentic_auth/services/tokens/jwt_profile.py +362 -0
  123. agentic_auth/services/tokens/keys.py +117 -0
  124. agentic_auth/services/tokens/profile.py +167 -0
  125. agentic_auth/services/tokens/replay.py +53 -0
  126. agentic_auth/services/transactions.py +172 -0
  127. agentic_auth/sidecar/__init__.py +7 -0
  128. agentic_auth/sidecar/__main__.py +66 -0
  129. agentic_auth/sidecar/app.py +349 -0
  130. agentic_auth/sidecar/config.py +253 -0
  131. agentic_auth/sidecar/deny.py +108 -0
  132. agentic_auth/sidecar/enforce.py +640 -0
  133. agentic_auth/sidecar/identity.py +37 -0
  134. agentic_auth/verify/__init__.py +208 -0
  135. agentic_auth/verify/admit.py +131 -0
  136. agentic_auth/verify/anchors.py +250 -0
  137. agentic_auth/verify/canonical.py +228 -0
  138. agentic_auth/verify/grants.py +158 -0
  139. agentic_auth/verify/identity.py +111 -0
  140. agentic_auth/verify/replay.py +67 -0
  141. agentic_auth/verify/transaction.py +164 -0
  142. authzai-0.2.0.dist-info/METADATA +276 -0
  143. authzai-0.2.0.dist-info/RECORD +148 -0
  144. authzai-0.2.0.dist-info/WHEEL +5 -0
  145. authzai-0.2.0.dist-info/entry_points.txt +5 -0
  146. authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
  147. authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
  148. authzai-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,439 @@
1
+ """``POST /v1/authorize`` — decide one hop against the session's pinned policy.
2
+
3
+ Always returns ``200`` with a decision body. A deny is a successful decision, not an HTTP
4
+ error: the sidecar and the SDK translate it into a refusal for the agent, and conflating
5
+ the two would make "the PDP is down" indistinguishable from "the PDP said no".
6
+
7
+ The response is rendered from what was **recorded**, after the record has committed. An
8
+ answer that would let a call leave the host is never sent for a decision that has no durable
9
+ audit row.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import uuid
16
+ from collections.abc import Mapping
17
+ from datetime import UTC, datetime
18
+
19
+ from fastapi import APIRouter, Request
20
+ from sqlalchemy.ext.asyncio import AsyncSession
21
+
22
+ from agentic_auth import observability
23
+ from agentic_auth.api.deps import PresentedTokenDep, SessionDep
24
+ from agentic_auth.api.service_deps import (
25
+ AuditServiceDep,
26
+ RedisDep,
27
+ RevocationServiceDep,
28
+ SessionServiceDep,
29
+ )
30
+ from agentic_auth.config import get_settings
31
+ from agentic_auth.errors import DomainError
32
+ from agentic_auth.models.audit_decision import target_kind_of
33
+ from agentic_auth.observability import logs, surface
34
+ from agentic_auth.schemas.authorize import AuthorizeDecision, AuthorizeRequest, DenyReason, Taint
35
+ from agentic_auth.services import decision_cache, policy_loader
36
+ from agentic_auth.services.audit import AuditService, RecordResult
37
+ from agentic_auth.services.metrics import get_metrics
38
+ from agentic_auth.services.pdp import Decision, decide
39
+ from agentic_auth.services.taint import (
40
+ Marked,
41
+ TaintStore,
42
+ TaintStoreUnavailable,
43
+ ancestors_of,
44
+ effective_taint,
45
+ )
46
+ from agentic_auth.services.tokens.profile import VerifiedToken
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ router = APIRouter(prefix="/v1", tags=["authorize"])
51
+
52
+ UNRECORDED_MESSAGE = "decision could not be recorded; refusing to dispatch without a record"
53
+
54
+
55
+ @router.post("/authorize", response_model=AuthorizeDecision)
56
+ async def authorize(
57
+ request: Request,
58
+ body: AuthorizeRequest,
59
+ db: SessionDep,
60
+ redis: RedisDep,
61
+ sessions: SessionServiceDep,
62
+ audit: AuditServiceDep,
63
+ token: PresentedTokenDep,
64
+ revocations: RevocationServiceDep,
65
+ ) -> AuthorizeDecision:
66
+ hop = token.next_hop
67
+
68
+ try:
69
+ session = await sessions.get(db, redis, body.session_id)
70
+ policy = await policy_loader.load(db, redis, session.scope, session.policy_version)
71
+ except DomainError:
72
+ # An expired session or a missing/unenforceable policy is the caller's answer to
73
+ # get, with its own status code. Re-raised rather than flattened into a deny.
74
+ raise
75
+ except Exception:
76
+ # Anything else — a dropped connection, a malformed row — is a deny, recorded.
77
+ # There is no path here that omits the record or returns an allow.
78
+ # NOT logger.exception: with a sink attached the SDK exports `exception.message` and
79
+ # the full `exception.stacktrace`, and a traceback through policy loading can carry
80
+ # connection-string or token fragments. We keep the type and lose the trace — a
81
+ # deliberate reduction. Do not revert.
82
+ logger.warning(
83
+ "policy load failed",
84
+ extra=logs.fields(
85
+ surface.COMPONENT_CONTROL_PLANE,
86
+ session_id=body.session_id,
87
+ error_type="PolicyLoadFailed",
88
+ ),
89
+ )
90
+ rendered, _ = await _record(
91
+ db,
92
+ audit,
93
+ body,
94
+ Decision(
95
+ outcome="deny",
96
+ hop=hop,
97
+ reason=DenyReason.PDP_UNAVAILABLE,
98
+ message="policy could not be loaded",
99
+ ),
100
+ policy_version=token.policy_version,
101
+ token=token,
102
+ headers=request.headers,
103
+ )
104
+ return rendered
105
+
106
+ settings = get_settings()
107
+
108
+ # -- provenance ---------------------------------
109
+ # What the session already knows about this context, from the calls it decided.
110
+ caller_agent = token.holder
111
+ protected = caller_agent is not None and policy.is_protected(
112
+ caller_agent, body.target, body.data_class
113
+ )
114
+ store = TaintStore(redis)
115
+ marked = Marked(False, None)
116
+ taint_known = True
117
+ try:
118
+ marked = Marked.of(await store.marked(body.session_id), token.jti)
119
+ except TaintStoreUnavailable:
120
+ if protected:
121
+ # Refusing on unknown taint is the only honest answer for a protected target.
122
+ logger.warning(
123
+ "taint store unavailable for a protected target",
124
+ extra=logs.fields(
125
+ surface.COMPONENT_CONTROL_PLANE,
126
+ session_id=body.session_id,
127
+ error_type="TaintStoreUnavailable",
128
+ ),
129
+ )
130
+ rendered, _ = await _record(
131
+ db,
132
+ audit,
133
+ body,
134
+ Decision(
135
+ outcome="deny",
136
+ hop=hop,
137
+ reason=DenyReason.PDP_UNAVAILABLE,
138
+ message="taint state could not be read for a protected target",
139
+ ),
140
+ policy_version=session.policy_version,
141
+ token=token,
142
+ headers=request.headers,
143
+ )
144
+ return rendered
145
+ taint_known = False
146
+ taint = effective_taint(token.taint, body.taint, marked.tainted) if taint_known else None
147
+ taint_source = marked.source if marked.tainted else None
148
+ if not marked.tainted and taint is Taint.UNTRUSTED_EXTERNAL:
149
+ taint_source = "reported" if body.taint is Taint.UNTRUSTED_EXTERNAL else "inherited"
150
+
151
+ revoked = await revocations.revoked_set(db, redis)
152
+ chain_agents = {a.removeprefix("agent://") for a in token.act_chain[1:]}
153
+ if caller_agent is not None:
154
+ chain_agents.add(caller_agent)
155
+ if body.target.startswith("agent://"):
156
+ chain_agents.add(body.target.removeprefix("agent://")) # delegating TO a revoked agent
157
+ revoked_on_chain = frozenset(revoked & chain_agents)
158
+
159
+ cache_key = decision_cache.key(
160
+ body,
161
+ policy_version=session.policy_version,
162
+ hop=hop,
163
+ # The chain is a decision input: the same call is allowed via one route and
164
+ # denied via another when the effective budgets differ.
165
+ act_chain=token.act_chain,
166
+ taint=taint,
167
+ revoked=revoked_on_chain,
168
+ )
169
+ decision = await decision_cache.get(redis, cache_key)
170
+ if decision is None:
171
+ decision = decide(
172
+ policy,
173
+ body,
174
+ token,
175
+ consented_scope=session.scope,
176
+ transaction_tokens_enabled=settings.transaction_tokens_enabled,
177
+ taint=taint,
178
+ taint_enforced=settings.taint_enforcement_enabled,
179
+ revoked=revoked_on_chain,
180
+ )
181
+ await decision_cache.put(redis, cache_key, decision)
182
+
183
+ if decision.reason is DenyReason.AGENT_REVOKED:
184
+ get_metrics().revoked_hop_refusals.labels(where="authorize").inc()
185
+ if decision.reason is DenyReason.TAINTED_INTO_PRIVILEGED:
186
+ get_metrics().taint_blocks.labels(source_class=_source_class(taint_source)).inc()
187
+
188
+ rendered, record = await _record(
189
+ db,
190
+ audit,
191
+ body,
192
+ decision,
193
+ policy_version=session.policy_version,
194
+ token=token,
195
+ taint_source=taint_source,
196
+ headers=request.headers,
197
+ )
198
+
199
+ get_metrics().decisions_by_guarantee.labels(
200
+ level=body.guarantee.value, outcome=rendered.outcome
201
+ ).inc()
202
+
203
+ # -- mark: this call reaches for a source the caller does not trust ---------------
204
+ # On an allow (or an observe-mode forwarded policy deny) the result will be consumed
205
+ # by this context and by every ancestor on the return path. Recorded first-writer-wins,
206
+ # so the source that introduced the taint is the one the audit trail names.
207
+ will_dispatch = rendered.allowed or (
208
+ rendered.reason is not None and rendered.reason in _POLICY_FORWARDABLE and not body.enforced
209
+ )
210
+ if (
211
+ will_dispatch
212
+ and caller_agent is not None
213
+ and not policy.is_trusted_source(caller_agent, body.target)
214
+ ):
215
+ contexts = ancestors_of(record.parent_chain, token.jti)
216
+ try:
217
+ await store.mark(
218
+ body.session_id,
219
+ contexts,
220
+ body.target,
221
+ action_id=str(record.action_id) if record.action_id else None,
222
+ ttl_seconds=int((session.expires_at - _now()).total_seconds()),
223
+ )
224
+ except TaintStoreUnavailable:
225
+ # An untrusted fetch whose taint cannot be remembered is how injected content
226
+ # gets laundered. The allow is withdrawn; the record already says allow, and
227
+ # the exchange will refuse because the response carries no usable action_id.
228
+ logger.warning(
229
+ "taint store unavailable while marking; withdrawing the allow",
230
+ extra=logs.fields(
231
+ surface.COMPONENT_CONTROL_PLANE,
232
+ session_id=body.session_id,
233
+ error_type="TaintStoreUnavailable",
234
+ ),
235
+ )
236
+ return _withdrawn(rendered, body, session.policy_version, token)
237
+ _count_marks(contexts, token.jti)
238
+
239
+ return rendered
240
+
241
+
242
+ _POLICY_FORWARDABLE = frozenset(
243
+ {
244
+ DenyReason.OUT_OF_SCOPE,
245
+ DenyReason.HOP_BUDGET_EXCEEDED,
246
+ DenyReason.EDGE_NOT_IN_DAG,
247
+ DenyReason.SCOPE_NOT_CONSENTED,
248
+ DenyReason.TAINTED_INTO_PRIVILEGED,
249
+ DenyReason.AGENT_REVOKED,
250
+ DenyReason.AGENT_NOT_ENROLLED,
251
+ }
252
+ )
253
+
254
+
255
+ def _now() -> datetime:
256
+ return datetime.now(UTC)
257
+
258
+
259
+ def _source_class(source: str | None) -> str:
260
+ if source is None:
261
+ return "unknown"
262
+ if source == "reported":
263
+ return "reported"
264
+ if source.startswith("agent://"):
265
+ return "agent"
266
+ if source.startswith("mcp://"):
267
+ return "tool"
268
+ return "unknown"
269
+
270
+
271
+ def _count_marks(contexts: set[str], own_jti: str) -> None:
272
+ metrics = get_metrics()
273
+ for ctx in contexts:
274
+ if ctx == own_jti:
275
+ metrics.taint_marks.labels(propagation="self").inc()
276
+ elif ctx == "*":
277
+ metrics.taint_marks.labels(propagation="sentinel").inc()
278
+ else:
279
+ metrics.taint_marks.labels(propagation="ancestor").inc()
280
+
281
+
282
+ def _withdrawn(
283
+ rendered: AuthorizeDecision, body: AuthorizeRequest, policy_version: int, token: VerifiedToken
284
+ ) -> AuthorizeDecision:
285
+ """An allow the caller must not act on: rendered as PDP_UNAVAILABLE with no action_id,
286
+ which the exchange refuses and the sidecar/SDK treat as an outage (blocks in every mode)."""
287
+ get_metrics().denials.labels(reason=DenyReason.PDP_UNAVAILABLE.value).inc()
288
+ return AuthorizeDecision(
289
+ outcome="deny",
290
+ hop=rendered.hop,
291
+ policy_version=policy_version,
292
+ session_id=body.session_id,
293
+ reason=DenyReason.PDP_UNAVAILABLE,
294
+ recoverable=False,
295
+ target=body.target,
296
+ taint=rendered.taint,
297
+ taint_source=rendered.taint_source,
298
+ privileged=rendered.privileged,
299
+ transaction_required=rendered.transaction_required,
300
+ message="taint state could not be recorded; refusing to dispatch an untrusted fetch",
301
+ action_id=None,
302
+ acting_agent=token.holder,
303
+ recorded=rendered.recorded,
304
+ guarantee=body.guarantee,
305
+ )
306
+
307
+
308
+ async def _record(
309
+ db: AsyncSession,
310
+ audit: AuditService,
311
+ body: AuthorizeRequest,
312
+ decision: Decision,
313
+ *,
314
+ policy_version: int,
315
+ token: VerifiedToken,
316
+ taint_source: str | None = None,
317
+ step_up_ref: uuid.UUID | None = None,
318
+ headers: Mapping[str, str] | None = None,
319
+ ) -> tuple[AuthorizeDecision, RecordResult]:
320
+ """Record, commit, then render from the result. Every decision is recorded — including
321
+ the ones caused by an unreachable dependency, which are the ones an operator most needs
322
+ to see."""
323
+ # `enforced=false` means this decision was NOT acted on — which only a deny can be. An
324
+ # allow in observe mode is still exchanged and forwarded, so it was acted on and is
325
+ # recorded as enforced. That keeps `enforced=false` meaning exactly "would have been
326
+ # blocked", which is the observe-mode report.
327
+ #
328
+ # Reported by the enforcement point, never seen by `decide()`: the PDP is mode-blind,
329
+ # so observe mode changes a consequence and never an outcome.
330
+ enforced = body.enforced or decision.allowed
331
+
332
+ result = await audit.record(
333
+ db,
334
+ session_id=body.session_id,
335
+ caller=body.caller,
336
+ target=body.target,
337
+ data_class=body.data_class,
338
+ decision=decision,
339
+ enforced=enforced,
340
+ taint=decision.taint.value if decision.taint else None,
341
+ taint_source=taint_source,
342
+ policy_version=policy_version,
343
+ token=token,
344
+ privileged=decision.privileged,
345
+ # Phase 5. What the enforcement point said it is; recorded on every row.
346
+ guarantee_level=body.guarantee.value,
347
+ step_up_ref=step_up_ref,
348
+ )
349
+
350
+ # A call leaves the host on an allow, and on an unenforced (observe-mode) deny. Either
351
+ # way, without a durable record it must not — so the answer becomes a refusal. An
352
+ # enforced deny blocks regardless, and stays the deny it was.
353
+ if not result.recorded and (decision.allowed or not enforced):
354
+ decision = Decision(
355
+ outcome="deny",
356
+ hop=decision.hop,
357
+ reason=DenyReason.AUDIT_UNAVAILABLE,
358
+ message=UNRECORDED_MESSAGE,
359
+ )
360
+
361
+ if decision.reason is not None:
362
+ get_metrics().denials.labels(reason=decision.reason.value).inc()
363
+
364
+ rendered = AuthorizeDecision(
365
+ outcome=decision.outcome,
366
+ hop=decision.hop,
367
+ policy_version=policy_version,
368
+ session_id=body.session_id,
369
+ reason=decision.reason,
370
+ recoverable=decision.recoverable if decision.reason else None,
371
+ target=body.target,
372
+ taint=decision.taint,
373
+ taint_source=taint_source,
374
+ privileged=decision.privileged,
375
+ transaction_required=decision.transaction_required,
376
+ message=decision.message,
377
+ action_id=result.action_id,
378
+ acting_agent=token.holder,
379
+ recorded=result.recorded,
380
+ guarantee=body.guarantee,
381
+ )
382
+ _emit_decision_span(rendered, body, token, policy_version, taint_source, headers)
383
+ return rendered, result
384
+
385
+
386
+ def _emit_decision_span(
387
+ rendered: AuthorizeDecision,
388
+ body: AuthorizeRequest,
389
+ token: VerifiedToken,
390
+ policy_version: int,
391
+ taint_source: str | None,
392
+ headers: Mapping[str, str] | None,
393
+ ) -> None:
394
+ """One span per decision, emitted from the single place every decision is rendered.
395
+
396
+ Deliberately **after** the audit record has committed, so ``authz.action_id`` is the
397
+ recorded id and never a guess. When the record failed there is no action id — and the
398
+ decision has already been rewritten to a deny with ``AUDIT_UNAVAILABLE``, so the pair
399
+ "no action id, no AUDIT_UNAVAILABLE" cannot occur.
400
+
401
+ ``record_exception`` is off: the SDK would attach ``exception.message`` and a full
402
+ ``exception.stacktrace``, and a traceback through token verification can carry a token
403
+ fragment.
404
+ """
405
+ config = observability.config()
406
+ if not config.enabled:
407
+ return
408
+ parent = observability.extract_parent(
409
+ headers or {},
410
+ session_id=str(body.session_id),
411
+ key=config.key,
412
+ metrics=get_metrics(),
413
+ )
414
+ attributes = observability.decision_attributes(
415
+ config,
416
+ action_id=str(rendered.action_id) if rendered.action_id else None,
417
+ session_id=str(body.session_id),
418
+ hop=rendered.hop,
419
+ outcome=rendered.outcome,
420
+ deny_reason=rendered.reason.value if rendered.reason else None,
421
+ recoverable=bool(rendered.recoverable),
422
+ enforced=body.enforced or rendered.allowed,
423
+ target_kind=target_kind_of(body.target),
424
+ data_class=body.data_class,
425
+ privileged=bool(rendered.privileged),
426
+ taint=rendered.taint.value if rendered.taint else None,
427
+ policy_version=policy_version,
428
+ guarantee_level=getattr(rendered, "guarantee", None) or getattr(body, "guarantee", None),
429
+ acting_agent=token.holder,
430
+ act_chain=list(token.act_chain),
431
+ taint_source=taint_source,
432
+ )
433
+ with observability.tracer().start_as_current_span(
434
+ surface.SPAN_DECIDE,
435
+ context=parent,
436
+ attributes=attributes,
437
+ record_exception=False,
438
+ ):
439
+ pass
@@ -0,0 +1,21 @@
1
+ """``POST /v1/consent`` — the human act that roots a session's authority."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import APIRouter, status
6
+
7
+ from agentic_auth.api.deps import AdminDep, SessionDep
8
+ from agentic_auth.api.service_deps import RedisDep, SessionServiceDep
9
+ from agentic_auth.schemas.consent import ConsentCreate, ConsentRead
10
+
11
+ router = APIRouter(prefix="/v1", tags=["consent"], dependencies=[AdminDep])
12
+
13
+
14
+ @router.post("/consent", response_model=ConsentRead, status_code=status.HTTP_201_CREATED)
15
+ async def create_consent(
16
+ body: ConsentCreate,
17
+ db: SessionDep,
18
+ redis: RedisDep,
19
+ sessions: SessionServiceDep,
20
+ ) -> ConsentRead:
21
+ return await sessions.consent(db, redis, body)
@@ -0,0 +1,43 @@
1
+ """``GET /v1/decisions`` — the Phase 2 observe-mode report. **Deprecated.**
2
+
3
+ Kept for one phase so existing observe-mode tooling keeps working, served by the same
4
+ history query as ``GET /v1/audit/decisions`` and accepting Phase 2's filters.
5
+ ``?enforced=false&outcome=deny`` is still the report proper: everything that would have been
6
+ blocked, while nothing was. New callers should use ``/v1/audit/decisions``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Annotated
12
+
13
+ from fastapi import APIRouter, Query
14
+
15
+ from agentic_auth.api.deps import AuditReaderDep, PaginationDep, SessionDep
16
+ from agentic_auth.schemas.audit import AuditDecisionPage
17
+ from agentic_auth.services.decision_history import history_page
18
+
19
+ router = APIRouter(prefix="/v1", tags=["decisions"], dependencies=[AuditReaderDep])
20
+
21
+ OptionalQuery = Annotated[str | None, Query()]
22
+
23
+
24
+ @router.get("/decisions", response_model=AuditDecisionPage, deprecated=True)
25
+ async def list_decisions(
26
+ db: SessionDep,
27
+ pagination: PaginationDep,
28
+ session_id: OptionalQuery = None,
29
+ outcome: OptionalQuery = None,
30
+ deny_reason: OptionalQuery = None,
31
+ enforced: OptionalQuery = None,
32
+ ) -> AuditDecisionPage:
33
+ return await history_page(
34
+ db,
35
+ raw_filters={
36
+ "session_id": session_id,
37
+ "outcome": outcome,
38
+ "deny_reason": deny_reason,
39
+ "enforced": enforced,
40
+ },
41
+ limit=pagination.limit,
42
+ cursor=pagination.cursor,
43
+ )
@@ -0,0 +1,48 @@
1
+ """``/v1/agents/{id}/enroll`` and ``/enroll/complete`` — challenge, then signed response.
2
+
3
+ A ``200`` from ``complete`` never means "authorized". It means a trust anchor now exists
4
+ (enrolled) or does not (quarantined). Authorization is the hop token, minted elsewhere.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import uuid
10
+
11
+ from fastapi import APIRouter, status
12
+
13
+ from agentic_auth.api.deps import EnrollerDep, SessionDep
14
+ from agentic_auth.api.service_deps import EnrollmentServiceDep, RedisDep
15
+ from agentic_auth.schemas.identity import (
16
+ EnrollBegin,
17
+ EnrollChallenge,
18
+ EnrollComplete,
19
+ EnrollOutcome,
20
+ )
21
+
22
+ router = APIRouter(prefix="/v1", tags=["enrollment"], dependencies=[EnrollerDep])
23
+
24
+
25
+ @router.post(
26
+ "/agents/{agent_id}/enroll",
27
+ response_model=EnrollChallenge,
28
+ status_code=status.HTTP_201_CREATED,
29
+ )
30
+ async def begin_enrollment(
31
+ agent_id: uuid.UUID,
32
+ body: EnrollBegin,
33
+ db: SessionDep,
34
+ redis: RedisDep,
35
+ service: EnrollmentServiceDep,
36
+ ) -> EnrollChallenge:
37
+ return await service.begin(db, redis, agent_id, body)
38
+
39
+
40
+ @router.post("/agents/{agent_id}/enroll/complete", response_model=EnrollOutcome)
41
+ async def complete_enrollment(
42
+ agent_id: uuid.UUID,
43
+ body: EnrollComplete,
44
+ db: SessionDep,
45
+ redis: RedisDep,
46
+ service: EnrollmentServiceDep,
47
+ ) -> EnrollOutcome:
48
+ return await service.complete(db, redis, agent_id, body)
@@ -0,0 +1,97 @@
1
+ """Identity material and revocation — what offline verifiers bootstrap from, and how an
2
+ operator cuts an agent off."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import uuid
7
+ from datetime import UTC, datetime
8
+ from typing import Annotated
9
+
10
+ from fastapi import APIRouter, Query
11
+
12
+ from agentic_auth.api.deps import AdminDep, IdentityReaderDep, SessionDep
13
+ from agentic_auth.api.service_deps import AnchorCacheDep, RedisDep, RevocationServiceDep
14
+ from agentic_auth.errors import NotFoundError, QueryValidationError
15
+ from agentic_auth.repositories import agents as agents_repo
16
+ from agentic_auth.repositories import trust_anchors as anchors_repo
17
+ from agentic_auth.schemas.common import DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT
18
+ from agentic_auth.schemas.identity import (
19
+ AgentIdentityRead,
20
+ RevocationListRead,
21
+ RevokeOutcome,
22
+ RevokeRequest,
23
+ )
24
+ from agentic_auth.services.anchors import identity_read
25
+
26
+ router = APIRouter(prefix="/v1", tags=["identity"])
27
+
28
+
29
+ @router.get(
30
+ "/agents/{agent_id}/identity",
31
+ response_model=AgentIdentityRead,
32
+ dependencies=[IdentityReaderDep],
33
+ )
34
+ async def get_identity(
35
+ agent_id: uuid.UUID, db: SessionDep, anchors: AnchorCacheDep
36
+ ) -> AgentIdentityRead:
37
+ agent = await agents_repo.get_by_id(db, agent_id)
38
+ if agent is None:
39
+ raise NotFoundError(f"agent {agent_id} not found")
40
+ anchor = await anchors_repo.current(db, agent.id)
41
+ return identity_read(agent, anchor, as_of=datetime.now(UTC))
42
+
43
+
44
+ @router.get(
45
+ "/identity/agents/{agent_name}",
46
+ response_model=AgentIdentityRead,
47
+ dependencies=[IdentityReaderDep],
48
+ )
49
+ async def get_identity_by_name(
50
+ agent_name: str, db: SessionDep, anchors: AnchorCacheDep
51
+ ) -> AgentIdentityRead:
52
+ """The same material as ``/agents/{id}/identity``, addressed by the agent's name.
53
+
54
+ A resource server knows the agents it expects by name and holds only an identity-reader
55
+ token, which cannot list agents (that listing is admin-only) — so it bootstraps through
56
+ this route instead.
57
+ """
58
+ read = await anchors.current(db, agent_name)
59
+ if read is None:
60
+ raise NotFoundError(f"agent {agent_name!r} not found")
61
+ return read
62
+
63
+
64
+ @router.post("/agents/{agent_id}/revoke", response_model=RevokeOutcome, dependencies=[AdminDep])
65
+ async def revoke_agent(
66
+ agent_id: uuid.UUID,
67
+ db: SessionDep,
68
+ redis: RedisDep,
69
+ service: RevocationServiceDep,
70
+ body: RevokeRequest | None = None,
71
+ ) -> RevokeOutcome:
72
+ """Idempotent. Cuts off the anchor and every hop that would extend this agent's
73
+ authority — checked at the next authorize and exchange, and by offline verifiers within
74
+ their freshness window."""
75
+ return await service.revoke(db, redis, agent_id, body.reason if body else None)
76
+
77
+
78
+ @router.get(
79
+ "/identity/revocations", response_model=RevocationListRead, dependencies=[IdentityReaderDep]
80
+ )
81
+ async def list_revocations(
82
+ db: SessionDep,
83
+ service: RevocationServiceDep,
84
+ since: Annotated[datetime | None, Query()] = None,
85
+ limit: Annotated[int, Query(ge=1, le=MAX_PAGE_LIMIT)] = DEFAULT_PAGE_LIMIT,
86
+ cursor: Annotated[str | None, Query()] = None,
87
+ ) -> RevocationListRead:
88
+ if since is not None and since.tzinfo is None:
89
+ raise QueryValidationError(
90
+ "since must include a timezone", [{"loc": ["since"], "msg": "must include a timezone"}]
91
+ )
92
+ try:
93
+ return await service.list(db, since=since, limit=limit, cursor=cursor)
94
+ except (ValueError, TypeError) as exc:
95
+ raise QueryValidationError(
96
+ "invalid cursor", [{"loc": ["cursor"], "msg": str(exc)}]
97
+ ) from exc
@@ -0,0 +1,21 @@
1
+ """``/.well-known/jwks.json`` — issuer public keys.
2
+
3
+ Unauthenticated by design: any resource server must be able to verify a hop token
4
+ **offline**, with no call back to the control plane on the hot path. Only public key
5
+ material is served here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from fastapi import APIRouter
13
+
14
+ from agentic_auth.services.tokens import keys
15
+
16
+ router = APIRouter(tags=["ops"])
17
+
18
+
19
+ @router.get("/.well-known/jwks.json")
20
+ async def get_jwks() -> dict[str, Any]:
21
+ return keys.jwks()