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,640 @@
1
+ """The single allow path.
2
+
3
+ Everything in this module exists to make one property structurally true: **forwarding is
4
+ reachable from exactly one place, guarded by one object.** ``enforce()`` returns either an
5
+ :class:`Allow` carrying a freshly issued token, or a :class:`Blocked` carrying a response
6
+ for the agent. There is no third outcome, no default-allow branch, and no ``except`` that
7
+ continues toward the forward path.
8
+
9
+ Every outcome also carries an :class:`EdgeAttribution` — what this call was, for edge
10
+ recording. It is data, computed here and consumed by ``agentic_auth.py`` after the outcome is fixed;
11
+ nothing in this module performs the recording, and nothing about it can change an outcome.
12
+
13
+ Rules for anyone editing this file:
14
+
15
+ - No bare ``except`` that falls through to a forward.
16
+ - No ``except: pass``.
17
+ - Every outbound call carries an explicit timeout. No unbounded wait.
18
+ - If you add a return, it returns ``Blocked`` unless you can prove the hop was allowed.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import base64
24
+ import binascii
25
+ import json
26
+ import logging
27
+ from collections.abc import Awaitable, Callable, Mapping
28
+ from dataclasses import dataclass
29
+ from typing import Protocol
30
+
31
+ import httpx
32
+ from starlette.responses import JSONResponse
33
+
34
+ from agentic_auth import observability
35
+ from agentic_auth.observability.pep import StageTimer
36
+ from agentic_auth.schemas.authorize import POLICY_REASONS, DenyReason
37
+ from agentic_auth.schemas.token import GRANT_TYPE, JWT_TOKEN_TYPE
38
+ from agentic_auth.sidecar import deny
39
+ from agentic_auth.sidecar.config import SidecarConfig, Upstream
40
+
41
+
42
+ class EnforcementConfig(Protocol):
43
+ """Everything ``enforce()`` reads off its config.
44
+
45
+ Declared as a Protocol so the gateway can pass a
46
+ :class:`~agentic_auth.gateway.config.GatewayConfig`
47
+ — which is deliberately *not* a ``SidecarConfig``, because it must not have a signing
48
+ key — without either module importing the other.
49
+ """
50
+
51
+ pdp_url: str
52
+ observe_mode: bool
53
+ guarantee_level: str
54
+ max_privileged_body_bytes: int
55
+
56
+ @property
57
+ def control_plane_timeout_seconds(self) -> float: ...
58
+
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+ TARGET_HEADER = "x-agentic-target"
63
+ DATA_CLASS_HEADER = "x-agentic-data-class"
64
+ TAINT_HEADER = "x-agentic-taint"
65
+ SESSION_HEADER = "x-agentic-session"
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class EdgeAttribution:
70
+ """What this call was, for edge recording.
71
+
72
+ ``outcome`` is one of ``allow``, ``deny`` (policy refused), ``observed`` (policy
73
+ refused, observe mode forwarded), ``blocked_infra`` (a dependency failed), or
74
+ ``blocked_local`` (refused before any decision). ``acting_agent`` comes only from the
75
+ decision service's verified answer — never from the presented token's unverified claims.
76
+ """
77
+
78
+ acting_agent: str | None
79
+ target: str | None
80
+ outcome: str
81
+ reason: str | None
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class Allow:
86
+ """The only success. Holding one means the PDP allowed this hop and a narrowed token
87
+ was issued for it — and, for a privileged target, a transaction token bound to the
88
+ buffered body."""
89
+
90
+ token: str
91
+ upstream: Upstream
92
+ prefix: str
93
+ target: str
94
+ attribution: EdgeAttribution
95
+ # Phase 4. Present together for a privileged call: the body was buffered to bind it.
96
+ transaction_token: str | None = None
97
+ body: bytes | None = None
98
+ # Phase 4 identity: the Agent-Identity assertion for this call, when a key is configured.
99
+ identity_assertion: str | None = None
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class Blocked:
104
+ """Everything else. ``response`` goes straight back to the agent."""
105
+
106
+ response: JSONResponse
107
+ attribution: EdgeAttribution
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class Observed:
112
+ """Observe mode only: policy said no, but the operator asked to watch rather than
113
+ block. The ORIGINAL token is forwarded — no exchange happened for a denied hop."""
114
+
115
+ upstream: Upstream
116
+ prefix: str
117
+ target: str
118
+ reason: DenyReason
119
+ attribution: EdgeAttribution
120
+
121
+
122
+ def _local(response: JSONResponse, target: str | None, reason: str) -> Blocked:
123
+ return Blocked(response, EdgeAttribution(None, target, "blocked_local", reason))
124
+
125
+
126
+ def _infra(
127
+ response: JSONResponse, acting_agent: str | None, target: str, reason: DenyReason
128
+ ) -> Blocked:
129
+ return Blocked(response, EdgeAttribution(acting_agent, target, "blocked_infra", reason.value))
130
+
131
+
132
+ def _infra_local(response: JSONResponse, acting_agent: str | None, target: str) -> Blocked:
133
+ """An infrastructure block whose reason is a sidecar-local code, not a DenyReason."""
134
+ return Blocked(
135
+ response, EdgeAttribution(acting_agent, target, "blocked_infra", _reason_of(response))
136
+ )
137
+
138
+
139
+ def _reason_of(response: JSONResponse) -> str:
140
+ try:
141
+ return str(json.loads(bytes(response.body))["error"]["details"]["reason"])
142
+ except (ValueError, KeyError, TypeError):
143
+ return "BLOCKED"
144
+
145
+
146
+ def _acting_agent(decision: Mapping[str, object]) -> str | None:
147
+ value = decision.get("acting_agent")
148
+ return value if isinstance(value, str) and value else None
149
+
150
+
151
+ def _unverified_claims(token: str) -> dict:
152
+ """Read claims WITHOUT verifying — only ever to populate a request the PDP then
153
+ checks authoritatively.
154
+
155
+ This is safe precisely because it is not a decision: the PDP verifies the signature
156
+ and denies any request whose ``session_id`` or ``caller`` disagrees with the token.
157
+ A lie here buys a deny, never an allow. Using these values to decide anything locally
158
+ would be a different and much worse thing.
159
+ """
160
+ try:
161
+ payload = token.split(".")[1]
162
+ return json.loads(base64.urlsafe_b64decode(payload + "=="))
163
+ except (IndexError, ValueError, binascii.Error, UnicodeDecodeError):
164
+ return {}
165
+
166
+
167
+ def _deny_reason(raw: object) -> DenyReason:
168
+ """A reason we do not recognise is not a policy verdict anyone can predict from. Treat
169
+ it as the decision service being unusable, which blocks in every mode — never as a
170
+ policy reason observe mode would forward."""
171
+ if not isinstance(raw, str):
172
+ return DenyReason.PDP_UNAVAILABLE
173
+ try:
174
+ return DenyReason(raw)
175
+ except ValueError:
176
+ return DenyReason.PDP_UNAVAILABLE
177
+
178
+
179
+ def _has_traversal(path: str) -> bool:
180
+ """True if the path contains anything that would make the matched prefix a lie.
181
+
182
+ The prefix selects which policy target the call is authorized against; the same
183
+ prefix is then stripped to build the upstream URL. If `httpx.URL` resolves a dot
184
+ segment after that match, the two disagree — `/kb/../admin` is authorized as the
185
+ `/kb` target and delivered to `/admin`. Reject rather than normalise: normalising
186
+ would silently change which prefix matched, which is the same class of surprise.
187
+
188
+ uvicorn percent-decodes before handing over `scope["path"]`, so `%2e%2e` arrives
189
+ here already as `..` and is caught by the same check.
190
+ """
191
+ return "\\" in path or any(seg in ("..", ".") for seg in path.split("/"))
192
+
193
+
194
+ def _resolve_call(
195
+ config: SidecarConfig, path: str, headers: Mapping[str, str]
196
+ ) -> tuple[str, Upstream, str, str] | JSONResponse:
197
+ if _has_traversal(path):
198
+ return deny.not_mapped(path)
199
+ match = config.resolve(path)
200
+ if match is None:
201
+ return deny.not_mapped(path)
202
+ prefix, upstream = match
203
+
204
+ target = upstream.target or headers.get(TARGET_HEADER)
205
+ data_class = upstream.data_class or headers.get(DATA_CLASS_HEADER)
206
+ if not target or not data_class:
207
+ return deny.target_unresolved(path)
208
+ return prefix, upstream, target, data_class
209
+
210
+
211
+ BodyReader = Callable[[int], Awaitable[bytes | None]]
212
+ """Reads the request body up to a byte cap; returns ``None`` when the cap is exceeded."""
213
+
214
+
215
+ async def _no_body(_cap: int) -> bytes | None:
216
+ return b""
217
+
218
+
219
+ ResolvedCall = tuple[str, Upstream, str, str]
220
+ """``(prefix, upstream, target, data_class)`` — a route that has already been matched."""
221
+
222
+
223
+ async def enforce(
224
+ client: httpx.AsyncClient,
225
+ config: SidecarConfig | EnforcementConfig,
226
+ *,
227
+ path: str,
228
+ headers: Mapping[str, str],
229
+ body_reader: BodyReader = _no_body,
230
+ identity: object | None = None,
231
+ actor_token: str | None = None,
232
+ resolved: ResolvedCall | JSONResponse | None = None,
233
+ timer: StageTimer | None = None,
234
+ ) -> Allow | Blocked | Observed:
235
+ """Decide, narrow, and hand back the token to forward — or block.
236
+
237
+ **This function has two callers**: the sidecar (:mod:`agentic_auth.sidecar.app`) and the shared
238
+ gateway (:mod:`agentic_auth.gateway.app`). That is deliberate and is what makes "the gateway
239
+ reaches the same decision as the sidecar" a structural property rather than a hope —
240
+ there is one ``enforce()``, so the two can only diverge by disagreeing about their
241
+ *inputs*, which the conformance suite exists to catch. Any change here must keep both
242
+ callers working.
243
+
244
+ ``body_reader`` is only ever called for a privileged target, so ordinary
245
+ calls keep streaming. ``identity`` is an :class:`agentic_auth.sidecar.identity.SidecarIdentity`
246
+ or ``None``; typed loosely to keep this module free of the key-handling imports.
247
+
248
+ ``actor_token`` is the gateway's path to proof-of-possession: it holds no signing key,
249
+ so instead of minting an actor token it relays the one the agent
250
+ supplied. Used only when ``identity`` is ``None``, so a sidecar with a key always
251
+ signs its own rather than trusting a header.
252
+
253
+ ``resolved`` lets a caller supply an already-matched route. The sidecar omits it and
254
+ resolves from its own single-agent ``upstream_map``; the gateway passes the result of
255
+ its shared, agent-keyed table.
256
+
257
+ ``timer`` records per-stage latency. It defaults to a timer with no
258
+ metrics attached, so every call site works unchanged and no branch is needed below.
259
+ """
260
+ timer = timer if timer is not None else StageTimer(None)
261
+ if resolved is None:
262
+ resolved = _resolve_call(config, path, headers)
263
+ if isinstance(resolved, JSONResponse):
264
+ return _local(resolved, None, _reason_of(resolved))
265
+ prefix, upstream, target, data_class = resolved
266
+
267
+ authorization = headers.get("authorization", "")
268
+ if not authorization.startswith("Bearer "):
269
+ return _local(
270
+ deny.unauthorized("missing or malformed bearer token"), target, "UNAUTHORIZED"
271
+ )
272
+ presented = authorization.removeprefix("Bearer ").strip()
273
+
274
+ claims = _unverified_claims(presented)
275
+ session_id = headers.get(SESSION_HEADER) or claims.get("session_id")
276
+ # Who holds this token: the agent it was issued to (`aud`) once delegation has
277
+ # begun, or the consenting human (`sub`) under the root grant. Never the `act`
278
+ # link — that is the previous actor, not the current one.
279
+ caller = claims.get("aud") if claims.get("act") else claims.get("sub")
280
+ if not session_id or not caller:
281
+ return _local(
282
+ deny.unauthorized("token does not carry a session or a subject"), target, "UNAUTHORIZED"
283
+ )
284
+
285
+ taint = headers.get(TAINT_HEADER)
286
+ timeout = httpx.Timeout(config.control_plane_timeout_seconds)
287
+
288
+ # -- 1. decide --------------------------------------------------------
289
+ try:
290
+ with timer.stage("decide"):
291
+ decision_response = await client.post(
292
+ f"{config.pdp_url}/v1/authorize",
293
+ # Every leg the SDK controls carries trace context, so the control
294
+ # plane's decision span lands in the same trace as this proxied call.
295
+ headers=observability.inject({"Authorization": f"Bearer {presented}"}),
296
+ json={
297
+ "session_id": session_id,
298
+ "caller": caller,
299
+ "target": target,
300
+ "data_class": data_class,
301
+ # Tell the PDP whether this decision will actually be acted on, so the
302
+ # record is truthful. It does not affect the decision.
303
+ "enforced": not config.observe_mode,
304
+ # Phase 5. Same contract as `enforced`: self-reported by the enforcement
305
+ # point, recorded, never an input to the decision. Mandatory with no
306
+ # default on the request, so omitting it is a 422 rather than a silent
307
+ # claim of full guarantee.
308
+ "guarantee": config.guarantee_level,
309
+ **({"taint": taint} if taint else {}),
310
+ },
311
+ timeout=timeout,
312
+ )
313
+ except Exception as exc:
314
+ logger.warning(
315
+ "policy decision point unreachable",
316
+ extra={"authz.component": "pep", "error.type": type(exc).__name__},
317
+ )
318
+ return _infra(
319
+ deny.policy_denied(
320
+ DenyReason.PDP_UNAVAILABLE,
321
+ f"decision service unreachable: {exc}",
322
+ target=target,
323
+ ),
324
+ None,
325
+ target,
326
+ DenyReason.PDP_UNAVAILABLE,
327
+ )
328
+
329
+ if decision_response.status_code == 401:
330
+ return _local(
331
+ deny.unauthorized("presented token was rejected by the decision service"),
332
+ target,
333
+ "UNAUTHORIZED",
334
+ )
335
+ if decision_response.status_code != 200:
336
+ return _infra(
337
+ deny.policy_denied(
338
+ DenyReason.PDP_UNAVAILABLE,
339
+ f"decision service returned {decision_response.status_code}",
340
+ target=target,
341
+ ),
342
+ None,
343
+ target,
344
+ DenyReason.PDP_UNAVAILABLE,
345
+ )
346
+
347
+ try:
348
+ decision = decision_response.json()
349
+ outcome = decision["outcome"]
350
+ except (ValueError, KeyError, TypeError) as exc:
351
+ return _infra(
352
+ deny.policy_denied(
353
+ DenyReason.PDP_UNAVAILABLE,
354
+ f"decision service returned an unusable body: {exc}",
355
+ target=target,
356
+ ),
357
+ None,
358
+ target,
359
+ DenyReason.PDP_UNAVAILABLE,
360
+ )
361
+
362
+ acting_agent = _acting_agent(decision)
363
+
364
+ if outcome != "allow":
365
+ reason = _deny_reason(decision.get("reason"))
366
+ if config.observe_mode and reason in POLICY_REASONS:
367
+ # Recorded by the PDP, not blocked here. The call proceeds carrying its
368
+ # ORIGINAL token, because no exchange happened for a denied hop.
369
+ logger.info(
370
+ "observe mode: would have denied this call",
371
+ extra={
372
+ "authz.component": "pep",
373
+ "authz.hop": decision.get("hop"),
374
+ "authz.action_id": decision.get("action_id"),
375
+ },
376
+ )
377
+ return Observed(
378
+ upstream=upstream,
379
+ prefix=prefix,
380
+ target=target,
381
+ reason=reason,
382
+ attribution=EdgeAttribution(acting_agent, target, "observed", reason.value),
383
+ )
384
+ # Observe mode predicts what POLICY would block. It never forwards an infrastructure
385
+ # failure — that would pass an outage off as a prediction.
386
+ response = deny.policy_denied(
387
+ reason,
388
+ decision.get("message") or "denied by policy",
389
+ target=target,
390
+ hop=decision.get("hop"),
391
+ session_id=decision.get("session_id"),
392
+ policy_version=decision.get("policy_version"),
393
+ )
394
+ if reason in POLICY_REASONS:
395
+ return Blocked(response, EdgeAttribution(acting_agent, target, "deny", reason.value))
396
+ return _infra(response, acting_agent, target, reason)
397
+
398
+ # The PDP committed a record before answering, and the exchange refuses without one.
399
+ # Checking here as well means a control plane that answers "allow" without a recorded
400
+ # decision still cannot get a call dispatched down this path.
401
+ action_id = decision.get("action_id")
402
+ if decision.get("recorded") is False or not action_id:
403
+ return _infra(
404
+ deny.policy_denied(
405
+ DenyReason.AUDIT_UNAVAILABLE,
406
+ "decision could not be recorded; refusing to dispatch without a record",
407
+ target=target,
408
+ ),
409
+ acting_agent,
410
+ target,
411
+ DenyReason.AUDIT_UNAVAILABLE,
412
+ )
413
+
414
+ # -- 1b. a privileged call must be bound: buffer the body, or refuse ----------
415
+ transaction_required = bool(decision.get("transaction_required"))
416
+ bound_body: bytes | None = None
417
+ params: dict | None = None
418
+ if transaction_required:
419
+ bound_body = await body_reader(config.max_privileged_body_bytes)
420
+ if bound_body is None:
421
+ return _local(
422
+ deny.unbindable(
423
+ deny.BODY_TOO_LARGE_TO_BIND,
424
+ f"body exceeds {config.max_privileged_body_bytes} bytes and cannot be bound",
425
+ target=target,
426
+ ),
427
+ target,
428
+ deny.BODY_TOO_LARGE_TO_BIND,
429
+ )
430
+ try:
431
+ parsed = json.loads(bound_body or b"{}")
432
+ except ValueError:
433
+ parsed = None
434
+ if not isinstance(parsed, dict):
435
+ return _local(
436
+ deny.unbindable(
437
+ deny.PARAMS_NOT_AN_OBJECT,
438
+ "a privileged call's body must be a JSON object so it can be bound",
439
+ target=target,
440
+ ),
441
+ target,
442
+ deny.PARAMS_NOT_AN_OBJECT,
443
+ )
444
+ params = parsed
445
+
446
+ # -- 2. narrow --------------------------------------------------------
447
+ exchange_form: dict[str, str] = {
448
+ "grant_type": GRANT_TYPE,
449
+ "subject_token": presented,
450
+ "subject_token_type": JWT_TOKEN_TYPE,
451
+ "resource": target,
452
+ "scope": data_class,
453
+ "action_id": str(action_id),
454
+ **({"taint": taint} if taint else {}),
455
+ }
456
+ if identity is not None:
457
+ exchange_form["actor_token"] = identity.actor_token(presented) # type: ignore[attr-defined]
458
+ exchange_form["actor_token_type"] = JWT_TOKEN_TYPE
459
+ elif actor_token:
460
+ # Relayed, not minted. The gateway cannot sign for an agent it does not hold a
461
+ # key for, and holding every agent's key is the thing the identity split forbids.
462
+ exchange_form["actor_token"] = actor_token
463
+ exchange_form["actor_token_type"] = JWT_TOKEN_TYPE
464
+ try:
465
+ with timer.stage("exchange"):
466
+ exchange_response = await client.post(
467
+ f"{config.pdp_url}/v1/token/exchange",
468
+ data=exchange_form,
469
+ headers=observability.inject({}),
470
+ timeout=timeout,
471
+ )
472
+ except Exception as exc:
473
+ logger.warning(
474
+ "token exchange unreachable",
475
+ extra={"authz.component": "pep", "error.type": type(exc).__name__},
476
+ )
477
+ return _infra(
478
+ deny.policy_denied(
479
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
480
+ f"token service unreachable: {exc}",
481
+ target=target,
482
+ ),
483
+ acting_agent,
484
+ target,
485
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
486
+ )
487
+
488
+ if exchange_response.status_code != 200:
489
+ # Distinguish "the service is down" from "the service said no". Both block, but
490
+ # they send an operator to different places: one is an outage, the other is a
491
+ # spent or refused token that no amount of retrying will fix.
492
+ description = ""
493
+ try:
494
+ body = exchange_response.json()
495
+ description = body.get("error_description") or body.get("error") or ""
496
+ except ValueError:
497
+ description = ""
498
+
499
+ if exchange_response.status_code == 403:
500
+ # Policy refused the hop between the decision and the exchange — normally a
501
+ # narrower re-check, e.g. the resource did not match the allowed target.
502
+ return Blocked(
503
+ deny.policy_denied(
504
+ DenyReason.OUT_OF_SCOPE,
505
+ description or "token service refused this target",
506
+ target=target,
507
+ ),
508
+ EdgeAttribution(acting_agent, target, "deny", DenyReason.OUT_OF_SCOPE.value),
509
+ )
510
+ if exchange_response.status_code == 400:
511
+ # The presented token itself was refused: already spent, expired, or altered.
512
+ return _local(
513
+ deny.unauthorized(
514
+ description or "presented token was refused by the token service"
515
+ ),
516
+ target,
517
+ "UNAUTHORIZED",
518
+ )
519
+ return _infra(
520
+ deny.policy_denied(
521
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
522
+ f"token service returned {exchange_response.status_code}",
523
+ target=target,
524
+ ),
525
+ acting_agent,
526
+ target,
527
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
528
+ )
529
+
530
+ try:
531
+ narrowed = exchange_response.json()["access_token"]
532
+ except (ValueError, KeyError, TypeError) as exc:
533
+ return _infra(
534
+ deny.policy_denied(
535
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
536
+ f"token service returned no usable token: {exc}",
537
+ target=target,
538
+ ),
539
+ acting_agent,
540
+ target,
541
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
542
+ )
543
+ if not narrowed:
544
+ return _infra(
545
+ deny.policy_denied(
546
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
547
+ "token service returned an empty token",
548
+ target=target,
549
+ ),
550
+ acting_agent,
551
+ target,
552
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE,
553
+ )
554
+
555
+ # -- 3. bind (privileged only) -----------------------------------------
556
+ transaction_token: str | None = None
557
+ if transaction_required:
558
+ assert params is not None # set together with transaction_required above
559
+ try:
560
+ with timer.stage("mint"):
561
+ mint_response = await client.post(
562
+ f"{config.pdp_url}/v1/token/transaction",
563
+ headers=observability.inject({"Authorization": f"Bearer {narrowed}"}),
564
+ json={"params": params},
565
+ timeout=timeout,
566
+ )
567
+ except Exception as exc:
568
+ logger.warning(
569
+ "transaction mint unreachable",
570
+ extra={"authz.component": "pep", "error.type": type(exc).__name__},
571
+ )
572
+ return _infra_local(
573
+ deny.transaction_unavailable(
574
+ f"transaction service unreachable: {exc}", target=target
575
+ ),
576
+ acting_agent,
577
+ target,
578
+ )
579
+ if mint_response.status_code != 200:
580
+ # 4xx: the mint refused (not privileged, already minted, tainted, too large) — a
581
+ # policy-shaped refusal, 403. 5xx or unusable: an outage, 503.
582
+ description = ""
583
+ try:
584
+ err = mint_response.json().get("error", {})
585
+ description = err.get("message") or ""
586
+ detail_reason = (err.get("details") or {}).get("reason")
587
+ except ValueError:
588
+ detail_reason = None
589
+ if 400 <= mint_response.status_code < 500:
590
+ return Blocked(
591
+ deny.policy_denied(
592
+ detail_reason or DenyReason.OUT_OF_SCOPE,
593
+ description or "transaction token refused",
594
+ target=target,
595
+ ),
596
+ EdgeAttribution(acting_agent, target, "deny", detail_reason or "OUT_OF_SCOPE"),
597
+ )
598
+ return _infra_local(
599
+ deny.transaction_unavailable(
600
+ f"transaction service returned {mint_response.status_code}", target=target
601
+ ),
602
+ acting_agent,
603
+ target,
604
+ )
605
+ try:
606
+ transaction_token = mint_response.json()["transaction_token"]
607
+ except (ValueError, KeyError, TypeError) as exc:
608
+ return _infra_local(
609
+ deny.transaction_unavailable(
610
+ f"transaction service returned no usable token: {exc}", target=target
611
+ ),
612
+ acting_agent,
613
+ target,
614
+ )
615
+ if not transaction_token:
616
+ return _infra_local(
617
+ deny.transaction_unavailable(
618
+ "transaction service returned an empty token", target=target
619
+ ),
620
+ acting_agent,
621
+ target,
622
+ )
623
+
624
+ identity_assertion = (
625
+ identity.identity_assertion(narrowed, target) # type: ignore[attr-defined]
626
+ if identity is not None
627
+ else None
628
+ )
629
+
630
+ # The only construction of Allow in the codebase.
631
+ return Allow(
632
+ token=narrowed,
633
+ upstream=upstream,
634
+ prefix=prefix,
635
+ target=target,
636
+ attribution=EdgeAttribution(acting_agent, target, "allow", None),
637
+ transaction_token=transaction_token,
638
+ body=bound_body,
639
+ identity_assertion=identity_assertion,
640
+ )
@@ -0,0 +1,37 @@
1
+ """The sidecar's agent identity: an Ed25519 key that signs the two small tokens the identity
2
+ contract defines. Present only when the operator configured
3
+ ``agent_name`` and ``identity_key_path`` together.
4
+
5
+ The key never leaves this process and never appears in a log or repr.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from agentic_auth.sdk.identity import AgentKey
11
+ from agentic_auth.sidecar.config import SidecarConfig, SidecarConfigError
12
+
13
+
14
+ class SidecarIdentity:
15
+ def __init__(self, agent_name: str, key: AgentKey, *, issuer: str = "agentic-auth") -> None:
16
+ self._agent = agent_name
17
+ self._key = key
18
+ self._issuer = issuer
19
+
20
+ def actor_token(self, subject_token: str) -> str:
21
+ return self._key.actor_token(self._agent, subject_token, aud=self._issuer)
22
+
23
+ def identity_assertion(self, grant: str, audience: str) -> str:
24
+ return self._key.identity_assertion(self._agent, grant, audience)
25
+
26
+ def __repr__(self) -> str: # pragma: no cover - never print the key
27
+ return f"SidecarIdentity(agent={self._agent!r})"
28
+
29
+
30
+ def load_identity(config: SidecarConfig) -> SidecarIdentity | None:
31
+ if not config.agent_name or not config.identity_key_path:
32
+ return None
33
+ try:
34
+ key = AgentKey.load(config.identity_key_path)
35
+ except Exception as exc: # a sidecar that cannot sign must not start permissive
36
+ raise SidecarConfigError(f"cannot load identity key: {type(exc).__name__}") from exc
37
+ return SidecarIdentity(config.agent_name, key)