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,677 @@
1
+ """The SDK client — inline enforcement for agent code you control.
2
+
3
+ Same endpoints, same decisions, same records as the sidecar. The difference is only where
4
+ enforcement sits: inline gives better errors and needs no extra process, but an agent can
5
+ skip it. The sidecar cannot be skipped when egress is pinned, which is why both exist.
6
+
7
+ With a trace path configured (or ``AGENTIC_AUTH_TRACE_PATH`` set, as ``agentic-auth drift
8
+ record`` does), every ``authorize`` also records one edge event, attributed to the agent the
9
+ decision service verified — the same shape the sidecar records.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Sequence
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ import httpx
19
+
20
+ from agentic_auth.boundary.guarantee import Guarantee
21
+ from agentic_auth.schemas.authorize import POLICY_REASONS, DenyReason, Taint
22
+ from agentic_auth.schemas.token import GRANT_TYPE, JWT_TOKEN_TYPE
23
+ from agentic_auth.sdk.context import HopContext
24
+ from agentic_auth.sdk.errors import (
25
+ ControlPlaneRejected,
26
+ ControlPlaneUnavailable,
27
+ ManifestRejected,
28
+ PolicyDenied,
29
+ TransactionParamsRequired,
30
+ )
31
+ from agentic_auth.sdk.identity import AgentKey
32
+ from agentic_auth.sdk.planes import AdminPlane, AuditPlane, IdentityPlane, Transport
33
+ from agentic_auth.sdk.provenance import LabeledResult, SourceClassifier
34
+ from agentic_auth.services.edge_trace import EdgeRecorder, recorder_from_env
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Grant:
39
+ """Narrowed authority for exactly one call — plus, for a privileged target, the
40
+ transaction token bound to its parameters, and the identity assertion when the client
41
+ holds an agent key."""
42
+
43
+ access_token: str
44
+ scope: str
45
+ expires_in: int
46
+ hop: int
47
+ target: str = ""
48
+ transaction_token: str | None = None
49
+ identity_assertion: str | None = None
50
+ # The effective taint the decision was made under, from the hop token's claim.
51
+ taint: Taint | None = None
52
+ # The audit row for the allow this grant was narrowed from. Pass it to
53
+ # ``client.audit.chain(...)`` to read the delegation chain back to the consenting
54
+ # human — the same id the resource server reads off the token it admits.
55
+ action_id: str | None = None
56
+
57
+ def headers(self) -> dict[str, str]:
58
+ out = {"Authorization": f"Bearer {self.access_token}"}
59
+ if self.transaction_token is not None:
60
+ out["Txn-Token"] = self.transaction_token
61
+ if self.identity_assertion is not None:
62
+ out["Agent-Identity"] = self.identity_assertion
63
+ return out
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class CompletedHop:
68
+ hop: int
69
+ target: str
70
+ action_id: str | None
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class PartialOutcome:
75
+ """What a chain that cannot resume gives back.
76
+
77
+ The hops in ``completed`` already ran, and some of them had side effects that no
78
+ refusal further along can undo. A bare exception would leave the caller guessing how
79
+ far the task got; naming the hops is the difference between "it failed" and "it read
80
+ the account but did not close it".
81
+ """
82
+
83
+ completed: tuple[CompletedHop, ...]
84
+ blocked_hop: int
85
+ blocked_target: str
86
+ reason: DenyReason
87
+ recoverable: bool
88
+ challenge: dict[str, Any] | None = None
89
+
90
+ @classmethod
91
+ def from_denial(cls, completed: Sequence[CompletedHop], denied: PolicyDenied) -> PartialOutcome:
92
+ return cls(
93
+ completed=tuple(completed),
94
+ blocked_hop=denied.hop,
95
+ blocked_target=denied.target,
96
+ reason=denied.reason,
97
+ recoverable=denied.recoverable,
98
+ challenge=denied.challenge,
99
+ )
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class Session:
104
+ session_id: str
105
+ root_grant: str
106
+ policy_version: int
107
+ scope: str
108
+ user_sub: str
109
+ hop_budget: int
110
+ expires_at: str
111
+ # Phase 5. What the session actually consented to: None means every data class the
112
+ # pinned policy declares, which is the Phase 2-4 behaviour and the default.
113
+ data_classes: list[str] | None = None
114
+
115
+ def context(self) -> HopContext:
116
+ return HopContext(session_id=self.session_id, token=self.root_grant)
117
+
118
+
119
+ def _acting_agent(decision: dict) -> str | None:
120
+ value = decision.get("acting_agent")
121
+ return value if isinstance(value, str) and value else None
122
+
123
+
124
+ class AgenticAuthClient:
125
+ def __init__(
126
+ self,
127
+ base_url: str,
128
+ *,
129
+ admin_token: str | None = None,
130
+ audit_token: str | None = None,
131
+ identity_token: str | None = None,
132
+ client: httpx.AsyncClient | None = None,
133
+ timeout: float = 5.0,
134
+ trace_path: str | None = None,
135
+ identity_key: AgentKey | None = None,
136
+ agent_name: str | None = None,
137
+ guarantee: Guarantee = Guarantee.FULL,
138
+ ) -> None:
139
+ if bool(identity_key) != bool(agent_name):
140
+ raise ValueError("identity_key and agent_name must be given together")
141
+ # Phase 5. The in-process client decides every hop before dispatch, so `full` is
142
+ # accurate. Overridable only so an embedding that knows it is weaker can say so.
143
+ self._guarantee = guarantee
144
+ self._identity_key = identity_key
145
+ self._agent_name = agent_name
146
+ # Phase 4: classify sources the way the PDP would, when the agent holds its manifest.
147
+ self._classifier = SourceClassifier()
148
+ self._base_url = base_url.rstrip("/")
149
+ self._admin_token = admin_token
150
+ self._timeout = httpx.Timeout(timeout)
151
+ self._client = client or httpx.AsyncClient()
152
+ self._owns_client = client is None
153
+ self._recorder: EdgeRecorder | None = (
154
+ EdgeRecorder(trace_path, "sdk") if trace_path else recorder_from_env("sdk")
155
+ )
156
+ # The planes around the hop path, each with its own least-privileged bearer. The
157
+ # read-only tokens fall back to the admin token, which every route also accepts —
158
+ # so one credential works in a notebook and three work in production.
159
+ transport = Transport(self._client, self._base_url, self._timeout)
160
+ self.admin = AdminPlane(transport, admin_token)
161
+ self.audit = AuditPlane(transport, audit_token or admin_token)
162
+ self.identity = IdentityPlane(transport, identity_token or audit_token or admin_token)
163
+ self._transport = transport
164
+
165
+ async def aclose(self) -> None:
166
+ if self._owns_client:
167
+ await self._client.aclose()
168
+
169
+ async def __aenter__(self) -> AgenticAuthClient:
170
+ return self
171
+
172
+ async def __aexit__(self, *_exc: object) -> None:
173
+ await self.aclose()
174
+
175
+ def use_manifest(self, manifest: dict[str, Any]) -> None:
176
+ """Adopt this agent's manifest so ``wrap_result`` classifies like the PDP."""
177
+ self._classifier = SourceClassifier.from_manifest(manifest)
178
+
179
+ def wrap_result(
180
+ self, value: Any, source_ref: str, *, trusted_sources: list[str] | None = None
181
+ ) -> LabeledResult[Any]:
182
+ """Label a value the agent obtained on its own. Unmatched
183
+ sources are untrusted_external — the label can only raise taint."""
184
+ classifier = (
185
+ SourceClassifier(trusted_sources) if trusted_sources is not None else self._classifier
186
+ )
187
+ return classifier.wrap(value, source_ref)
188
+
189
+ # -- ops: is it there, and what does it sign with? --------------------------
190
+
191
+ async def healthz(self) -> dict[str, Any]:
192
+ """Liveness. Answers without touching the database or Redis."""
193
+ return await self._transport.json("GET", "/healthz")
194
+
195
+ async def readyz(self) -> dict[str, Any]:
196
+ """Readiness: the control plane could reach its database and Redis just now.
197
+
198
+ Raises :class:`ControlPlaneUnavailable` when it could not — which is the answer,
199
+ not an error to swallow. Check this before a deploy gate, never per hop.
200
+ """
201
+ return await self._transport.json("GET", "/readyz")
202
+
203
+ async def jwks(self) -> dict[str, Any]:
204
+ """The issuer's public keys. Unauthenticated by design: a resource server must be
205
+ able to verify a hop token offline, with no call back on the hot path."""
206
+ return await self._transport.json("GET", "/.well-known/jwks.json")
207
+
208
+ def _admin_headers(self) -> dict[str, str]:
209
+ return {"Authorization": f"Bearer {self._admin_token}"} if self._admin_token else {}
210
+
211
+ def _record(
212
+ self, acting_agent: str | None, target: str, outcome: str, reason: str | None
213
+ ) -> None:
214
+ if self._recorder is not None:
215
+ self._recorder.record(
216
+ acting_agent=acting_agent, target=target, outcome=outcome, reason=reason
217
+ )
218
+
219
+ async def consent(
220
+ self,
221
+ *,
222
+ scope: str,
223
+ user_sub: str,
224
+ ttl_seconds: int | None = None,
225
+ data_classes: list[str] | None = None,
226
+ ) -> Session:
227
+ """Record a human's consent and pin the policy version for the session."""
228
+ body: dict[str, object] = {"scope": scope, "user_sub": user_sub}
229
+ if ttl_seconds is not None:
230
+ body["ttl_seconds"] = ttl_seconds
231
+ if data_classes is not None:
232
+ # Phase 5: consent to a subset. Omitting it consents to everything the pinned
233
+ # policy declares, exactly as before.
234
+ body["data_classes"] = list(data_classes)
235
+
236
+ response = await self._client.post(
237
+ f"{self._base_url}/v1/consent",
238
+ headers=self._admin_headers(),
239
+ json=body,
240
+ timeout=self._timeout,
241
+ )
242
+ if response.status_code != 201:
243
+ raise ControlPlaneUnavailable(
244
+ f"consent failed with {response.status_code}: {response.text}"
245
+ )
246
+ return Session(**response.json())
247
+
248
+ async def enroll(
249
+ self,
250
+ agent_id: str,
251
+ *,
252
+ key: AgentKey,
253
+ agent_name: str,
254
+ claims: dict[str, Any] | None = None,
255
+ principal_assertion: str | None = None,
256
+ enroll_token: str | None = None,
257
+ ) -> dict[str, Any]:
258
+ """Begin + sign + complete enrollment. Returns the
259
+ outcome body: ``enrolled`` or ``quarantined``. Grants nothing."""
260
+ headers = {"Authorization": f"Bearer {enroll_token or self._admin_token}"}
261
+ doc = key.identity_document(
262
+ agent_name, claims=claims, principal_assertion=principal_assertion
263
+ )
264
+ begun = await self._client.post(
265
+ f"{self._base_url}/v1/agents/{agent_id}/enroll",
266
+ headers=headers,
267
+ json={"identity_doc": doc},
268
+ timeout=self._timeout,
269
+ )
270
+ if begun.status_code != 201:
271
+ raise ControlPlaneUnavailable(
272
+ f"enrollment could not begin: {begun.status_code} {begun.text}"
273
+ )
274
+ challenge = begun.json()
275
+ completed = await self._client.post(
276
+ f"{self._base_url}/v1/agents/{agent_id}/enroll/complete",
277
+ headers=headers,
278
+ json={
279
+ "challenge_id": challenge["challenge_id"],
280
+ "signed_response": key.sign_challenge(agent_name, challenge["nonce"]),
281
+ },
282
+ timeout=self._timeout,
283
+ )
284
+ if completed.status_code != 200:
285
+ raise ControlPlaneUnavailable(
286
+ f"enrollment refused: {completed.status_code} {completed.text}"
287
+ )
288
+ return dict(completed.json())
289
+
290
+ async def revoke(self, agent_id: str, *, reason: str | None = None) -> dict[str, Any]:
291
+ """Admin: revoke an agent's trust anchor and every chain built on it."""
292
+ response = await self._client.post(
293
+ f"{self._base_url}/v1/agents/{agent_id}/revoke",
294
+ headers=self._admin_headers(),
295
+ json={"reason": reason} if reason else {},
296
+ timeout=self._timeout,
297
+ )
298
+ if response.status_code != 200:
299
+ raise ControlPlaneUnavailable(f"revoke failed: {response.status_code} {response.text}")
300
+ return dict(response.json())
301
+
302
+ async def authorize(
303
+ self,
304
+ ctx: HopContext,
305
+ *,
306
+ target: str,
307
+ data_class: str,
308
+ taint: Taint | str | None = None,
309
+ params: dict[str, Any] | None = None,
310
+ ) -> Grant:
311
+ """Decide and narrow, in that order — and bind, for a privileged target.
312
+
313
+ Both, never one: there is no legitimate reason to take a decision without acting
314
+ on it, and an exchange without a decision would issue authority nobody approved.
315
+ ``params`` is the call's JSON body; required when the decision says
316
+ ``transaction_required``, ignored otherwise.
317
+ """
318
+ acting_agent: str | None = None
319
+ effective_taint = _max_taint(ctx.taint, taint)
320
+ try:
321
+ decision = await self._decide(
322
+ ctx, target=target, data_class=data_class, taint=effective_taint
323
+ )
324
+ acting_agent = _acting_agent(decision)
325
+ if decision["outcome"] != "allow":
326
+ raise PolicyDenied(
327
+ DenyReason(decision["reason"]),
328
+ message=decision.get("message") or "denied by policy",
329
+ target=target,
330
+ hop=decision.get("hop", ctx.hop),
331
+ session_id=ctx.session_id,
332
+ policy_version=decision.get("policy_version"),
333
+ action_id=decision.get("action_id"),
334
+ taint=decision.get("taint"),
335
+ taint_source=decision.get("taint_source"),
336
+ challenge=decision.get("step_up"),
337
+ data_class=data_class,
338
+ )
339
+ action_id = decision.get("action_id")
340
+ if decision.get("recorded") is False or not action_id:
341
+ # The exchange would refuse anyway; saying why here is the actionable part.
342
+ raise ControlPlaneUnavailable(
343
+ "decision could not be recorded; refusing to proceed without a record"
344
+ )
345
+ transaction_required = bool(decision.get("transaction_required"))
346
+ if transaction_required and params is None:
347
+ raise TransactionParamsRequired(
348
+ f"{target} is privileged: pass params= so the call can be bound"
349
+ )
350
+ grant = await self._exchange(
351
+ ctx,
352
+ target=target,
353
+ data_class=data_class,
354
+ taint=effective_taint,
355
+ action_id=str(action_id),
356
+ )
357
+ if transaction_required:
358
+ assert params is not None
359
+ grant = await self._mint_transaction(grant, params)
360
+ if self._identity_key is not None and self._agent_name is not None:
361
+ grant = Grant(
362
+ **{
363
+ **grant.__dict__,
364
+ "identity_assertion": self._identity_key.identity_assertion(
365
+ self._agent_name, grant.access_token, target
366
+ ),
367
+ }
368
+ )
369
+ except TransactionParamsRequired:
370
+ self._record(acting_agent, target, "blocked_local", "TRANSACTION_PARAMS_REQUIRED")
371
+ raise
372
+ except PolicyDenied as denied:
373
+ outcome = "deny" if denied.reason in POLICY_REASONS else "blocked_infra"
374
+ self._record(acting_agent, target, outcome, denied.reason.value)
375
+ raise
376
+ except ControlPlaneUnavailable:
377
+ self._record(acting_agent, target, "blocked_infra", None)
378
+ raise
379
+
380
+ self._record(acting_agent, target, "allow", None)
381
+ return grant
382
+
383
+ async def _decide(
384
+ self, ctx: HopContext, *, target: str, data_class: str, taint: Taint | str | None
385
+ ) -> dict:
386
+ payload: dict[str, object] = {
387
+ "session_id": ctx.session_id,
388
+ "caller": ctx.caller, # read off the token, not tracked alongside it
389
+ "target": target,
390
+ "data_class": data_class,
391
+ # Phase 5. The in-process client is in the call path and decides every hop,
392
+ # so it reports `full`. Mandatory on the request with no default, so this
393
+ # cannot be forgotten silently.
394
+ "guarantee": self._guarantee.value,
395
+ }
396
+ if taint is not None:
397
+ payload["taint"] = taint.value if isinstance(taint, Taint) else taint
398
+
399
+ try:
400
+ response = await self._client.post(
401
+ f"{self._base_url}/v1/authorize",
402
+ headers=ctx.headers(),
403
+ json=payload,
404
+ timeout=self._timeout,
405
+ )
406
+ except httpx.HTTPError as exc:
407
+ raise ControlPlaneUnavailable(f"decision service unreachable: {exc}") from exc
408
+
409
+ if response.status_code != 200:
410
+ raise ControlPlaneUnavailable(
411
+ f"decision service returned {response.status_code}: {response.text}"
412
+ )
413
+ try:
414
+ decision = response.json()
415
+ decision["outcome"]
416
+ except (ValueError, KeyError, TypeError) as exc:
417
+ raise ControlPlaneUnavailable(
418
+ f"decision service returned an unusable body: {exc}"
419
+ ) from exc
420
+ return decision
421
+
422
+ async def _exchange(
423
+ self,
424
+ ctx: HopContext,
425
+ *,
426
+ target: str,
427
+ data_class: str,
428
+ taint: Taint | str | None,
429
+ action_id: str,
430
+ ) -> Grant:
431
+ form: dict[str, str] = {
432
+ "grant_type": GRANT_TYPE,
433
+ "subject_token": ctx.token,
434
+ "subject_token_type": JWT_TOKEN_TYPE,
435
+ "resource": target,
436
+ "scope": data_class,
437
+ # The recorded allow this exchange spends; the token service refuses without it.
438
+ "action_id": action_id,
439
+ }
440
+ if taint is not None:
441
+ form["taint"] = taint.value if isinstance(taint, Taint) else str(taint)
442
+ if self._identity_key is not None and self._agent_name is not None:
443
+ # Proof of possession.
444
+ form["actor_token"] = self._identity_key.actor_token(self._agent_name, ctx.token)
445
+ form["actor_token_type"] = JWT_TOKEN_TYPE
446
+
447
+ try:
448
+ response = await self._client.post(
449
+ f"{self._base_url}/v1/token/exchange", data=form, timeout=self._timeout
450
+ )
451
+ except httpx.HTTPError as exc:
452
+ raise ControlPlaneUnavailable(f"token service unreachable: {exc}") from exc
453
+
454
+ if response.status_code == 403:
455
+ body = response.json()
456
+ # The exchange re-decides, so it can refuse an allow the decision endpoint had
457
+ # just granted — and it is the only place that establishes AGENT_NOT_ENROLLED,
458
+ # since proof of possession is checked here. Take the reason it reports; fall
459
+ # back to OUT_OF_SCOPE only when there is none to take.
460
+ raise PolicyDenied(
461
+ _deny_reason(body.get("reason")),
462
+ message=body.get("error_description", "denied by policy"),
463
+ target=target,
464
+ hop=ctx.hop,
465
+ session_id=ctx.session_id,
466
+ )
467
+ if response.status_code != 200:
468
+ raise ControlPlaneUnavailable(
469
+ f"token service returned {response.status_code}: {response.text}"
470
+ )
471
+
472
+ body = response.json()
473
+ token = body.get("access_token")
474
+ if not token:
475
+ raise ControlPlaneUnavailable("token service returned no usable token")
476
+
477
+ return Grant(
478
+ access_token=token,
479
+ scope=body.get("scope", data_class),
480
+ expires_in=body.get("expires_in", 0),
481
+ hop=ctx.hop + 1,
482
+ target=target,
483
+ taint=_token_taint(token),
484
+ action_id=action_id,
485
+ )
486
+
487
+ async def _mint_transaction(self, grant: Grant, params: dict[str, Any]) -> Grant:
488
+ """``POST /v1/token/transaction`` with the narrowed token."""
489
+ try:
490
+ response = await self._client.post(
491
+ f"{self._base_url}/v1/token/transaction",
492
+ headers={"Authorization": f"Bearer {grant.access_token}"},
493
+ json={"params": params},
494
+ timeout=self._timeout,
495
+ )
496
+ except httpx.HTTPError as exc:
497
+ raise ControlPlaneUnavailable(f"transaction service unreachable: {exc}") from exc
498
+ if response.status_code in (403, 409, 422):
499
+ body = response.json().get("error", {})
500
+ details = body.get("details") or {}
501
+ reason = details.get("reason")
502
+ deny_reason = (
503
+ DenyReason(reason)
504
+ if isinstance(reason, str) and reason in DenyReason.__members__
505
+ else DenyReason.OUT_OF_SCOPE
506
+ )
507
+ raise PolicyDenied(
508
+ deny_reason,
509
+ message=body.get("message", "transaction token refused"),
510
+ target=grant.target,
511
+ hop=grant.hop,
512
+ session_id="",
513
+ )
514
+ if response.status_code != 200:
515
+ raise ControlPlaneUnavailable(
516
+ f"transaction service returned {response.status_code}: {response.text}"
517
+ )
518
+ token = response.json().get("transaction_token")
519
+ if not token:
520
+ raise ControlPlaneUnavailable("transaction service returned no usable token")
521
+ return Grant(**{**grant.__dict__, "transaction_token": token})
522
+
523
+ async def call(self, grant: Grant, method: str, url: str, **kwargs: Any) -> httpx.Response:
524
+ """Make the call the grant authorizes, with every header the resource needs."""
525
+ headers = {**kwargs.pop("headers", {}), **grant.headers()}
526
+ return await self._client.request(
527
+ method, url, headers=headers, timeout=self._timeout, **kwargs
528
+ )
529
+
530
+ async def hop(
531
+ self,
532
+ ctx: HopContext,
533
+ *,
534
+ target: str,
535
+ data_class: str,
536
+ taint: Taint | str | None = None,
537
+ ) -> tuple[Grant, HopContext]:
538
+ """``authorize`` plus the context for whoever receives the delegation."""
539
+ grant = await self.authorize(ctx, target=target, data_class=data_class, taint=taint)
540
+ return grant, ctx.advanced(grant.access_token)
541
+
542
+ async def run_chain(
543
+ self, ctx: HopContext, plan: Sequence[tuple[str, str]]
544
+ ) -> tuple[list[Grant], PartialOutcome | None]:
545
+ """Walk a plan of ``(target, data_class)`` hops, stopping at the first refusal.
546
+
547
+ Returns the grants that succeeded and, when something was refused, a
548
+ :class:`PartialOutcome` naming what completed and where it stopped — rather than
549
+ raising and discarding the history.
550
+
551
+ The caller decides what to do next. If the outcome is recoverable it carries a
552
+ challenge; if it is not, the task is over and the caller still knows exactly
553
+ which hops took effect.
554
+ """
555
+ grants: list[Grant] = []
556
+ completed: list[CompletedHop] = []
557
+ current = ctx
558
+ for target, data_class in plan:
559
+ try:
560
+ grant = await self.authorize(current, target=target, data_class=data_class)
561
+ except PolicyDenied as denied:
562
+ return grants, PartialOutcome.from_denial(completed, denied)
563
+ grants.append(grant)
564
+ completed.append(CompletedHop(hop=grant.hop, target=target, action_id=None))
565
+ current = current.advanced(grant.access_token)
566
+ return grants, None
567
+
568
+ # -- step-up consent ---------------------------------------------
569
+
570
+ async def step_up(self, denied: PolicyDenied) -> dict[str, Any]:
571
+ """Raise a challenge for a refusal that carries one.
572
+
573
+ Almost always unnecessary: a recoverable refusal already arrives with its
574
+ challenge attached, so ``denied.challenge`` is the normal path. This exists for
575
+ the case where the refusal was recorded earlier — an operator working through an
576
+ audit trail, say — and only the action id is to hand.
577
+ """
578
+ if denied.action_id is None:
579
+ raise ValueError("that refusal was never recorded; there is nothing to step up from")
580
+ response = await self._client.post(
581
+ f"{self._base_url}/v1/consent/step-up",
582
+ headers=self._admin_headers(),
583
+ json={
584
+ "session_id": denied.session_id,
585
+ "blocked_action_id": denied.action_id,
586
+ },
587
+ timeout=self._timeout,
588
+ )
589
+ if response.status_code != 201:
590
+ raise ControlPlaneUnavailable(
591
+ f"step-up challenge failed with {response.status_code}: {response.text}"
592
+ )
593
+ return response.json()
594
+
595
+ async def approve(
596
+ self, challenge: dict[str, Any], *, credential: str, approved: bool = True
597
+ ) -> dict[str, Any]:
598
+ """Answer a challenge as the consenting human.
599
+
600
+ ``credential`` is the **human's**, not the agent's: the control plane refuses the
601
+ session's own grant here, because an agent that could approve its own widening
602
+ would make the whole flow decorative. The SDK does not hold this
603
+ credential and does not try to — it is passed in by whatever channel the
604
+ integrator uses to reach the person.
605
+ """
606
+ response = await self._client.post(
607
+ f"{self._base_url}/v1/consent/step-up/complete",
608
+ headers={"Authorization": f"Bearer {credential}"},
609
+ json={"challenge_id": challenge["challenge_id"], "approved": approved},
610
+ timeout=self._timeout,
611
+ )
612
+ if response.status_code != 200:
613
+ raise ControlPlaneUnavailable(
614
+ f"step-up completion failed with {response.status_code}: {response.text}"
615
+ )
616
+ return response.json()
617
+
618
+ async def resume(
619
+ self, ctx: HopContext, denied: PolicyDenied, *, taint: Taint | str | None = None
620
+ ) -> Grant:
621
+ """Re-attempt the hop that was blocked, after a human approved the widening.
622
+
623
+ Re-attempting with the same context works because **a refused hop performs no
624
+ exchange**, so the presented token was never spent: Phase 4 moved the single-use
625
+ guard to ``spent:{action_id}``, and a refusal has no allow decision to spend.
626
+ The delegation record is therefore the original one and the hop budget continues
627
+ from where it was, which is the point.
628
+ """
629
+ if denied.data_class is None:
630
+ raise ValueError("that refusal did not record a data class to resume with")
631
+ return await self.authorize(
632
+ ctx, target=denied.target, data_class=denied.data_class, taint=taint
633
+ )
634
+
635
+
636
+ def _deny_reason(raw: object) -> DenyReason:
637
+ """The reported reason, or ``OUT_OF_SCOPE`` when a refusal names none."""
638
+ if isinstance(raw, str):
639
+ try:
640
+ return DenyReason(raw)
641
+ except ValueError:
642
+ return DenyReason.OUT_OF_SCOPE
643
+ return DenyReason.OUT_OF_SCOPE
644
+
645
+
646
+ def _max_taint(*labels: Taint | str | None) -> Taint | None:
647
+ """The highest label present; ``None`` when none is. Additive only."""
648
+ present = [Taint(label) if isinstance(label, str) else label for label in labels if label]
649
+ if not present:
650
+ return None
651
+ return (
652
+ Taint.UNTRUSTED_EXTERNAL if Taint.UNTRUSTED_EXTERNAL in present else Taint.TRUSTED_INTERNAL
653
+ )
654
+
655
+
656
+ def _token_taint(token: str) -> Taint | None:
657
+ from agentic_auth.sdk.context import _claims
658
+
659
+ raw = _claims(token).get("taint")
660
+ try:
661
+ return Taint(raw) if raw else None
662
+ except ValueError:
663
+ return None
664
+
665
+
666
+ __all__ = [
667
+ "AgenticAuthClient",
668
+ # Re-exported so `from agentic_auth.sdk.client import PolicyDenied` keeps working; they are
669
+ # defined in agentic_auth.sdk.errors, which the planes raise from too.
670
+ "ControlPlaneRejected",
671
+ "ControlPlaneUnavailable",
672
+ "Grant",
673
+ "ManifestRejected",
674
+ "PolicyDenied",
675
+ "Session",
676
+ "TransactionParamsRequired",
677
+ ]