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.
- agentic_auth/__init__.py +8 -0
- agentic_auth/_extras.py +24 -0
- agentic_auth/api/__init__.py +0 -0
- agentic_auth/api/deps.py +112 -0
- agentic_auth/api/errors.py +51 -0
- agentic_auth/api/responses.py +38 -0
- agentic_auth/api/service_deps.py +113 -0
- agentic_auth/api/v1/__init__.py +0 -0
- agentic_auth/api/v1/agents.py +88 -0
- agentic_auth/api/v1/audit.py +67 -0
- agentic_auth/api/v1/authorize.py +439 -0
- agentic_auth/api/v1/consent.py +21 -0
- agentic_auth/api/v1/decisions.py +43 -0
- agentic_auth/api/v1/enrollment.py +48 -0
- agentic_auth/api/v1/identity.py +97 -0
- agentic_auth/api/v1/jwks.py +21 -0
- agentic_auth/api/v1/manifests.py +68 -0
- agentic_auth/api/v1/scopes.py +22 -0
- agentic_auth/api/v1/token.py +203 -0
- agentic_auth/api/v1/transaction.py +94 -0
- agentic_auth/boundary/__init__.py +26 -0
- agentic_auth/boundary/guarantee.py +96 -0
- agentic_auth/cli/__init__.py +27 -0
- agentic_auth/cli/audit.py +130 -0
- agentic_auth/cli/drift.py +164 -0
- agentic_auth/cli/drift_render.py +148 -0
- agentic_auth/cli/identity.py +63 -0
- agentic_auth/cli/manifest.py +275 -0
- agentic_auth/config.py +182 -0
- agentic_auth/db.py +49 -0
- agentic_auth/embedded/__init__.py +427 -0
- agentic_auth/embedded/_schema.py +8 -0
- agentic_auth/embedded/_transport.py +39 -0
- agentic_auth/embedded/capabilities.py +34 -0
- agentic_auth/embedded/export.py +86 -0
- agentic_auth/embedded/idp.py +78 -0
- agentic_auth/embedded/store.py +240 -0
- agentic_auth/errors.py +145 -0
- agentic_auth/main.py +141 -0
- agentic_auth/models/__init__.py +70 -0
- agentic_auth/models/agent.py +58 -0
- agentic_auth/models/audit_decision.py +199 -0
- agentic_auth/models/compiled_policy.py +28 -0
- agentic_auth/models/manifest.py +96 -0
- agentic_auth/models/reconciliation_report.py +27 -0
- agentic_auth/models/sandbox_run.py +93 -0
- agentic_auth/models/session.py +63 -0
- agentic_auth/models/step_up_grant.py +106 -0
- agentic_auth/models/transaction_token.py +73 -0
- agentic_auth/models/trust_anchor.py +59 -0
- agentic_auth/models/types.py +95 -0
- agentic_auth/observability/__init__.py +370 -0
- agentic_auth/observability/config.py +137 -0
- agentic_auth/observability/context.py +128 -0
- agentic_auth/observability/ids.py +122 -0
- agentic_auth/observability/logs.py +191 -0
- agentic_auth/observability/pep.py +169 -0
- agentic_auth/observability/spans.py +225 -0
- agentic_auth/observability/surface.py +286 -0
- agentic_auth/observability/tracing.py +167 -0
- agentic_auth/redis.py +27 -0
- agentic_auth/repositories/__init__.py +0 -0
- agentic_auth/repositories/agents.py +96 -0
- agentic_auth/repositories/audit_decisions.py +152 -0
- agentic_auth/repositories/compiled_policies.py +72 -0
- agentic_auth/repositories/manifests.py +149 -0
- agentic_auth/repositories/reconciliation_reports.py +40 -0
- agentic_auth/repositories/sessions.py +41 -0
- agentic_auth/repositories/transaction_tokens.py +60 -0
- agentic_auth/repositories/trust_anchors.py +150 -0
- agentic_auth/runtime.py +81 -0
- agentic_auth/schemas/__init__.py +0 -0
- agentic_auth/schemas/agent.py +58 -0
- agentic_auth/schemas/audit.py +207 -0
- agentic_auth/schemas/authorize.py +205 -0
- agentic_auth/schemas/common.py +40 -0
- agentic_auth/schemas/consent.py +74 -0
- agentic_auth/schemas/dag.py +39 -0
- agentic_auth/schemas/edge_trace.py +166 -0
- agentic_auth/schemas/identity.py +152 -0
- agentic_auth/schemas/manifest.py +117 -0
- agentic_auth/schemas/manifest_api.py +38 -0
- agentic_auth/schemas/reconciliation.py +49 -0
- agentic_auth/schemas/token.py +122 -0
- agentic_auth/schemas/transaction.py +28 -0
- agentic_auth/sdk/__init__.py +114 -0
- agentic_auth/sdk/client.py +677 -0
- agentic_auth/sdk/context.py +95 -0
- agentic_auth/sdk/drift.py +118 -0
- agentic_auth/sdk/errors.py +147 -0
- agentic_auth/sdk/identity.py +162 -0
- agentic_auth/sdk/planes.py +362 -0
- agentic_auth/sdk/provenance.py +63 -0
- agentic_auth/services/__init__.py +0 -0
- agentic_auth/services/anchors.py +81 -0
- agentic_auth/services/audit.py +222 -0
- agentic_auth/services/audit_chain.py +144 -0
- agentic_auth/services/audit_cursor.py +55 -0
- agentic_auth/services/catalog_service.py +58 -0
- agentic_auth/services/chain_query.py +152 -0
- agentic_auth/services/dag_compiler.py +199 -0
- agentic_auth/services/decision_cache.py +123 -0
- agentic_auth/services/decision_history.py +71 -0
- agentic_auth/services/discovery.py +95 -0
- agentic_auth/services/drift.py +330 -0
- agentic_auth/services/edge_rules.py +62 -0
- agentic_auth/services/edge_trace.py +198 -0
- agentic_auth/services/enrollment.py +310 -0
- agentic_auth/services/enrollment_rules.py +80 -0
- agentic_auth/services/manifest_service.py +166 -0
- agentic_auth/services/metrics.py +419 -0
- agentic_auth/services/pdp.py +312 -0
- agentic_auth/services/policy_loader.py +255 -0
- agentic_auth/services/principal.py +143 -0
- agentic_auth/services/reconciler.py +119 -0
- agentic_auth/services/revocation.py +149 -0
- agentic_auth/services/sessions.py +231 -0
- agentic_auth/services/taint.py +204 -0
- agentic_auth/services/tokens/__init__.py +11 -0
- agentic_auth/services/tokens/act_chain.py +76 -0
- agentic_auth/services/tokens/exchange.py +319 -0
- agentic_auth/services/tokens/jwt_profile.py +362 -0
- agentic_auth/services/tokens/keys.py +117 -0
- agentic_auth/services/tokens/profile.py +167 -0
- agentic_auth/services/tokens/replay.py +53 -0
- agentic_auth/services/transactions.py +172 -0
- agentic_auth/sidecar/__init__.py +7 -0
- agentic_auth/sidecar/__main__.py +66 -0
- agentic_auth/sidecar/app.py +349 -0
- agentic_auth/sidecar/config.py +253 -0
- agentic_auth/sidecar/deny.py +108 -0
- agentic_auth/sidecar/enforce.py +640 -0
- agentic_auth/sidecar/identity.py +37 -0
- agentic_auth/verify/__init__.py +208 -0
- agentic_auth/verify/admit.py +131 -0
- agentic_auth/verify/anchors.py +250 -0
- agentic_auth/verify/canonical.py +228 -0
- agentic_auth/verify/grants.py +158 -0
- agentic_auth/verify/identity.py +111 -0
- agentic_auth/verify/replay.py +67 -0
- agentic_auth/verify/transaction.py +164 -0
- authzai-0.2.0.dist-info/METADATA +276 -0
- authzai-0.2.0.dist-info/RECORD +148 -0
- authzai-0.2.0.dist-info/WHEEL +5 -0
- authzai-0.2.0.dist-info/entry_points.txt +5 -0
- authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
- authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
- authzai-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Provenance taint — derived by the control plane, never trusted from the agent.
|
|
2
|
+
|
|
3
|
+
The PDP decides every call, so it knows when a caller reaches for a source its pinned
|
|
4
|
+
manifest does not trust. That moment marks the caller's context — and every ancestor
|
|
5
|
+
context, whose owners will consume the result on the way back — in a per-session Redis
|
|
6
|
+
HASH. The effective taint of a decision is the maximum of the presented token's signed
|
|
7
|
+
``taint`` claim, the agent-reported label (additive only), and that mark
|
|
8
|
+
(https://authzai.dev/explanation/the-taint-and-provenance-model).
|
|
9
|
+
|
|
10
|
+
The pure functions here take a :class:`PolicyIndex` and plain values; :class:`TaintStore`
|
|
11
|
+
is the only I/O.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import json
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Iterable, Mapping
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from redis.asyncio import Redis
|
|
24
|
+
|
|
25
|
+
from agentic_auth.schemas.authorize import Taint
|
|
26
|
+
from agentic_auth.services.policy_loader import PolicyIndex
|
|
27
|
+
|
|
28
|
+
SENTINEL = "*"
|
|
29
|
+
"""Marks the whole session: an ancestor's ``jti`` was unknown (a chain written by Phase 3),
|
|
30
|
+
so the fail-closed reading is that every context in the session may have consumed it."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TaintStoreUnavailable(RuntimeError):
|
|
34
|
+
"""The taint set could not be read or written. The caller decides: a protected target
|
|
35
|
+
is refused ``PDP_UNAVAILABLE``; an unprotected one proceeds with taint unknown."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# -- pure ------------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def classify_source(policy: PolicyIndex, agent: str, target: str) -> Taint:
|
|
42
|
+
"""What a result from ``target`` is worth to ``agent``: trusted only if a glob says so."""
|
|
43
|
+
return (
|
|
44
|
+
Taint.TRUSTED_INTERNAL
|
|
45
|
+
if policy.is_trusted_source(agent, target)
|
|
46
|
+
else Taint.UNTRUSTED_EXTERNAL
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_protected(policy: PolicyIndex, agent: str, target: str, data_class: str) -> bool:
|
|
51
|
+
return policy.is_protected(agent, target, data_class)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def effective_taint(token_taint: Taint | None, request_taint: Taint | None, marked: bool) -> Taint:
|
|
55
|
+
"""``max`` over the three inputs. Never lowers: a missing input is trusted, an untrusted
|
|
56
|
+
input anywhere wins."""
|
|
57
|
+
if (
|
|
58
|
+
token_taint is Taint.UNTRUSTED_EXTERNAL
|
|
59
|
+
or request_taint is Taint.UNTRUSTED_EXTERNAL
|
|
60
|
+
or marked
|
|
61
|
+
):
|
|
62
|
+
return Taint.UNTRUSTED_EXTERNAL
|
|
63
|
+
return Taint.TRUSTED_INTERNAL
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def ancestors_of(parent_chain: Iterable[Mapping[str, Any]] | None, own_jti: str) -> set[str]:
|
|
67
|
+
"""Every context that will consume this call's result: this one and each ancestor hop's
|
|
68
|
+
``subject_jti``. An ancestor written before Phase 4 has none, and yields the sentinel."""
|
|
69
|
+
contexts = {own_jti}
|
|
70
|
+
for entry in parent_chain or ():
|
|
71
|
+
jti = entry.get("subject_jti")
|
|
72
|
+
contexts.add(jti if isinstance(jti, str) and jti else SENTINEL)
|
|
73
|
+
return contexts
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class Mark:
|
|
78
|
+
"""One recorded mark: which context, the source that introduced the taint, the decision
|
|
79
|
+
whose allow introduced it, and when.
|
|
80
|
+
|
|
81
|
+
The action id matters once: the exchange that spends THAT decision must not see the mark
|
|
82
|
+
its own allow created (the result is not consumed until the call is made), while every
|
|
83
|
+
later decision in the context must. Marks are stored one per ``(context, action)`` so an
|
|
84
|
+
exclusion never hides a mark some other decision left.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
context: str
|
|
88
|
+
source: str
|
|
89
|
+
action_id: str | None
|
|
90
|
+
ts: float
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def field(self) -> str:
|
|
94
|
+
return f"{self.context}|{self.action_id or '-'}"
|
|
95
|
+
|
|
96
|
+
def encode(self) -> str:
|
|
97
|
+
return json.dumps({"source": self.source, "ts": self.ts}, separators=(",", ":"))
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def decode(field: str, raw: str) -> Mark:
|
|
101
|
+
context, _, action = field.partition("|")
|
|
102
|
+
action_id = action if action and action != "-" else None
|
|
103
|
+
try:
|
|
104
|
+
data = json.loads(raw)
|
|
105
|
+
return Mark(context, str(data["source"]), action_id, float(data.get("ts", 0.0)))
|
|
106
|
+
except (ValueError, KeyError, TypeError):
|
|
107
|
+
return Mark(context, str(raw), action_id, 0.0) # a pre-JSON value: source alone
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class Marked:
|
|
112
|
+
"""What the store knows about one presented context."""
|
|
113
|
+
|
|
114
|
+
tainted: bool
|
|
115
|
+
source: str | None
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def of(marks: Iterable[Mark], jti: str, *, exclude_action_id: str | None = None) -> Marked:
|
|
119
|
+
relevant = [
|
|
120
|
+
m
|
|
121
|
+
for m in marks
|
|
122
|
+
if m.context in (jti, SENTINEL)
|
|
123
|
+
and not (exclude_action_id is not None and m.action_id == exclude_action_id)
|
|
124
|
+
]
|
|
125
|
+
if not relevant:
|
|
126
|
+
return Marked(False, None)
|
|
127
|
+
# The source named is the one that introduced the taint: the earliest exact mark,
|
|
128
|
+
# or the earliest sentinel when nothing exact exists.
|
|
129
|
+
exact = [m for m in relevant if m.context == jti]
|
|
130
|
+
chosen = min(exact or relevant, key=lambda m: m.ts)
|
|
131
|
+
return Marked(True, chosen.source)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# -- the store -----------------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def taint_key(session_id: str) -> str:
|
|
138
|
+
return f"taint:{session_id}"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class TaintStore:
|
|
142
|
+
def __init__(self, redis: Redis | None) -> None:
|
|
143
|
+
self._redis = redis
|
|
144
|
+
|
|
145
|
+
async def marked(self, session_id: str) -> list[Mark]:
|
|
146
|
+
"""Every mark in the session."""
|
|
147
|
+
if self._redis is None:
|
|
148
|
+
raise TaintStoreUnavailable("no taint store configured")
|
|
149
|
+
try:
|
|
150
|
+
raw = await self._redis.hgetall(taint_key(session_id))
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
raise TaintStoreUnavailable(f"taint store unreachable: {exc}") from exc
|
|
153
|
+
out: list[Mark] = []
|
|
154
|
+
for k, v in (raw or {}).items():
|
|
155
|
+
field = k.decode() if isinstance(k, bytes) else k
|
|
156
|
+
value = v.decode() if isinstance(v, bytes) else v
|
|
157
|
+
out.append(Mark.decode(field, value))
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
async def mark(
|
|
161
|
+
self,
|
|
162
|
+
session_id: str,
|
|
163
|
+
contexts: Iterable[str],
|
|
164
|
+
source: str,
|
|
165
|
+
*,
|
|
166
|
+
action_id: str | None,
|
|
167
|
+
ttl_seconds: int,
|
|
168
|
+
) -> None:
|
|
169
|
+
"""Mark every context in ``contexts`` as having consumed ``source`` through the
|
|
170
|
+
decision ``action_id``. One field per (context, action); ``HSETNX`` keeps the first
|
|
171
|
+
timestamp if the same decision marks twice."""
|
|
172
|
+
if self._redis is None:
|
|
173
|
+
raise TaintStoreUnavailable("no taint store configured")
|
|
174
|
+
key = taint_key(session_id)
|
|
175
|
+
now = time.time()
|
|
176
|
+
try:
|
|
177
|
+
pipe = self._redis.pipeline(transaction=True)
|
|
178
|
+
for ctx in contexts:
|
|
179
|
+
mark = Mark(ctx, source, action_id, now)
|
|
180
|
+
pipe.hsetnx(key, mark.field, mark.encode())
|
|
181
|
+
pipe.expire(key, max(int(ttl_seconds), 1))
|
|
182
|
+
await pipe.execute()
|
|
183
|
+
except Exception as exc:
|
|
184
|
+
raise TaintStoreUnavailable(f"taint store unreachable: {exc}") from exc
|
|
185
|
+
|
|
186
|
+
async def clear(self, session_id: str) -> None: # tests only
|
|
187
|
+
if self._redis is None:
|
|
188
|
+
return
|
|
189
|
+
with contextlib.suppress(Exception):
|
|
190
|
+
await self._redis.delete(taint_key(session_id))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
__all__ = [
|
|
194
|
+
"SENTINEL",
|
|
195
|
+
"Mark",
|
|
196
|
+
"Marked",
|
|
197
|
+
"TaintStore",
|
|
198
|
+
"TaintStoreUnavailable",
|
|
199
|
+
"ancestors_of",
|
|
200
|
+
"classify_source",
|
|
201
|
+
"effective_taint",
|
|
202
|
+
"is_protected",
|
|
203
|
+
"taint_key",
|
|
204
|
+
]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Token issuance and verification.
|
|
2
|
+
|
|
3
|
+
Everything about the token format lives behind :class:`TokenProfile`. No route, PDP, or
|
|
4
|
+
sidecar module imports ``jwt`` directly — the RFC surface here is still moving, and
|
|
5
|
+
Phase 4 (transaction tokens) and Phase 5 (external issuer) both replace the
|
|
6
|
+
implementation without touching a caller.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from agentic_auth.services.tokens.profile import TokenProfile, VerifiedToken
|
|
10
|
+
|
|
11
|
+
__all__ = ["TokenProfile", "VerifiedToken"]
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The nested ``act`` claim — the only module that parses it.
|
|
2
|
+
|
|
3
|
+
Per RFC 8693 §4.1 the chain nests inside-out: the outermost ``act`` is the current actor
|
|
4
|
+
and the innermost is the first delegate. ``sub`` never moves — it stays the consenting
|
|
5
|
+
human at every depth.
|
|
6
|
+
|
|
7
|
+
Delegation depth is read from here and nowhere else. A caller-supplied hop count is a
|
|
8
|
+
number the attacker controls; ``act`` sits inside a signed envelope, so under-reporting
|
|
9
|
+
depth requires forging a signature.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
MAX_DEPTH = 32 # a chain deeper than any legal hop budget is malformed, not slow
|
|
17
|
+
|
|
18
|
+
# `mutmut run` leaves 5 equivalent mutants in `depth()`, all inside the `extra = ...`
|
|
19
|
+
# expression that only builds the text of a MalformedActChain message. The guard above it
|
|
20
|
+
# — `set(node) - {"sub", "act"}` — is the behaviour, and mutating it is killed. Every
|
|
21
|
+
# mutant that changes whether a chain is rejected, or the depth reported, is killed.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MalformedActChain(ValueError):
|
|
25
|
+
"""The presented ``act`` claim is not a well-formed delegation chain."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def nest(act: dict[str, Any] | None, agent: str) -> dict[str, Any]:
|
|
29
|
+
"""Add ``agent`` as the new outermost actor."""
|
|
30
|
+
if not agent:
|
|
31
|
+
raise MalformedActChain("actor must be a non-empty identifier")
|
|
32
|
+
return {"sub": agent} if act is None else {"sub": agent, "act": act}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def depth(act: dict[str, Any] | None) -> int:
|
|
36
|
+
"""Nesting count. Absent -> 0 (the root grant), {sub} -> 1, {sub, act:{sub}} -> 2."""
|
|
37
|
+
n = 0
|
|
38
|
+
node = act
|
|
39
|
+
while node is not None:
|
|
40
|
+
if not isinstance(node, dict):
|
|
41
|
+
raise MalformedActChain(f"act link is {type(node).__name__}, expected object")
|
|
42
|
+
sub = node.get("sub")
|
|
43
|
+
if not isinstance(sub, str) or not sub:
|
|
44
|
+
raise MalformedActChain("act link is missing a non-empty 'sub'")
|
|
45
|
+
if set(node) - {"sub", "act"}:
|
|
46
|
+
extra = sorted(set(node) - {"sub", "act"})
|
|
47
|
+
raise MalformedActChain(f"unexpected keys in act link: {extra}")
|
|
48
|
+
n += 1
|
|
49
|
+
if n > MAX_DEPTH:
|
|
50
|
+
raise MalformedActChain(f"act chain deeper than {MAX_DEPTH}")
|
|
51
|
+
node = node.get("act")
|
|
52
|
+
return n
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def walk(act: dict[str, Any] | None, sub: str) -> list[str]:
|
|
56
|
+
"""The chain in delegation order: ``[human, first delegate, ..., current actor]``."""
|
|
57
|
+
actors: list[str] = []
|
|
58
|
+
node = act
|
|
59
|
+
while node is not None:
|
|
60
|
+
depth(node) # validate this link before trusting it
|
|
61
|
+
actors.append(node["sub"])
|
|
62
|
+
node = node.get("act")
|
|
63
|
+
return [sub, *reversed(actors)]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def hop_of(act: dict[str, Any] | None) -> int:
|
|
67
|
+
"""The hop a token carrying this chain was issued for. Root grant is hop 1."""
|
|
68
|
+
return depth(act) + 1
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def current_actor(act: dict[str, Any] | None, sub: str) -> str:
|
|
72
|
+
"""Who is presenting this token: the outermost actor, or the human at the root."""
|
|
73
|
+
if act is None:
|
|
74
|
+
return sub
|
|
75
|
+
depth(act)
|
|
76
|
+
return act["sub"]
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""RFC 8693 token exchange — the only place narrowed authority is minted.
|
|
2
|
+
|
|
3
|
+
The service re-runs the policy decision rather than trusting that ``/v1/authorize`` was
|
|
4
|
+
called first. That is not belt-and-braces: an exchange endpoint that issues on request
|
|
5
|
+
would hand out narrowed tokens for hops the PDP refused, which is exactly the containment
|
|
6
|
+
failure the phase exists to prevent. With the decision cache warm the re-check is a cache
|
|
7
|
+
hit, so honesty here costs almost nothing.
|
|
8
|
+
|
|
9
|
+
From Phase 3 it also refuses to mint unless the allow it is spending is **recorded**: the
|
|
10
|
+
``action_id`` must name a committed allow row for exactly this session, hop, target, data
|
|
11
|
+
class, and subject token. This request can only see committed rows, so an allow whose audit
|
|
12
|
+
commit never landed cannot be turned into a token — whatever the route or the sidecar did.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import uuid
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import UTC, datetime
|
|
20
|
+
|
|
21
|
+
from redis.asyncio import Redis
|
|
22
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
23
|
+
|
|
24
|
+
from agentic_auth.boundary.guarantee import Guarantee
|
|
25
|
+
from agentic_auth.config import get_settings
|
|
26
|
+
from agentic_auth.repositories import audit_decisions as audit_repo
|
|
27
|
+
from agentic_auth.schemas.authorize import AuthorizeRequest, DenyReason, Taint
|
|
28
|
+
from agentic_auth.schemas.token import TokenExchangeRequest, TokenExchangeResponse
|
|
29
|
+
from agentic_auth.services import policy_loader
|
|
30
|
+
from agentic_auth.services.anchors import AnchorCache
|
|
31
|
+
from agentic_auth.services.metrics import get_metrics
|
|
32
|
+
from agentic_auth.services.pdp import Decision, decide
|
|
33
|
+
from agentic_auth.services.revocation import RevocationService
|
|
34
|
+
from agentic_auth.services.sessions import SessionService
|
|
35
|
+
from agentic_auth.services.taint import Marked, TaintStore, TaintStoreUnavailable, effective_taint
|
|
36
|
+
from agentic_auth.services.tokens import replay
|
|
37
|
+
from agentic_auth.services.tokens.act_chain import nest
|
|
38
|
+
from agentic_auth.services.tokens.jwt_profile import LEEWAY_SECONDS, TokenVerificationError
|
|
39
|
+
from agentic_auth.services.tokens.profile import TokenProfile, VerifiedToken
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ExchangeRefused(Exception):
|
|
43
|
+
"""The exchange cannot proceed. ``oauth_error`` is the RFC 6749 §5.2 code."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, oauth_error: str, description: str) -> None:
|
|
46
|
+
super().__init__(description)
|
|
47
|
+
self.oauth_error = oauth_error
|
|
48
|
+
self.description = description
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class ExchangeDenied(Exception):
|
|
53
|
+
"""Policy refused this hop, so no token is issued.
|
|
54
|
+
|
|
55
|
+
Carries everything the decision record needs — including the verified subject token,
|
|
56
|
+
which the record's chain is built from — so the route does not have to re-derive
|
|
57
|
+
context from a half-processed request.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
decision: Decision
|
|
61
|
+
target: str
|
|
62
|
+
session_id: str
|
|
63
|
+
caller: str
|
|
64
|
+
data_class: str
|
|
65
|
+
policy_version: int
|
|
66
|
+
act_chain: list[str]
|
|
67
|
+
# Phase 4: the effective taint and its source, for the record.
|
|
68
|
+
taint_source: str | None = None
|
|
69
|
+
# `repr=False`: a VerifiedToken holds the raw JWT, and a dataclass repr would put it in
|
|
70
|
+
# any traceback or `logger.exception` that renders this exception. The audit record only
|
|
71
|
+
# ever reads jti/holder/act_chain/action_id off it.
|
|
72
|
+
token: VerifiedToken = field(repr=False, kw_only=True)
|
|
73
|
+
|
|
74
|
+
def __str__(self) -> str:
|
|
75
|
+
return self.decision.message or "hop denied"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _normalized(session_id: str) -> str:
|
|
79
|
+
try:
|
|
80
|
+
return str(uuid.UUID(session_id))
|
|
81
|
+
except (ValueError, TypeError, AttributeError):
|
|
82
|
+
return session_id
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class TokenExchangeService:
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
tokens: TokenProfile,
|
|
89
|
+
sessions: SessionService,
|
|
90
|
+
*,
|
|
91
|
+
ttl_seconds: int | None = None,
|
|
92
|
+
) -> None:
|
|
93
|
+
self._tokens = tokens
|
|
94
|
+
self._sessions = sessions
|
|
95
|
+
self._ttl = ttl_seconds or get_settings().hop_token_ttl_seconds
|
|
96
|
+
|
|
97
|
+
async def exchange(
|
|
98
|
+
self,
|
|
99
|
+
db: AsyncSession,
|
|
100
|
+
redis: Redis | None,
|
|
101
|
+
body: TokenExchangeRequest,
|
|
102
|
+
*,
|
|
103
|
+
action_id: uuid.UUID,
|
|
104
|
+
taint: Taint | None = None,
|
|
105
|
+
) -> tuple[TokenExchangeResponse, Decision, VerifiedToken]:
|
|
106
|
+
subject = self._verify_subject(body.subject_token)
|
|
107
|
+
|
|
108
|
+
holder = subject.holder
|
|
109
|
+
if holder is None:
|
|
110
|
+
raise ExchangeRefused(
|
|
111
|
+
"invalid_grant",
|
|
112
|
+
f"subject token was issued for tool call {subject.aud!r} and cannot be exchanged",
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
# Before the re-decision and before the jti is spent, so an exchange refused here
|
|
116
|
+
# costs the caller nothing: the same subject token still works with the right id.
|
|
117
|
+
await self._require_recorded_allow(db, action_id, subject, body)
|
|
118
|
+
|
|
119
|
+
session = await self._sessions.get(db, redis, subject.session_id)
|
|
120
|
+
policy = await policy_loader.load(db, redis, session.scope, session.policy_version)
|
|
121
|
+
settings = get_settings()
|
|
122
|
+
|
|
123
|
+
# Phase 4: with identity on, a bearer grant alone buys nothing.
|
|
124
|
+
# The holder must prove possession of its enrolled key over THIS subject token.
|
|
125
|
+
not_enrolled = False
|
|
126
|
+
if settings.identity_required:
|
|
127
|
+
not_enrolled = not await self._require_possession(db, redis, holder, body, subject)
|
|
128
|
+
|
|
129
|
+
# Phase 4: re-decide under the same effective taint the PDP used, read fresh — a
|
|
130
|
+
# context marked between authorize and exchange is refused here.
|
|
131
|
+
protected = policy.is_protected(holder, body.resource, body.scope)
|
|
132
|
+
try:
|
|
133
|
+
# The allow being spent may itself have marked this context (its target is an
|
|
134
|
+
# untrusted source). That mark is for the NEXT decision, not this exchange.
|
|
135
|
+
marked = Marked.of(
|
|
136
|
+
await TaintStore(redis).marked(subject.session_id),
|
|
137
|
+
subject.jti,
|
|
138
|
+
exclude_action_id=str(action_id),
|
|
139
|
+
)
|
|
140
|
+
except TaintStoreUnavailable:
|
|
141
|
+
if protected:
|
|
142
|
+
raise ExchangeRefused(
|
|
143
|
+
"invalid_grant", "taint state could not be read for a protected target"
|
|
144
|
+
) from None
|
|
145
|
+
marked = Marked(False, None)
|
|
146
|
+
effective = effective_taint(subject.taint, taint, marked.tainted)
|
|
147
|
+
taint_source = marked.source if marked.tainted else None
|
|
148
|
+
|
|
149
|
+
# This is an internal re-decision, not a report from an enforcement point: the
|
|
150
|
+
# exchange re-checks the hop it is about to narrow for. `guarantee` is required on
|
|
151
|
+
# the schema so no PEP can omit it, but nothing here is recorded under
|
|
152
|
+
# it — this request never reaches `_record()`. FULL is the honest value for a
|
|
153
|
+
# check the control plane performs on itself.
|
|
154
|
+
request = AuthorizeRequest(
|
|
155
|
+
session_id=subject.session_id,
|
|
156
|
+
caller=subject.presenter,
|
|
157
|
+
target=body.resource,
|
|
158
|
+
data_class=body.scope,
|
|
159
|
+
taint=taint,
|
|
160
|
+
guarantee=Guarantee.FULL,
|
|
161
|
+
)
|
|
162
|
+
revoked = await RevocationService(AnchorCache(redis)).revoked_set(db, redis)
|
|
163
|
+
decision = decide(
|
|
164
|
+
policy,
|
|
165
|
+
request,
|
|
166
|
+
subject,
|
|
167
|
+
consented_scope=session.scope,
|
|
168
|
+
transaction_tokens_enabled=settings.transaction_tokens_enabled,
|
|
169
|
+
taint=effective,
|
|
170
|
+
taint_enforced=settings.taint_enforcement_enabled,
|
|
171
|
+
revoked=revoked,
|
|
172
|
+
)
|
|
173
|
+
if decision.reason is DenyReason.AGENT_REVOKED:
|
|
174
|
+
get_metrics().revoked_hop_refusals.labels(where="exchange").inc()
|
|
175
|
+
if not_enrolled:
|
|
176
|
+
# Recorded like any policy refusal: predictable from state, not an outage.
|
|
177
|
+
decision = Decision(
|
|
178
|
+
outcome="deny",
|
|
179
|
+
hop=decision.hop,
|
|
180
|
+
reason=DenyReason.AGENT_NOT_ENROLLED,
|
|
181
|
+
message=f"agent {holder!r} has no live trust anchor; enroll it first",
|
|
182
|
+
privileged=decision.privileged,
|
|
183
|
+
taint=decision.taint,
|
|
184
|
+
)
|
|
185
|
+
get_metrics().exchange_pop_failures.labels(cause="not_enrolled").inc()
|
|
186
|
+
if not decision.allowed:
|
|
187
|
+
# A refused hop yields no token, ever.
|
|
188
|
+
raise ExchangeDenied(
|
|
189
|
+
decision=decision,
|
|
190
|
+
target=body.resource,
|
|
191
|
+
session_id=subject.session_id,
|
|
192
|
+
caller=subject.presenter,
|
|
193
|
+
data_class=body.scope,
|
|
194
|
+
policy_version=session.policy_version,
|
|
195
|
+
act_chain=subject.act_chain,
|
|
196
|
+
taint_source=taint_source,
|
|
197
|
+
token=subject,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
if body.audience is not None and body.audience != body.resource:
|
|
201
|
+
raise ExchangeRefused(
|
|
202
|
+
"invalid_target",
|
|
203
|
+
f"audience {body.audience!r} does not match resource {body.resource!r}",
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Spend the DECISION. After this point the same recorded
|
|
207
|
+
# allow cannot buy a second token; the same subject token can still be exchanged
|
|
208
|
+
# for OTHER recorded allows until it expires, which is what lets an agent make more
|
|
209
|
+
# than one call at a hop. Deliberately the last check before minting.
|
|
210
|
+
#
|
|
211
|
+
# The guard must outlive the window in which `verify()` will still ACCEPT the
|
|
212
|
+
# subject token, not merely its nominal lifetime. `verify()` allows LEEWAY_SECONDS
|
|
213
|
+
# past `exp`, so a guard sized to `hop_token_ttl_seconds` from the moment of
|
|
214
|
+
# spending always dies first and reopens a replay window — with the shipped
|
|
215
|
+
# defaults (60s TTL, 60s leeway) that window is up to 59 seconds wide.
|
|
216
|
+
remaining = (subject.expires_at - datetime.now(UTC)).total_seconds()
|
|
217
|
+
guard_ttl = int(remaining) + LEEWAY_SECONDS + 1
|
|
218
|
+
await replay.consume(
|
|
219
|
+
redis, replay.spent_key(action_id), ttl_seconds=guard_ttl, subject_jti=subject.jti
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
access_token = self._tokens.mint_hop_token(
|
|
223
|
+
sub=subject.sub, # the human never changes
|
|
224
|
+
target=body.resource,
|
|
225
|
+
data_class=body.scope,
|
|
226
|
+
session_id=subject.session_id,
|
|
227
|
+
policy_version=session.policy_version,
|
|
228
|
+
hop=decision.hop + 1,
|
|
229
|
+
act=nest(subject.act, f"agent://{holder}"),
|
|
230
|
+
# The next hop's audit row links to this one through this claim.
|
|
231
|
+
action_id=str(action_id),
|
|
232
|
+
# The delegate inherits its delegator's taint through this signed claim.
|
|
233
|
+
taint=effective,
|
|
234
|
+
)
|
|
235
|
+
return (
|
|
236
|
+
TokenExchangeResponse(
|
|
237
|
+
access_token=access_token, expires_in=self._ttl, scope=body.scope
|
|
238
|
+
),
|
|
239
|
+
decision,
|
|
240
|
+
subject,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
async def _require_possession(
|
|
244
|
+
self,
|
|
245
|
+
db: AsyncSession,
|
|
246
|
+
redis: Redis | None,
|
|
247
|
+
holder: str,
|
|
248
|
+
body: TokenExchangeRequest,
|
|
249
|
+
subject: VerifiedToken,
|
|
250
|
+
) -> bool:
|
|
251
|
+
"""Verify the actor_token against the holder's live anchor. Returns ``False`` when
|
|
252
|
+
the holder has no live anchor (recorded as AGENT_NOT_ENROLLED by the caller); raises
|
|
253
|
+
``ExchangeRefused`` for a missing or bad actor_token."""
|
|
254
|
+
anchor = await AnchorCache(redis).current(db, holder)
|
|
255
|
+
if anchor is None or anchor.status != "enrolled" or anchor.jwks is None:
|
|
256
|
+
return False
|
|
257
|
+
metrics = get_metrics()
|
|
258
|
+
if not body.actor_token:
|
|
259
|
+
metrics.exchange_pop_failures.labels(cause="missing").inc()
|
|
260
|
+
raise ExchangeRefused(
|
|
261
|
+
"invalid_grant",
|
|
262
|
+
"actor_token is required: sign the subject token with your enrolled key",
|
|
263
|
+
)
|
|
264
|
+
try:
|
|
265
|
+
self._tokens.verify_actor_token(
|
|
266
|
+
body.actor_token,
|
|
267
|
+
anchor_jwks=anchor.jwks,
|
|
268
|
+
subject_token=body.subject_token,
|
|
269
|
+
expected_agent=holder,
|
|
270
|
+
)
|
|
271
|
+
except TokenVerificationError as exc:
|
|
272
|
+
cause = "wrong_agent" if "different agent" in str(exc) else "invalid"
|
|
273
|
+
metrics.exchange_pop_failures.labels(cause=cause).inc()
|
|
274
|
+
raise ExchangeRefused("invalid_grant", str(exc)) from exc
|
|
275
|
+
return True
|
|
276
|
+
|
|
277
|
+
async def _require_recorded_allow(
|
|
278
|
+
self,
|
|
279
|
+
db: AsyncSession,
|
|
280
|
+
action_id: uuid.UUID,
|
|
281
|
+
subject: VerifiedToken,
|
|
282
|
+
body: TokenExchangeRequest,
|
|
283
|
+
) -> None:
|
|
284
|
+
row = await audit_repo.get_committed_allow(db, action_id)
|
|
285
|
+
if row is None:
|
|
286
|
+
raise ExchangeRefused("invalid_grant", f"no recorded allow decision {action_id}")
|
|
287
|
+
if row.outcome != "allow":
|
|
288
|
+
raise ExchangeRefused("invalid_grant", f"recorded decision {action_id} was a deny")
|
|
289
|
+
|
|
290
|
+
bindings = (
|
|
291
|
+
("session_id", str(row.session_id), _normalized(subject.session_id)),
|
|
292
|
+
("hop", row.hop, subject.next_hop),
|
|
293
|
+
("target", row.target, body.resource),
|
|
294
|
+
("data_class", row.data_class, body.scope),
|
|
295
|
+
("subject_jti", row.subject_jti, subject.jti),
|
|
296
|
+
)
|
|
297
|
+
for bound, recorded, presented in bindings:
|
|
298
|
+
if recorded != presented:
|
|
299
|
+
raise ExchangeRefused(
|
|
300
|
+
"invalid_grant",
|
|
301
|
+
f"recorded decision {action_id} does not authorize this exchange: "
|
|
302
|
+
f"{bound} differs",
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
def _verify_subject(self, raw: str) -> VerifiedToken:
|
|
306
|
+
try:
|
|
307
|
+
# No audience is asserted here: the subject token's audience is whoever holds
|
|
308
|
+
# it, and the holder is exactly what we are about to read off it.
|
|
309
|
+
return self._tokens.verify(raw)
|
|
310
|
+
except TokenVerificationError as exc:
|
|
311
|
+
raise ExchangeRefused("invalid_grant", f"subject token rejected: {exc}") from exc
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
__all__ = [
|
|
315
|
+
"TokenExchangeService",
|
|
316
|
+
"ExchangeRefused",
|
|
317
|
+
"ExchangeDenied",
|
|
318
|
+
"DenyReason",
|
|
319
|
+
]
|