agent-certify 0.5.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.
- agent_certify/__init__.py +53 -0
- agent_certify/anomaly.py +250 -0
- agent_certify/baseline.py +259 -0
- agent_certify/blast.py +141 -0
- agent_certify/certificate.py +503 -0
- agent_certify/cli.py +708 -0
- agent_certify/graph.py +325 -0
- agent_certify/mcp_server.py +603 -0
- agent_certify/otel.py +195 -0
- agent_certify/parser/__init__.py +10 -0
- agent_certify/parser/auto.py +118 -0
- agent_certify/parser/base.py +67 -0
- agent_certify/parser/claude_code.py +267 -0
- agent_certify/parser/cursor_trace.py +227 -0
- agent_certify/parser/mcp_logs.py +240 -0
- agent_certify/paths.py +128 -0
- agent_certify/policy.py +214 -0
- agent_certify/scanner.py +400 -0
- agent_certify/viz.py +299 -0
- agent_certify/watcher.py +242 -0
- agent_certify-0.5.0.dist-info/METADATA +564 -0
- agent_certify-0.5.0.dist-info/RECORD +26 -0
- agent_certify-0.5.0.dist-info/WHEEL +5 -0
- agent_certify-0.5.0.dist-info/entry_points.txt +2 -0
- agent_certify-0.5.0.dist-info/licenses/LICENSE +204 -0
- agent_certify-0.5.0.dist-info/top_level.txt +1 -0
agent_certify/cli.py
ADDED
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Command-line interface.
|
|
5
|
+
|
|
6
|
+
agent-certify scan <session.jsonl | project-dir> [--format text|json|markdown|html] [-o FILE]
|
|
7
|
+
[--perspective engineering|risk|compliance|monitoring|classic]
|
|
8
|
+
[--baseline FILE | --no-baseline] [--policy FILE | --no-policy] [--include-mcp]
|
|
9
|
+
[--fail-on critical|warning|never]
|
|
10
|
+
agent-certify watch <session.jsonl | project-dir> [--interval S] [--scans N] [--duration S]
|
|
11
|
+
[--baseline FILE | --no-baseline] [--policy FILE | --no-policy] [--perspective P]
|
|
12
|
+
agent-certify learn <session.jsonl | dir>... [-o FILE]
|
|
13
|
+
agent-certify suggest-policy [--baseline FILE] [-o FILE] [--force]
|
|
14
|
+
agent-certify mcp # MCP server on stdio
|
|
15
|
+
(scan and watch take --otel / --otel-stdout to emit OpenTelemetry spans)
|
|
16
|
+
agent-certify blast <path> --node bash
|
|
17
|
+
agent-certify keygen signing.key
|
|
18
|
+
agent-certify certify <path> --key signing.key [--validity-days 90] -o system.cert.json
|
|
19
|
+
agent-certify verify system.cert.json <path> --public-key signing.key.pub
|
|
20
|
+
[--ignore-expiry] [--expect-system-id ID] [--allow-unsigned]
|
|
21
|
+
|
|
22
|
+
Exit codes: ``scan`` returns 2 when a finding reaches ``--fail-on`` (default:
|
|
23
|
+
any critical anomaly or critical policy violation); ``verify`` returns 1 on
|
|
24
|
+
drift or an untrusted certificate, 2 on usage errors.
|
|
25
|
+
|
|
26
|
+
A directory is scanned session by session and as one merged graph (every
|
|
27
|
+
session's agents and tools combined); ``html``, ``blast``, ``certify`` and
|
|
28
|
+
``verify`` use the merged graph. Anomalies and policy are evaluated per session.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import argparse
|
|
33
|
+
import contextlib
|
|
34
|
+
import json
|
|
35
|
+
import logging
|
|
36
|
+
import os
|
|
37
|
+
import stat
|
|
38
|
+
import sys
|
|
39
|
+
import textwrap
|
|
40
|
+
from datetime import datetime, timezone
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
|
|
43
|
+
from agent_certify import __version__
|
|
44
|
+
from agent_certify.anomaly import AnomalyDetector, AnomalyReport
|
|
45
|
+
from agent_certify.baseline import DEFAULT_BASELINE_PATH, Baseline, BaselineLearner, load_baseline
|
|
46
|
+
from agent_certify.blast import BlastRadiusAnalyzer
|
|
47
|
+
from agent_certify.certificate import DEFAULT_VALIDITY_DAYS, AgentCertificate, _public_key_hex, generate_keypair
|
|
48
|
+
from agent_certify.graph import AgentGraph
|
|
49
|
+
from agent_certify.mcp_server import AgentCertifyMCPServer
|
|
50
|
+
from agent_certify.otel import DEFAULT_TRACES_PATH, OTelExporter
|
|
51
|
+
from agent_certify.parser import AutoParser, MCPLogsParser
|
|
52
|
+
from agent_certify.parser.auto import is_trace_dir
|
|
53
|
+
from agent_certify.paths import expand_cli
|
|
54
|
+
from agent_certify.policy import DEFAULT_POLICY_PATH, Policy, PolicyGenerator, PolicyViolation
|
|
55
|
+
from agent_certify.scanner import AgentFIScanner, Perspective, ScanResult
|
|
56
|
+
from agent_certify.watcher import SessionWatcher, latest_session
|
|
57
|
+
|
|
58
|
+
DEFAULT_PATH = "~/.claude/projects"
|
|
59
|
+
FAIL_EXIT = 2
|
|
60
|
+
SKIPPED_WARN_RATIO = 0.05
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _path(p: str) -> Path:
|
|
64
|
+
"""A path typed by the user: ``~`` and environment variables are expanded, as a shell would."""
|
|
65
|
+
return expand_cli(p)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _warn(message: str) -> None:
|
|
69
|
+
print(f"WARNING: {message}", file=sys.stderr)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def load(path: str, include_mcp: bool = False) -> tuple[list[AgentGraph], AgentGraph]:
|
|
73
|
+
"""(per-session graphs, merged graph) for a session file or a directory.
|
|
74
|
+
|
|
75
|
+
The format is detected from the content (Claude Code transcript, Cursor
|
|
76
|
+
Agent Trace, MCP server log). ``include_mcp`` adds each session's calls from
|
|
77
|
+
the MCP server logs.
|
|
78
|
+
"""
|
|
79
|
+
p = _path(path)
|
|
80
|
+
parser = AutoParser()
|
|
81
|
+
try:
|
|
82
|
+
if p.is_file() or is_trace_dir(p):
|
|
83
|
+
graphs = [parser.parse(str(p))]
|
|
84
|
+
elif p.is_dir():
|
|
85
|
+
graphs = parser.parse_directory(str(p))
|
|
86
|
+
if not graphs:
|
|
87
|
+
raise SystemExit(f"agent-certify: no sessions (.jsonl, .agent-trace) found under {p}")
|
|
88
|
+
else:
|
|
89
|
+
raise SystemExit(f"agent-certify: {p} does not exist")
|
|
90
|
+
except ValueError as exc:
|
|
91
|
+
raise SystemExit(f"agent-certify: {exc}") from exc
|
|
92
|
+
if include_mcp:
|
|
93
|
+
mcp = MCPLogsParser()
|
|
94
|
+
enriched, added = [], 0
|
|
95
|
+
for g in graphs:
|
|
96
|
+
enriched.append(mcp.enrich(g))
|
|
97
|
+
added += mcp.added_calls
|
|
98
|
+
graphs = enriched
|
|
99
|
+
print(f"MCP logs: {added} call(s) added from {len(mcp.find_logs())} log file(s) on this machine"
|
|
100
|
+
if mcp.roots else "MCP logs: no log directory on this platform", file=sys.stderr)
|
|
101
|
+
if len(graphs) == 1:
|
|
102
|
+
return graphs, graphs[0]
|
|
103
|
+
return graphs, AgentGraph.merge(graphs, session_id=f"{p.name} ({len(graphs)} sessions)")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ---------------------------------------------------------------- formatting
|
|
107
|
+
def _fmt_duration(s: float | None) -> str:
|
|
108
|
+
if not s:
|
|
109
|
+
return "-"
|
|
110
|
+
return f"{s / 3600:.1f}h" if s >= 3600 else f"{s / 60:.0f}m"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_LEVEL_ORDER = {"high": 0, "medium": 1, "low": 2}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _skipped_note(g: AgentGraph) -> str | None:
|
|
117
|
+
"""A line about unreadable records, or None when every record was read."""
|
|
118
|
+
if not g.skipped_records:
|
|
119
|
+
return None
|
|
120
|
+
total = g.total_messages + g.skipped_records
|
|
121
|
+
share = g.skipped_records / total if total else 1.0
|
|
122
|
+
return (f"Skipped records {g.skipped_records} ({share:.1%} of {total}) — malformed or oversized lines; "
|
|
123
|
+
"the graph may be incomplete")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _text_report(g: AgentGraph, r: ScanResult, anomalies: AnomalyReport | None = None,
|
|
127
|
+
baseline: Baseline | None = None, violations: str | None = None) -> str:
|
|
128
|
+
fi_line = f"Fragility Index {r.fi:.4f} ({len(r.fragile_edges)}/{r.edge_count} links with tri(e)=0"
|
|
129
|
+
fi_line += f"; baseline: {baseline.fi_mean:.2f} ± {baseline.fi_std:.2f})" if baseline else ")"
|
|
130
|
+
lines = [
|
|
131
|
+
f"Session {g.session_id}",
|
|
132
|
+
f"Project {g.project or '-'}",
|
|
133
|
+
f"Messages {g.total_messages} Tool calls {g.total_tool_calls} Duration {_fmt_duration(g.duration_seconds)}",
|
|
134
|
+
fi_line,
|
|
135
|
+
]
|
|
136
|
+
note = _skipped_note(g)
|
|
137
|
+
if note:
|
|
138
|
+
lines.append(note)
|
|
139
|
+
lines.append("")
|
|
140
|
+
if anomalies is not None:
|
|
141
|
+
lines += [str(anomalies), ""]
|
|
142
|
+
if violations is not None:
|
|
143
|
+
lines += [violations, ""]
|
|
144
|
+
lines += [
|
|
145
|
+
(f"Nodes {r.node_count} Links {r.edge_count} Bridges {len(r.bridges)} "
|
|
146
|
+
f"Components {r.components} Articulation points {len(r.articulation_points)}"),
|
|
147
|
+
"",
|
|
148
|
+
f"{'NODE':<52} {'KIND':<12} {'CALLS':>6} {'ERR':>4} {'dFI':>8} ROLE",
|
|
149
|
+
]
|
|
150
|
+
for nid in sorted(g.nodes, key=lambda n: (_LEVEL_ORDER[r.node_levels[n]], -g.nodes[n].call_count, n)):
|
|
151
|
+
n = g.nodes[nid]
|
|
152
|
+
label = f"{nid[:14]} {n.name}" if n.kind == "agent" else nid
|
|
153
|
+
lines.append(f"{label[:52]:<52} {n.kind:<12} {n.call_count:>6} {n.error_count:>4} "
|
|
154
|
+
f"{r.fi_deltas[nid]:>+8.4f} {r.node_classifications[nid]}")
|
|
155
|
+
triangulated = sorted((e for e in g.edges if e.tri_count > 0), key=lambda e: -e.tri_count)
|
|
156
|
+
if triangulated:
|
|
157
|
+
lines += ["", "Links with a backup path (tri(e) > 0):"]
|
|
158
|
+
lines += [f" {e.source} -> {e.target} tri={e.tri_count}" for e in triangulated]
|
|
159
|
+
return "\n".join(lines)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _markdown_report(g: AgentGraph, r: ScanResult, anomalies: AnomalyReport | None = None) -> str:
|
|
163
|
+
lines = [
|
|
164
|
+
f"## agent-certify scan: `{g.session_id}`", "",
|
|
165
|
+
f"- **Project:** {g.project or '-'}",
|
|
166
|
+
f"- **Fragility Index:** {r.fi:.4f} ({len(r.fragile_edges)}/{r.edge_count} links with tri(e)=0)",
|
|
167
|
+
f"- **Nodes / links / bridges:** {r.node_count} / {r.edge_count} / {len(r.bridges)}",
|
|
168
|
+
(f"- **Tool calls:** {g.total_tool_calls} · **Messages:** {g.total_messages} · "
|
|
169
|
+
f"**Duration:** {_fmt_duration(g.duration_seconds)}"),
|
|
170
|
+
]
|
|
171
|
+
note = _skipped_note(g)
|
|
172
|
+
if note:
|
|
173
|
+
lines.append(f"- **{note}**")
|
|
174
|
+
lines += ["", "| Node | Kind | Calls | Errors | ΔFI | Role |", "|---|---|--:|--:|--:|---|"]
|
|
175
|
+
for nid in sorted(g.nodes, key=lambda n: -g.nodes[n].call_count):
|
|
176
|
+
n = g.nodes[nid]
|
|
177
|
+
lines.append(f"| `{nid}` | {n.kind} | {n.call_count} | {n.error_count} | "
|
|
178
|
+
f"{r.fi_deltas[nid]:+.4f} | {r.node_classifications[nid]} |")
|
|
179
|
+
if anomalies is not None:
|
|
180
|
+
lines += ["", f"### Anomalies: {anomalies.summary}", ""]
|
|
181
|
+
lines += [f"- **{a.severity.upper()}** {a.message}" + (f" — {a.detail}" if a.detail else "")
|
|
182
|
+
for a in anomalies.anomalies]
|
|
183
|
+
return "\n".join(lines)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _counts(rep: AnomalyReport | None, violations: list[PolicyViolation] | None) -> tuple[str, str]:
|
|
187
|
+
anomalies = "-" if rep is None else (
|
|
188
|
+
", ".join(f"{rep.count(s)} {s}" for s in ("critical", "warning", "info") if rep.count(s)) or "0")
|
|
189
|
+
if violations is None:
|
|
190
|
+
return anomalies, "-"
|
|
191
|
+
by = {s: sum(1 for v in violations if v.severity == s) for s in ("critical", "warning")}
|
|
192
|
+
return anomalies, ", ".join(f"{n} {s}" for s, n in by.items() if n) or "0"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _session_table(sessions: list[dict], with_anomalies: bool, with_policy: bool) -> str:
|
|
196
|
+
head = f"{'SESSION':<38} {'AGENTS':>6} {'TOOLS':>5} {'CALLS':>6} {'LINKS':>5} {'BRIDGES':>7} {'FI':>7}"
|
|
197
|
+
head += " ANOMALIES" + " " * 10 if with_anomalies else ""
|
|
198
|
+
head += " VIOLATIONS" if with_policy else ""
|
|
199
|
+
lines = [head.rstrip()]
|
|
200
|
+
for s in sessions:
|
|
201
|
+
g, r = s["graph"], s["result"]
|
|
202
|
+
agents = sum(1 for n in g.nodes.values() if n.kind == "agent")
|
|
203
|
+
tools = sum(1 for n in g.nodes.values() if n.kind == "tool")
|
|
204
|
+
row = (f"{(g.session_id or '')[:38]:<38} {agents:>6} {tools:>5} {g.total_tool_calls:>6} "
|
|
205
|
+
f"{r.edge_count:>5} {len(r.bridges):>7} {r.fi:>7.4f}")
|
|
206
|
+
anomaly_text, violation_text = _counts(s["anomalies"], s["violations"])
|
|
207
|
+
if with_anomalies:
|
|
208
|
+
row += f" {anomaly_text:<19}"
|
|
209
|
+
if with_policy:
|
|
210
|
+
row += f" {violation_text}"
|
|
211
|
+
lines.append(row.rstrip())
|
|
212
|
+
return "\n".join(lines)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _fmt_period(start: str, end: str) -> str:
|
|
216
|
+
def parse(s):
|
|
217
|
+
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ") if s else None
|
|
218
|
+
a, b = parse(start), parse(end)
|
|
219
|
+
if not a or not b:
|
|
220
|
+
return "unknown period"
|
|
221
|
+
|
|
222
|
+
def day(d):
|
|
223
|
+
return f"{d:%b} {d.day}"
|
|
224
|
+
if a.year == b.year:
|
|
225
|
+
return f"{day(a)} — {day(b)}, {b.year}"
|
|
226
|
+
return f"{day(a)}, {a.year} — {day(b)}, {b.year}"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _learn_report(b: Baseline, saved: Path) -> str:
|
|
230
|
+
tools = sorted(b.tool_frequency.items(), key=lambda kv: (-kv[1], kv[0].lower()))
|
|
231
|
+
tool_text = textwrap.fill(", ".join(f"{t} ({f:.0%})" for t, f in tools), width=88,
|
|
232
|
+
initial_indent=" ", subsequent_indent=" ", break_on_hyphens=False)
|
|
233
|
+
return "\n".join([
|
|
234
|
+
(f"Learned baseline from {b.learned_from} session{'s' if b.learned_from != 1 else ''} "
|
|
235
|
+
f"({_fmt_period(b.period_start, b.period_end)})"),
|
|
236
|
+
"",
|
|
237
|
+
"Structural profile:",
|
|
238
|
+
f" FI: {b.fi_mean:.2f} ± {b.fi_std:.2f} (range: {b.fi_min:.2f} — {b.fi_max:.2f})",
|
|
239
|
+
f" Nodes: {b.node_count_mean:.1f} ± {b.node_count_std:.1f}",
|
|
240
|
+
f" Links: {b.edge_count_mean:.1f} ± {b.edge_count_std:.1f}",
|
|
241
|
+
f" Bridges: {b.bridge_count_mean:.1f} ± {b.bridge_count_std:.1f}",
|
|
242
|
+
"",
|
|
243
|
+
f"Tools seen ({len(b.known_tools)}):",
|
|
244
|
+
tool_text,
|
|
245
|
+
"",
|
|
246
|
+
(f"Sub-agents: {b.sub_agent_count_mean:.1f} ± {b.sub_agent_count_std:.1f} "
|
|
247
|
+
f"(max seen: {b.max_sub_agents_seen})"),
|
|
248
|
+
f"Error rate: {b.error_rate_mean:.1%} ± {b.error_rate_std:.1%}",
|
|
249
|
+
f"Known links: {len(b.known_links)}",
|
|
250
|
+
"",
|
|
251
|
+
f"Saved to {saved.as_posix()}",
|
|
252
|
+
])
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _emit(text: str, output: str | None) -> None:
|
|
256
|
+
if output:
|
|
257
|
+
Path(output).write_text(text, encoding="utf-8")
|
|
258
|
+
print(f"wrote {output}", file=sys.stderr)
|
|
259
|
+
else:
|
|
260
|
+
sys.stdout.write(text + ("\n" if not text.endswith("\n") else ""))
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ------------------------------------------------------------------ commands
|
|
264
|
+
def _find_file(explicit: str | None, disabled: bool, default: Path, loader, what: str):
|
|
265
|
+
"""Load ``explicit``, else ``default`` if it exists; (None, "") when disabled or absent."""
|
|
266
|
+
if disabled:
|
|
267
|
+
return None, ""
|
|
268
|
+
if explicit:
|
|
269
|
+
p = _path(explicit)
|
|
270
|
+
if not p.is_file():
|
|
271
|
+
raise SystemExit(f"agent-certify: {what} {p} not found")
|
|
272
|
+
else:
|
|
273
|
+
p = default
|
|
274
|
+
if not p.is_file():
|
|
275
|
+
return None, ""
|
|
276
|
+
try:
|
|
277
|
+
return loader(p), p.as_posix()
|
|
278
|
+
except (ValueError, KeyError, TypeError, OSError, json.JSONDecodeError) as exc:
|
|
279
|
+
raise SystemExit(f"agent-certify: {p} is not a valid {what} ({exc})") from None
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _find_baseline(args) -> tuple[Baseline | None, str]:
|
|
283
|
+
"""The baseline to compare against: --baseline, else ./.agent-certify/baseline.json if present."""
|
|
284
|
+
return _find_file(args.baseline, args.no_baseline, DEFAULT_BASELINE_PATH, load_baseline, "baseline")
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _find_policy(args) -> tuple[Policy | None, str]:
|
|
288
|
+
"""The policy to enforce: --policy, else ./.agent-certify/policy.json if present."""
|
|
289
|
+
return _find_file(args.policy, args.no_policy, DEFAULT_POLICY_PATH, Policy.load, "policy")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _violations_text(violations: list[PolicyViolation]) -> str:
|
|
293
|
+
if not violations:
|
|
294
|
+
return "✓ No policy violations"
|
|
295
|
+
lines = [f"⛔ POLICY VIOLATIONS ({len(violations)}):", ""]
|
|
296
|
+
for v in violations:
|
|
297
|
+
lines.append(f"{'[' + v.severity.upper() + ']':<11}{v.message}")
|
|
298
|
+
lines.append(f"{'':<11}Rule: {v.rule.describe()} — {v.rule.message}")
|
|
299
|
+
lines.append("")
|
|
300
|
+
return "\n".join(lines).rstrip()
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _fails(sessions: list[dict], fail_on: str) -> bool:
|
|
304
|
+
"""True when a session has a finding at or above ``fail_on`` (info-level anomalies never count)."""
|
|
305
|
+
if fail_on == "never":
|
|
306
|
+
return False
|
|
307
|
+
levels = {"critical"} if fail_on == "critical" else {"critical", "warning"}
|
|
308
|
+
for s in sessions:
|
|
309
|
+
if s["anomalies"] is not None and any(a.severity in levels for a in s["anomalies"].anomalies):
|
|
310
|
+
return True
|
|
311
|
+
if s["violations"] is not None and any(v.severity in levels for v in s["violations"]):
|
|
312
|
+
return True
|
|
313
|
+
return False
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def cmd_scan(args) -> int:
|
|
317
|
+
started = datetime.now(timezone.utc)
|
|
318
|
+
# --otel-stdout keeps stdout for OTLP lines (to pipe into a collector); the report goes to stderr.
|
|
319
|
+
with contextlib.redirect_stdout(sys.stderr) if args.otel_stdout else contextlib.nullcontext():
|
|
320
|
+
sessions = _scan_report(args)
|
|
321
|
+
if args.otel or args.otel_stdout:
|
|
322
|
+
exporter = OTelExporter()
|
|
323
|
+
written = None
|
|
324
|
+
for s in sessions: # one span per session
|
|
325
|
+
span = exporter.export_scan(s["graph"], s["result"], s["anomalies"], s["violations"], start_time=started)
|
|
326
|
+
written = exporter.write(span, args.otel_file, stdout=args.otel_stdout)
|
|
327
|
+
if written:
|
|
328
|
+
print(f"OTel: {len(sessions)} span(s) appended to {written.as_posix()}", file=sys.stderr)
|
|
329
|
+
for s in sessions:
|
|
330
|
+
g = s["graph"]
|
|
331
|
+
total = g.total_messages + g.skipped_records
|
|
332
|
+
if total and g.skipped_records / total > SKIPPED_WARN_RATIO:
|
|
333
|
+
_warn(f"{g.session_id}: {g.skipped_records} of {total} records could not be read")
|
|
334
|
+
if _fails(sessions, args.fail_on):
|
|
335
|
+
print(f"agent-certify: findings at or above '{args.fail_on}' (exit {FAIL_EXIT})", file=sys.stderr)
|
|
336
|
+
return FAIL_EXIT
|
|
337
|
+
return 0
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _scan_report(args) -> list[dict]:
|
|
341
|
+
"""Print the report; return every session's graph, scan, anomalies and violations."""
|
|
342
|
+
graphs, merged = load(args.path, include_mcp=args.include_mcp)
|
|
343
|
+
baseline, source = _find_baseline(args)
|
|
344
|
+
policy, policy_source = _find_policy(args)
|
|
345
|
+
detector = AnomalyDetector(baseline, source) if baseline else None
|
|
346
|
+
sessions = []
|
|
347
|
+
for g in graphs:
|
|
348
|
+
r = AgentFIScanner(g, perspective=args.perspective).scan()
|
|
349
|
+
sessions.append({"graph": g, "result": r,
|
|
350
|
+
"anomalies": detector.detect(g, r) if detector else None,
|
|
351
|
+
"violations": policy.check(g) if policy else None})
|
|
352
|
+
single = len(graphs) == 1
|
|
353
|
+
result = sessions[0]["result"] if single else AgentFIScanner(merged, perspective=args.perspective).scan()
|
|
354
|
+
anomalies = sessions[0]["anomalies"] if single else None
|
|
355
|
+
violations = sessions[0]["violations"] if single else None
|
|
356
|
+
|
|
357
|
+
if args.format == "json":
|
|
358
|
+
payload = {"graph": merged.to_dict(), "scan": result.to_dict()}
|
|
359
|
+
if anomalies is not None:
|
|
360
|
+
payload["anomalies"] = anomalies.to_dict()
|
|
361
|
+
if violations is not None:
|
|
362
|
+
payload["policy_violations"] = [v.to_dict() for v in violations]
|
|
363
|
+
if not single:
|
|
364
|
+
payload["sessions"] = []
|
|
365
|
+
for s in sessions:
|
|
366
|
+
entry = {"session_id": s["graph"].session_id, "project": s["graph"].project,
|
|
367
|
+
"scan": s["result"].to_dict()}
|
|
368
|
+
if s["anomalies"] is not None:
|
|
369
|
+
entry["anomalies"] = s["anomalies"].to_dict()
|
|
370
|
+
if s["violations"] is not None:
|
|
371
|
+
entry["policy_violations"] = [v.to_dict() for v in s["violations"]]
|
|
372
|
+
payload["sessions"].append(entry)
|
|
373
|
+
_emit(json.dumps(payload, indent=2), args.output)
|
|
374
|
+
elif args.format == "html":
|
|
375
|
+
from agent_certify.viz import render_html
|
|
376
|
+
out = args.output or f"agent-graph-{_safe(merged.session_id)}.html"
|
|
377
|
+
per_session = None if single or not (detector or policy) else [
|
|
378
|
+
(s["graph"].session_id or "", s["anomalies"], s["violations"]) for s in sessions]
|
|
379
|
+
Path(out).write_text(render_html(merged, result, perspective=args.perspective, anomalies=anomalies,
|
|
380
|
+
violations=violations, session_findings=per_session), encoding="utf-8")
|
|
381
|
+
print(f"wrote {out}")
|
|
382
|
+
elif args.format == "markdown":
|
|
383
|
+
text = _markdown_report(merged, result, anomalies)
|
|
384
|
+
if violations is not None:
|
|
385
|
+
text += f"\n\n### Policy violations: {len(violations)}\n\n" + "\n".join(
|
|
386
|
+
f"- **{v.severity.upper()}** {v.message} (rule: {v.rule.describe()})" for v in violations)
|
|
387
|
+
if not single and (detector or policy):
|
|
388
|
+
text += "\n\n### Per session\n\n| Session | Anomalies | Policy violations |\n|---|---|---|\n"
|
|
389
|
+
text += "\n".join(f"| `{s['graph'].session_id}` | {a} | {v} |"
|
|
390
|
+
for s in sessions for a, v in [_counts(s["anomalies"], s["violations"])])
|
|
391
|
+
if policy:
|
|
392
|
+
text += "\n\n" + "\n".join(f"- `{s['graph'].session_id}`: **{v.severity.upper()}** {v.message}"
|
|
393
|
+
for s in sessions for v in (s["violations"] or []))
|
|
394
|
+
_emit(text, args.output)
|
|
395
|
+
else:
|
|
396
|
+
text = _text_report(merged, result, anomalies, baseline if single else None,
|
|
397
|
+
_violations_text(violations) if violations is not None else None)
|
|
398
|
+
if not single:
|
|
399
|
+
text = (_session_table(sessions, detector is not None, policy is not None)
|
|
400
|
+
+ "\n\nMerged graph\n============\n" + text)
|
|
401
|
+
if policy:
|
|
402
|
+
listed = [f" {s['graph'].session_id}: [{v.severity.upper()}] {v.message}"
|
|
403
|
+
for s in sessions for v in s["violations"]]
|
|
404
|
+
text += "\n\nPolicy violations per session:\n" + ("\n".join(listed) if listed else " none")
|
|
405
|
+
if source:
|
|
406
|
+
text += f"\n\nBaseline: {source} ({baseline.learned_from} sessions)"
|
|
407
|
+
if policy_source:
|
|
408
|
+
scope = "" if single else ", evaluated per session"
|
|
409
|
+
text += f"\nPolicy: {policy_source} ({len(policy.rules)} rules{scope})"
|
|
410
|
+
_emit(text, args.output)
|
|
411
|
+
return sessions
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def cmd_watch(args) -> int:
|
|
415
|
+
p = _path(args.path)
|
|
416
|
+
if p.is_dir():
|
|
417
|
+
session = latest_session(p)
|
|
418
|
+
if session is None:
|
|
419
|
+
raise SystemExit(f"agent-certify: no .jsonl sessions in {p}")
|
|
420
|
+
else:
|
|
421
|
+
session = p # may not exist yet: the watcher waits for it
|
|
422
|
+
baseline, _ = _find_baseline(args)
|
|
423
|
+
policy, _ = _find_policy(args)
|
|
424
|
+
on_scan, out = None, print
|
|
425
|
+
if args.otel or args.otel_stdout:
|
|
426
|
+
exporter = OTelExporter()
|
|
427
|
+
|
|
428
|
+
def on_scan(graph, result, report, violations, started):
|
|
429
|
+
exporter.write(exporter.export_scan(graph, result, report, violations, start_time=started),
|
|
430
|
+
args.otel_file, stdout=args.otel_stdout)
|
|
431
|
+
|
|
432
|
+
if args.otel_stdout:
|
|
433
|
+
def out(line):
|
|
434
|
+
print(line, file=sys.stderr)
|
|
435
|
+
SessionWatcher(str(session), baseline=baseline, policy=policy, interval=args.interval,
|
|
436
|
+
perspective=args.perspective, max_scans=args.scans, max_seconds=args.duration,
|
|
437
|
+
out=out, on_scan=on_scan).watch()
|
|
438
|
+
return 0
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def cmd_mcp(args) -> int:
|
|
442
|
+
AgentCertifyMCPServer().run()
|
|
443
|
+
return 0
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def cmd_suggest_policy(args) -> int:
|
|
447
|
+
baseline, _source = _find_file(args.baseline, False, DEFAULT_BASELINE_PATH, load_baseline, "baseline")
|
|
448
|
+
if baseline is None:
|
|
449
|
+
raise SystemExit(f"agent-certify: no baseline at {DEFAULT_BASELINE_PATH.as_posix()}; "
|
|
450
|
+
"run `agent-certify learn <sessions>` first or pass --baseline")
|
|
451
|
+
out = Path(args.output) if args.output else DEFAULT_POLICY_PATH
|
|
452
|
+
if out.exists() and not args.force:
|
|
453
|
+
raise SystemExit(f"agent-certify: {out.as_posix()} exists and may hold your edits; "
|
|
454
|
+
"use --force to overwrite or --output for another file")
|
|
455
|
+
policy = PolicyGenerator().suggest(baseline)
|
|
456
|
+
saved = policy.save(out)
|
|
457
|
+
lines = [f"Generated policy from {policy.generated_from}:", ""]
|
|
458
|
+
for r in policy.rules:
|
|
459
|
+
note = (f"seen in {baseline.tool_frequency.get(r.target, 0):.0%} of sessions" if r.kind == "required_tool"
|
|
460
|
+
else r.message)
|
|
461
|
+
lines.append(f" {'[' + r.severity.upper() + ']':<11}{r.describe()} ({note})")
|
|
462
|
+
lines += ["", f"Saved draft to {saved.as_posix()}", "",
|
|
463
|
+
"Edit the file to add FORBIDDEN rules, for example:",
|
|
464
|
+
(' {"kind": "forbidden_tool", "target": "deploy_production", "severity": "critical", '
|
|
465
|
+
'"message": "No agent may deploy to production"}'),
|
|
466
|
+
(' {"kind": "forbidden_link", "target": "agent:* → *database*", "severity": "critical", '
|
|
467
|
+
'"message": "Sub-agents may not reach the database"}')]
|
|
468
|
+
print("\n".join(lines))
|
|
469
|
+
return 0
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def cmd_learn(args) -> int:
|
|
473
|
+
learner = BaselineLearner()
|
|
474
|
+
try:
|
|
475
|
+
if args.include_mcp:
|
|
476
|
+
# Learn from the same data `scan --include-mcp` will compare against.
|
|
477
|
+
graphs = []
|
|
478
|
+
for p in args.paths:
|
|
479
|
+
if not _path(p).exists():
|
|
480
|
+
raise FileNotFoundError(str(_path(p)))
|
|
481
|
+
graphs += load(p, include_mcp=True)[0]
|
|
482
|
+
baseline = learner.learn_graphs(graphs)
|
|
483
|
+
else:
|
|
484
|
+
baseline = learner.learn([str(_path(p)) for p in args.paths])
|
|
485
|
+
except FileNotFoundError as exc:
|
|
486
|
+
raise SystemExit(f"agent-certify: {exc.args[0]} does not exist") from None
|
|
487
|
+
except ValueError as exc:
|
|
488
|
+
raise SystemExit(f"agent-certify: {exc}") from None
|
|
489
|
+
saved = learner.save(baseline, args.output)
|
|
490
|
+
print(_learn_report(baseline, saved))
|
|
491
|
+
return 0
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def cmd_blast(args) -> int:
|
|
495
|
+
_, g = load(args.path)
|
|
496
|
+
try:
|
|
497
|
+
report = BlastRadiusAnalyzer(g, hops=args.hops).analyze(args.node)
|
|
498
|
+
except KeyError as exc:
|
|
499
|
+
raise SystemExit(f"agent-certify: {exc.args[0]}") from None
|
|
500
|
+
_emit(json.dumps(report.to_dict(), indent=2) if args.format == "json" else str(report), args.output)
|
|
501
|
+
return 0
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _create_exclusive(path: Path, text: str, mode: int) -> None:
|
|
505
|
+
"""Create ``path`` atomically with ``mode``; fail if it exists, never follow a symlink there.
|
|
506
|
+
|
|
507
|
+
On Windows ``mode`` only controls the read-only flag: the file inherits the
|
|
508
|
+
ACL of its directory, so keep keys in a directory only you can read.
|
|
509
|
+
"""
|
|
510
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
|
|
511
|
+
fd = os.open(path, flags, mode)
|
|
512
|
+
try:
|
|
513
|
+
os.write(fd, text.encode("ascii"))
|
|
514
|
+
finally:
|
|
515
|
+
os.close(fd)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def cmd_keygen(args) -> int:
|
|
519
|
+
out = Path(args.output)
|
|
520
|
+
pub_path = Path(str(out) + ".pub")
|
|
521
|
+
if args.force:
|
|
522
|
+
for p in (out, pub_path):
|
|
523
|
+
if p.is_symlink() or p.exists():
|
|
524
|
+
p.unlink() # unlinking a symlink removes the link, not its target
|
|
525
|
+
priv, pub = generate_keypair()
|
|
526
|
+
for path, text, mode in ((out, priv, 0o600), (pub_path, pub, 0o644)):
|
|
527
|
+
try:
|
|
528
|
+
_create_exclusive(path, text + "\n", mode)
|
|
529
|
+
except FileExistsError:
|
|
530
|
+
raise SystemExit(f"agent-certify: {path} exists (use --force to replace it)") from None
|
|
531
|
+
except OSError as exc:
|
|
532
|
+
raise SystemExit(f"agent-certify: cannot create {path} safely ({exc.strerror})") from None
|
|
533
|
+
print(f"private key: {out} (mode 600 — store it outside the repository and never commit it)")
|
|
534
|
+
print(f"public key: {pub_path} ({pub})")
|
|
535
|
+
return 0
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _read_private_key(path: str) -> str:
|
|
539
|
+
p = _path(path)
|
|
540
|
+
if os.name == "posix":
|
|
541
|
+
mode = p.stat().st_mode
|
|
542
|
+
if mode & (stat.S_IRGRP | stat.S_IROTH | stat.S_IWGRP | stat.S_IWOTH):
|
|
543
|
+
_warn(f"{p} is accessible by other users (mode {stat.S_IMODE(mode):o}); run: chmod 600 {p}")
|
|
544
|
+
return p.read_text(encoding="utf-8").strip()
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def cmd_certify(args) -> int:
|
|
548
|
+
_, g = load(args.path)
|
|
549
|
+
key = _read_private_key(args.key) if args.key else None
|
|
550
|
+
if key is None:
|
|
551
|
+
_warn("issuing an UNSIGNED certificate (no --key): it can only be checked with --allow-unsigned")
|
|
552
|
+
if g.skipped_records:
|
|
553
|
+
_warn(f"{g.skipped_records} record(s) could not be read; the certificate covers a possibly "
|
|
554
|
+
"incomplete graph (recorded in the certificate as skipped_records)")
|
|
555
|
+
cert = AgentCertificate.create(g, system_id=args.system_id, signing_key=key, validity_days=args.validity_days)
|
|
556
|
+
out = args.output or f"{_safe(cert.system_id)}.cert.json"
|
|
557
|
+
cert.save(out)
|
|
558
|
+
print(f"certificate {cert.certificate_id} -> {out}")
|
|
559
|
+
print(f" FI {cert.fi_score:.4f} | {cert.node_count} nodes, {cert.edge_count} links, "
|
|
560
|
+
f"{cert.bridge_count} bridges | signed: {cert.is_signed} | valid until {cert.not_after}")
|
|
561
|
+
return 0
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def cmd_verify(args) -> int:
|
|
565
|
+
if not args.public_key and not args.allow_unsigned:
|
|
566
|
+
print("agent-certify: verify needs --public-key ISSUER.pub (the issuer's public key, obtained out of "
|
|
567
|
+
"band); --allow-unsigned skips the signature check", file=sys.stderr)
|
|
568
|
+
return 2
|
|
569
|
+
if args.allow_unsigned:
|
|
570
|
+
_warn("--allow-unsigned: the certificate's signature is NOT checked; anyone could have written it")
|
|
571
|
+
try:
|
|
572
|
+
cert = AgentCertificate.load(_path(args.certificate))
|
|
573
|
+
except (OSError, ValueError):
|
|
574
|
+
raise SystemExit(f"agent-certify: {args.certificate} is not a readable agent-certify certificate") from None
|
|
575
|
+
pub = None
|
|
576
|
+
if args.public_key:
|
|
577
|
+
try:
|
|
578
|
+
pub = _path(args.public_key).read_text(encoding="utf-8").strip()
|
|
579
|
+
except OSError:
|
|
580
|
+
raise SystemExit(f"agent-certify: cannot read public key {args.public_key}") from None
|
|
581
|
+
if _public_key_hex(pub) is None:
|
|
582
|
+
raise SystemExit(f"agent-certify: {args.public_key} does not hold an Ed25519 public key (64 hex chars)")
|
|
583
|
+
_, g = load(args.path)
|
|
584
|
+
report = cert.verify(g, fi_tolerance=args.fi_tolerance, public_key=pub, allow_unsigned=args.allow_unsigned,
|
|
585
|
+
ignore_expiry=args.ignore_expiry, expected_system_id=args.expect_system_id)
|
|
586
|
+
_emit(json.dumps(report.to_dict(), indent=2) if args.format == "json" else str(report), None)
|
|
587
|
+
return 0 if report.is_valid else 1
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _safe(s: str | None) -> str:
|
|
591
|
+
return "".join(c if c.isalnum() or c in "-_." else "-" for c in (s or "graph"))[:60].strip("-")
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
# ---------------------------------------------------------------------- main
|
|
595
|
+
def _baseline_args(p: argparse.ArgumentParser) -> None:
|
|
596
|
+
g = p.add_mutually_exclusive_group()
|
|
597
|
+
g.add_argument("--baseline", help=f"baseline to compare against (default: {DEFAULT_BASELINE_PATH} if present)")
|
|
598
|
+
g.add_argument("--no-baseline", action="store_true", help="skip anomaly detection")
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _otel_args(p: argparse.ArgumentParser) -> None:
|
|
602
|
+
p.add_argument("--otel", action="store_true",
|
|
603
|
+
help=f"append an OpenTelemetry span per scan (OTLP/JSON) to {DEFAULT_TRACES_PATH.as_posix()}")
|
|
604
|
+
p.add_argument("--otel-stdout", action="store_true",
|
|
605
|
+
help="write the OTLP/JSON spans to stdout instead (the report moves to stderr)")
|
|
606
|
+
p.add_argument("--otel-file", help=f"span file (default: {DEFAULT_TRACES_PATH.as_posix()})")
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _policy_args(p: argparse.ArgumentParser) -> None:
|
|
610
|
+
g = p.add_mutually_exclusive_group()
|
|
611
|
+
g.add_argument("--policy", help=f"policy to enforce (default: {DEFAULT_POLICY_PATH} if present)")
|
|
612
|
+
g.add_argument("--no-policy", action="store_true", help="skip policy checks")
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
616
|
+
ap = argparse.ArgumentParser(prog="agent-certify", description="Structural verification of multiagent systems.")
|
|
617
|
+
ap.add_argument("--version", action="version", version=f"agent-certify {__version__}")
|
|
618
|
+
ap.add_argument("-q", "--quiet", action="store_true", help="hide parser warnings")
|
|
619
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
620
|
+
|
|
621
|
+
s = sub.add_parser("scan", help="compute FI, bridges and node roles")
|
|
622
|
+
s.add_argument("path", nargs="?", default=DEFAULT_PATH, help="session .jsonl or a directory of sessions")
|
|
623
|
+
s.add_argument("--format", choices=["text", "json", "markdown", "html"], default="text")
|
|
624
|
+
s.add_argument("-o", "--output")
|
|
625
|
+
s.add_argument("--perspective", choices=list(Perspective.NAMES), default="engineering",
|
|
626
|
+
help="labels for node roles (default: engineering)")
|
|
627
|
+
_baseline_args(s)
|
|
628
|
+
_policy_args(s)
|
|
629
|
+
s.add_argument("--include-mcp", action="store_true",
|
|
630
|
+
help="add the session's calls from MCP server logs (claude-cli-nodejs cache)")
|
|
631
|
+
s.add_argument("--fail-on", choices=["critical", "warning", "never"], default="critical",
|
|
632
|
+
help=f"exit {FAIL_EXIT} when an anomaly or policy violation reaches this severity (default: critical)")
|
|
633
|
+
_otel_args(s)
|
|
634
|
+
s.set_defaults(func=cmd_scan)
|
|
635
|
+
|
|
636
|
+
w = sub.add_parser("watch", help="watch an active session live")
|
|
637
|
+
w.add_argument("path", help="session file (may not exist yet), or a project directory (newest session)")
|
|
638
|
+
w.add_argument("--interval", type=float, default=30.0, help="seconds between checks (default: 30)")
|
|
639
|
+
w.add_argument("--perspective", choices=list(Perspective.NAMES), default="engineering")
|
|
640
|
+
w.add_argument("--scans", type=int, help="stop after this many scans (default: until Ctrl+C)")
|
|
641
|
+
w.add_argument("--duration", type=float, help="stop after this many seconds (default: until Ctrl+C)")
|
|
642
|
+
_baseline_args(w)
|
|
643
|
+
_policy_args(w)
|
|
644
|
+
_otel_args(w)
|
|
645
|
+
w.set_defaults(func=cmd_watch)
|
|
646
|
+
|
|
647
|
+
sp = sub.add_parser("suggest-policy", help="draft a policy from a learned baseline")
|
|
648
|
+
sp.add_argument("--baseline", help=f"baseline to read (default: {DEFAULT_BASELINE_PATH})")
|
|
649
|
+
sp.add_argument("-o", "--output", help=f"where to write the draft (default: {DEFAULT_POLICY_PATH})")
|
|
650
|
+
sp.add_argument("--force", action="store_true", help="overwrite an existing policy file")
|
|
651
|
+
sp.set_defaults(func=cmd_suggest_policy)
|
|
652
|
+
|
|
653
|
+
m = sub.add_parser("mcp", help="run as an MCP server on stdio (claude mcp add agent-certify -- agent-certify mcp)")
|
|
654
|
+
m.set_defaults(func=cmd_mcp)
|
|
655
|
+
|
|
656
|
+
learn = sub.add_parser("learn", help="learn a statistical baseline from past sessions")
|
|
657
|
+
learn.add_argument("paths", nargs="+", help="session .jsonl files and/or directories of sessions")
|
|
658
|
+
learn.add_argument("-o", "--output", help=f"where to save it (default: {DEFAULT_BASELINE_PATH})")
|
|
659
|
+
learn.add_argument("--include-mcp", action="store_true",
|
|
660
|
+
help="include MCP server log calls (use with `scan --include-mcp`)")
|
|
661
|
+
learn.set_defaults(func=cmd_learn)
|
|
662
|
+
|
|
663
|
+
b = sub.add_parser("blast", help="blast radius of a compromised node")
|
|
664
|
+
b.add_argument("path", nargs="?", default=DEFAULT_PATH)
|
|
665
|
+
b.add_argument("--node", required=True, help="node id or name, e.g. bash, tool:Bash, claude")
|
|
666
|
+
b.add_argument("--hops", type=int, default=3)
|
|
667
|
+
b.add_argument("--format", choices=["text", "json"], default="text")
|
|
668
|
+
b.add_argument("-o", "--output")
|
|
669
|
+
b.set_defaults(func=cmd_blast)
|
|
670
|
+
|
|
671
|
+
k = sub.add_parser("keygen", help="create an Ed25519 signing key (writes KEY with mode 600, and KEY.pub)")
|
|
672
|
+
k.add_argument("output", help="private key file; keep it outside the repository")
|
|
673
|
+
k.add_argument("--force", action="store_true", help="replace existing key files")
|
|
674
|
+
k.set_defaults(func=cmd_keygen)
|
|
675
|
+
|
|
676
|
+
c = sub.add_parser("certify", help="issue a structural certificate for a graph")
|
|
677
|
+
c.add_argument("path")
|
|
678
|
+
c.add_argument("--key", help="private key file from `agent-certify keygen`; omit for an unsigned certificate")
|
|
679
|
+
c.add_argument("--system-id")
|
|
680
|
+
c.add_argument("--validity-days", type=int, default=DEFAULT_VALIDITY_DAYS,
|
|
681
|
+
help=f"how long the certificate is valid (default: {DEFAULT_VALIDITY_DAYS})")
|
|
682
|
+
c.add_argument("-o", "--output")
|
|
683
|
+
c.set_defaults(func=cmd_certify)
|
|
684
|
+
|
|
685
|
+
v = sub.add_parser("verify", help="check a graph against a certificate (exit 1 on drift)")
|
|
686
|
+
v.add_argument("certificate")
|
|
687
|
+
v.add_argument("path")
|
|
688
|
+
v.add_argument("--public-key", help="REQUIRED: the issuer's public key file (KEY.pub), obtained out of band")
|
|
689
|
+
v.add_argument("--allow-unsigned", action="store_true",
|
|
690
|
+
help="skip the signature check (unsafe: anyone can write an unsigned certificate)")
|
|
691
|
+
v.add_argument("--ignore-expiry", action="store_true", help="accept a certificate outside its validity period")
|
|
692
|
+
v.add_argument("--expect-system-id", help="fail unless the certificate was issued for this system id")
|
|
693
|
+
v.add_argument("--fi-tolerance", type=float, default=0.001)
|
|
694
|
+
v.add_argument("--format", choices=["text", "json"], default="text")
|
|
695
|
+
v.set_defaults(func=cmd_verify)
|
|
696
|
+
return ap
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def main(argv: list[str] | None = None) -> int:
|
|
700
|
+
args = build_parser().parse_args(argv)
|
|
701
|
+
logging.basicConfig(level=logging.ERROR if args.quiet else logging.WARNING, format="%(levelname)s %(message)s")
|
|
702
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
703
|
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
704
|
+
return args.func(args)
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
if __name__ == "__main__":
|
|
708
|
+
sys.exit(main())
|