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,199 @@
|
|
|
1
|
+
"""Compose reconciled manifests into a versioned scope→capability DAG.
|
|
2
|
+
|
|
3
|
+
- downstream-agent edges are resolved transitively
|
|
4
|
+
- the effective hop budget on any path is the minimum declared along it
|
|
5
|
+
(agent ``hop_budget`` values and edge ``max_hop_depth`` values)
|
|
6
|
+
- data classes for a multi-parent agent are the union across paths
|
|
7
|
+
- delegation cycles are rejected
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
from agentic_auth.errors import DagCycleError
|
|
15
|
+
from agentic_auth.schemas.manifest import AgentManifest
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _agent_name(uri: str) -> str:
|
|
19
|
+
return uri.removeprefix("agent://")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# Bumped when the compiled-DAG JSONB shape changes. The runtime PDP requires >= 2:
|
|
23
|
+
# v1 flattened `tools` across the whole closure, so it cannot answer "may THIS agent
|
|
24
|
+
# call THIS target" or "is B->C a declared edge". v1 policies must be recompiled.
|
|
25
|
+
#
|
|
26
|
+
# v3 is additive: each node carries `taint_policy` (with `trusted_sources`
|
|
27
|
+
# materialized to the declared downstream agents when the manifest omits it) and each tool
|
|
28
|
+
# entry carries `binding_params`. A v2 policy still loads, with the documented defaults.
|
|
29
|
+
DAG_SCHEMA_VERSION = 3
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class CompiledScope:
|
|
34
|
+
scope: str
|
|
35
|
+
tools: list[dict]
|
|
36
|
+
data_classes: dict[str, list[str]]
|
|
37
|
+
downstream_agents: list[str]
|
|
38
|
+
hop_budget: int
|
|
39
|
+
paths: list[dict]
|
|
40
|
+
unresolved_downstream: list[str] = field(default_factory=list)
|
|
41
|
+
source_agents: list[str] = field(default_factory=list)
|
|
42
|
+
# v2: per-agent capability, keyed by agent name. `tools` above stays the
|
|
43
|
+
# flattened union (the human-readable scope catalog reads it).
|
|
44
|
+
nodes: dict[str, dict] = field(default_factory=dict)
|
|
45
|
+
# v2: the direct declared delegation edges inside this closure.
|
|
46
|
+
edges: list[dict] = field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
def to_dag(self) -> dict:
|
|
49
|
+
return {
|
|
50
|
+
"dag_schema_version": DAG_SCHEMA_VERSION,
|
|
51
|
+
"scope": self.scope,
|
|
52
|
+
"tools": self.tools,
|
|
53
|
+
"data_classes": self.data_classes,
|
|
54
|
+
"downstream_agents": self.downstream_agents,
|
|
55
|
+
"hop_budget": self.hop_budget,
|
|
56
|
+
"paths": self.paths,
|
|
57
|
+
"unresolved_downstream": self.unresolved_downstream,
|
|
58
|
+
"source_agents": self.source_agents,
|
|
59
|
+
"nodes": self.nodes,
|
|
60
|
+
"edges": self.edges,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class DagCompiler:
|
|
65
|
+
# `mutmut run` leaves 10 equivalent mutants here: the unused sentinel value of
|
|
66
|
+
# BLACK, the `edges.get(node, [])` fallbacks (every node is always a key), and the
|
|
67
|
+
# defensive `if nxt in path` branch (unreachable once `_reject_cycles` has run).
|
|
68
|
+
def compile(self, manifests: dict[str, AgentManifest]) -> dict[str, CompiledScope]:
|
|
69
|
+
edges: dict[str, list[tuple[str, int]]] = {}
|
|
70
|
+
for name, m in manifests.items():
|
|
71
|
+
edges[name] = [(_agent_name(d.ref), d.max_hop_depth) for d in m.spec.downstream_agents]
|
|
72
|
+
|
|
73
|
+
self._reject_cycles(edges)
|
|
74
|
+
|
|
75
|
+
return {name: self._compile_scope(name, manifests, edges) for name in manifests}
|
|
76
|
+
|
|
77
|
+
# -- cycle detection ---------------------------------------------------
|
|
78
|
+
|
|
79
|
+
def _reject_cycles(self, edges: dict[str, list[tuple[str, int]]]) -> None:
|
|
80
|
+
WHITE, GREY, BLACK = 0, 1, 2
|
|
81
|
+
color = dict.fromkeys(edges, WHITE)
|
|
82
|
+
stack: list[str] = []
|
|
83
|
+
|
|
84
|
+
def visit(node: str) -> None:
|
|
85
|
+
color[node] = GREY
|
|
86
|
+
stack.append(node)
|
|
87
|
+
for nxt, _ in edges.get(node, []):
|
|
88
|
+
if nxt not in color: # unresolved downstream — not a cycle risk here
|
|
89
|
+
continue
|
|
90
|
+
if color[nxt] == GREY:
|
|
91
|
+
cycle = stack[stack.index(nxt) :] + [nxt]
|
|
92
|
+
raise DagCycleError(
|
|
93
|
+
"delegation cycle detected: " + " -> ".join(cycle),
|
|
94
|
+
{"cycle": cycle},
|
|
95
|
+
)
|
|
96
|
+
if color[nxt] == WHITE:
|
|
97
|
+
visit(nxt)
|
|
98
|
+
stack.pop()
|
|
99
|
+
color[node] = BLACK
|
|
100
|
+
|
|
101
|
+
for node in edges:
|
|
102
|
+
if color[node] == WHITE:
|
|
103
|
+
visit(node)
|
|
104
|
+
|
|
105
|
+
# -- per-scope closure ------------------------------------------------
|
|
106
|
+
|
|
107
|
+
def _compile_scope(
|
|
108
|
+
self,
|
|
109
|
+
root: str,
|
|
110
|
+
manifests: dict[str, AgentManifest],
|
|
111
|
+
edges: dict[str, list[tuple[str, int]]],
|
|
112
|
+
) -> CompiledScope:
|
|
113
|
+
root_manifest = manifests[root]
|
|
114
|
+
reachable: set[str] = set()
|
|
115
|
+
unresolved: set[str] = set()
|
|
116
|
+
paths: list[dict] = []
|
|
117
|
+
|
|
118
|
+
def walk(node: str, path: list[str], budget: int) -> None:
|
|
119
|
+
reachable.add(node)
|
|
120
|
+
node_budget = min(budget, manifests[node].spec.hop_budget)
|
|
121
|
+
for nxt, edge_cap in edges.get(node, []):
|
|
122
|
+
if nxt not in manifests:
|
|
123
|
+
unresolved.add(nxt)
|
|
124
|
+
continue
|
|
125
|
+
if nxt in path: # already guarded by cycle check; defensive
|
|
126
|
+
continue
|
|
127
|
+
next_budget = min(node_budget, edge_cap)
|
|
128
|
+
new_path = [*path, nxt]
|
|
129
|
+
paths.append(
|
|
130
|
+
{
|
|
131
|
+
"path": [f"agent://{p}" for p in new_path],
|
|
132
|
+
"effective_hop_budget": next_budget,
|
|
133
|
+
}
|
|
134
|
+
)
|
|
135
|
+
walk(nxt, new_path, next_budget)
|
|
136
|
+
|
|
137
|
+
walk(root, [root], root_manifest.spec.hop_budget)
|
|
138
|
+
|
|
139
|
+
tools: dict[str, dict] = {}
|
|
140
|
+
reads: set[str] = set()
|
|
141
|
+
writes: set[str] = set()
|
|
142
|
+
nodes: dict[str, dict] = {}
|
|
143
|
+
edge_list: list[dict] = []
|
|
144
|
+
for name in sorted(reachable):
|
|
145
|
+
m = manifests[name]
|
|
146
|
+
node_tools: list[dict] = [
|
|
147
|
+
{
|
|
148
|
+
"ref": t.ref,
|
|
149
|
+
"data_classes": sorted(t.data_classes),
|
|
150
|
+
"privileged": t.privileged,
|
|
151
|
+
# v3: None = whole body binds (docs/canonicalization.md §2)
|
|
152
|
+
"binding_params": list(t.binding_params) if t.binding_params else None,
|
|
153
|
+
}
|
|
154
|
+
for t in sorted(m.spec.tools, key=lambda t: t.ref)
|
|
155
|
+
]
|
|
156
|
+
for node_tool in node_tools:
|
|
157
|
+
tools[str(node_tool["ref"])] = node_tool
|
|
158
|
+
reads.update(m.spec.data_classes.reads)
|
|
159
|
+
writes.update(m.spec.data_classes.writes)
|
|
160
|
+
|
|
161
|
+
policy = m.spec.taint_policy
|
|
162
|
+
# The default is materialized here so the runtime never has to know it: an agent
|
|
163
|
+
# that lists no trusted sources trusts exactly its declared downstream agents.
|
|
164
|
+
trusted = (
|
|
165
|
+
list(policy.trusted_sources)
|
|
166
|
+
if policy.trusted_sources is not None
|
|
167
|
+
else [d.ref for d in m.spec.downstream_agents]
|
|
168
|
+
)
|
|
169
|
+
nodes[name] = {
|
|
170
|
+
"tools": node_tools,
|
|
171
|
+
"data_classes": {
|
|
172
|
+
"reads": sorted(m.spec.data_classes.reads),
|
|
173
|
+
"writes": sorted(m.spec.data_classes.writes),
|
|
174
|
+
},
|
|
175
|
+
"hop_budget": m.spec.hop_budget,
|
|
176
|
+
"taint_policy": {
|
|
177
|
+
"trusted_sources": trusted,
|
|
178
|
+
"block_tainted_into": list(policy.block_tainted_into),
|
|
179
|
+
},
|
|
180
|
+
}
|
|
181
|
+
# Only edges whose target is registered and reachable are declared. An
|
|
182
|
+
# unresolved downstream stays out, so delegating to it denies with
|
|
183
|
+
# EDGE_NOT_IN_DAG rather than resolving against a node that isn't there.
|
|
184
|
+
for nxt, edge_cap in edges.get(name, []):
|
|
185
|
+
if nxt in reachable:
|
|
186
|
+
edge_list.append({"from": name, "to": nxt, "max_hop_depth": edge_cap})
|
|
187
|
+
|
|
188
|
+
return CompiledScope(
|
|
189
|
+
scope=root,
|
|
190
|
+
tools=[tools[k] for k in sorted(tools)],
|
|
191
|
+
data_classes={"reads": sorted(reads), "writes": sorted(writes)},
|
|
192
|
+
downstream_agents=[d.ref for d in root_manifest.spec.downstream_agents],
|
|
193
|
+
hop_budget=root_manifest.spec.hop_budget,
|
|
194
|
+
paths=paths,
|
|
195
|
+
unresolved_downstream=sorted(f"agent://{u}" for u in unresolved),
|
|
196
|
+
source_agents=sorted(reachable),
|
|
197
|
+
nodes=nodes,
|
|
198
|
+
edges=edge_list,
|
|
199
|
+
)
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Short-lived decision cache.
|
|
2
|
+
|
|
3
|
+
The policy version is **inside the key**, so invalidation is structural: a session pinned
|
|
4
|
+
to version 42 can never read a version 43 entry, and there is no invalidation event to
|
|
5
|
+
forget. This mirrors Phase 1's immutable ``dag:{scope}:{version}`` keys, where the same
|
|
6
|
+
trick made invalidation a non-problem.
|
|
7
|
+
|
|
8
|
+
Only decisions are cached. Tokens are always minted fresh — a cached token would break
|
|
9
|
+
single-hop binding, which is the one thing the whole phase is for.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
|
|
18
|
+
from redis.asyncio import Redis
|
|
19
|
+
|
|
20
|
+
from agentic_auth.config import get_settings
|
|
21
|
+
from agentic_auth.schemas.authorize import AuthorizeRequest, DenyReason, Taint
|
|
22
|
+
from agentic_auth.services.pdp import Decision
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def key(
|
|
26
|
+
request: AuthorizeRequest,
|
|
27
|
+
*,
|
|
28
|
+
policy_version: int,
|
|
29
|
+
hop: int,
|
|
30
|
+
act_chain: list[str],
|
|
31
|
+
taint: Taint | None = None,
|
|
32
|
+
revoked: frozenset[str] = frozenset(),
|
|
33
|
+
consented_data_classes: frozenset[str] | None = None,
|
|
34
|
+
step_up: frozenset[str] = frozenset(),
|
|
35
|
+
) -> str:
|
|
36
|
+
"""Every input `decide()` reads, hashed into one unambiguous key.
|
|
37
|
+
|
|
38
|
+
Two things this must not get wrong.
|
|
39
|
+
|
|
40
|
+
**The chain is part of the decision.** `decide()` builds `path_so_far` from the
|
|
41
|
+
delegation chain and looks up `budget_for_path(full_path)`, so the same
|
|
42
|
+
(caller, target, data_class, hop) can be allowed via one route and denied via
|
|
43
|
+
another — fan-out is ordinary DAG shape, and both routes live in one session.
|
|
44
|
+
Omitting the chain would serve the allow for the wrong path.
|
|
45
|
+
|
|
46
|
+
**Concatenation is ambiguous.** Targets are URIs full of colons, so a `":".join`
|
|
47
|
+
lets `(target="mcp://kb", data_class="x:read")` and `(target="mcp://kb:x",
|
|
48
|
+
data_class="read")` produce the same key. JSON-encoding the parts first removes
|
|
49
|
+
the ambiguity; hashing keeps the key a bounded length.
|
|
50
|
+
|
|
51
|
+
`policy_version` stays in the plaintext prefix so structural invalidation — a
|
|
52
|
+
pinned session can never read another version's entry — is still greppable in a
|
|
53
|
+
running Redis.
|
|
54
|
+
"""
|
|
55
|
+
canonical = json.dumps(
|
|
56
|
+
[
|
|
57
|
+
policy_version,
|
|
58
|
+
request.session_id,
|
|
59
|
+
request.caller,
|
|
60
|
+
request.target,
|
|
61
|
+
request.data_class,
|
|
62
|
+
hop,
|
|
63
|
+
act_chain,
|
|
64
|
+
# Phase 4: both are decision inputs, so a context that became tainted, or an
|
|
65
|
+
# agent that was revoked, can never read an earlier allow.
|
|
66
|
+
taint.value if taint else None,
|
|
67
|
+
sorted(revoked),
|
|
68
|
+
# Phase 5: both are decision inputs too. Without `step_up` in the key, a
|
|
69
|
+
# session a human has just widened would read back the deny it was widened
|
|
70
|
+
# past — the cache would undo the consent. `None` and the empty set are
|
|
71
|
+
# deliberately distinct: None means "everything the policy declares".
|
|
72
|
+
None if consented_data_classes is None else sorted(consented_data_classes),
|
|
73
|
+
sorted(step_up),
|
|
74
|
+
],
|
|
75
|
+
separators=(",", ":"),
|
|
76
|
+
)
|
|
77
|
+
return f"pdp:{policy_version}:{hashlib.sha256(canonical.encode()).hexdigest()}"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def get(redis: Redis | None, cache_key: str) -> Decision | None:
|
|
81
|
+
"""A miss, a malformed entry, or an outage all return ``None`` — the caller then
|
|
82
|
+
evaluates fully. Slower, never wrong, and never an allow a fresh evaluation would
|
|
83
|
+
refuse."""
|
|
84
|
+
if redis is None:
|
|
85
|
+
return None
|
|
86
|
+
try:
|
|
87
|
+
raw = await redis.get(cache_key)
|
|
88
|
+
except Exception:
|
|
89
|
+
return None
|
|
90
|
+
if raw is None:
|
|
91
|
+
return None
|
|
92
|
+
try:
|
|
93
|
+
d = json.loads(raw)
|
|
94
|
+
return Decision(
|
|
95
|
+
outcome=d["outcome"],
|
|
96
|
+
hop=d["hop"],
|
|
97
|
+
reason=DenyReason(d["reason"]) if d.get("reason") else None,
|
|
98
|
+
message=d.get("message"),
|
|
99
|
+
privileged=bool(d.get("privileged", False)),
|
|
100
|
+
transaction_required=bool(d.get("transaction_required", False)),
|
|
101
|
+
taint=Taint(d["taint"]) if d.get("taint") else None,
|
|
102
|
+
)
|
|
103
|
+
except (ValueError, KeyError, TypeError):
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def put(redis: Redis | None, cache_key: str, decision: Decision) -> None:
|
|
108
|
+
"""Best effort. A cache that cannot be written is a slower system, not a wrong one."""
|
|
109
|
+
if redis is None:
|
|
110
|
+
return
|
|
111
|
+
payload = json.dumps(
|
|
112
|
+
{
|
|
113
|
+
"outcome": decision.outcome,
|
|
114
|
+
"hop": decision.hop,
|
|
115
|
+
"reason": decision.reason.value if decision.reason else None,
|
|
116
|
+
"message": decision.message,
|
|
117
|
+
"privileged": decision.privileged,
|
|
118
|
+
"transaction_required": decision.transaction_required,
|
|
119
|
+
"taint": decision.taint.value if decision.taint else None,
|
|
120
|
+
}
|
|
121
|
+
)
|
|
122
|
+
with contextlib.suppress(Exception):
|
|
123
|
+
await redis.set(cache_key, payload, ex=get_settings().decision_cache_ttl_seconds)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""The decision history — "show me the pattern", where the chain query is "explain this one".
|
|
2
|
+
|
|
3
|
+
Query parameters arrive as raw strings and are validated here as one model, so every
|
|
4
|
+
invalid filter — including one that is only invalid in combination, like ``since`` after
|
|
5
|
+
``until`` — comes back as the same ``422 validation_error`` naming the parameter.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
|
|
12
|
+
from pydantic import ValidationError
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
14
|
+
|
|
15
|
+
from agentic_auth.errors import QueryValidationError
|
|
16
|
+
from agentic_auth.repositories import audit_decisions as audit_repo
|
|
17
|
+
from agentic_auth.repositories import transaction_tokens as txn_repo
|
|
18
|
+
from agentic_auth.schemas.audit import (
|
|
19
|
+
AuditDecisionFilter,
|
|
20
|
+
AuditDecisionListItem,
|
|
21
|
+
AuditDecisionPage,
|
|
22
|
+
AuditPageInfo,
|
|
23
|
+
TransactionFingerprint,
|
|
24
|
+
)
|
|
25
|
+
from agentic_auth.services.audit_cursor import decode_cursor, encode_cursor
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse_filters(raw: Mapping[str, str | None]) -> AuditDecisionFilter:
|
|
29
|
+
try:
|
|
30
|
+
return AuditDecisionFilter.model_validate({k: v for k, v in raw.items() if v is not None})
|
|
31
|
+
except ValidationError as exc:
|
|
32
|
+
fields = [
|
|
33
|
+
{
|
|
34
|
+
# A cross-field failure has no location of its own; it is about the range.
|
|
35
|
+
"loc": ["query", str(error["loc"][0]) if error["loc"] else "since"],
|
|
36
|
+
"msg": error["msg"],
|
|
37
|
+
}
|
|
38
|
+
for error in exc.errors()
|
|
39
|
+
]
|
|
40
|
+
raise QueryValidationError("invalid decision history filter", fields) from exc
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def history_page(
|
|
44
|
+
db: AsyncSession,
|
|
45
|
+
*,
|
|
46
|
+
raw_filters: Mapping[str, str | None],
|
|
47
|
+
limit: int,
|
|
48
|
+
cursor: str | None,
|
|
49
|
+
) -> AuditDecisionPage:
|
|
50
|
+
filters = parse_filters(raw_filters)
|
|
51
|
+
position = decode_cursor(cursor) if cursor else None
|
|
52
|
+
|
|
53
|
+
rows, has_more, hwm = await audit_repo.list_page(
|
|
54
|
+
db, filters=filters, limit=limit, position=position
|
|
55
|
+
)
|
|
56
|
+
next_cursor = encode_cursor(rows[-1].seq, hwm) if has_more and rows and hwm else None
|
|
57
|
+
# Phase 4: the transaction fingerprint for any privileged allow on this page.
|
|
58
|
+
fingerprints = await txn_repo.get_by_actions(db, [r.id for r in rows if r.privileged])
|
|
59
|
+
items = []
|
|
60
|
+
for row in rows:
|
|
61
|
+
item = AuditDecisionListItem.model_validate(row)
|
|
62
|
+
txn = fingerprints.get(row.id)
|
|
63
|
+
if txn is not None:
|
|
64
|
+
item = item.model_copy(
|
|
65
|
+
update={"transaction": TransactionFingerprint.model_validate(txn)}
|
|
66
|
+
)
|
|
67
|
+
items.append(item)
|
|
68
|
+
return AuditDecisionPage(
|
|
69
|
+
data=items,
|
|
70
|
+
page=AuditPageInfo(next_cursor=next_cursor, limit=limit, as_of_seq=hwm),
|
|
71
|
+
)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""RFC 9728 capability discovery.
|
|
2
|
+
|
|
3
|
+
Resolves each ``mcp://host[:port]/tool`` reference to an authority and fetches
|
|
4
|
+
``/.well-known/oauth-protected-resource``. A network/parse failure is never a silent
|
|
5
|
+
pass — it surfaces as a :class:`DiscoveryResult` with ``ok=False`` which the reconciler
|
|
6
|
+
turns into a ``DISCOVERY_UNAVAILABLE`` diff entry.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
from pydantic import BaseModel, ConfigDict
|
|
16
|
+
|
|
17
|
+
WELL_KNOWN_PATH = "/.well-known/oauth-protected-resource"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class DiscoveredTool(BaseModel):
|
|
21
|
+
model_config = ConfigDict(extra="ignore")
|
|
22
|
+
data_classes: list[str] = []
|
|
23
|
+
privileged: bool = False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DiscoveredResource(BaseModel):
|
|
27
|
+
model_config = ConfigDict(extra="ignore")
|
|
28
|
+
resource: str = ""
|
|
29
|
+
scopes_supported: list[str] = []
|
|
30
|
+
tools: dict[str, DiscoveredTool] = {}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class DiscoveryResult:
|
|
35
|
+
authority: str
|
|
36
|
+
ok: bool
|
|
37
|
+
resource: DiscoveredResource | None = None
|
|
38
|
+
error: str | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def authority_for(tool_ref: str) -> str:
|
|
42
|
+
"""``mcp://kb.internal:8443/search`` -> ``https://kb.internal:8443``."""
|
|
43
|
+
parts = urlsplit(tool_ref)
|
|
44
|
+
if parts.scheme != "mcp" or not parts.netloc:
|
|
45
|
+
raise ValueError(f"not an mcp:// tool ref: {tool_ref!r}")
|
|
46
|
+
return f"https://{parts.netloc}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def tool_name(tool_ref: str) -> str:
|
|
50
|
+
return urlsplit(tool_ref).path.lstrip("/")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DiscoveryClient:
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
*,
|
|
57
|
+
timeout: float = 5.0,
|
|
58
|
+
client: httpx.AsyncClient | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
self._timeout = timeout
|
|
61
|
+
self._client = client
|
|
62
|
+
self._owns_client = client is None
|
|
63
|
+
|
|
64
|
+
async def _get_client(self) -> httpx.AsyncClient:
|
|
65
|
+
if self._client is None:
|
|
66
|
+
self._client = httpx.AsyncClient(timeout=self._timeout)
|
|
67
|
+
return self._client
|
|
68
|
+
|
|
69
|
+
async def aclose(self) -> None:
|
|
70
|
+
if self._owns_client and self._client is not None:
|
|
71
|
+
await self._client.aclose()
|
|
72
|
+
self._client = None
|
|
73
|
+
|
|
74
|
+
async def discover(self, authorities: set[str]) -> dict[str, DiscoveryResult]:
|
|
75
|
+
client = await self._get_client()
|
|
76
|
+
out: dict[str, DiscoveryResult] = {}
|
|
77
|
+
for authority in sorted(authorities):
|
|
78
|
+
url = authority.rstrip("/") + WELL_KNOWN_PATH
|
|
79
|
+
try:
|
|
80
|
+
resp = await client.get(url, timeout=self._timeout)
|
|
81
|
+
except httpx.HTTPError as exc: # timeout, connection error, etc.
|
|
82
|
+
out[authority] = DiscoveryResult(authority, ok=False, error=str(exc))
|
|
83
|
+
continue
|
|
84
|
+
if resp.status_code != 200:
|
|
85
|
+
out[authority] = DiscoveryResult(
|
|
86
|
+
authority, ok=False, error=f"HTTP {resp.status_code}"
|
|
87
|
+
)
|
|
88
|
+
continue
|
|
89
|
+
try:
|
|
90
|
+
resource = DiscoveredResource.model_validate(resp.json())
|
|
91
|
+
except (ValueError, TypeError) as exc:
|
|
92
|
+
out[authority] = DiscoveryResult(authority, ok=False, error=str(exc))
|
|
93
|
+
continue
|
|
94
|
+
out[authority] = DiscoveryResult(authority, ok=True, resource=resource)
|
|
95
|
+
return out
|