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,228 @@
1
+ """RFC 8785 JSON Canonicalization Scheme, and the transaction-token binding hash.
2
+
3
+ This is the one implementation the control plane MINTS with and a resource server VERIFIES
4
+ with (``docs/canonicalization.md``). It is
5
+ written from the RFC so an independent implementation agrees with it, and it imports only
6
+ the standard library so ``agentic_auth.verify`` stays installable without the control plane.
7
+
8
+ Rules, in RFC order:
9
+
10
+ - object members sorted by key as UTF-16 code units; no whitespace anywhere
11
+ - strings escaped per §3.2.2.2; non-ASCII stays literal UTF-8
12
+ - integers as-is; every other number per ECMAScript ``Number::toString`` (shortest
13
+ round-trip digits, positional between 1e-7 and 1e21, ``1e+21`` style exponents outside);
14
+ ``-0`` → ``0``
15
+ - ``NaN`` / ``Infinity`` rejected (they are not JSON)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import hashlib
22
+ import math
23
+ from collections.abc import Mapping, Sequence
24
+ from decimal import Decimal
25
+ from typing import Any
26
+
27
+ # `mutmut run` leaves 11 equivalent mutants in this module, none of which changes a result:
28
+ #
29
+ # - three change only the CASE of a codec name (`"utf-16-be"`, `"utf-8"`, `"ascii"`); Python
30
+ # codec lookup is case-insensitive;
31
+ # - two strip a longer character SET that removes the same characters: `rstrip("XX0XX")` on a
32
+ # digit string and `rstrip(b"XX=XX")` on a base64 digest. Neither string contains `X`, and
33
+ # the 43rd character of a 32-byte base64 digest encodes 4 bits, so it is never `X`;
34
+ # - five sit on `_number` boundaries no input reaches: `value <= 0` (zero returned above),
35
+ # `n < 21` (a 21-digit positional number needs more than 17 significant digits),
36
+ # `n <= 1` (n = 1 is taken by the branch before), and the sign of an exponent `e >= 0` /
37
+ # `e > 1` (this branch only runs for n > 21 or n <= -6, so e >= 21 or e <= -7);
38
+ # - one is `first = None` for `first = False`: both are falsy at its only use.
39
+ #
40
+ # Every mutant that changes a rendered number, a key order, a depth limit, a pointer
41
+ # resolution or a hash is killed (tests/unit/test_canonical.py, test_phase4_edges.py, and the
42
+ # independent reference in test_canonical_reference.py).
43
+
44
+ MAX_DEPTH = 64
45
+ HASH_ALG = "sha-256"
46
+ CANON = "rfc8785"
47
+
48
+ _ESCAPES = {
49
+ '"': '\\"',
50
+ "\\": "\\\\",
51
+ "\b": "\\b",
52
+ "\f": "\\f",
53
+ "\n": "\\n",
54
+ "\r": "\\r",
55
+ "\t": "\\t",
56
+ }
57
+
58
+
59
+ class CanonicalizationError(ValueError):
60
+ """The value cannot be canonicalized: not JSON, or deeper than allowed."""
61
+
62
+
63
+ def _utf16_key(key: str) -> bytes:
64
+ """Sort keys by UTF-16 code units (RFC 8785 §3.2.3): big-endian UTF-16 bytes compare
65
+ in code-unit order, which is what the RFC specifies (and differs from code-point order
66
+ only for supplementary-plane characters)."""
67
+ return key.encode("utf-16-be")
68
+
69
+
70
+ def _string(value: str) -> str:
71
+ out: list[str] = ['"']
72
+ for ch in value:
73
+ if ch in _ESCAPES:
74
+ out.append(_ESCAPES[ch])
75
+ elif ord(ch) < 0x20:
76
+ out.append(f"\\u{ord(ch):04x}")
77
+ else:
78
+ out.append(ch)
79
+ out.append('"')
80
+ return "".join(out)
81
+
82
+
83
+ def _number(value: float) -> str:
84
+ """ECMAScript ``Number::toString`` for a finite double (ECMA-262 §6.1.6.1.20).
85
+
86
+ With ``s`` the shortest round-trip digit string of ``k`` digits and ``n`` such that
87
+ ``value = s × 10^(n-k)``:
88
+
89
+ - ``k <= n <= 21`` → the digits followed by ``n-k`` zeros
90
+ - ``0 < n <= 21`` → digits with a point after the first ``n``
91
+ - ``-6 < n <= 0`` → ``0.`` then ``-n`` zeros then the digits
92
+ - otherwise → ``d.ddd e±(n-1)`` (no point when ``k == 1``)
93
+ """
94
+ if math.isnan(value) or math.isinf(value):
95
+ raise CanonicalizationError("NaN and Infinity are not JSON numbers")
96
+ if value == 0:
97
+ return "0" # covers -0.0
98
+ sign = "-" if value < 0 else "" # value == 0 returned above; -0.0 is "0"
99
+ # repr() is the shortest string that round-trips, exactly the digits ES6 picks.
100
+ digits_tuple, raw_exponent = Decimal(repr(abs(value))).as_tuple()[1:]
101
+ exponent = int(raw_exponent) # finite by construction; as_tuple types it loosely
102
+ digits = "".join(str(d) for d in digits_tuple)
103
+ stripped = digits.rstrip("0")
104
+ exponent += len(digits) - len(stripped)
105
+ # `Decimal.as_tuple()` never has leading zeros, and a nonzero value has a nonzero digit.
106
+ digits = stripped
107
+ k = len(digits)
108
+ n = k + exponent
109
+
110
+ if k <= n <= 21:
111
+ body = digits + "0" * (n - k)
112
+ elif 0 < n <= 21:
113
+ body = digits[:n] + "." + digits[n:]
114
+ elif -6 < n <= 0:
115
+ body = "0." + "0" * (-n) + digits
116
+ else:
117
+ mantissa = digits if k == 1 else digits[0] + "." + digits[1:]
118
+ e = n - 1
119
+ body = f"{mantissa}e{'+' if e > 0 else '-'}{abs(e)}"
120
+ return sign + body
121
+
122
+
123
+ def _canonical(value: Any, depth: int, out: list[str]) -> None:
124
+ if depth > MAX_DEPTH:
125
+ raise CanonicalizationError(f"nesting deeper than {MAX_DEPTH}")
126
+ if value is None:
127
+ out.append("null")
128
+ elif value is True:
129
+ out.append("true")
130
+ elif value is False:
131
+ out.append("false")
132
+ elif isinstance(value, int):
133
+ out.append(str(value))
134
+ elif isinstance(value, float):
135
+ out.append(_number(value))
136
+ elif isinstance(value, str):
137
+ out.append(_string(value))
138
+ elif isinstance(value, Mapping):
139
+ out.append("{")
140
+ first = True
141
+ for key in sorted(value, key=_utf16_key):
142
+ if not isinstance(key, str):
143
+ raise CanonicalizationError("object keys must be strings")
144
+ if not first:
145
+ out.append(",")
146
+ first = False
147
+ out.append(_string(key))
148
+ out.append(":")
149
+ _canonical(value[key], depth + 1, out)
150
+ out.append("}")
151
+ elif isinstance(value, Sequence) and not isinstance(value, bytes | bytearray):
152
+ out.append("[")
153
+ for index, item in enumerate(value):
154
+ if index:
155
+ out.append(",")
156
+ _canonical(item, depth + 1, out)
157
+ out.append("]")
158
+ else:
159
+ raise CanonicalizationError(f"{type(value).__name__} is not a JSON value")
160
+
161
+
162
+ def canonical_json(value: Any) -> bytes:
163
+ """The RFC 8785 canonical form of ``value``, as UTF-8 bytes."""
164
+ out: list[str] = []
165
+ _canonical(value, 0, out)
166
+ return "".join(out).encode("utf-8")
167
+
168
+
169
+ # -- binding selection: RFC 6901 --------------------------------------------------------
170
+
171
+
172
+ def _resolve_pointer(document: Any, pointer: str) -> tuple[bool, Any]:
173
+ if pointer == "":
174
+ return True, document
175
+ if not pointer.startswith("/"):
176
+ raise CanonicalizationError(f"invalid JSON pointer {pointer!r}")
177
+ node = document
178
+ for raw in pointer.split("/")[1:]:
179
+ token = raw.replace("~1", "/").replace("~0", "~")
180
+ if isinstance(node, Mapping):
181
+ if token not in node:
182
+ return False, None
183
+ node = node[token]
184
+ elif isinstance(node, Sequence) and not isinstance(node, str | bytes):
185
+ if not token.isdigit() or int(token) >= len(node):
186
+ return False, None
187
+ node = node[int(token)]
188
+ else:
189
+ return False, None
190
+ return True, node
191
+
192
+
193
+ def select_binding(params: Mapping[str, Any], binding: Sequence[str] | None) -> dict[str, Any]:
194
+ """The object a transaction token binds: the whole body, or ``{pointer: value}`` for
195
+ every pointer that resolves. Pointers that do not resolve are omitted, on both sides,
196
+ so "absent at both" matches and "present at one side only" mismatches."""
197
+ if binding is None:
198
+ return dict(params)
199
+ selected: dict[str, Any] = {}
200
+ for pointer in binding:
201
+ found, value = _resolve_pointer(params, pointer)
202
+ if found:
203
+ selected[pointer] = value
204
+ return selected
205
+
206
+
207
+ def binding_document(
208
+ target: str, params: Mapping[str, Any], binding: Sequence[str] | None
209
+ ) -> dict[str, Any]:
210
+ return {"target": target, "params": select_binding(params, binding)}
211
+
212
+
213
+ def binding_hash(target: str, params: Mapping[str, Any], binding: Sequence[str] | None) -> str:
214
+ """base64url, no padding, of SHA-256 over the canonical binding document."""
215
+ digest = hashlib.sha256(canonical_json(binding_document(target, params, binding))).digest()
216
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
217
+
218
+
219
+ __all__ = [
220
+ "CANON",
221
+ "HASH_ALG",
222
+ "MAX_DEPTH",
223
+ "CanonicalizationError",
224
+ "binding_document",
225
+ "binding_hash",
226
+ "canonical_json",
227
+ "select_binding",
228
+ ]
@@ -0,0 +1,158 @@
1
+ """Verifying a hop token at a resource, against the control plane's JWKS.
2
+
3
+ The verification order is the control plane's, re-implemented here so a
4
+ resource server needs only ``pyjwt[crypto]`` and a JWKS dict — never the control plane's
5
+ own modules. Every step is mandatory; any failure is a :class:`VerificationFailed` naming
6
+ its cause.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import hashlib
13
+ from collections.abc import Mapping
14
+ from dataclasses import dataclass
15
+ from datetime import UTC, datetime
16
+ from typing import Any
17
+
18
+ import jwt
19
+
20
+ ALGORITHM = "EdDSA"
21
+ AGENT_PREFIX = "agent://"
22
+ DEFAULT_LEEWAY = 60
23
+
24
+
25
+ class VerificationFailed(Exception):
26
+ """A resource-side check failed. ``reason`` is one of the contract's reason codes."""
27
+
28
+ def __init__(self, reason: str, detail: str = "") -> None:
29
+ super().__init__(f"{reason}: {detail}" if detail else reason)
30
+ self.reason = reason
31
+ self.detail = detail
32
+
33
+
34
+ def key_from_jwks(jwks: Mapping[str, Any], kid: str | None) -> Any:
35
+ """The public key named by ``kid`` in a JWKS dict, or ``None``."""
36
+ for entry in jwks.get("keys", []):
37
+ if entry.get("kid") == kid:
38
+ if entry.get("kty") != "OKP" or entry.get("crv") != "Ed25519":
39
+ return None
40
+ return jwt.PyJWK(dict(entry), algorithm=ALGORITHM).key
41
+ return None
42
+
43
+
44
+ def sha256_b64url(text: str) -> str:
45
+ return base64.urlsafe_b64encode(hashlib.sha256(text.encode()).digest()).rstrip(b"=").decode()
46
+
47
+
48
+ def _act_chain(act: Any, sub: str) -> tuple[list[str], int]:
49
+ """``([human, delegate..., current actor], depth)``; raises on a malformed chain."""
50
+ actors: list[str] = []
51
+ node = act
52
+ depth = 0
53
+ while node is not None:
54
+ if not isinstance(node, dict) or not isinstance(node.get("sub"), str) or not node["sub"]:
55
+ raise VerificationFailed("GRANT_INVALID", "malformed act chain")
56
+ if set(node) - {"sub", "act"}:
57
+ raise VerificationFailed("GRANT_INVALID", "unexpected keys in act link")
58
+ actors.append(node["sub"])
59
+ node = node.get("act")
60
+ depth += 1
61
+ if depth > 32:
62
+ raise VerificationFailed("GRANT_INVALID", "act chain too deep")
63
+ return [sub, *reversed(actors)], depth
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class VerifiedGrant:
68
+ raw: str
69
+ sub: str
70
+ aud: str
71
+ scope: str
72
+ session_id: str
73
+ action_id: str | None
74
+ hop: int
75
+ jti: str
76
+ act: dict[str, Any] | None
77
+ act_chain: list[str]
78
+ taint: str | None
79
+ expires_at: datetime
80
+
81
+ @property
82
+ def holder_agent(self) -> str | None:
83
+ """The agent acting on this grant: the outermost ``act.sub``. ``None`` for a root
84
+ grant, which is never valid at a resource."""
85
+ if self.act is None:
86
+ return None
87
+ return str(self.act["sub"]).removeprefix(AGENT_PREFIX)
88
+
89
+
90
+ def verify_grant(
91
+ token: str | None,
92
+ *,
93
+ issuer_jwks: Mapping[str, Any],
94
+ audience: str,
95
+ issuer: str = "agentic-auth",
96
+ leeway_seconds: int = DEFAULT_LEEWAY,
97
+ ) -> VerifiedGrant:
98
+ if not token:
99
+ raise VerificationFailed("GRANT_MISSING", "no bearer token")
100
+ try:
101
+ header = jwt.get_unverified_header(token)
102
+ except jwt.PyJWTError as exc:
103
+ raise VerificationFailed("GRANT_INVALID", f"malformed header: {exc}") from exc
104
+ if header.get("alg") != ALGORITHM:
105
+ raise VerificationFailed("GRANT_INVALID", f"unexpected alg {header.get('alg')!r}")
106
+ if header.get("typ") not in (None, "JWT"):
107
+ raise VerificationFailed("GRANT_INVALID", f"unexpected typ {header.get('typ')!r}")
108
+ key = key_from_jwks(issuer_jwks, header.get("kid"))
109
+ if key is None:
110
+ raise VerificationFailed("GRANT_INVALID", f"unknown issuer kid {header.get('kid')!r}")
111
+ try:
112
+ claims = jwt.decode(
113
+ token,
114
+ key,
115
+ algorithms=[ALGORITHM],
116
+ issuer=issuer,
117
+ audience=audience,
118
+ leeway=leeway_seconds,
119
+ options={"require": ["exp", "iat", "jti", "sub", "aud", "iss"]},
120
+ )
121
+ except jwt.InvalidAudienceError as exc:
122
+ raise VerificationFailed("GRANT_TARGET_MISMATCH", str(exc)) from exc
123
+ except jwt.ExpiredSignatureError as exc:
124
+ raise VerificationFailed("GRANT_EXPIRED", str(exc)) from exc
125
+ except jwt.PyJWTError as exc:
126
+ raise VerificationFailed("GRANT_INVALID", str(exc)) from exc
127
+
128
+ for claim in ("scope", "session_id", "policy_version", "hop"):
129
+ if claim not in claims:
130
+ raise VerificationFailed("GRANT_INVALID", f"missing claim {claim!r}")
131
+ act = claims.get("act")
132
+ chain, depth = _act_chain(act, claims["sub"])
133
+ if claims["hop"] != depth + 1:
134
+ raise VerificationFailed("GRANT_INVALID", "hop disagrees with act depth")
135
+ if act is None:
136
+ # The root grant names a scope, not a resource; it is never presentable here.
137
+ raise VerificationFailed("GRANT_INVALID", "a root grant is not valid at a resource")
138
+ taint = claims.get("taint")
139
+ if taint is not None and taint not in ("trusted_internal", "untrusted_external"):
140
+ raise VerificationFailed("GRANT_INVALID", f"unknown taint {taint!r}")
141
+ action_id = claims.get("action_id")
142
+ return VerifiedGrant(
143
+ raw=token,
144
+ sub=claims["sub"],
145
+ aud=claims["aud"] if isinstance(claims["aud"], str) else claims["aud"][0],
146
+ scope=claims["scope"],
147
+ session_id=str(claims["session_id"]),
148
+ action_id=str(action_id) if action_id is not None else None,
149
+ hop=int(claims["hop"]),
150
+ jti=claims["jti"],
151
+ act=act,
152
+ act_chain=chain,
153
+ taint=taint,
154
+ expires_at=datetime.fromtimestamp(claims["exp"], tz=UTC),
155
+ )
156
+
157
+
158
+ __all__ = ["VerificationFailed", "VerifiedGrant", "key_from_jwks", "sha256_b64url", "verify_grant"]
@@ -0,0 +1,111 @@
1
+ """Verifying the ``Agent-Identity`` assertion at a resource.
2
+
3
+ The assertion is a JWT the agent signed with a key in its CURRENT pinned trust anchor. It
4
+ proves who is calling and is bound to the exact grant string through ``grant_hash``, so an
5
+ assertion minted for one call cannot be paired with another grant. It authorizes nothing:
6
+ ``admit()`` still requires the grant.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from datetime import UTC, datetime
13
+
14
+ import jwt
15
+
16
+ from agentic_auth.verify.anchors import AnchorStore
17
+ from agentic_auth.verify.grants import (
18
+ AGENT_PREFIX,
19
+ ALGORITHM,
20
+ DEFAULT_LEEWAY,
21
+ VerificationFailed,
22
+ VerifiedGrant,
23
+ key_from_jwks,
24
+ sha256_b64url,
25
+ )
26
+
27
+ MAX_LIFETIME = 60
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class VerifiedIdentity:
32
+ raw: str
33
+ agent: str
34
+ trust_anchor_version: int | None
35
+ jti: str
36
+ expires_at: datetime
37
+
38
+
39
+ def verify_identity(
40
+ assertion: str | None,
41
+ *,
42
+ anchors: AnchorStore,
43
+ target: str,
44
+ grant: VerifiedGrant,
45
+ freshness_seconds: int,
46
+ leeway_seconds: int = DEFAULT_LEEWAY,
47
+ now: datetime | None = None,
48
+ ) -> VerifiedIdentity:
49
+ if not assertion:
50
+ raise VerificationFailed("IDENTITY_MISSING", "no Agent-Identity header")
51
+
52
+ as_of = anchors.as_of()
53
+ current = now or datetime.now(UTC)
54
+ if as_of is None:
55
+ raise VerificationFailed("IDENTITY_STALE", "anchor view was never bootstrapped")
56
+ if (current - as_of).total_seconds() > freshness_seconds:
57
+ raise VerificationFailed(
58
+ "IDENTITY_STALE", f"anchor view is older than {freshness_seconds}s"
59
+ )
60
+
61
+ holder = grant.holder_agent
62
+ if holder is None:
63
+ raise VerificationFailed("GRANT_INVALID", "grant names no acting agent")
64
+ anchor = anchors.current(holder)
65
+ if anchor is None or anchor.status in ("registered", "quarantined"):
66
+ raise VerificationFailed("IDENTITY_UNKNOWN_AGENT", f"no trust anchor for {holder!r}")
67
+ if anchor.revoked:
68
+ raise VerificationFailed("IDENTITY_REVOKED", f"{holder!r} is revoked")
69
+ if anchor.jwks is None:
70
+ raise VerificationFailed("IDENTITY_UNKNOWN_AGENT", f"no keys pinned for {holder!r}")
71
+
72
+ try:
73
+ header = jwt.get_unverified_header(assertion)
74
+ except jwt.PyJWTError as exc:
75
+ raise VerificationFailed("IDENTITY_INVALID", f"malformed header: {exc}") from exc
76
+ if header.get("alg") != ALGORITHM:
77
+ raise VerificationFailed("IDENTITY_INVALID", f"unexpected alg {header.get('alg')!r}")
78
+ key = key_from_jwks(anchor.jwks, header.get("kid"))
79
+ if key is None:
80
+ raise VerificationFailed(
81
+ "IDENTITY_INVALID", f"kid {header.get('kid')!r} is not in the pinned anchor"
82
+ )
83
+ try:
84
+ claims = jwt.decode(
85
+ assertion,
86
+ key,
87
+ algorithms=[ALGORITHM],
88
+ audience=target,
89
+ leeway=leeway_seconds,
90
+ options={"require": ["exp", "iat", "jti", "sub", "aud", "grant_hash"]},
91
+ )
92
+ except jwt.PyJWTError as exc:
93
+ raise VerificationFailed("IDENTITY_INVALID", str(exc)) from exc
94
+
95
+ if claims.get("sub") != f"{AGENT_PREFIX}{holder}" or claims.get("iss") != claims.get("sub"):
96
+ raise VerificationFailed("IDENTITY_INVALID", "assertion is for another agent")
97
+ if int(claims["exp"]) - int(claims["iat"]) > MAX_LIFETIME:
98
+ raise VerificationFailed("IDENTITY_INVALID", "assertion lifetime exceeds 60s")
99
+ if claims["grant_hash"] != sha256_b64url(grant.raw):
100
+ raise VerificationFailed("IDENTITY_INVALID", "assertion is bound to a different grant")
101
+
102
+ return VerifiedIdentity(
103
+ raw=assertion,
104
+ agent=holder,
105
+ trust_anchor_version=anchor.trust_anchor_version,
106
+ jti=claims["jti"],
107
+ expires_at=datetime.fromtimestamp(claims["exp"], tz=UTC),
108
+ )
109
+
110
+
111
+ __all__ = ["MAX_LIFETIME", "VerifiedIdentity", "verify_identity"]
@@ -0,0 +1,67 @@
1
+ """Single-use stores for transaction tokens at the resource side.
2
+
3
+ ``claim(key, ttl)`` is atomic: the first caller gets ``True``, everyone after ``False``. A
4
+ store that cannot answer raises, and the verifier refuses — a replay guard that quietly
5
+ degrades is worse than one that says so.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ import time
12
+ from typing import TYPE_CHECKING, Any, Protocol
13
+
14
+ if TYPE_CHECKING: # pragma: no cover - typing only; agentic_auth.verify must not import redis
15
+ from redis import Redis
16
+
17
+
18
+ class ReplayStoreUnavailable(RuntimeError):
19
+ """The store could not be consulted. Always a refusal."""
20
+
21
+
22
+ class ReplayStore(Protocol):
23
+ def claim(self, key: str, ttl_seconds: int) -> bool:
24
+ """``True`` if this is the first claim of ``key``; raises ``ReplayStoreUnavailable``."""
25
+ ...
26
+
27
+
28
+ class InMemoryReplay:
29
+ """Single-process store with expiry. Fine for one resource server instance; use
30
+ :class:`RedisReplay` behind more than one."""
31
+
32
+ def __init__(self, clock: Any = time.monotonic) -> None:
33
+ self._seen: dict[str, float] = {}
34
+ self._lock = threading.Lock()
35
+ self._clock = clock
36
+
37
+ def claim(self, key: str, ttl_seconds: int) -> bool:
38
+ now = self._clock()
39
+ with self._lock:
40
+ expired = [k for k, until in self._seen.items() if until <= now]
41
+ for k in expired:
42
+ del self._seen[k]
43
+ if key in self._seen:
44
+ return False
45
+ self._seen[key] = now + max(ttl_seconds, 1)
46
+ return True
47
+
48
+
49
+ class RedisReplay:
50
+ """``SET NX EX`` on a synchronous redis client (any object with a compatible ``set``)."""
51
+
52
+ def __init__(self, client: Redis | Any) -> None:
53
+ self._client = client
54
+
55
+ def claim(self, key: str, ttl_seconds: int) -> bool:
56
+ try:
57
+ claimed = self._client.set(key, "1", ex=max(ttl_seconds, 1), nx=True)
58
+ except Exception as exc:
59
+ raise ReplayStoreUnavailable(f"replay store unreachable: {exc}") from exc
60
+ return bool(claimed)
61
+
62
+
63
+ def txn_key(jti: str) -> str:
64
+ return f"txn:{jti}"
65
+
66
+
67
+ __all__ = ["InMemoryReplay", "RedisReplay", "ReplayStore", "ReplayStoreUnavailable", "txn_key"]