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,362 @@
1
+ """The three read/admin planes, as the SDK exposes them.
2
+
3
+ The hop path (``consent`` → ``authorize`` → ``call``) is what an agent runs. These are
4
+ what everything *around* the agent runs: the pipeline that registers manifests, the
5
+ auditor that reads decision history, the resource server that bootstraps identity
6
+ material. Same base URL, different credential — which is the point of splitting them:
7
+
8
+ ==================== ========================= ==================================
9
+ ``client.admin`` admin bearer register, submit, catalogs, reports
10
+ ``client.audit`` audit-reader bearer decision history, delegation chains
11
+ ``client.identity`` identity-reader bearer agent identity, revocation list
12
+ ==================== ========================= ==================================
13
+
14
+ ``client.audit`` and ``client.identity`` send the read-only token when one is configured
15
+ and fall back to the admin token, so a notebook or a test can hold one credential while
16
+ production holds three. An auditor should never need the bearer that can record consent.
17
+
18
+ Every method raises rather than returning something falsy, for the same reason
19
+ ``authorize`` does: see :mod:`agentic_auth.sdk.errors`.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import uuid
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+ import httpx
29
+
30
+ from agentic_auth.sdk.errors import ControlPlaneRejected, ControlPlaneUnavailable, ManifestRejected
31
+
32
+ # Reconciliation outcomes, which the manifest routes report as error envelopes even though
33
+ # nothing is wrong with the request shape (contracts: 422 hard reject, 409 needs review).
34
+ _MANIFEST_OUTCOMES = frozenset({"reconciliation_rejected", "needs_review"})
35
+
36
+
37
+ def _params(**values: Any) -> dict[str, Any]:
38
+ """Query parameters, minus the ones not asked for. A ``None`` must not be sent as the
39
+ string ``"None"`` — the server would reject it as an invalid filter value."""
40
+ return {k: v for k, v in values.items() if v is not None}
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Transport:
45
+ """One HTTP conversation with the control plane, shared by every plane."""
46
+
47
+ client: httpx.AsyncClient
48
+ base_url: str
49
+ timeout: httpx.Timeout
50
+
51
+ async def json(
52
+ self,
53
+ method: str,
54
+ path: str,
55
+ *,
56
+ token: str | None = None,
57
+ json: Any = None,
58
+ params: dict[str, Any] | None = None,
59
+ expect: tuple[int, ...] = (200,),
60
+ ) -> Any:
61
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
62
+ try:
63
+ response = await self.client.request(
64
+ method,
65
+ f"{self.base_url}{path}",
66
+ headers=headers,
67
+ json=json,
68
+ params=params,
69
+ timeout=self.timeout,
70
+ )
71
+ except httpx.HTTPError as exc:
72
+ raise ControlPlaneUnavailable(f"{method} {path} failed: {exc}") from exc
73
+
74
+ if response.status_code in expect:
75
+ return _decode(response, method, path)
76
+ raise _refusal(response, method, path)
77
+
78
+
79
+ def _decode(response: httpx.Response, method: str, path: str) -> Any:
80
+ try:
81
+ return response.json()
82
+ except ValueError as exc:
83
+ raise ControlPlaneUnavailable(f"{method} {path} returned an unusable body: {exc}") from exc
84
+
85
+
86
+ def _refusal(response: httpx.Response, method: str, path: str) -> Exception:
87
+ """A 4xx is the caller's to fix; anything else is an outage, and the two are never
88
+ conflated — one is worth retrying unchanged and the other never is."""
89
+ if not 400 <= response.status_code < 500:
90
+ return ControlPlaneUnavailable(
91
+ f"{method} {path} returned {response.status_code}: {response.text[:500]}"
92
+ )
93
+ try:
94
+ body = response.json()
95
+ except ValueError:
96
+ # A refusal with no parseable body is still a refusal; the status carries it.
97
+ body = {}
98
+ envelope = body.get("error") if isinstance(body, dict) else None
99
+ if isinstance(envelope, dict):
100
+ code = str(envelope.get("code", "error"))
101
+ message = str(envelope.get("message", response.text[:500]))
102
+ details = envelope.get("details") if isinstance(envelope.get("details"), dict) else None
103
+ else:
104
+ # The token endpoint speaks OAuth (RFC 6749 §5.2), not this envelope.
105
+ code = str(envelope or "error")
106
+ message = (
107
+ str(body.get("error_description", response.text[:500]))
108
+ if isinstance(body, dict)
109
+ else response.text[:500]
110
+ )
111
+ details = None
112
+ kind = ManifestRejected if code in _MANIFEST_OUTCOMES else ControlPlaneRejected
113
+ return kind(
114
+ status=response.status_code,
115
+ code=code,
116
+ message=message,
117
+ details=details,
118
+ method=method,
119
+ path=path,
120
+ )
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class AgentRegistration:
125
+ """What ``register_agent`` returns on a 201. ``status`` is the reconciliation verdict:
126
+ ``reconciled`` (discovery agreed) or ``needs_review`` (an override was attested)."""
127
+
128
+ agent_id: str
129
+ manifest_version: int
130
+ status: str
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class ManifestSubmission:
135
+ agent: str
136
+ version: int
137
+ status: str
138
+
139
+
140
+ class AdminPlane:
141
+ """Registration, manifest versions, compiled catalogs, reconciliation reports.
142
+
143
+ Everything here needs the admin bearer. It is the pipeline's credential, not an
144
+ agent's: nothing on the hop path uses it.
145
+ """
146
+
147
+ def __init__(self, transport: Transport, token: str | None) -> None:
148
+ self._t = transport
149
+ self._token = token
150
+
151
+ # -- registration ----------------------------------------------------------
152
+
153
+ async def register_agent(
154
+ self,
155
+ name: str,
156
+ manifest: dict[str, Any],
157
+ *,
158
+ override_reason: str | None = None,
159
+ ) -> AgentRegistration:
160
+ """Register an agent and its first manifest version.
161
+
162
+ The manifest is reconciled against what each tool's host advertises
163
+ (RFC 9728 capability discovery) before anything is compiled. Raises
164
+ :class:`ManifestRejected` when the declaration exceeds what is discoverable, and
165
+ again — with ``needs_review`` — when discovery could not be reached. Pass
166
+ ``override_reason`` to proceed on the second case: it is stored as the human
167
+ attestation for that version, so the gap is recorded rather than hidden.
168
+ """
169
+ body: dict[str, Any] = {"name": name, "manifest": manifest}
170
+ if override_reason is not None:
171
+ body["override"] = {"reason": override_reason}
172
+ created = await self._t.json(
173
+ "POST", "/v1/agents", token=self._token, json=body, expect=(201,)
174
+ )
175
+ return AgentRegistration(
176
+ agent_id=created["agent_id"],
177
+ manifest_version=created["manifest_version"],
178
+ status=created["status"],
179
+ )
180
+
181
+ async def submit_manifest(
182
+ self,
183
+ agent: str,
184
+ manifest: dict[str, Any],
185
+ *,
186
+ override_reason: str | None = None,
187
+ ) -> ManifestSubmission:
188
+ """Add a new, immutable manifest version for an agent that already exists.
189
+
190
+ Sessions keep the policy version they were consented under, so a submission never
191
+ changes a decision already in flight.
192
+ """
193
+ body: dict[str, Any] = {"agent": agent, "manifest": manifest}
194
+ if override_reason is not None:
195
+ body["override"] = {"reason": override_reason}
196
+ created = await self._t.json(
197
+ "POST", "/v1/manifests", token=self._token, json=body, expect=(201,)
198
+ )
199
+ return ManifestSubmission(
200
+ agent=created["agent"], version=created["version"], status=created["status"]
201
+ )
202
+
203
+ # -- reads -----------------------------------------------------------------
204
+
205
+ async def manifest(self, scope: str, *, version: int | None = None) -> dict[str, Any]:
206
+ """One stored manifest version, verbatim. Omit ``version`` for the latest."""
207
+ return await self._t.json(
208
+ "GET",
209
+ f"/v1/manifests/{scope}",
210
+ token=self._token,
211
+ params=_params(version=version),
212
+ )
213
+
214
+ async def agents(
215
+ self, *, status: str | None = None, limit: int | None = None, cursor: str | None = None
216
+ ) -> dict[str, Any]:
217
+ """One page of registered agents: ``{"data": [...], "page": {...}}``."""
218
+ return await self._t.json(
219
+ "GET",
220
+ "/v1/agents",
221
+ token=self._token,
222
+ params=_params(status=status, limit=limit, cursor=cursor),
223
+ )
224
+
225
+ async def agent_id(self, name: str) -> str:
226
+ """Resolve an agent name to the id that ``enroll`` and ``revoke`` address.
227
+
228
+ Registration already returns it; this is for the pipeline that comes back later
229
+ holding only a name.
230
+ """
231
+ cursor: str | None = None
232
+ while True:
233
+ page = await self.agents(limit=100, cursor=cursor)
234
+ for item in page["data"]:
235
+ if item["name"] == name:
236
+ return str(item["id"])
237
+ cursor = page["page"].get("next_cursor")
238
+ if not cursor:
239
+ raise ControlPlaneRejected(
240
+ status=404,
241
+ code="not_found",
242
+ message=f"no agent named {name!r} is registered",
243
+ method="GET",
244
+ path="/v1/agents",
245
+ )
246
+
247
+ async def reconciliation(self, agent_id: str | uuid.UUID) -> dict[str, Any]:
248
+ """The latest reconciliation report: the diff between what the agent declared and
249
+ what its tools advertise. Empty ``diff`` with ``discovery_ok`` is a clean pass."""
250
+ return await self._t.json("GET", f"/v1/agents/{agent_id}/reconciliation", token=self._token)
251
+
252
+ async def scope_catalog(self, scope: str, *, version: int | None = None) -> dict[str, Any]:
253
+ """What consenting to ``scope`` actually grants: every tool, data class, declared
254
+ downstream agent and the hop budget, as compiled. This is what a consent screen
255
+ should be built from — not the manifest, which is the declaration, not the DAG."""
256
+ return await self._t.json(
257
+ "GET",
258
+ f"/v1/scopes/{scope}/catalog",
259
+ token=self._token,
260
+ params=_params(version=version),
261
+ )
262
+
263
+
264
+ class AuditPlane:
265
+ """The read-only audit plane. Nothing here writes: audit rows are created only by the
266
+ decision path, and the database refuses to change them afterwards."""
267
+
268
+ def __init__(self, transport: Transport, token: str | None) -> None:
269
+ self._t = transport
270
+ self._token = token
271
+
272
+ async def chain(self, action_id: str | uuid.UUID) -> dict[str, Any]:
273
+ """The full delegation chain for one recorded action, back to the consenting human.
274
+
275
+ Every :class:`~agentic_auth.sdk.errors.PolicyDenied` carries the ``action_id`` to pass here,
276
+ so "why was this refused, and who asked for it" is one call from the exception.
277
+ """
278
+ return await self._t.json("GET", f"/v1/audit/actions/{action_id}/chain", token=self._token)
279
+
280
+ async def decisions(
281
+ self,
282
+ *,
283
+ session_id: str | None = None,
284
+ agent: str | None = None,
285
+ outcome: str | None = None,
286
+ deny_reason: str | None = None,
287
+ enforced: bool | None = None,
288
+ target_kind: str | None = None,
289
+ since: str | None = None,
290
+ until: str | None = None,
291
+ taint: str | None = None,
292
+ privileged: bool | None = None,
293
+ limit: int | None = None,
294
+ cursor: str | None = None,
295
+ ) -> dict[str, Any]:
296
+ """Filtered decision history, newest first, stable under concurrent appends.
297
+
298
+ ``enforced=False`` is the observe-mode query: every call that *would* have been
299
+ blocked. Booleans go on the wire lowercased, as the API's filters expect.
300
+ """
301
+ return await self._t.json(
302
+ "GET",
303
+ "/v1/audit/decisions",
304
+ token=self._token,
305
+ params=_params(
306
+ session_id=session_id,
307
+ agent=agent,
308
+ outcome=outcome,
309
+ deny_reason=deny_reason,
310
+ enforced=None if enforced is None else str(enforced).lower(),
311
+ target_kind=target_kind,
312
+ since=since,
313
+ until=until,
314
+ taint=taint,
315
+ privileged=None if privileged is None else str(privileged).lower(),
316
+ limit=limit,
317
+ cursor=cursor,
318
+ ),
319
+ )
320
+
321
+
322
+ class IdentityPlane:
323
+ """What an offline verifier bootstraps from, and what an operator reads back.
324
+
325
+ A resource server needs exactly these two routes and an identity-reader bearer — it
326
+ cannot list agents, and does not need to.
327
+ """
328
+
329
+ def __init__(self, transport: Transport, token: str | None) -> None:
330
+ self._t = transport
331
+ self._token = token
332
+
333
+ async def of(self, agent_name: str) -> dict[str, Any]:
334
+ """One agent's pinned identity: status, trust-anchor version, public JWKS, whether
335
+ it is revoked, and the ``as_of`` the view was taken."""
336
+ return await self._t.json("GET", f"/v1/identity/agents/{agent_name}", token=self._token)
337
+
338
+ async def by_id(self, agent_id: str | uuid.UUID) -> dict[str, Any]:
339
+ """The same material, addressed by agent id."""
340
+ return await self._t.json("GET", f"/v1/agents/{agent_id}/identity", token=self._token)
341
+
342
+ async def revocations(
343
+ self, *, since: str | None = None, limit: int | None = None, cursor: str | None = None
344
+ ) -> dict[str, Any]:
345
+ """Revoked agents, newest first. ``as_of`` is the freshness a verifier refuses on:
346
+ past its own window without a successful refresh, every identity is stale."""
347
+ return await self._t.json(
348
+ "GET",
349
+ "/v1/identity/revocations",
350
+ token=self._token,
351
+ params=_params(since=since, limit=limit, cursor=cursor),
352
+ )
353
+
354
+
355
+ __all__ = [
356
+ "AdminPlane",
357
+ "AgentRegistration",
358
+ "AuditPlane",
359
+ "IdentityPlane",
360
+ "ManifestSubmission",
361
+ "Transport",
362
+ ]
@@ -0,0 +1,63 @@
1
+ """Agent-side provenance: label a value by where it came from.
2
+
3
+ The control plane derives most taint itself from the calls it decides.
4
+ This module covers what it cannot see — content the agent obtained outside the system —
5
+ and mirrors the same glob rules so an agent that holds its own manifest classifies the way
6
+ the PDP would. A label can only RAISE the effective taint at the next decision.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ from collections.abc import Iterable
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ from agentic_auth.schemas.authorize import Taint
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Provenance:
21
+ source_ref: str
22
+ trust: Taint
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class LabeledResult[T]:
27
+ value: T
28
+ provenance: Provenance
29
+
30
+ @property
31
+ def tainted(self) -> bool:
32
+ return self.provenance.trust is Taint.UNTRUSTED_EXTERNAL
33
+
34
+
35
+ class SourceClassifier:
36
+ """``trusted_globs`` are this agent's ``taint_policy.trusted_sources`` (materialized:
37
+ include ``agent://<downstream>`` for each declared downstream agent). Anything unmatched
38
+ is untrusted_external, exactly as the PDP decides."""
39
+
40
+ def __init__(self, trusted_globs: Iterable[str] = ()) -> None:
41
+ self._globs = tuple(trusted_globs)
42
+
43
+ @classmethod
44
+ def from_manifest(cls, manifest: dict[str, Any]) -> SourceClassifier:
45
+ spec = manifest.get("spec", {})
46
+ policy = spec.get("taint_policy") or {}
47
+ trusted = policy.get("trusted_sources")
48
+ if trusted is None:
49
+ trusted = [d["ref"] for d in spec.get("downstream_agents", [])]
50
+ return cls(trusted)
51
+
52
+ def classify(self, source_ref: str) -> Taint:
53
+ return (
54
+ Taint.TRUSTED_INTERNAL
55
+ if any(fnmatch.fnmatchcase(source_ref, g) for g in self._globs)
56
+ else Taint.UNTRUSTED_EXTERNAL
57
+ )
58
+
59
+ def wrap[T](self, value: T, source_ref: str) -> LabeledResult[T]:
60
+ return LabeledResult(value, Provenance(source_ref, self.classify(source_ref)))
61
+
62
+
63
+ __all__ = ["LabeledResult", "Provenance", "SourceClassifier"]
File without changes
@@ -0,0 +1,81 @@
1
+ """The current trust anchor per agent, cached in Redis and invalidated on every change.
2
+
3
+ ``anchor:{agent_name}`` holds the serialized :class:`AgentIdentityRead`; no TTL, because an
4
+ anchor only changes through enrollment and revocation, and both delete the key after
5
+ commit. A cache miss reads the database. Redis being down is a slower read, never a wrong
6
+ one.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import contextlib
13
+ import hashlib
14
+ from datetime import UTC, datetime
15
+ from typing import Any
16
+
17
+ from redis.asyncio import Redis
18
+ from sqlalchemy.ext.asyncio import AsyncSession
19
+
20
+ from agentic_auth.models import Agent, TrustAnchor
21
+ from agentic_auth.repositories import agents as agents_repo
22
+ from agentic_auth.repositories import trust_anchors as anchors_repo
23
+ from agentic_auth.schemas.identity import AgentIdentityRead
24
+
25
+
26
+ def anchor_key(agent_name: str) -> str:
27
+ return f"anchor:{agent_name}"
28
+
29
+
30
+ def thumbprint(jwk: dict[str, Any]) -> str:
31
+ """SHA-256 of the raw public key bytes, base64url — the identity of the KEY itself."""
32
+ raw = base64.urlsafe_b64decode(jwk["x"] + "=" * (-len(jwk["x"]) % 4))
33
+ return base64.urlsafe_b64encode(hashlib.sha256(raw).digest()).rstrip(b"=").decode()
34
+
35
+
36
+ def identity_read(
37
+ agent: Agent, anchor: TrustAnchor | None, *, as_of: datetime
38
+ ) -> AgentIdentityRead:
39
+ show = anchor is not None and agent.status in ("enrolled", "revoked")
40
+ return AgentIdentityRead(
41
+ agent=agent.name,
42
+ status=agent.status,
43
+ trust_anchor_version=agent.trust_anchor_version,
44
+ jwks=anchor.jwks if show and anchor is not None else None,
45
+ principal_ref=agent.principal_ref if show else None,
46
+ manifest_version=anchor.manifest_version if show and anchor is not None else None,
47
+ revoked=agent.status == "revoked",
48
+ revoked_at=anchor.revoked_at if anchor is not None else None,
49
+ as_of=as_of,
50
+ )
51
+
52
+
53
+ class AnchorCache:
54
+ def __init__(self, redis: Redis | None) -> None:
55
+ self._redis = redis
56
+
57
+ async def current(self, db: AsyncSession, agent_name: str) -> AgentIdentityRead | None:
58
+ """The agent's identity material, or ``None`` for an unknown agent."""
59
+ if self._redis is not None:
60
+ with contextlib.suppress(Exception):
61
+ cached = await self._redis.get(anchor_key(agent_name))
62
+ if cached is not None:
63
+ return AgentIdentityRead.model_validate_json(cached)
64
+ agent = await agents_repo.get_by_name(db, agent_name)
65
+ if agent is None:
66
+ return None
67
+ anchor = await anchors_repo.current(db, agent.id)
68
+ read = identity_read(agent, anchor, as_of=datetime.now(UTC))
69
+ if self._redis is not None:
70
+ with contextlib.suppress(Exception):
71
+ await self._redis.set(anchor_key(agent_name), read.model_dump_json())
72
+ return read
73
+
74
+ async def invalidate(self, agent_name: str) -> None:
75
+ if self._redis is None:
76
+ return
77
+ with contextlib.suppress(Exception):
78
+ await self._redis.delete(anchor_key(agent_name))
79
+
80
+
81
+ __all__ = ["AnchorCache", "anchor_key", "identity_read", "thumbprint"]