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,330 @@
|
|
|
1
|
+
"""The offline drift check — observed edges versus declared manifests.
|
|
2
|
+
|
|
3
|
+
Runs from files only: manifests from local directories, edges from a recorded trace. There is
|
|
4
|
+
no network code on this path — no discovery, no reconciliation, no control plane —
|
|
5
|
+
because the question is only "was every observed edge declared", and CI should be able to
|
|
6
|
+
answer it with no credentials and no services.
|
|
7
|
+
|
|
8
|
+
The verdict for every edge comes from :func:`agentic_auth.services.edge_rules.classify_edge`, the
|
|
9
|
+
function the runtime PDP calls, over an index built by the same compiler.
|
|
10
|
+
|
|
11
|
+
Never a pass without evidence. Invalid or missing inputs, lost events, and a run that
|
|
12
|
+
observed nothing at all are each a distinct ``error`` result.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
import yaml
|
|
24
|
+
from pydantic import ValidationError
|
|
25
|
+
|
|
26
|
+
from agentic_auth.errors import DagCycleError
|
|
27
|
+
from agentic_auth.schemas.edge_trace import (
|
|
28
|
+
DriftError,
|
|
29
|
+
DriftInputs,
|
|
30
|
+
DriftReport,
|
|
31
|
+
DriftSummary,
|
|
32
|
+
DriftWarning,
|
|
33
|
+
EdgeTrace,
|
|
34
|
+
UndeclaredEdge,
|
|
35
|
+
)
|
|
36
|
+
from agentic_auth.schemas.manifest import AgentManifest
|
|
37
|
+
from agentic_auth.services.dag_compiler import DagCompiler
|
|
38
|
+
from agentic_auth.services.edge_rules import RUNTIME_REASON, EdgeVerdict, classify_edge
|
|
39
|
+
from agentic_auth.services.policy_loader import PolicyIndex, build_graph_index
|
|
40
|
+
|
|
41
|
+
MANIFEST_SUFFIXES = frozenset({".yaml", ".yml", ".json"})
|
|
42
|
+
|
|
43
|
+
# `mutmut run` leaves a handful of equivalent mutants here, all of which rewrite prose: the
|
|
44
|
+
# `message` of a `DriftError`/`DriftWarning`, or the text `_hint` composes. Neither is the
|
|
45
|
+
# machine contract — CI branches on the exit code, and a reader branches on `code`,
|
|
46
|
+
# `verdict`, `runtime_reason` and the edge itself, every one of which is asserted in
|
|
47
|
+
# tests/unit/test_drift_diff.py. Any mutant that changes a result, a verdict, a count, or
|
|
48
|
+
# which edges are reported is killed.
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class LoadedManifests:
|
|
53
|
+
manifests: dict[str, AgentManifest] = field(default_factory=dict)
|
|
54
|
+
# agent name -> the file that declares it, as found under the given directory
|
|
55
|
+
paths: dict[str, str] = field(default_factory=dict)
|
|
56
|
+
skipped: list[str] = field(default_factory=list)
|
|
57
|
+
errors: list[DriftError] = field(default_factory=list)
|
|
58
|
+
empty_dirs: list[str] = field(default_factory=list)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _field_errors(exc: ValidationError) -> str:
|
|
62
|
+
return "; ".join(
|
|
63
|
+
f"{'.'.join(str(p) for p in err['loc']) or '(root)'}: {err['msg']}" for err in exc.errors()
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def load_manifest_dirs(dirs: Sequence[Path]) -> LoadedManifests:
|
|
68
|
+
loaded = LoadedManifests()
|
|
69
|
+
for directory in dirs:
|
|
70
|
+
if not directory.is_dir():
|
|
71
|
+
loaded.errors.append(
|
|
72
|
+
DriftError(
|
|
73
|
+
code="NO_MANIFESTS_FOUND",
|
|
74
|
+
message=f"manifest location {directory} is not a directory",
|
|
75
|
+
path=str(directory),
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
continue
|
|
79
|
+
|
|
80
|
+
# A flag, not a tally: nothing downstream cares how many this directory contributed,
|
|
81
|
+
# only whether it contributed anything at all.
|
|
82
|
+
contributed = False
|
|
83
|
+
candidates = sorted(
|
|
84
|
+
p for p in directory.rglob("*") if p.is_file() and p.suffix in MANIFEST_SUFFIXES
|
|
85
|
+
)
|
|
86
|
+
for path in candidates:
|
|
87
|
+
try:
|
|
88
|
+
doc = yaml.safe_load(path.read_text(encoding="utf-8")) # also parses JSON
|
|
89
|
+
except (yaml.YAMLError, UnicodeDecodeError) as exc:
|
|
90
|
+
loaded.errors.append(
|
|
91
|
+
DriftError(
|
|
92
|
+
code="MANIFEST_INVALID",
|
|
93
|
+
message=f"not valid YAML or JSON: {type(exc).__name__}",
|
|
94
|
+
path=str(path),
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
if not isinstance(doc, dict) or doc.get("kind") != "AgentManifest":
|
|
100
|
+
loaded.skipped.append(str(path))
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
manifest = AgentManifest.model_validate(doc)
|
|
105
|
+
except ValidationError as exc:
|
|
106
|
+
loaded.errors.append(
|
|
107
|
+
DriftError(code="MANIFEST_INVALID", message=_field_errors(exc), path=str(path))
|
|
108
|
+
)
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
name = manifest.metadata.agent
|
|
112
|
+
if name in loaded.manifests:
|
|
113
|
+
loaded.errors.append(
|
|
114
|
+
DriftError(
|
|
115
|
+
code="MANIFEST_DUPLICATE_AGENT",
|
|
116
|
+
message=(
|
|
117
|
+
f"agent {name!r} is declared in both {loaded.paths[name]} and {path}"
|
|
118
|
+
),
|
|
119
|
+
path=str(path),
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
loaded.manifests[name] = manifest
|
|
125
|
+
loaded.paths[name] = str(path)
|
|
126
|
+
contributed = True
|
|
127
|
+
|
|
128
|
+
if not contributed:
|
|
129
|
+
loaded.empty_dirs.append(str(directory))
|
|
130
|
+
|
|
131
|
+
if not loaded.manifests and not loaded.errors:
|
|
132
|
+
loaded.errors.append(
|
|
133
|
+
DriftError(
|
|
134
|
+
code="NO_MANIFESTS_FOUND",
|
|
135
|
+
message="no AgentManifest documents under any --manifest location",
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
return loaded
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def declared_graph(manifests: Mapping[str, AgentManifest]) -> PolicyIndex:
|
|
142
|
+
"""Compile with the runtime's compiler, then index every agent. Raises ``DagCycleError``."""
|
|
143
|
+
return build_graph_index(DagCompiler().compile(dict(manifests)))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def registration_order(manifests: Mapping[str, AgentManifest]) -> list[str]:
|
|
147
|
+
"""Leaf first: every downstream agent before the agent that delegates to it, so each
|
|
148
|
+
reference resolves at compile time when registering against a control plane."""
|
|
149
|
+
ordered: list[str] = []
|
|
150
|
+
|
|
151
|
+
def visit(name: str, stack: tuple[str, ...]) -> None:
|
|
152
|
+
if name in ordered or name not in manifests or name in stack:
|
|
153
|
+
return
|
|
154
|
+
for downstream in manifests[name].spec.downstream_agents:
|
|
155
|
+
visit(downstream.ref.removeprefix("agent://"), (*stack, name))
|
|
156
|
+
ordered.append(name)
|
|
157
|
+
|
|
158
|
+
for name in sorted(manifests):
|
|
159
|
+
visit(name, ())
|
|
160
|
+
return ordered
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def load_trace(path: Path) -> EdgeTrace | DriftError:
|
|
164
|
+
if not path.is_file():
|
|
165
|
+
return DriftError(code="TRACE_MISSING", message=f"no trace file at {path}", path=str(path))
|
|
166
|
+
try:
|
|
167
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
168
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
169
|
+
return DriftError(
|
|
170
|
+
code="TRACE_MALFORMED", message=f"not valid JSON: {type(exc).__name__}", path=str(path)
|
|
171
|
+
)
|
|
172
|
+
if isinstance(raw, dict) and raw.get("schema_version") not in (None, 1):
|
|
173
|
+
return DriftError(
|
|
174
|
+
code="TRACE_UNSUPPORTED_VERSION",
|
|
175
|
+
message=(
|
|
176
|
+
f"trace schema_version {raw.get('schema_version')!r} is not supported (expected 1)"
|
|
177
|
+
),
|
|
178
|
+
path=str(path),
|
|
179
|
+
)
|
|
180
|
+
try:
|
|
181
|
+
return EdgeTrace.model_validate(raw)
|
|
182
|
+
except ValidationError as exc:
|
|
183
|
+
return DriftError(code="TRACE_MALFORMED", message=_field_errors(exc), path=str(path))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _hint(verdict: EdgeVerdict, caller: str, target: str, manifest_path: str | None) -> str:
|
|
187
|
+
where = manifest_path or "its manifest"
|
|
188
|
+
if verdict is EdgeVerdict.UNDECLARED_TOOL:
|
|
189
|
+
return f"remove the call from {caller}, or add {target} to spec.tools in {where}"
|
|
190
|
+
if verdict is EdgeVerdict.UNDECLARED_DELEGATION:
|
|
191
|
+
return (
|
|
192
|
+
f"remove the delegation from {caller}, or add {target} to spec.downstream_agents in "
|
|
193
|
+
f"{where} (with that agent's manifest in a --manifest location)"
|
|
194
|
+
)
|
|
195
|
+
return f"no manifest declares agent {caller!r}; add its manifest to a --manifest location"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def diff(
|
|
199
|
+
trace: EdgeTrace,
|
|
200
|
+
graph: PolicyIndex,
|
|
201
|
+
manifest_paths: Mapping[str, str],
|
|
202
|
+
*,
|
|
203
|
+
inputs: DriftInputs,
|
|
204
|
+
) -> DriftReport:
|
|
205
|
+
"""Pure: every observed edge judged by the runtime's own edge rule."""
|
|
206
|
+
errors: list[DriftError] = []
|
|
207
|
+
if trace.recorder_errors > 0:
|
|
208
|
+
errors.append(
|
|
209
|
+
DriftError(
|
|
210
|
+
code="TRACE_RECORDER_ERRORS",
|
|
211
|
+
message=(
|
|
212
|
+
f"{trace.recorder_errors} recorded event(s) were lost or unreadable; "
|
|
213
|
+
"the evidence is incomplete, so no pass can be reported"
|
|
214
|
+
),
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
if not trace.edges:
|
|
218
|
+
errors.append(
|
|
219
|
+
DriftError(
|
|
220
|
+
code="NO_EDGES_OBSERVED",
|
|
221
|
+
message=(
|
|
222
|
+
"the trace contains no attributed edges — was the sidecar or SDK in the call "
|
|
223
|
+
"path, and could it reach the control plane?"
|
|
224
|
+
),
|
|
225
|
+
)
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
undeclared: list[UndeclaredEdge] = []
|
|
229
|
+
declared = 0
|
|
230
|
+
for edge in sorted(trace.edges, key=lambda e: (e.from_, e.to)):
|
|
231
|
+
verdict = classify_edge(graph, edge.from_, edge.to)
|
|
232
|
+
if verdict is EdgeVerdict.DECLARED:
|
|
233
|
+
declared += 1
|
|
234
|
+
continue
|
|
235
|
+
manifest_path = (
|
|
236
|
+
None if verdict is EdgeVerdict.UNKNOWN_AGENT else manifest_paths.get(edge.from_)
|
|
237
|
+
)
|
|
238
|
+
undeclared.append(
|
|
239
|
+
UndeclaredEdge(
|
|
240
|
+
from_=edge.from_,
|
|
241
|
+
to=edge.to,
|
|
242
|
+
kind=edge.kind,
|
|
243
|
+
count=edge.count,
|
|
244
|
+
verdict=verdict.value,
|
|
245
|
+
runtime_reason=RUNTIME_REASON[verdict].value,
|
|
246
|
+
manifest_path=manifest_path,
|
|
247
|
+
hint=_hint(verdict, edge.from_, edge.to, manifest_path),
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
warnings: list[DriftWarning] = []
|
|
252
|
+
if trace.unattributed.count:
|
|
253
|
+
breakdown = ", ".join(f"{k}: {v}" for k, v in sorted(trace.unattributed.by_reason.items()))
|
|
254
|
+
warnings.append(
|
|
255
|
+
DriftWarning(
|
|
256
|
+
code="UNATTRIBUTED_CALLS",
|
|
257
|
+
message=f"{trace.unattributed.count} call(s) could not be attributed ({breakdown})",
|
|
258
|
+
)
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
result = "error" if errors else ("drift" if undeclared else "pass")
|
|
262
|
+
return DriftReport(
|
|
263
|
+
result=result,
|
|
264
|
+
summary=DriftSummary(
|
|
265
|
+
edges_observed=len(trace.edges),
|
|
266
|
+
edges_declared=declared,
|
|
267
|
+
edges_undeclared=len(undeclared),
|
|
268
|
+
calls_observed=sum(e.count for e in trace.edges),
|
|
269
|
+
unattributed_calls=trace.unattributed.count,
|
|
270
|
+
),
|
|
271
|
+
undeclared=undeclared,
|
|
272
|
+
errors=errors,
|
|
273
|
+
warnings=warnings,
|
|
274
|
+
inputs=inputs,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _error_report(
|
|
279
|
+
errors: list[DriftError], warnings: list[DriftWarning], inputs: DriftInputs
|
|
280
|
+
) -> DriftReport:
|
|
281
|
+
return DriftReport(
|
|
282
|
+
result="error",
|
|
283
|
+
summary=DriftSummary(
|
|
284
|
+
edges_observed=0,
|
|
285
|
+
edges_declared=0,
|
|
286
|
+
edges_undeclared=0,
|
|
287
|
+
calls_observed=0,
|
|
288
|
+
unattributed_calls=0,
|
|
289
|
+
),
|
|
290
|
+
undeclared=[],
|
|
291
|
+
errors=errors,
|
|
292
|
+
warnings=warnings,
|
|
293
|
+
inputs=inputs,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def run_check(
|
|
298
|
+
manifest_dirs: Sequence[Path], trace_path: Path, *, generated_at: datetime | None
|
|
299
|
+
) -> DriftReport:
|
|
300
|
+
loaded = load_manifest_dirs(manifest_dirs)
|
|
301
|
+
inputs = DriftInputs(
|
|
302
|
+
manifest_dirs=[str(d) for d in manifest_dirs],
|
|
303
|
+
trace=str(trace_path),
|
|
304
|
+
manifests_loaded=len(loaded.manifests),
|
|
305
|
+
skipped_files=loaded.skipped,
|
|
306
|
+
generated_at=generated_at,
|
|
307
|
+
)
|
|
308
|
+
errors = list(loaded.errors)
|
|
309
|
+
warnings = [
|
|
310
|
+
DriftWarning(code="UNUSED_MANIFEST_DIR", message=f"{d} contributed no manifests")
|
|
311
|
+
for d in loaded.empty_dirs
|
|
312
|
+
if loaded.manifests # an all-empty run is already the NO_MANIFESTS_FOUND error
|
|
313
|
+
]
|
|
314
|
+
|
|
315
|
+
trace = load_trace(trace_path)
|
|
316
|
+
if isinstance(trace, DriftError):
|
|
317
|
+
errors.append(trace)
|
|
318
|
+
|
|
319
|
+
graph: PolicyIndex | None = None
|
|
320
|
+
if not loaded.errors:
|
|
321
|
+
try:
|
|
322
|
+
graph = declared_graph(loaded.manifests)
|
|
323
|
+
except DagCycleError as exc:
|
|
324
|
+
errors.append(DriftError(code="DELEGATION_CYCLE", message=exc.message))
|
|
325
|
+
|
|
326
|
+
if errors or graph is None or isinstance(trace, DriftError):
|
|
327
|
+
return _error_report(errors, warnings, inputs)
|
|
328
|
+
|
|
329
|
+
report = diff(trace, graph, loaded.paths, inputs=inputs)
|
|
330
|
+
return report.model_copy(update={"warnings": [*warnings, *report.warnings]})
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""The edge rule — shared, verbatim, by the runtime PDP and the offline drift check.
|
|
2
|
+
|
|
3
|
+
"May this agent call this target?" has exactly one implementation in the codebase. The PDP
|
|
4
|
+
asks it before every hop (``agentic_auth/services/pdp.py``); ``agentic-auth drift check`` asks it
|
|
5
|
+
for
|
|
6
|
+
every edge a test run observed (``agentic_auth/services/drift.py``). Two implementations of one rule
|
|
7
|
+
is precisely the divergence the CI check exists to rule out, so there is one.
|
|
8
|
+
|
|
9
|
+
Pure: a policy index and an edge in, a verdict out.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from enum import StrEnum
|
|
15
|
+
|
|
16
|
+
from agentic_auth.schemas.authorize import DenyReason
|
|
17
|
+
from agentic_auth.services.policy_loader import PolicyIndex
|
|
18
|
+
|
|
19
|
+
AGENT_PREFIX = "agent://"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class EdgeVerdict(StrEnum):
|
|
23
|
+
DECLARED = "DECLARED"
|
|
24
|
+
# The caller is not an agent any supplied manifest declares.
|
|
25
|
+
UNKNOWN_AGENT = "UNKNOWN_AGENT"
|
|
26
|
+
# The caller does not itself declare this tool.
|
|
27
|
+
UNDECLARED_TOOL = "UNDECLARED_TOOL"
|
|
28
|
+
# The caller has no declared delegation edge to this agent.
|
|
29
|
+
UNDECLARED_DELEGATION = "UNDECLARED_DELEGATION"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# What the runtime refuses with, for each verdict that is not DECLARED. The drift report
|
|
33
|
+
# prints this so a developer sees the production consequence of the edge they just added.
|
|
34
|
+
RUNTIME_REASON: dict[EdgeVerdict, DenyReason] = {
|
|
35
|
+
EdgeVerdict.UNKNOWN_AGENT: DenyReason.OUT_OF_SCOPE,
|
|
36
|
+
EdgeVerdict.UNDECLARED_TOOL: DenyReason.OUT_OF_SCOPE,
|
|
37
|
+
EdgeVerdict.UNDECLARED_DELEGATION: DenyReason.EDGE_NOT_IN_DAG,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def delegate_of(target: str) -> str | None:
|
|
42
|
+
"""The bare agent name for a delegation target, or ``None`` for a tool ref."""
|
|
43
|
+
return target.removeprefix(AGENT_PREFIX) if target.startswith(AGENT_PREFIX) else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def classify_edge(index: PolicyIndex, caller_agent: str | None, target: str) -> EdgeVerdict:
|
|
47
|
+
if caller_agent is None or caller_agent not in index.agents:
|
|
48
|
+
return EdgeVerdict.UNKNOWN_AGENT
|
|
49
|
+
|
|
50
|
+
delegate = delegate_of(target)
|
|
51
|
+
if delegate is not None:
|
|
52
|
+
# A delegation must be a declared edge. An edge to an agent whose manifest was never
|
|
53
|
+
# registered is not compiled into `edges`, so it is undeclared here too.
|
|
54
|
+
if index.has_edge(caller_agent, delegate):
|
|
55
|
+
return EdgeVerdict.DECLARED
|
|
56
|
+
return EdgeVerdict.UNDECLARED_DELEGATION
|
|
57
|
+
|
|
58
|
+
# A tool call: the caller must declare the tool itself. Reaching it through another
|
|
59
|
+
# agent's declaration would let any agent borrow any other agent's tools.
|
|
60
|
+
if index.declares_tool(caller_agent, target):
|
|
61
|
+
return EdgeVerdict.DECLARED
|
|
62
|
+
return EdgeVerdict.UNDECLARED_TOOL
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Recording observed edges, and aggregating them into a trace.
|
|
2
|
+
|
|
3
|
+
**Recording is passive and cannot change enforcement.** The sidecar and SDK call
|
|
4
|
+
:meth:`EdgeRecorder.record` *after* an outcome is fixed, and ``record`` never raises: a write
|
|
5
|
+
that fails is counted, and the count is written into the events file on the next success,
|
|
6
|
+
so lost evidence surfaces as ``recorder_errors`` — which makes ``drift check`` refuse to
|
|
7
|
+
report a pass — instead of silently shrinking the trace.
|
|
8
|
+
|
|
9
|
+
**Lines are appended atomically.** One ``os.write`` of one line under 4 KiB, on a descriptor
|
|
10
|
+
opened ``O_APPEND``, so several recorders sharing a file on a local filesystem never
|
|
11
|
+
interleave partial lines. Networked filesystems are not supported for shared event files.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import threading
|
|
20
|
+
from collections import Counter
|
|
21
|
+
from collections.abc import Sequence
|
|
22
|
+
from datetime import UTC, datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from pydantic import ValidationError
|
|
26
|
+
|
|
27
|
+
from agentic_auth.schemas.edge_trace import (
|
|
28
|
+
EVALUATED_OUTCOMES,
|
|
29
|
+
EdgeEvent,
|
|
30
|
+
EdgeOutcomes,
|
|
31
|
+
EdgeTrace,
|
|
32
|
+
ObservedEdge,
|
|
33
|
+
RecorderErrorLine,
|
|
34
|
+
Source,
|
|
35
|
+
TraceRun,
|
|
36
|
+
Unattributed,
|
|
37
|
+
kind_of,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
TRACE_PATH_ENV = "AGENTIC_AUTH_TRACE_PATH"
|
|
43
|
+
MAX_LINE_BYTES = 4096
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class EdgeRecorder:
|
|
47
|
+
def __init__(self, path: str | os.PathLike[str], source: Source) -> None:
|
|
48
|
+
self._path = os.fspath(path)
|
|
49
|
+
self._source: Source = source
|
|
50
|
+
self._lost = 0
|
|
51
|
+
self._lock = threading.Lock()
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def path(self) -> str:
|
|
55
|
+
return self._path
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def lost(self) -> int:
|
|
59
|
+
"""Events not yet accounted for in the file."""
|
|
60
|
+
return self._lost
|
|
61
|
+
|
|
62
|
+
def record(
|
|
63
|
+
self,
|
|
64
|
+
*,
|
|
65
|
+
acting_agent: str | None,
|
|
66
|
+
target: str | None,
|
|
67
|
+
outcome: str,
|
|
68
|
+
reason: str | None,
|
|
69
|
+
) -> None:
|
|
70
|
+
try:
|
|
71
|
+
event = EdgeEvent(
|
|
72
|
+
ts=datetime.now(UTC),
|
|
73
|
+
source=self._source,
|
|
74
|
+
acting_agent=acting_agent,
|
|
75
|
+
target=target,
|
|
76
|
+
kind=kind_of(target),
|
|
77
|
+
outcome=outcome,
|
|
78
|
+
reason=reason,
|
|
79
|
+
)
|
|
80
|
+
except (ValidationError, ValueError):
|
|
81
|
+
# An event this recorder cannot express faithfully is a lost event, never a
|
|
82
|
+
# guessed one.
|
|
83
|
+
self._note_loss("event did not fit the edge-event schema")
|
|
84
|
+
return
|
|
85
|
+
self._append(event.model_dump_json())
|
|
86
|
+
|
|
87
|
+
def _note_loss(self, why: str) -> None:
|
|
88
|
+
with self._lock:
|
|
89
|
+
self._lost += 1
|
|
90
|
+
logger.error("edge recorder %s lost an event: %s", self._path, why)
|
|
91
|
+
|
|
92
|
+
def _append(self, line: str) -> None:
|
|
93
|
+
data = (line + "\n").encode("utf-8")
|
|
94
|
+
if len(data) > MAX_LINE_BYTES:
|
|
95
|
+
self._note_loss("event line exceeds 4 KiB")
|
|
96
|
+
return
|
|
97
|
+
with self._lock:
|
|
98
|
+
try:
|
|
99
|
+
fd = os.open(self._path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
100
|
+
except OSError as exc:
|
|
101
|
+
self._lost += 1
|
|
102
|
+
logger.error("edge recorder cannot open %s: %s", self._path, type(exc).__name__)
|
|
103
|
+
return
|
|
104
|
+
try:
|
|
105
|
+
if self._lost:
|
|
106
|
+
lost_line = RecorderErrorLine(
|
|
107
|
+
ts=datetime.now(UTC), source=self._source, recorder_error=self._lost
|
|
108
|
+
).model_dump_json()
|
|
109
|
+
os.write(fd, (lost_line + "\n").encode("utf-8"))
|
|
110
|
+
self._lost = 0
|
|
111
|
+
if os.write(fd, data) != len(data):
|
|
112
|
+
self._lost += 1
|
|
113
|
+
except OSError as exc:
|
|
114
|
+
self._lost += 1
|
|
115
|
+
logger.error("edge recorder cannot write %s: %s", self._path, type(exc).__name__)
|
|
116
|
+
finally:
|
|
117
|
+
os.close(fd)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def recorder_from_env(source: Source) -> EdgeRecorder | None:
|
|
121
|
+
path = os.environ.get(TRACE_PATH_ENV)
|
|
122
|
+
return EdgeRecorder(path, source) if path else None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def aggregate(
|
|
126
|
+
event_files: Sequence[Path],
|
|
127
|
+
*,
|
|
128
|
+
started_at: datetime,
|
|
129
|
+
finished_at: datetime,
|
|
130
|
+
command: list[str] | None,
|
|
131
|
+
exit_code: int | None,
|
|
132
|
+
) -> EdgeTrace:
|
|
133
|
+
"""Deduplicate recorded events into one trace. Anything unreadable counts against it."""
|
|
134
|
+
buckets: dict[tuple[str, str], Counter[str]] = {}
|
|
135
|
+
unattributed: Counter[str] = Counter()
|
|
136
|
+
recorder_errors = 0
|
|
137
|
+
events_total = 0
|
|
138
|
+
|
|
139
|
+
for event_file in event_files:
|
|
140
|
+
if not event_file.is_file():
|
|
141
|
+
continue
|
|
142
|
+
for raw in event_file.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
143
|
+
if not raw.strip():
|
|
144
|
+
continue
|
|
145
|
+
try:
|
|
146
|
+
obj = json.loads(raw)
|
|
147
|
+
except ValueError:
|
|
148
|
+
recorder_errors += 1 # includes a line truncated by a killed process
|
|
149
|
+
continue
|
|
150
|
+
|
|
151
|
+
if isinstance(obj, dict) and "recorder_error" in obj:
|
|
152
|
+
try:
|
|
153
|
+
recorder_errors += RecorderErrorLine.model_validate(obj).recorder_error
|
|
154
|
+
except ValidationError:
|
|
155
|
+
recorder_errors += 1
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
event = EdgeEvent.model_validate(obj)
|
|
160
|
+
except ValidationError:
|
|
161
|
+
recorder_errors += 1
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
events_total += 1
|
|
165
|
+
if event.acting_agent and event.target and event.outcome in EVALUATED_OUTCOMES:
|
|
166
|
+
buckets.setdefault((event.acting_agent, event.target), Counter())[
|
|
167
|
+
event.outcome
|
|
168
|
+
] += 1
|
|
169
|
+
else:
|
|
170
|
+
unattributed[event.reason or event.outcome.upper()] += 1
|
|
171
|
+
|
|
172
|
+
edges = [
|
|
173
|
+
ObservedEdge(
|
|
174
|
+
from_=caller,
|
|
175
|
+
to=target,
|
|
176
|
+
kind=kind_of(target) or "tool",
|
|
177
|
+
count=sum(outcomes.values()),
|
|
178
|
+
outcomes=EdgeOutcomes(
|
|
179
|
+
allow=outcomes["allow"], deny=outcomes["deny"], observed=outcomes["observed"]
|
|
180
|
+
),
|
|
181
|
+
)
|
|
182
|
+
for (caller, target), outcomes in sorted(buckets.items())
|
|
183
|
+
]
|
|
184
|
+
return EdgeTrace(
|
|
185
|
+
run=TraceRun(
|
|
186
|
+
started_at=started_at,
|
|
187
|
+
finished_at=finished_at,
|
|
188
|
+
command=command,
|
|
189
|
+
event_files=[str(f) for f in event_files],
|
|
190
|
+
exit_code=exit_code,
|
|
191
|
+
),
|
|
192
|
+
edges=edges,
|
|
193
|
+
unattributed=Unattributed(
|
|
194
|
+
count=sum(unattributed.values()), by_reason=dict(sorted(unattributed.items()))
|
|
195
|
+
),
|
|
196
|
+
recorder_errors=recorder_errors,
|
|
197
|
+
events_total=events_total,
|
|
198
|
+
)
|