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
+ """PyJWT + Ed25519 implementation of :class:`TokenProfile`.
2
+
3
+ The verification order in :meth:`JwtTokenProfile.verify` is the one specified in
4
+ the hop-token profile. Every step is mandatory and every failure is a rejection —
5
+ there is no partial acceptance, and no claim may be read before all steps pass.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import uuid
11
+ from datetime import UTC, datetime, timedelta
12
+ from typing import Any
13
+
14
+ import jwt
15
+
16
+ from agentic_auth.config import get_settings
17
+ from agentic_auth.schemas.authorize import Taint
18
+ from agentic_auth.services.tokens.act_chain import MalformedActChain, hop_of
19
+ from agentic_auth.services.tokens.keys import ALGORITHM, IssuerKey, get_issuer_key
20
+ from agentic_auth.services.tokens.profile import (
21
+ TRANSACTION_TYP,
22
+ TokenProfile,
23
+ VerifiedToken,
24
+ VerifiedTransaction,
25
+ )
26
+
27
+ LEEWAY_SECONDS = 60
28
+
29
+
30
+ class TokenVerificationError(Exception):
31
+ """The presented token cannot be trusted. Always terminal — never retried, never
32
+ downgraded to a partial acceptance."""
33
+
34
+
35
+ class JwtTokenProfile(TokenProfile):
36
+ def __init__(
37
+ self,
38
+ key: IssuerKey | None = None,
39
+ *,
40
+ issuer: str | None = None,
41
+ ttl_seconds: int | None = None,
42
+ ) -> None:
43
+ settings = get_settings()
44
+ self._key = key or get_issuer_key()
45
+ self._issuer = issuer or settings.issuer
46
+ self._ttl = ttl_seconds or settings.hop_token_ttl_seconds
47
+
48
+ # -- issuance ---------------------------------------------------------
49
+
50
+ def _mint(
51
+ self,
52
+ claims: dict[str, Any],
53
+ *,
54
+ ttl_seconds: int | None = None,
55
+ typ: str | None = None,
56
+ ) -> str:
57
+ now = datetime.now(UTC)
58
+ payload = {
59
+ "iss": self._issuer,
60
+ "iat": int(now.timestamp()),
61
+ "exp": int((now + timedelta(seconds=ttl_seconds or self._ttl)).timestamp()),
62
+ "jti": str(uuid.uuid4()),
63
+ **claims,
64
+ }
65
+ headers: dict[str, Any] = {"kid": self._key.kid}
66
+ if typ is not None:
67
+ headers["typ"] = typ
68
+ return jwt.encode(payload, self._key.private_pem(), algorithm=ALGORITHM, headers=headers)
69
+
70
+ def mint_root_grant(self, *, sub: str, scope: str, session_id: str, policy_version: int) -> str:
71
+ # aud is the consented scope, not a concrete target: the root grant is the only
72
+ # token that names a scope, and it is never presentable to a resource server.
73
+ return self._mint(
74
+ {
75
+ "sub": sub,
76
+ "aud": scope,
77
+ "scope": scope,
78
+ "resource": scope,
79
+ "session_id": session_id,
80
+ "policy_version": policy_version,
81
+ "hop": 1,
82
+ }
83
+ )
84
+
85
+ def mint_hop_token(
86
+ self,
87
+ *,
88
+ sub: str,
89
+ target: str,
90
+ data_class: str,
91
+ session_id: str,
92
+ policy_version: int,
93
+ hop: int,
94
+ act: dict[str, Any] | None,
95
+ action_id: str,
96
+ taint: Taint | None = None,
97
+ ) -> str:
98
+ claims: dict[str, Any] = {
99
+ "sub": sub,
100
+ "aud": target,
101
+ "resource": target,
102
+ "scope": data_class,
103
+ "session_id": session_id,
104
+ "policy_version": policy_version,
105
+ "hop": hop,
106
+ "action_id": action_id,
107
+ }
108
+ if act is not None:
109
+ claims["act"] = act
110
+ if taint is not None:
111
+ claims["taint"] = taint.value
112
+ return self._mint(claims)
113
+
114
+ # -- verification -----------------------------------------------------
115
+
116
+ def verify(self, token: str, *, audience: str | None = None) -> VerifiedToken:
117
+ # 1. Signature against the kid-named key, algorithm pinned. Never `none`, never
118
+ # inferred from the header.
119
+ try:
120
+ header = jwt.get_unverified_header(token)
121
+ except jwt.PyJWTError as exc:
122
+ raise TokenVerificationError(f"malformed token header: {exc}") from exc
123
+ if header.get("alg") != ALGORITHM:
124
+ raise TokenVerificationError(
125
+ f"unexpected alg {header.get('alg')!r}; only {ALGORITHM} is accepted"
126
+ )
127
+ # A transaction token (`typ: txn+jwt`) is signed by the same key and carries most of
128
+ # the same claims; it must never pass as a hop token (security audit).
129
+ if header.get("typ") not in (None, "JWT"):
130
+ raise TokenVerificationError(
131
+ f"unexpected typ {header.get('typ')!r}; a hop token has typ JWT"
132
+ )
133
+ if header.get("kid") != self._key.kid:
134
+ raise TokenVerificationError(f"unknown kid {header.get('kid')!r}")
135
+
136
+ try:
137
+ # 2. exp/iat and 3. iss are enforced here; 4. aud when a target is given.
138
+ claims = jwt.decode(
139
+ token,
140
+ self._key.public_pem(),
141
+ algorithms=[ALGORITHM],
142
+ issuer=self._issuer,
143
+ audience=audience,
144
+ leeway=LEEWAY_SECONDS,
145
+ options={
146
+ "require": ["exp", "iat", "jti", "sub", "aud", "iss"],
147
+ "verify_aud": audience is not None,
148
+ },
149
+ )
150
+ except jwt.PyJWTError as exc:
151
+ raise TokenVerificationError(str(exc)) from exc
152
+
153
+ for claim in ("scope", "session_id", "policy_version", "hop"):
154
+ if claim not in claims:
155
+ raise TokenVerificationError(f"missing required claim {claim!r}")
156
+
157
+ act = claims.get("act")
158
+ if act is not None and not isinstance(act, dict):
159
+ raise TokenVerificationError("act claim must be an object")
160
+
161
+ # 5. hop and act depth must agree. A mismatch means a hand-assembled token.
162
+ try:
163
+ expected_hop = hop_of(act)
164
+ except MalformedActChain as exc:
165
+ raise TokenVerificationError(f"malformed act chain: {exc}") from exc
166
+ if claims["hop"] != expected_hop:
167
+ raise TokenVerificationError(
168
+ f"hop claim {claims['hop']} disagrees with act depth (expected {expected_hop})"
169
+ )
170
+
171
+ aud = claims["aud"]
172
+ if isinstance(aud, list): # a hop token names exactly one target
173
+ if len(aud) != 1:
174
+ raise TokenVerificationError("hop token must name exactly one audience")
175
+ aud = aud[0]
176
+
177
+ # The audit link. Optional (root grants have none), but when present it must be an
178
+ # action id — a malformed one would otherwise surface later as a broken chain.
179
+ action_id = claims.get("action_id")
180
+ if action_id is not None:
181
+ if not isinstance(action_id, str):
182
+ raise TokenVerificationError("action_id claim must be a UUID string")
183
+ try:
184
+ uuid.UUID(action_id)
185
+ except ValueError as exc:
186
+ raise TokenVerificationError("action_id claim must be a UUID string") from exc
187
+
188
+ # Phase 4: a present taint must be one of the two classes; anything else is a
189
+ # hand-assembled token.
190
+ raw_taint = claims.get("taint")
191
+ taint: Taint | None = None
192
+ if raw_taint is not None:
193
+ try:
194
+ taint = Taint(raw_taint)
195
+ except ValueError as exc:
196
+ raise TokenVerificationError(f"unknown taint claim {raw_taint!r}") from exc
197
+
198
+ # Step 6 (session live, policy version matching) belongs to the PDP and the
199
+ # exchange service — they hold the session, this module does not.
200
+ return VerifiedToken(
201
+ raw=token,
202
+ sub=claims["sub"],
203
+ aud=aud,
204
+ scope=claims["scope"],
205
+ session_id=claims["session_id"],
206
+ policy_version=claims["policy_version"],
207
+ hop=claims["hop"],
208
+ jti=claims["jti"],
209
+ expires_at=datetime.fromtimestamp(claims["exp"], tz=UTC),
210
+ act=act,
211
+ action_id=action_id,
212
+ taint=taint,
213
+ )
214
+
215
+ # -- transaction tokens ------------------------------------------------
216
+
217
+ def mint_transaction_token(
218
+ self, *, hop: VerifiedToken, params_hash: str, binding: list[str] | None
219
+ ) -> str:
220
+ jti = str(uuid.uuid4())
221
+ claims: dict[str, Any] = {
222
+ "jti": jti,
223
+ "txn": jti,
224
+ "sub": hop.sub,
225
+ "aud": hop.aud,
226
+ "session_id": hop.session_id,
227
+ "action_id": hop.action_id,
228
+ "hop": hop.hop,
229
+ "azd": {
230
+ "target": hop.aud,
231
+ "params_hash": params_hash,
232
+ "hash_alg": "sha-256",
233
+ "canon": "rfc8785",
234
+ "binding": list(binding) if binding is not None else None,
235
+ },
236
+ }
237
+ if hop.act is not None:
238
+ claims["act"] = hop.act
239
+ if hop.taint is not None:
240
+ claims["taint"] = hop.taint.value
241
+ return self._mint(
242
+ claims,
243
+ ttl_seconds=get_settings().transaction_token_ttl_seconds,
244
+ typ=TRANSACTION_TYP,
245
+ )
246
+
247
+ def verify_transaction_token(self, token: str, *, audience: str) -> VerifiedTransaction:
248
+ try:
249
+ header = jwt.get_unverified_header(token)
250
+ except jwt.PyJWTError as exc:
251
+ raise TokenVerificationError(f"malformed token header: {exc}") from exc
252
+ # `typ` first: a hop token presented as a transaction token (or the reverse) is
253
+ # refused before any claim is read.
254
+ if header.get("typ") != TRANSACTION_TYP:
255
+ raise TokenVerificationError(
256
+ f"expected typ {TRANSACTION_TYP!r}, got {header.get('typ')!r}"
257
+ )
258
+ if header.get("alg") != ALGORITHM:
259
+ raise TokenVerificationError(f"unexpected alg {header.get('alg')!r}")
260
+ if header.get("kid") != self._key.kid:
261
+ raise TokenVerificationError(f"unknown kid {header.get('kid')!r}")
262
+ try:
263
+ claims = jwt.decode(
264
+ token,
265
+ self._key.public_pem(),
266
+ algorithms=[ALGORITHM],
267
+ issuer=self._issuer,
268
+ audience=audience,
269
+ leeway=LEEWAY_SECONDS,
270
+ options={"require": ["exp", "iat", "jti", "sub", "aud", "iss"]},
271
+ )
272
+ except jwt.PyJWTError as exc:
273
+ raise TokenVerificationError(str(exc)) from exc
274
+ for claim in ("txn", "session_id", "action_id", "hop", "azd"):
275
+ if claim not in claims:
276
+ raise TokenVerificationError(f"missing required claim {claim!r}")
277
+ if claims["txn"] != claims["jti"]:
278
+ raise TokenVerificationError("txn must equal jti")
279
+ azd = claims["azd"]
280
+ if not isinstance(azd, dict) or not isinstance(azd.get("params_hash"), str):
281
+ raise TokenVerificationError("azd claim is malformed")
282
+ if azd.get("hash_alg") != "sha-256" or azd.get("canon") != "rfc8785":
283
+ raise TokenVerificationError("unsupported binding algorithm")
284
+ if azd.get("target") != claims["aud"]:
285
+ raise TokenVerificationError("azd.target disagrees with aud")
286
+ binding = azd.get("binding")
287
+ if binding is not None and not (
288
+ isinstance(binding, list) and all(isinstance(b, str) for b in binding)
289
+ ):
290
+ raise TokenVerificationError("azd.binding must be a list of pointers or null")
291
+ act = claims.get("act")
292
+ if act is not None and not isinstance(act, dict):
293
+ raise TokenVerificationError("act claim must be an object")
294
+ raw_taint = claims.get("taint")
295
+ taint: Taint | None = None
296
+ if raw_taint is not None:
297
+ try:
298
+ taint = Taint(raw_taint)
299
+ except ValueError as exc:
300
+ raise TokenVerificationError(f"unknown taint claim {raw_taint!r}") from exc
301
+ return VerifiedTransaction(
302
+ raw=token,
303
+ jti=claims["jti"],
304
+ sub=claims["sub"],
305
+ aud=claims["aud"],
306
+ session_id=claims["session_id"],
307
+ action_id=str(claims["action_id"]),
308
+ hop=int(claims["hop"]),
309
+ act=act,
310
+ taint=taint,
311
+ params_hash=azd["params_hash"],
312
+ binding=list(binding) if binding is not None else None,
313
+ expires_at=datetime.fromtimestamp(claims["exp"], tz=UTC),
314
+ )
315
+
316
+ # -- proof of possession at the exchange -------------------------------
317
+
318
+ def verify_actor_token(
319
+ self, token: str, *, anchor_jwks: dict[str, Any], subject_token: str, expected_agent: str
320
+ ) -> str:
321
+ import base64
322
+ import hashlib
323
+
324
+ try:
325
+ header = jwt.get_unverified_header(token)
326
+ except jwt.PyJWTError as exc:
327
+ raise TokenVerificationError(f"malformed actor_token header: {exc}") from exc
328
+ if header.get("alg") != ALGORITHM:
329
+ raise TokenVerificationError(f"actor_token alg {header.get('alg')!r} is not accepted")
330
+ entry = next(
331
+ (k for k in anchor_jwks.get("keys", []) if k.get("kid") == header.get("kid")), None
332
+ )
333
+ if entry is None:
334
+ raise TokenVerificationError(
335
+ f"actor_token kid {header.get('kid')!r} is not in the pinned trust anchor"
336
+ )
337
+ try:
338
+ key = jwt.PyJWK(dict(entry), algorithm=ALGORITHM).key
339
+ claims = jwt.decode(
340
+ token,
341
+ key,
342
+ algorithms=[ALGORITHM],
343
+ audience=self._issuer,
344
+ leeway=5,
345
+ options={"require": ["exp", "iat", "jti", "sub", "aud", "st_hash"]},
346
+ )
347
+ except jwt.PyJWTError as exc:
348
+ raise TokenVerificationError(f"actor_token rejected: {exc}") from exc
349
+ expected_sub = f"agent://{expected_agent}"
350
+ if claims.get("sub") != expected_sub or claims.get("iss") != expected_sub:
351
+ raise TokenVerificationError("actor_token was issued for a different agent")
352
+ if int(claims["exp"]) - int(claims["iat"]) > 60:
353
+ raise TokenVerificationError("actor_token lifetime exceeds 60s")
354
+ digest = hashlib.sha256(subject_token.encode()).digest()
355
+ if claims["st_hash"] != base64.urlsafe_b64encode(digest).rstrip(b"=").decode():
356
+ raise TokenVerificationError("actor_token does not hash this subject token")
357
+ return expected_agent
358
+
359
+ def jwks(self) -> dict[str, Any]:
360
+ # This profile's OWN key. A profile built around an injected key (tests, rotation
361
+ # rehearsals) must publish the key it signs with, not the process-global one.
362
+ return {"keys": [self._key.public_jwk()]}
@@ -0,0 +1,117 @@
1
+ """Issuer keypair and JWK Set.
2
+
3
+ Ed25519: ~64-byte signatures that verify in tens of microseconds, which matters because
4
+ verification happens on every hop inside the 15 ms per-hop budget.
5
+
6
+ ``kid`` is present from day one so that key rotation — Phase 4's problem — never becomes
7
+ a breaking change.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import hashlib
14
+ import logging
15
+ from dataclasses import dataclass
16
+ from functools import lru_cache
17
+ from typing import Any
18
+
19
+ from cryptography.hazmat.primitives import serialization
20
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
21
+ Ed25519PrivateKey,
22
+ Ed25519PublicKey,
23
+ )
24
+
25
+ from agentic_auth import runtime
26
+ from agentic_auth.config import get_settings
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ ALGORITHM = "EdDSA"
31
+
32
+
33
+ def _b64url(raw: bytes) -> str:
34
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
35
+
36
+
37
+ def _raw_public_bytes(public_key: Ed25519PublicKey) -> bytes:
38
+ return public_key.public_bytes(
39
+ encoding=serialization.Encoding.Raw,
40
+ format=serialization.PublicFormat.Raw,
41
+ )
42
+
43
+
44
+ def _thumbprint(public_key: Ed25519PublicKey) -> str:
45
+ """A stable kid derived from the key itself, so it survives a restart."""
46
+ return _b64url(hashlib.sha256(_raw_public_bytes(public_key)).digest())[:16]
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class IssuerKey:
51
+ private_key: Ed25519PrivateKey
52
+ kid: str
53
+
54
+ @property
55
+ def public_key(self) -> Ed25519PublicKey:
56
+ return self.private_key.public_key()
57
+
58
+ def public_jwk(self) -> dict[str, Any]:
59
+ return {
60
+ "kty": "OKP",
61
+ "crv": "Ed25519",
62
+ "x": _b64url(_raw_public_bytes(self.public_key)),
63
+ "kid": self.kid,
64
+ "alg": ALGORITHM,
65
+ "use": "sig",
66
+ }
67
+
68
+ def private_pem(self) -> bytes:
69
+ return self.private_key.private_bytes(
70
+ encoding=serialization.Encoding.PEM,
71
+ format=serialization.PrivateFormat.PKCS8,
72
+ encryption_algorithm=serialization.NoEncryption(),
73
+ )
74
+
75
+ def public_pem(self) -> bytes:
76
+ return self.public_key.public_bytes(
77
+ encoding=serialization.Encoding.PEM,
78
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
79
+ )
80
+
81
+
82
+ def load_or_generate(pem: str = "", kid: str = "") -> IssuerKey:
83
+ """Load an Ed25519 private key from PEM, or generate an ephemeral one.
84
+
85
+ An ephemeral key is a development convenience: it is logged as ephemeral, and every
86
+ token it signed stops verifying when the process restarts. That is loud by design —
87
+ a silently rotating issuer key is far worse than a noisy one.
88
+ """
89
+ if pem.strip():
90
+ loaded = serialization.load_pem_private_key(pem.encode(), password=None)
91
+ if not isinstance(loaded, Ed25519PrivateKey):
92
+ raise ValueError(f"issuer key must be Ed25519, got {type(loaded).__name__}")
93
+ private_key = loaded
94
+ else:
95
+ private_key = Ed25519PrivateKey.generate()
96
+ logger.warning(
97
+ "no AGENTIC_AUTH_ISSUER_PRIVATE_KEY configured — generated an EPHEMERAL "
98
+ "issuer key. Tokens will not verify after a restart. Development only."
99
+ )
100
+ return IssuerKey(private_key=private_key, kid=kid or _thumbprint(private_key.public_key()))
101
+
102
+
103
+ @lru_cache
104
+ def _process_issuer_key() -> IssuerKey:
105
+ settings = get_settings()
106
+ return load_or_generate(settings.issuer_private_key, settings.issuer_kid)
107
+
108
+
109
+ def get_issuer_key() -> IssuerKey:
110
+ """The process's issuer key, or an embedded instance's own: two instances in one
111
+ process never sign with the same key."""
112
+ current = runtime.override()
113
+ return current.issuer_key if current is not None else _process_issuer_key()
114
+
115
+
116
+ def jwks() -> dict[str, Any]:
117
+ return {"keys": [get_issuer_key().public_jwk()]}
@@ -0,0 +1,167 @@
1
+ """``TokenProfile`` — the seam that isolates a moving spec surface.
2
+
3
+ The design doc's versioning strategy puts token-exchange, transaction-token and AAuth
4
+ handling behind this interface: spec changes ship as new profiles, and a pinned manifest
5
+ keeps resolving against the profile version it was attested under.
6
+
7
+ Concretely, this is what lets Phase 4 add transaction tokens and Phase 5 swap in an
8
+ external issuer without the PDP, the routes, or the sidecar changing at all.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from abc import ABC, abstractmethod
14
+ from dataclasses import dataclass
15
+ from datetime import datetime
16
+ from typing import Any
17
+
18
+ from agentic_auth.schemas.authorize import Taint
19
+ from agentic_auth.services.tokens.act_chain import current_actor, hop_of, walk
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class VerifiedToken:
24
+ """A token whose signature and claims have already been checked.
25
+
26
+ Only ever constructed by :meth:`TokenProfile.verify`. Every consumer takes this
27
+ rather than a raw string, so there is no way to read a claim off an unverified token.
28
+ """
29
+
30
+ raw: str
31
+ sub: str
32
+ aud: str
33
+ scope: str
34
+ session_id: str
35
+ policy_version: int
36
+ hop: int
37
+ jti: str
38
+ expires_at: datetime
39
+ act: dict[str, Any] | None = None
40
+ # The recorded allow that authorized minting this token. Absent on root grants and on
41
+ # tokens minted before Phase 3. Grants nothing: it links the next audit row to this one.
42
+ action_id: str | None = None
43
+ # Phase 4: the effective taint of the decision that minted this token. A delegate
44
+ # inherits its delegator's taint through this signed claim and cannot lower it. Absent
45
+ # on root grants and pre-Phase-4 tokens, which reads as trusted_internal.
46
+ taint: Taint | None = None
47
+
48
+ @property
49
+ def actor(self) -> str:
50
+ """Who is presenting this token — the outermost actor, or the human at the root."""
51
+ return current_actor(self.act, self.sub)
52
+
53
+ @property
54
+ def act_chain(self) -> list[str]:
55
+ """``[human, first delegate, ..., current actor]``."""
56
+ return walk(self.act, self.sub)
57
+
58
+ @property
59
+ def next_hop(self) -> int:
60
+ """The depth of the hop this token is being presented *for*."""
61
+ return hop_of(self.act)
62
+
63
+ @property
64
+ def holder(self) -> str | None:
65
+ """The agent this token was issued *to* — the one entitled to present it.
66
+
67
+ ``act`` records who has already delegated; ``aud`` records who holds it now.
68
+ Confusing the two would let a delegator's identity stand in for its delegate's.
69
+
70
+ ``None`` when the token was issued for a tool call rather than a delegation:
71
+ such a token goes to a resource server and can never authorize a further hop.
72
+ """
73
+ if self.act is None:
74
+ return self.aud # the root grant names the consented scope
75
+ return self.aud.removeprefix("agent://") if self.aud.startswith("agent://") else None
76
+
77
+ @property
78
+ def presenter(self) -> str:
79
+ """The identity expected to present this token: the human at the root, or the
80
+ agent it was issued to."""
81
+ return self.sub if self.act is None else self.aud
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class VerifiedTransaction:
86
+ """A transaction token whose signature and claims have been checked.
87
+
88
+ Only ever constructed by :meth:`TokenProfile.verify_transaction_token`. Single use and
89
+ parameter binding are NOT checked here — they belong to the resource-side verifier,
90
+ which holds the presented params and the replay store.
91
+ """
92
+
93
+ raw: str
94
+ jti: str
95
+ sub: str
96
+ aud: str
97
+ session_id: str
98
+ action_id: str
99
+ hop: int
100
+ act: dict[str, Any] | None
101
+ taint: Taint | None
102
+ params_hash: str
103
+ binding: list[str] | None
104
+ expires_at: datetime
105
+
106
+
107
+ TRANSACTION_TYP = "txn+jwt"
108
+
109
+
110
+ class TokenProfile(ABC):
111
+ """Mints and verifies the tokens that carry authority between hops."""
112
+
113
+ @abstractmethod
114
+ def mint_root_grant(self, *, sub: str, scope: str, session_id: str, policy_version: int) -> str:
115
+ """The hop-1 token produced at consent: no ``act``, ``aud`` = the consented scope.
116
+
117
+ It is never presentable to a resource server — every real call exchanges first.
118
+ """
119
+
120
+ @abstractmethod
121
+ def mint_hop_token(
122
+ self,
123
+ *,
124
+ sub: str,
125
+ target: str,
126
+ data_class: str,
127
+ session_id: str,
128
+ policy_version: int,
129
+ hop: int,
130
+ act: dict[str, Any] | None,
131
+ action_id: str,
132
+ taint: Taint | None = None,
133
+ ) -> str:
134
+ """A single-hop token bound to exactly one target and one data class, naming the
135
+ recorded allow decision that authorized it, carrying the effective taint."""
136
+
137
+ @abstractmethod
138
+ def verify(self, token: str, *, audience: str | None = None) -> VerifiedToken:
139
+ """Verify signature and claims, or raise.
140
+
141
+ Must fail closed: any step that cannot be completed is a rejection, never a
142
+ partial acceptance.
143
+ """
144
+
145
+ @abstractmethod
146
+ def mint_transaction_token(
147
+ self, *, hop: VerifiedToken, params_hash: str, binding: list[str] | None
148
+ ) -> str:
149
+ """Call-bound authority layered on ``hop`` (a verified tool-call token): same
150
+ ``sub``/``aud``/``session_id``/``action_id``/``hop``/``act``/``taint``, plus the
151
+ binding. Header ``typ`` is ``txn+jwt``. Short lifetime, single use at the resource."""
152
+
153
+ @abstractmethod
154
+ def verify_transaction_token(self, token: str, *, audience: str) -> VerifiedTransaction:
155
+ """Verify signature, ``typ``, claims and audience, or raise. Fails closed."""
156
+
157
+ @abstractmethod
158
+ def verify_actor_token(
159
+ self, token: str, *, anchor_jwks: dict[str, Any], subject_token: str, expected_agent: str
160
+ ) -> str:
161
+ """Proof of possession at the exchange: the actor token verifies against
162
+ the holder's pinned keys, names ``expected_agent``, is addressed to this issuer, is
163
+ fresh, and hashes the exact ``subject_token``. Returns the agent name, or raises."""
164
+
165
+ @abstractmethod
166
+ def jwks(self) -> dict[str, Any]:
167
+ """Public keys, so any resource server can verify offline."""