authzai 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. agentic_auth/__init__.py +8 -0
  2. agentic_auth/_extras.py +24 -0
  3. agentic_auth/api/__init__.py +0 -0
  4. agentic_auth/api/deps.py +112 -0
  5. agentic_auth/api/errors.py +51 -0
  6. agentic_auth/api/responses.py +38 -0
  7. agentic_auth/api/service_deps.py +113 -0
  8. agentic_auth/api/v1/__init__.py +0 -0
  9. agentic_auth/api/v1/agents.py +88 -0
  10. agentic_auth/api/v1/audit.py +67 -0
  11. agentic_auth/api/v1/authorize.py +439 -0
  12. agentic_auth/api/v1/consent.py +21 -0
  13. agentic_auth/api/v1/decisions.py +43 -0
  14. agentic_auth/api/v1/enrollment.py +48 -0
  15. agentic_auth/api/v1/identity.py +97 -0
  16. agentic_auth/api/v1/jwks.py +21 -0
  17. agentic_auth/api/v1/manifests.py +68 -0
  18. agentic_auth/api/v1/scopes.py +22 -0
  19. agentic_auth/api/v1/token.py +203 -0
  20. agentic_auth/api/v1/transaction.py +94 -0
  21. agentic_auth/boundary/__init__.py +26 -0
  22. agentic_auth/boundary/guarantee.py +96 -0
  23. agentic_auth/cli/__init__.py +27 -0
  24. agentic_auth/cli/audit.py +130 -0
  25. agentic_auth/cli/drift.py +164 -0
  26. agentic_auth/cli/drift_render.py +148 -0
  27. agentic_auth/cli/identity.py +63 -0
  28. agentic_auth/cli/manifest.py +275 -0
  29. agentic_auth/config.py +182 -0
  30. agentic_auth/db.py +49 -0
  31. agentic_auth/embedded/__init__.py +427 -0
  32. agentic_auth/embedded/_schema.py +8 -0
  33. agentic_auth/embedded/_transport.py +39 -0
  34. agentic_auth/embedded/capabilities.py +34 -0
  35. agentic_auth/embedded/export.py +86 -0
  36. agentic_auth/embedded/idp.py +78 -0
  37. agentic_auth/embedded/store.py +240 -0
  38. agentic_auth/errors.py +145 -0
  39. agentic_auth/main.py +141 -0
  40. agentic_auth/models/__init__.py +70 -0
  41. agentic_auth/models/agent.py +58 -0
  42. agentic_auth/models/audit_decision.py +199 -0
  43. agentic_auth/models/compiled_policy.py +28 -0
  44. agentic_auth/models/manifest.py +96 -0
  45. agentic_auth/models/reconciliation_report.py +27 -0
  46. agentic_auth/models/sandbox_run.py +93 -0
  47. agentic_auth/models/session.py +63 -0
  48. agentic_auth/models/step_up_grant.py +106 -0
  49. agentic_auth/models/transaction_token.py +73 -0
  50. agentic_auth/models/trust_anchor.py +59 -0
  51. agentic_auth/models/types.py +95 -0
  52. agentic_auth/observability/__init__.py +370 -0
  53. agentic_auth/observability/config.py +137 -0
  54. agentic_auth/observability/context.py +128 -0
  55. agentic_auth/observability/ids.py +122 -0
  56. agentic_auth/observability/logs.py +191 -0
  57. agentic_auth/observability/pep.py +169 -0
  58. agentic_auth/observability/spans.py +225 -0
  59. agentic_auth/observability/surface.py +286 -0
  60. agentic_auth/observability/tracing.py +167 -0
  61. agentic_auth/redis.py +27 -0
  62. agentic_auth/repositories/__init__.py +0 -0
  63. agentic_auth/repositories/agents.py +96 -0
  64. agentic_auth/repositories/audit_decisions.py +152 -0
  65. agentic_auth/repositories/compiled_policies.py +72 -0
  66. agentic_auth/repositories/manifests.py +149 -0
  67. agentic_auth/repositories/reconciliation_reports.py +40 -0
  68. agentic_auth/repositories/sessions.py +41 -0
  69. agentic_auth/repositories/transaction_tokens.py +60 -0
  70. agentic_auth/repositories/trust_anchors.py +150 -0
  71. agentic_auth/runtime.py +81 -0
  72. agentic_auth/schemas/__init__.py +0 -0
  73. agentic_auth/schemas/agent.py +58 -0
  74. agentic_auth/schemas/audit.py +207 -0
  75. agentic_auth/schemas/authorize.py +205 -0
  76. agentic_auth/schemas/common.py +40 -0
  77. agentic_auth/schemas/consent.py +74 -0
  78. agentic_auth/schemas/dag.py +39 -0
  79. agentic_auth/schemas/edge_trace.py +166 -0
  80. agentic_auth/schemas/identity.py +152 -0
  81. agentic_auth/schemas/manifest.py +117 -0
  82. agentic_auth/schemas/manifest_api.py +38 -0
  83. agentic_auth/schemas/reconciliation.py +49 -0
  84. agentic_auth/schemas/token.py +122 -0
  85. agentic_auth/schemas/transaction.py +28 -0
  86. agentic_auth/sdk/__init__.py +114 -0
  87. agentic_auth/sdk/client.py +677 -0
  88. agentic_auth/sdk/context.py +95 -0
  89. agentic_auth/sdk/drift.py +118 -0
  90. agentic_auth/sdk/errors.py +147 -0
  91. agentic_auth/sdk/identity.py +162 -0
  92. agentic_auth/sdk/planes.py +362 -0
  93. agentic_auth/sdk/provenance.py +63 -0
  94. agentic_auth/services/__init__.py +0 -0
  95. agentic_auth/services/anchors.py +81 -0
  96. agentic_auth/services/audit.py +222 -0
  97. agentic_auth/services/audit_chain.py +144 -0
  98. agentic_auth/services/audit_cursor.py +55 -0
  99. agentic_auth/services/catalog_service.py +58 -0
  100. agentic_auth/services/chain_query.py +152 -0
  101. agentic_auth/services/dag_compiler.py +199 -0
  102. agentic_auth/services/decision_cache.py +123 -0
  103. agentic_auth/services/decision_history.py +71 -0
  104. agentic_auth/services/discovery.py +95 -0
  105. agentic_auth/services/drift.py +330 -0
  106. agentic_auth/services/edge_rules.py +62 -0
  107. agentic_auth/services/edge_trace.py +198 -0
  108. agentic_auth/services/enrollment.py +310 -0
  109. agentic_auth/services/enrollment_rules.py +80 -0
  110. agentic_auth/services/manifest_service.py +166 -0
  111. agentic_auth/services/metrics.py +419 -0
  112. agentic_auth/services/pdp.py +312 -0
  113. agentic_auth/services/policy_loader.py +255 -0
  114. agentic_auth/services/principal.py +143 -0
  115. agentic_auth/services/reconciler.py +119 -0
  116. agentic_auth/services/revocation.py +149 -0
  117. agentic_auth/services/sessions.py +231 -0
  118. agentic_auth/services/taint.py +204 -0
  119. agentic_auth/services/tokens/__init__.py +11 -0
  120. agentic_auth/services/tokens/act_chain.py +76 -0
  121. agentic_auth/services/tokens/exchange.py +319 -0
  122. agentic_auth/services/tokens/jwt_profile.py +362 -0
  123. agentic_auth/services/tokens/keys.py +117 -0
  124. agentic_auth/services/tokens/profile.py +167 -0
  125. agentic_auth/services/tokens/replay.py +53 -0
  126. agentic_auth/services/transactions.py +172 -0
  127. agentic_auth/sidecar/__init__.py +7 -0
  128. agentic_auth/sidecar/__main__.py +66 -0
  129. agentic_auth/sidecar/app.py +349 -0
  130. agentic_auth/sidecar/config.py +253 -0
  131. agentic_auth/sidecar/deny.py +108 -0
  132. agentic_auth/sidecar/enforce.py +640 -0
  133. agentic_auth/sidecar/identity.py +37 -0
  134. agentic_auth/verify/__init__.py +208 -0
  135. agentic_auth/verify/admit.py +131 -0
  136. agentic_auth/verify/anchors.py +250 -0
  137. agentic_auth/verify/canonical.py +228 -0
  138. agentic_auth/verify/grants.py +158 -0
  139. agentic_auth/verify/identity.py +111 -0
  140. agentic_auth/verify/replay.py +67 -0
  141. agentic_auth/verify/transaction.py +164 -0
  142. authzai-0.2.0.dist-info/METADATA +276 -0
  143. authzai-0.2.0.dist-info/RECORD +148 -0
  144. authzai-0.2.0.dist-info/WHEEL +5 -0
  145. authzai-0.2.0.dist-info/entry_points.txt +5 -0
  146. authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
  147. authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
  148. authzai-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,164 @@
1
+ """``agentic-auth drift record|check`` — see https://authzai.dev/reference/cli/drift.
2
+
3
+ ``record`` runs a test command with edge recording switched on and aggregates what the
4
+ sidecar and SDK observed. ``check`` compares a trace with local manifests, offline, and
5
+ exits 0 (pass), 1 (drift), or 2 (could not run) — never 0 without evidence.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import subprocess
12
+ import tempfile
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+
16
+ import typer
17
+ from prometheus_client import write_to_textfile
18
+
19
+ from agentic_auth.cli.drift_render import render_github, render_json, render_text
20
+ from agentic_auth.schemas.edge_trace import DriftReport
21
+ from agentic_auth.services.drift import run_check
22
+ from agentic_auth.services.edge_trace import TRACE_PATH_ENV, aggregate
23
+ from agentic_auth.services.metrics import build_drift_metrics
24
+
25
+ drift_app = typer.Typer(help="Record observed agent edges and check them against manifests")
26
+
27
+ EXIT_PASS = 0
28
+ EXIT_DRIFT = 1
29
+ EXIT_ERROR = 2
30
+ EXIT_FOR_RESULT = {"pass": EXIT_PASS, "drift": EXIT_DRIFT, "error": EXIT_ERROR}
31
+ FORMATS = ("text", "json", "github")
32
+ VERDICTS = ("UNDECLARED_TOOL", "UNDECLARED_DELEGATION", "UNKNOWN_AGENT")
33
+
34
+
35
+ def _fail(message: str) -> typer.Exit:
36
+ typer.echo(f"agentic-auth drift: {message}", err=True)
37
+ return typer.Exit(EXIT_ERROR)
38
+
39
+
40
+ @drift_app.command(
41
+ "record",
42
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
43
+ )
44
+ def record(
45
+ ctx: typer.Context,
46
+ out: Path = typer.Option(..., "--out", help="Where to write the aggregated edge trace"),
47
+ events: Path | None = typer.Option(
48
+ None, "--events", help="Events file to aggregate (required when no command is given)"
49
+ ),
50
+ ) -> None:
51
+ """Run COMMAND (after --) with edge recording on, then aggregate. Exits with COMMAND's code."""
52
+ command = list(ctx.args)
53
+ if not out.parent.is_dir():
54
+ raise _fail(f"cannot write {out}: directory {out.parent} does not exist")
55
+
56
+ started_at = datetime.now(UTC)
57
+ temporary: Path | None = None
58
+ exit_code: int | None = None
59
+
60
+ if command:
61
+ if events is not None and events.is_file() and events.stat().st_size > 0:
62
+ raise _fail(f"refusing to mix runs: {events} already contains events")
63
+ if events is None:
64
+ fd, name = tempfile.mkstemp(prefix="agentic-auth-events-", suffix=".jsonl")
65
+ os.close(fd)
66
+ temporary = events_path = Path(name)
67
+ else:
68
+ events_path = events
69
+ events_path.touch()
70
+ os.chmod(events_path, 0o600)
71
+
72
+ env = {**os.environ, TRACE_PATH_ENV: str(events_path.resolve())}
73
+ try:
74
+ exit_code = subprocess.run(command, env=env, check=False).returncode # noqa: S603
75
+ except OSError as exc:
76
+ if temporary is not None:
77
+ temporary.unlink(missing_ok=True)
78
+ raise _fail(f"cannot run {command[0]!r}: {type(exc).__name__}") from exc
79
+ else:
80
+ if events is None:
81
+ raise _fail("--events is required when no command is given")
82
+ if not events.is_file():
83
+ raise _fail(f"no events file at {events}")
84
+ events_path = events
85
+
86
+ try:
87
+ trace = aggregate(
88
+ [events_path],
89
+ started_at=started_at,
90
+ finished_at=datetime.now(UTC),
91
+ command=command or None,
92
+ exit_code=exit_code,
93
+ )
94
+ out.write_text(trace.model_dump_json(by_alias=True, indent=2) + "\n", encoding="utf-8")
95
+ except OSError as exc:
96
+ raise _fail(f"cannot write {out}: {type(exc).__name__}") from exc
97
+ finally:
98
+ if temporary is not None:
99
+ temporary.unlink(missing_ok=True)
100
+
101
+ typer.echo(
102
+ f"agentic-auth drift record: {len(trace.edges)} edges from {trace.events_total} events "
103
+ f"({trace.unattributed.count} unattributed, {trace.recorder_errors} recorder errors) "
104
+ f"-> {out}",
105
+ err=True,
106
+ )
107
+ raise typer.Exit(exit_code if command and exit_code is not None else EXIT_PASS)
108
+
109
+
110
+ def write_drift_metrics(report: DriftReport, path: Path) -> None:
111
+ """One run's drift metrics, written atomically for the node-exporter textfile collector.
112
+ Labels carry verdicts and results — never agent names."""
113
+ metrics = build_drift_metrics()
114
+ metrics.checks.labels(result=report.result).inc()
115
+ for verdict in VERDICTS:
116
+ metrics.undeclared_edges.labels(verdict=verdict).set(
117
+ sum(1 for edge in report.undeclared if edge.verdict == verdict)
118
+ )
119
+ metrics.observed_edges.set(report.summary.edges_observed)
120
+ metrics.unattributed_calls.set(report.summary.unattributed_calls)
121
+ write_to_textfile(str(path), metrics.registry)
122
+
123
+
124
+ @drift_app.command("check")
125
+ def check(
126
+ manifest: list[Path] = typer.Option(
127
+ ..., "--manifest", help="Manifest directory (repeatable); the union is the declared set"
128
+ ),
129
+ trace: Path = typer.Option(..., "--trace", help="Edge trace from `drift record`"),
130
+ output_format: str = typer.Option("text", "--format", help="text | json | github"),
131
+ report: Path | None = typer.Option(None, "--report", help="Also write the JSON report here"),
132
+ metrics_out: Path | None = typer.Option(
133
+ None, "--metrics-out", help="Write drift metrics to this .prom textfile"
134
+ ),
135
+ deterministic: bool = typer.Option(
136
+ False, "--deterministic", help="Omit the wall-clock timestamp, for golden files"
137
+ ),
138
+ ) -> None:
139
+ """Compare observed edges with declared manifests. Exit 0 pass, 1 drift, 2 could not run."""
140
+ if output_format not in FORMATS:
141
+ raise _fail(f"--format must be one of {', '.join(FORMATS)}, got {output_format!r}")
142
+ if metrics_out is not None and metrics_out.suffix != ".prom":
143
+ raise _fail("--metrics-out must end in .prom for the node-exporter textfile collector")
144
+
145
+ result = run_check(manifest, trace, generated_at=None if deterministic else datetime.now(UTC))
146
+
147
+ try:
148
+ if report is not None:
149
+ report.write_text(render_json(result) + "\n", encoding="utf-8")
150
+ if metrics_out is not None:
151
+ write_drift_metrics(result, metrics_out)
152
+ except OSError as exc:
153
+ raise _fail(f"cannot write output: {type(exc).__name__}") from exc
154
+
155
+ if output_format == "json":
156
+ typer.echo(render_json(result))
157
+ elif output_format == "github":
158
+ text, annotations = render_github(result, os.environ.get("GITHUB_STEP_SUMMARY"))
159
+ typer.echo(text)
160
+ for annotation in annotations:
161
+ typer.echo(annotation)
162
+ else:
163
+ typer.echo(render_text(result))
164
+ raise typer.Exit(EXIT_FOR_RESULT[result.result])
@@ -0,0 +1,148 @@
1
+ """Rendering a drift report — text for humans, JSON for machines, and GitHub for pull requests.
2
+
3
+ Output is deterministic for identical inputs: undeclared edges are already sorted
4
+ by the check, JSON keys are sorted, and the one wall-clock field is dropped under
5
+ ``--deterministic``.
6
+
7
+ The GitHub rendering is the text output plus two things a reviewer sees without opening a
8
+ log: a Markdown table appended to the job's step summary, and one workflow annotation per
9
+ undeclared edge, anchored on the manifest that would have to change.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+
16
+ from agentic_auth.schemas.edge_trace import DriftReport
17
+
18
+ VERDICT_TITLES = {
19
+ "UNDECLARED_TOOL": "Undeclared tool edge",
20
+ "UNDECLARED_DELEGATION": "Undeclared delegation edge",
21
+ "UNKNOWN_AGENT": "Unknown agent",
22
+ }
23
+ RESULT_BADGES = {"pass": "✅", "drift": "❌", "error": "⚠️"}
24
+
25
+
26
+ def _plural(count: int, word: str) -> str:
27
+ return f"{count} {word}" if count == 1 else f"{count} {word}s"
28
+
29
+
30
+ def render_json(report: DriftReport) -> str:
31
+ data = report.model_dump(mode="json", by_alias=True)
32
+ if data["inputs"].get("generated_at") is None:
33
+ data["inputs"].pop("generated_at", None)
34
+ return json.dumps(data, sort_keys=True, indent=2)
35
+
36
+
37
+ def render_text(report: DriftReport) -> str:
38
+ summary = report.summary
39
+ lines: list[str] = []
40
+
41
+ if report.result == "error":
42
+ lines.append("agentic-auth drift check: ERROR, the check could not run")
43
+ lines.append("")
44
+ for error in report.errors:
45
+ suffix = f" ({error.path})" if error.path else ""
46
+ lines.append(f" {error.code}: {error.message}{suffix}")
47
+ elif report.result == "drift":
48
+ undeclared = _plural(summary.edges_undeclared, "undeclared edge")
49
+ observed = _plural(summary.edges_observed, "edge")
50
+ lines.append(
51
+ f"agentic-auth drift check: DRIFT, {undeclared} "
52
+ f"({observed} observed, {summary.edges_declared} declared)"
53
+ )
54
+ lines.append("")
55
+ for edge in report.undeclared:
56
+ lines.append(
57
+ f" {edge.verdict} {edge.from_} -> {edge.to} ({_plural(edge.count, 'call')})"
58
+ )
59
+ lines.append(f" runtime would deny: {edge.runtime_reason}")
60
+ lines.append(f" declared in: {edge.manifest_path or '(no manifest for this agent)'}")
61
+ lines.append(f" fix: {edge.hint}")
62
+ else:
63
+ lines.append(
64
+ f"agentic-auth drift check: PASS, {_plural(summary.edges_observed, 'edge')} observed, "
65
+ "all declared"
66
+ )
67
+
68
+ if report.warnings:
69
+ lines.append("")
70
+ lines.extend(f"warning: {warning.code}: {warning.message}" for warning in report.warnings)
71
+ return "\n".join(lines)
72
+
73
+
74
+ # -- GitHub ----------------------------------------------------------------------------
75
+
76
+
77
+ def _escape_data(text: str) -> str:
78
+ """Workflow-command message escaping."""
79
+ return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
80
+
81
+
82
+ def _escape_property(text: str) -> str:
83
+ """Workflow-command property escaping: data escaping, plus the separators."""
84
+ return _escape_data(text).replace(":", "%3A").replace(",", "%2C")
85
+
86
+
87
+ def _cell(text: object) -> str:
88
+ return str(text).replace("|", "\\|").replace("\n", " ")
89
+
90
+
91
+ def render_annotations(report: DriftReport) -> list[str]:
92
+ if report.result == "error":
93
+ return [
94
+ "::error title=Drift check could not run::"
95
+ + _escape_data(f"{error.code}: {error.message}")
96
+ for error in report.errors
97
+ ]
98
+
99
+ annotations = []
100
+ for edge in report.undeclared:
101
+ message = (
102
+ f"{edge.from_} -> {edge.to} ({_plural(edge.count, 'call')}). "
103
+ f"Runtime would deny with {edge.runtime_reason}."
104
+ )
105
+ location = f"file={_escape_property(edge.manifest_path)}," if edge.manifest_path else ""
106
+ title = _escape_property(VERDICT_TITLES[edge.verdict])
107
+ annotations.append(f"::error {location}title={title}::{_escape_data(message)}")
108
+ return annotations
109
+
110
+
111
+ def render_step_summary(report: DriftReport) -> str:
112
+ summary = report.summary
113
+ lines = [
114
+ f"## {RESULT_BADGES[report.result]} agentic-auth drift check: {report.result.upper()}",
115
+ "",
116
+ "| Edges observed | Declared | Undeclared | Calls | Unattributed calls |",
117
+ "|---|---|---|---|---|",
118
+ f"| {summary.edges_observed} | {summary.edges_declared} | {summary.edges_undeclared} "
119
+ f"| {summary.calls_observed} | {summary.unattributed_calls} |",
120
+ ]
121
+ if report.undeclared:
122
+ lines += [
123
+ "",
124
+ "### Undeclared edges",
125
+ "",
126
+ "| Verdict | From | To | Calls | Runtime reason | Manifest |",
127
+ "|---|---|---|---|---|---|",
128
+ ]
129
+ lines += [
130
+ f"| {_cell(edge.verdict)} | `{_cell(edge.from_)}` | `{_cell(edge.to)}` | {edge.count} "
131
+ f"| {_cell(edge.runtime_reason)} | {_cell(edge.manifest_path or '—')} |"
132
+ for edge in report.undeclared
133
+ ]
134
+ if report.errors:
135
+ lines += ["", "### The check could not run", ""]
136
+ lines += [f"- **{_cell(e.code)}**: {_cell(e.message)}" for e in report.errors]
137
+ if report.warnings:
138
+ lines += ["", "### Warnings", ""]
139
+ lines += [f"- **{_cell(w.code)}**: {_cell(w.message)}" for w in report.warnings]
140
+ return "\n".join(lines) + "\n"
141
+
142
+
143
+ def render_github(report: DriftReport, summary_path: str | None) -> tuple[str, list[str]]:
144
+ """``(text, annotations)``. Appends the Markdown summary to ``summary_path`` when set."""
145
+ if summary_path:
146
+ with open(summary_path, "a", encoding="utf-8") as handle:
147
+ handle.write(render_step_summary(report))
148
+ return render_text(report), render_annotations(report)
@@ -0,0 +1,63 @@
1
+ """``agentic-auth identity`` — key generation, challenge signing, revocation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import typer
9
+ from rich import print as rprint
10
+
11
+ from agentic_auth.sdk.identity import AgentKey
12
+
13
+ app = typer.Typer(help="Agent identity: keys, challenges, revocation.")
14
+
15
+
16
+ @app.command()
17
+ def keygen(out: Path = typer.Option(..., "--out", help="Where to write the PKCS8 PEM")) -> None:
18
+ """Generate an Ed25519 agent key (mode 0600) and print its public JWK."""
19
+ key = AgentKey.generate()
20
+ key.save(out)
21
+ rprint(json.dumps(key.jwk(), indent=2))
22
+
23
+
24
+ @app.command("sign-challenge")
25
+ def sign_challenge(
26
+ key: Path = typer.Option(..., "--key"),
27
+ agent: str = typer.Option(..., "--agent"),
28
+ challenge: Path = typer.Option(..., "--challenge", help="The JSON body from POST .../enroll"),
29
+ aud: str = typer.Option("agentic-auth", "--aud"),
30
+ ) -> None:
31
+ """Sign an enrollment challenge; prints the compact JWS for POST .../enroll/complete."""
32
+ nonce = json.loads(challenge.read_text())["nonce"]
33
+ typer.echo(AgentKey.load(key).sign_challenge(agent, nonce, aud=aud))
34
+
35
+
36
+ @app.command("identity-document")
37
+ def identity_document(
38
+ key: Path = typer.Option(..., "--key"),
39
+ agent: str = typer.Option(..., "--agent"),
40
+ principal_assertion: str | None = typer.Option(None, "--principal-assertion"),
41
+ ) -> None:
42
+ """Print the identity document to POST to .../enroll."""
43
+ doc = AgentKey.load(key).identity_document(agent, principal_assertion=principal_assertion)
44
+ typer.echo(json.dumps({"identity_doc": doc}, indent=2))
45
+
46
+
47
+ @app.command()
48
+ def revoke(
49
+ agent_id: str = typer.Argument(...),
50
+ base_url: str = typer.Option("http://localhost:8000", "--base-url"),
51
+ admin_token: str = typer.Option(..., "--admin-token", envvar="AGENTIC_AUTH_ADMIN_TOKEN"),
52
+ reason: str | None = typer.Option(None, "--reason"),
53
+ ) -> None:
54
+ """Revoke an agent's trust anchor (admin)."""
55
+ import asyncio
56
+
57
+ from agentic_auth.sdk.client import AgenticAuthClient
58
+
59
+ async def _run() -> dict:
60
+ async with AgenticAuthClient(base_url, admin_token=admin_token) as client:
61
+ return await client.revoke(agent_id, reason=reason)
62
+
63
+ rprint(json.dumps(asyncio.run(_run()), indent=2, default=str))
@@ -0,0 +1,275 @@
1
+ """``agentic-auth manifest validate|lint|diff`` — offline authoring helpers.
2
+
3
+ ``diff`` shares :class:`ReconcilerService` and :class:`DiscoveryClient` with the server, so
4
+ its output matches ``POST /v1/agents`` for the same manifest.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import httpx
16
+ import typer
17
+ import yaml
18
+ from pydantic import ValidationError
19
+ from rich import print as rprint
20
+
21
+ from agentic_auth.schemas.manifest import AgentManifest
22
+ from agentic_auth.services.discovery import DiscoveryClient
23
+ from agentic_auth.services.reconciler import ReconcilerService
24
+
25
+ manifest_app = typer.Typer(help="Author, validate, and preview-reconcile agent manifests")
26
+
27
+ EXIT_OK = 0
28
+ EXIT_FINDINGS = 1
29
+ EXIT_USAGE = 2
30
+
31
+
32
+ def _load(path: Path) -> dict[str, Any]:
33
+ if not path.is_file():
34
+ rprint(f"[red]cannot read {path}[/red]")
35
+ raise typer.Exit(EXIT_USAGE)
36
+ text = path.read_text()
37
+ try:
38
+ data = yaml.safe_load(text) # also parses JSON
39
+ except yaml.YAMLError as exc:
40
+ rprint(f"[red]not valid YAML or JSON: {exc}[/red]")
41
+ raise typer.Exit(EXIT_USAGE) from exc
42
+ if not isinstance(data, dict):
43
+ rprint("[red]manifest must be a mapping[/red]")
44
+ raise typer.Exit(EXIT_USAGE)
45
+ return data
46
+
47
+
48
+ def _errors(exc: ValidationError) -> list[dict[str, Any]]:
49
+ return [{"loc": [str(p) for p in e["loc"]], "msg": e["msg"]} for e in exc.errors()]
50
+
51
+
52
+ def _parse(doc: dict[str, Any]) -> AgentManifest:
53
+ try:
54
+ return AgentManifest.model_validate(doc)
55
+ except ValidationError as exc:
56
+ raise _Invalid(_errors(exc)) from exc
57
+
58
+
59
+ class _Invalid(Exception):
60
+ def __init__(self, errors: list[dict[str, Any]]) -> None:
61
+ self.errors = errors
62
+
63
+
64
+ def _make_discovery_client(timeout: float) -> DiscoveryClient:
65
+ return DiscoveryClient(timeout=timeout)
66
+
67
+
68
+ @manifest_app.command()
69
+ def validate(
70
+ file: Path = typer.Argument(..., help="Manifest file (YAML or JSON)"),
71
+ json_out: bool = typer.Option(False, "--json"),
72
+ ) -> None:
73
+ """Schema-validate a manifest. No network calls."""
74
+ doc = _load(file)
75
+ try:
76
+ _parse(doc)
77
+ except _Invalid as inv:
78
+ if json_out:
79
+ typer.echo(json.dumps({"valid": False, "errors": inv.errors}))
80
+ else:
81
+ for e in inv.errors:
82
+ rprint(f"[red]{'.'.join(e['loc'])}[/red]: {e['msg']}")
83
+ raise typer.Exit(EXIT_FINDINGS) from None
84
+ rprint(json.dumps({"valid": True}) if json_out else "[green]valid[/green]")
85
+
86
+
87
+ def _lint_warnings(m: AgentManifest) -> list[dict[str, str]]:
88
+ w: list[dict[str, str]] = []
89
+ depths = [d.max_hop_depth for d in m.spec.downstream_agents]
90
+ if depths and m.spec.hop_budget > max(depths):
91
+ w.append(
92
+ {
93
+ "code": "DEAD_HOP_HEADROOM",
94
+ "message": "hop_budget exceeds every declared max_hop_depth",
95
+ }
96
+ )
97
+ if m.spec.downstream_agents and m.spec.hop_budget == 1:
98
+ w.append(
99
+ {"code": "CANNOT_DELEGATE", "message": "downstream_agents declared but hop_budget is 1"}
100
+ )
101
+ writes = set(m.spec.data_classes.writes)
102
+ for t in m.spec.tools:
103
+ if t.privileged and writes.intersection(t.data_classes):
104
+ w.append(
105
+ {"code": "PRIVILEGED_WRITE", "message": f"privileged tool {t.ref} also writes"}
106
+ )
107
+ seen: set[str] = set()
108
+ for t in m.spec.tools:
109
+ if t.ref in seen:
110
+ w.append({"code": "DUPLICATE_TOOL", "message": f"duplicate tool ref {t.ref}"})
111
+ seen.add(t.ref)
112
+ used = {dc for t in m.spec.tools for dc in t.data_classes}
113
+ for dc in set(m.spec.data_classes.reads) | writes:
114
+ if dc not in used:
115
+ w.append(
116
+ {"code": "UNUSED_DATA_CLASS", "message": f"data class {dc} referenced by no tool"}
117
+ )
118
+ return w
119
+
120
+
121
+ @manifest_app.command()
122
+ def lint(
123
+ file: Path = typer.Argument(...),
124
+ json_out: bool = typer.Option(False, "--json"),
125
+ strict: bool = typer.Option(False, "--strict", help="exit non-zero on any warning"),
126
+ ) -> None:
127
+ """Schema-validate, then report best-practice warnings."""
128
+ doc = _load(file)
129
+ try:
130
+ m = _parse(doc)
131
+ except _Invalid as inv:
132
+ rprint(
133
+ json.dumps({"valid": False, "errors": inv.errors}) if json_out else "[red]invalid[/red]"
134
+ )
135
+ raise typer.Exit(EXIT_FINDINGS) from None
136
+ warnings = _lint_warnings(m)
137
+ if json_out:
138
+ typer.echo(json.dumps({"warnings": warnings}))
139
+ else:
140
+ for warn in warnings:
141
+ rprint(f"[yellow]{warn['code']}[/yellow]: {warn['message']}")
142
+ if not warnings:
143
+ rprint("[green]no warnings[/green]")
144
+ if strict and warnings:
145
+ raise typer.Exit(EXIT_FINDINGS) from None
146
+
147
+
148
+ async def _run_diff(m: AgentManifest, timeout: float) -> dict[str, Any]:
149
+ reconciler = ReconcilerService()
150
+ client = _make_discovery_client(timeout)
151
+ try:
152
+ discovered = await client.discover(reconciler.authorities(m))
153
+ finally:
154
+ await client.aclose()
155
+ outcome = reconciler.reconcile(m, discovered)
156
+ return {
157
+ "status": outcome.status,
158
+ "diff": [d.model_dump(mode="json") for d in outcome.diff],
159
+ }
160
+
161
+
162
+ def _make_http_client(timeout: float) -> httpx.AsyncClient:
163
+ return httpx.AsyncClient(timeout=timeout)
164
+
165
+
166
+ async def _register_all(
167
+ control_plane: str,
168
+ admin_token: str,
169
+ order: list[str],
170
+ manifests: dict[str, AgentManifest],
171
+ override_reason: str,
172
+ timeout: float,
173
+ ) -> list[tuple[str, int, dict[str, Any]]]:
174
+ client = _make_http_client(timeout)
175
+ results: list[tuple[str, int, dict[str, Any]]] = []
176
+ try:
177
+ for name in order:
178
+ response = await client.post(
179
+ f"{control_plane.rstrip('/')}/v1/agents",
180
+ headers={"Authorization": f"Bearer {admin_token}"},
181
+ json={
182
+ "name": name,
183
+ "manifest": manifests[name].canonical_doc(),
184
+ # Test environments rarely serve the tools' discovery documents. An
185
+ # unreachable capability source lands in needs_review — not a hard
186
+ # reject — and a recorded override reason reconciles it.
187
+ "override": {"reason": override_reason},
188
+ },
189
+ )
190
+ try:
191
+ body = response.json()
192
+ except ValueError:
193
+ body = {}
194
+ results.append((name, response.status_code, body))
195
+ finally:
196
+ await client.aclose()
197
+ return results
198
+
199
+
200
+ @manifest_app.command("register-dir")
201
+ def register_dir(
202
+ directory: Path = typer.Argument(..., help="Directory of agent manifests"),
203
+ control_plane: str = typer.Option(..., "--control-plane", help="Control plane base URL"),
204
+ override_reason: str = typer.Option(
205
+ ..., "--override-reason", help="Recorded on every registration that needs an override"
206
+ ),
207
+ timeout: float = typer.Option(10.0, "--timeout"),
208
+ ) -> None:
209
+ """Register every manifest in a directory, leaf first — for test and CI environments.
210
+
211
+ The admin token is read from AGENTIC_AUTH_ADMIN_TOKEN and never accepted on the command
212
+ line, where it would land in shell history and CI logs.
213
+ """
214
+ from agentic_auth.services.drift import load_manifest_dirs, registration_order
215
+
216
+ admin_token = os.environ.get("AGENTIC_AUTH_ADMIN_TOKEN", "")
217
+ if not admin_token:
218
+ rprint("[red]AGENTIC_AUTH_ADMIN_TOKEN is not set[/red]")
219
+ raise typer.Exit(EXIT_USAGE)
220
+ if not override_reason.strip():
221
+ rprint("[red]--override-reason must not be empty[/red]")
222
+ raise typer.Exit(EXIT_USAGE)
223
+
224
+ loaded = load_manifest_dirs([directory])
225
+ if loaded.errors:
226
+ for error in loaded.errors:
227
+ rprint(f"[red]{error.code}[/red] {error.path or ''} {error.message}")
228
+ raise typer.Exit(EXIT_USAGE)
229
+
230
+ order = registration_order(loaded.manifests)
231
+ results = asyncio.run(
232
+ _register_all(control_plane, admin_token, order, loaded.manifests, override_reason, timeout)
233
+ )
234
+
235
+ failed = False
236
+ for name, status, body in results:
237
+ if status == 201:
238
+ version = body.get("manifest_version")
239
+ rprint(f"registered {name}: {body.get('status')} (manifest v{version})")
240
+ continue
241
+ failed = True
242
+ error = body.get("error", {}) if isinstance(body, dict) else {}
243
+ code, message = error.get("code", ""), error.get("message", "")
244
+ rprint(f"[red]failed {name}: HTTP {status} {code}[/red] {message}")
245
+ for entry in (error.get("details") or {}).get("diff", []):
246
+ rprint(f" {entry.get('code')} {entry.get('tool_ref')} — {entry.get('remedy')}")
247
+ if failed:
248
+ raise typer.Exit(EXIT_FINDINGS)
249
+
250
+
251
+ @manifest_app.command()
252
+ def diff(
253
+ file: Path = typer.Argument(...),
254
+ json_out: bool = typer.Option(False, "--json"),
255
+ discovery_timeout: float = typer.Option(5.0, "--discovery-timeout"),
256
+ ) -> None:
257
+ """Preview the reconciliation diff the server would return for this manifest."""
258
+ doc = _load(file)
259
+ try:
260
+ m = _parse(doc)
261
+ except _Invalid as inv:
262
+ rprint(
263
+ json.dumps({"valid": False, "errors": inv.errors}) if json_out else "[red]invalid[/red]"
264
+ )
265
+ raise typer.Exit(EXIT_FINDINGS) from None
266
+
267
+ result = asyncio.run(_run_diff(m, discovery_timeout))
268
+ if json_out:
269
+ typer.echo(json.dumps(result))
270
+ else:
271
+ rprint(f"status: [bold]{result['status']}[/bold]")
272
+ for d in result["diff"]:
273
+ rprint(f" [red]{d['code']}[/red] {d['tool_ref']} — {d['remedy']}")
274
+ if result["status"] != "reconciled":
275
+ raise typer.Exit(EXIT_FINDINGS) from None