agentmetry 0.4.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.
- agentmetry/__init__.py +12 -0
- agentmetry/api/__init__.py +0 -0
- agentmetry/api/main.py +232 -0
- agentmetry/api/routes/__init__.py +0 -0
- agentmetry/api/routes/audit.py +396 -0
- agentmetry/api/websocket.py +53 -0
- agentmetry/api/ws_bridge.py +34 -0
- agentmetry/cli/__init__.py +941 -0
- agentmetry/cli/__main__.py +5 -0
- agentmetry/core/__init__.py +0 -0
- agentmetry/core/audit/__init__.py +1 -0
- agentmetry/core/audit/adapters/__init__.py +0 -0
- agentmetry/core/audit/adapters/agt.py +304 -0
- agentmetry/core/audit/adapters/cloudevents.py +159 -0
- agentmetry/core/audit/adapters/ecs.py +103 -0
- agentmetry/core/audit/adapters/splunk.py +40 -0
- agentmetry/core/audit/alerts.py +56 -0
- agentmetry/core/audit/canonical.py +150 -0
- agentmetry/core/audit/compliance_digest.py +299 -0
- agentmetry/core/audit/detection/__init__.py +9 -0
- agentmetry/core/audit/detection/benchmark.py +194 -0
- agentmetry/core/audit/detection/corpus/attack_approval_denied_then_executed.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/attack_arbitrary_host_stage_execute.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/attack_autonomous_unapproved_write.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/attack_credential_exfil.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_credential_then_cloud_api.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_destructive_delete_burst.jsonl +6 -0
- agentmetry/core/audit/detection/corpus/attack_discovery_then_collect.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/attack_dotfile_then_git_push.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_encoded_command_download.jsonl +1 -0
- agentmetry/core/audit/detection/corpus/attack_env_credential_exfil.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/attack_hashed_only_no_command.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_interpreter_egress.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_pr_merged_without_review.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_proc_substitution_cradle.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_remote_pipe_to_shell.jsonl +1 -0
- agentmetry/core/audit/detection/corpus/attack_remote_staging_then_execute.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_session_tool_burst.jsonl +42 -0
- agentmetry/core/audit/detection/corpus/attack_single_command_exfil.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_ssh_directory_exfil.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/attack_subagent_swarm.jsonl +6 -0
- agentmetry/core/audit/detection/corpus/attack_timestamp_collision.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/attack_untrusted_input_then_action.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_authoring_merge_fixtures.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_autonomous_after_approval.jsonl +4 -0
- agentmetry/core/audit/detection/corpus/benign_build_artifact_cleanup.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_ci_artifact_download.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_database_migration.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_dependency_install_and_build.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_download_release_archive.jsonl +4 -0
- agentmetry/core/audit/detection/corpus/benign_fetch_data_then_run_repo_script.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_fetch_dataset_then_analyse.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_fetch_lockfile_then_install.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_git_review_and_push.jsonl +6 -0
- agentmetry/core/audit/detection/corpus/benign_human_driven_deletes.jsonl +6 -0
- agentmetry/core/audit/detection/corpus/benign_local_api_probing.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_long_but_calm_session.jsonl +30 -0
- agentmetry/core/audit/detection/corpus/benign_loopback_is_not_egress.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/benign_loopback_pipe_to_interpreter.jsonl +3 -0
- agentmetry/core/audit/detection/corpus/benign_ordinary_development.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_package_manager_after_fetch.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/benign_reading_config_that_is_not_secret.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_remote_api_call_no_credentials.jsonl +4 -0
- agentmetry/core/audit/detection/corpus/benign_research_then_docs.jsonl +5 -0
- agentmetry/core/audit/detection/corpus/benign_reversed_order_is_not_exfil.jsonl +2 -0
- agentmetry/core/audit/detection/corpus/benign_test_and_fix_loop.jsonl +6 -0
- agentmetry/core/audit/detection/corpus/benign_writing_about_credentials.jsonl +6 -0
- agentmetry/core/audit/detection/corpus/corpus.yaml +443 -0
- agentmetry/core/audit/detection/disposition.py +651 -0
- agentmetry/core/audit/detection/engine.py +78 -0
- agentmetry/core/audit/detection/live.py +127 -0
- agentmetry/core/audit/detection/live_store.py +355 -0
- agentmetry/core/audit/detection/models.py +53 -0
- agentmetry/core/audit/detection/rules.py +1314 -0
- agentmetry/core/audit/detection/traits.py +648 -0
- agentmetry/core/audit/detection/yaml_config.py +91 -0
- agentmetry/core/audit/detection/yaml_rules.py +83 -0
- agentmetry/core/audit/dlp/__init__.py +4 -0
- agentmetry/core/audit/dlp/loader.py +29 -0
- agentmetry/core/audit/dlp/models.py +29 -0
- agentmetry/core/audit/dlp/scanner.py +96 -0
- agentmetry/core/audit/dogfood.py +398 -0
- agentmetry/core/audit/evidence_pack.py +500 -0
- agentmetry/core/audit/external.py +213 -0
- agentmetry/core/audit/hashing.py +21 -0
- agentmetry/core/audit/hook_bootstrap.py +451 -0
- agentmetry/core/audit/identity.py +39 -0
- agentmetry/core/audit/ingest.py +242 -0
- agentmetry/core/audit/migrate.py +73 -0
- agentmetry/core/audit/mitre.py +244 -0
- agentmetry/core/audit/policy.py +99 -0
- agentmetry/core/audit/redaction.py +50 -0
- agentmetry/core/audit/replay.py +54 -0
- agentmetry/core/audit/run_context.py +129 -0
- agentmetry/core/audit/sinks.py +235 -0
- agentmetry/core/audit/spool.py +394 -0
- agentmetry/core/audit/tool_policy/__init__.py +4 -0
- agentmetry/core/audit/tool_policy/evaluator.py +198 -0
- agentmetry/core/audit/tool_policy/loader.py +44 -0
- agentmetry/core/audit/tool_policy/models.py +25 -0
- agentmetry/core/audit/trail_chain.py +300 -0
- agentmetry/core/audit/trail_db.py +491 -0
- agentmetry/core/audit/trail_merkle.py +332 -0
- agentmetry/core/auth.py +54 -0
- agentmetry/core/bus/__init__.py +5 -0
- agentmetry/core/bus/audit_exporter.py +107 -0
- agentmetry/core/bus/bridges.py +26 -0
- agentmetry/core/bus/bus.py +102 -0
- agentmetry/core/bus/events.py +50 -0
- agentmetry/core/bus/outbox.py +124 -0
- agentmetry/core/config.py +177 -0
- agentmetry/core/diagnostics/__init__.py +0 -0
- agentmetry/core/diagnostics/autostart.py +563 -0
- agentmetry/core/diagnostics/doctor.py +535 -0
- agentmetry/core/diagnostics/driver_paths.py +156 -0
- agentmetry/core/diagnostics/env_file.py +45 -0
- agentmetry/core/drivers/__init__.py +4 -0
- agentmetry/core/drivers/host.py +263 -0
- agentmetry/core/drivers/permissions.py +37 -0
- agentmetry/core/drivers/spec.py +118 -0
- agentmetry/core/extensions.py +107 -0
- agentmetry/core/health.py +26 -0
- agentmetry/core/version.py +13 -0
- agentmetry/policies/detection/manifest.yaml +43 -0
- agentmetry/policies/dlp/manifest.yaml +161 -0
- agentmetry/policies/opa/agent_rules.rego +33 -0
- agentmetry/policies/tool/manifest.yaml +117 -0
- agentmetry-0.4.0.dist-info/METADATA +86 -0
- agentmetry-0.4.0.dist-info/RECORD +131 -0
- agentmetry-0.4.0.dist-info/WHEEL +4 -0
- agentmetry-0.4.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
"""Assemble tamper-evident compliance evidence packs from the audit trail.
|
|
2
|
+
|
|
3
|
+
Reads the canonical Tier B trail (`audit.db`) — the same events the dashboard
|
|
4
|
+
and the SIEM sinks see — and binds each pack to a verifiable position in the
|
|
5
|
+
JSONL hash chain.
|
|
6
|
+
|
|
7
|
+
History worth keeping: until 2026-07-24 this module read the legacy event
|
|
8
|
+
outbox and `runs.jsonl` from the removed governed runtime. The hook ingest path
|
|
9
|
+
never published to that bus, so on a recorder-only install the flagship
|
|
10
|
+
compliance export contained driver-mount noise while thousands of captured
|
|
11
|
+
agent tool calls sat in the trail, unexported. Anything added here must read the
|
|
12
|
+
trail; if a future feature needs a second source, it belongs alongside the
|
|
13
|
+
trail, never instead of it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
from collections import Counter
|
|
21
|
+
from datetime import date, datetime, time, timezone
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from agentmetry.core.audit.detection.disposition import extract_dispositions
|
|
26
|
+
from agentmetry.core.config import settings
|
|
27
|
+
from agentmetry.core.version import __version__
|
|
28
|
+
|
|
29
|
+
SCHEMA_VERSION = "2.1"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_COMPLIANCE_MAPPING = {
|
|
33
|
+
"art_12_logging": (
|
|
34
|
+
"EU AI Act Art. 12 (record-keeping): events[] is the canonical, "
|
|
35
|
+
"time-ordered record of every captured agent tool call, approval gate "
|
|
36
|
+
"and correlated detection, with per-event input hashes. "
|
|
37
|
+
"meta.trail_chain binds this pack to a position in the tamper-evident "
|
|
38
|
+
"JSONL hash chain, verifiable with `agentmetry verify --trail`."
|
|
39
|
+
),
|
|
40
|
+
"art_14_human_oversight": (
|
|
41
|
+
"EU AI Act Art. 14 (human oversight): approvals[] records each gated "
|
|
42
|
+
"action and its resolution. Entries carry `inferred: true` when the "
|
|
43
|
+
"response was derived from the event stream rather than observed from "
|
|
44
|
+
"the IDE — no IDE reports the human's click, and an auditor must be "
|
|
45
|
+
"able to tell the difference."
|
|
46
|
+
),
|
|
47
|
+
"art_15_cybersecurity": (
|
|
48
|
+
"EU AI Act Art. 15 (accuracy, robustness, cybersecurity): detections[] "
|
|
49
|
+
"records correlated behavioural findings (credential exfiltration, "
|
|
50
|
+
"guardrail bypass, download cradles, agent data injection). "
|
|
51
|
+
"controls[] records the DLP and tool-policy manifests in force, with "
|
|
52
|
+
"content hashes and enforcement modes."
|
|
53
|
+
),
|
|
54
|
+
"art_17_qms": (
|
|
55
|
+
"EU AI Act Art. 17 / EN 18286 cl. 6 (operation and control): the pack "
|
|
56
|
+
"evidences which agents acted, under which policy configuration, and "
|
|
57
|
+
"what was denied — process evidence for a quality management system "
|
|
58
|
+
"covering AI-assisted development."
|
|
59
|
+
),
|
|
60
|
+
"iso_42001_cl10_corrective_action": (
|
|
61
|
+
"ISO/IEC 42001 cl. 10 / EN 18286 cl. 8 (corrective action): "
|
|
62
|
+
"dispositions[] records what a human decided about each finding — "
|
|
63
|
+
"acknowledged, resolved, false positive or accepted risk — with the "
|
|
64
|
+
"decider, the timestamp and the written justification. Each decision "
|
|
65
|
+
"is itself an event on the same hash chain as the detection it "
|
|
66
|
+
"answers, and superseded decisions are retained. "
|
|
67
|
+
"summary.detections_untriaged is the count of findings with no human "
|
|
68
|
+
"decision at all; that number is the honest measure of whether the "
|
|
69
|
+
"detection capability is operating as a control."
|
|
70
|
+
),
|
|
71
|
+
"art_72_post_market": (
|
|
72
|
+
"EU AI Act Art. 72 (post-market monitoring): summary[] and detections[] "
|
|
73
|
+
"support periodic review; the trail supports incident reconstruction "
|
|
74
|
+
"within Art. 73 reporting windows."
|
|
75
|
+
),
|
|
76
|
+
"scope_limits": (
|
|
77
|
+
"Agentmetry records the agents wired into it via IDE hooks and the MCP "
|
|
78
|
+
"audit proxy. It does not observe unmanaged assistants (browser "
|
|
79
|
+
"ChatGPT, unhooked IDEs) and is not a CASB, a sandbox, or a model "
|
|
80
|
+
"evaluation tool. Absence of an event is not evidence that nothing "
|
|
81
|
+
"happened outside the monitored boundary."
|
|
82
|
+
),
|
|
83
|
+
"disclaimer": (
|
|
84
|
+
"This pack is an operator-generated audit artifact. It is not legal "
|
|
85
|
+
"advice or a certification of EU AI Act compliance. Map requirements "
|
|
86
|
+
"to your risk classification with qualified counsel."
|
|
87
|
+
),
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def date_range_to_timestamps(from_date: date, to_date: date) -> tuple[str, str]:
|
|
92
|
+
"""Inclusive calendar dates → UTC ISO bounds for trail queries."""
|
|
93
|
+
if to_date < from_date:
|
|
94
|
+
raise ValueError("--to must be on or after --from")
|
|
95
|
+
start = datetime.combine(from_date, time.min, tzinfo=timezone.utc).isoformat()
|
|
96
|
+
end = datetime.combine(to_date, time.max, tzinfo=timezone.utc).isoformat()
|
|
97
|
+
return start, end
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_date(value: str) -> date:
|
|
101
|
+
return date.fromisoformat(value)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# --- canonical event accessors ------------------------------------------------
|
|
105
|
+
# Events are plain dicts read back from SQLite; never assume a nested key exists.
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _action(event: dict[str, Any]) -> dict[str, Any]:
|
|
109
|
+
action = event.get("action")
|
|
110
|
+
return action if isinstance(action, dict) else {}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _tool(event: dict[str, Any]) -> dict[str, Any]:
|
|
114
|
+
tool = event.get("tool")
|
|
115
|
+
return tool if isinstance(tool, dict) else {}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _source_app(event: dict[str, Any]) -> str:
|
|
119
|
+
source = event.get("source")
|
|
120
|
+
return str(source.get("app") or "") if isinstance(source, dict) else ""
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _actor_type(event: dict[str, Any]) -> str:
|
|
124
|
+
initiator = event.get("initiator")
|
|
125
|
+
return str(initiator.get("actor_type") or "") if isinstance(initiator, dict) else ""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _extract_tool_calls(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
129
|
+
calls: list[dict[str, Any]] = []
|
|
130
|
+
for event in events:
|
|
131
|
+
action = _action(event)
|
|
132
|
+
if action.get("type") != "tool_called":
|
|
133
|
+
continue
|
|
134
|
+
tool = _tool(event)
|
|
135
|
+
mitre = tool.get("mitre") if isinstance(tool.get("mitre"), dict) else {}
|
|
136
|
+
entry: dict[str, Any] = {
|
|
137
|
+
"ts": event.get("timestamp_utc"),
|
|
138
|
+
"event_id": event.get("event_id"),
|
|
139
|
+
"correlation_id": event.get("correlation_id"),
|
|
140
|
+
"source_app": _source_app(event),
|
|
141
|
+
"actor_type": _actor_type(event),
|
|
142
|
+
"tool": tool.get("qualified"),
|
|
143
|
+
"server": tool.get("server"),
|
|
144
|
+
"input_hash": tool.get("input_hash"),
|
|
145
|
+
"outcome": action.get("outcome"),
|
|
146
|
+
"reason": action.get("reason"),
|
|
147
|
+
"denied": action.get("outcome") == "denied",
|
|
148
|
+
"tactic_id": mitre.get("tactic_id"),
|
|
149
|
+
"technique_id": mitre.get("technique_id"),
|
|
150
|
+
}
|
|
151
|
+
# Command text is opt-in (AGENTMETRY_AUDIT_LOG_COMMANDS); traits are the
|
|
152
|
+
# privacy-preserving classification that is always available.
|
|
153
|
+
if tool.get("command"):
|
|
154
|
+
entry["command"] = tool.get("command")
|
|
155
|
+
if tool.get("traits"):
|
|
156
|
+
entry["traits"] = tool.get("traits")
|
|
157
|
+
dlp = event.get("dlp")
|
|
158
|
+
if isinstance(dlp, dict) and dlp.get("rule_id"):
|
|
159
|
+
entry["dlp_rule_id"] = dlp.get("rule_id")
|
|
160
|
+
entry["dlp_mode"] = dlp.get("mode")
|
|
161
|
+
policy = event.get("tool_policy")
|
|
162
|
+
if isinstance(policy, dict) and policy.get("rule_id"):
|
|
163
|
+
entry["tool_policy_rule_id"] = policy.get("rule_id")
|
|
164
|
+
entry["tool_policy_blocked"] = policy.get("blocked")
|
|
165
|
+
calls.append(entry)
|
|
166
|
+
return calls
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _extract_approvals(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
170
|
+
"""Pair approval requests with their resolutions.
|
|
171
|
+
|
|
172
|
+
`inferred` is load-bearing for an auditor: no IDE reports the human's click,
|
|
173
|
+
so a response derived from the event stream must never be presented as an
|
|
174
|
+
observed one.
|
|
175
|
+
"""
|
|
176
|
+
gates: list[dict[str, Any]] = []
|
|
177
|
+
open_by_corr: dict[str, list[int]] = {}
|
|
178
|
+
|
|
179
|
+
for event in events:
|
|
180
|
+
action = _action(event)
|
|
181
|
+
atype = action.get("type")
|
|
182
|
+
corr = str(event.get("correlation_id") or "")
|
|
183
|
+
|
|
184
|
+
if atype == "approval_request":
|
|
185
|
+
tool = _tool(event)
|
|
186
|
+
gates.append({
|
|
187
|
+
"correlation_id": corr,
|
|
188
|
+
"source_app": _source_app(event),
|
|
189
|
+
"requested_at": event.get("timestamp_utc"),
|
|
190
|
+
"tool": tool.get("qualified"),
|
|
191
|
+
"input_hash": tool.get("input_hash"),
|
|
192
|
+
"decision": "pending",
|
|
193
|
+
"inferred": False,
|
|
194
|
+
})
|
|
195
|
+
open_by_corr.setdefault(corr, []).append(len(gates) - 1)
|
|
196
|
+
|
|
197
|
+
elif atype == "approval_response":
|
|
198
|
+
reason = str(action.get("reason") or "")
|
|
199
|
+
inferred = reason.startswith("inferred:")
|
|
200
|
+
gated = event.get("gated_action")
|
|
201
|
+
gated = gated if isinstance(gated, dict) else {}
|
|
202
|
+
outcome = action.get("outcome")
|
|
203
|
+
decision = "granted" if outcome == "success" else "denied"
|
|
204
|
+
|
|
205
|
+
idx = None
|
|
206
|
+
for candidate in open_by_corr.get(corr, []):
|
|
207
|
+
gate = gates[candidate]
|
|
208
|
+
if gate["decision"] != "pending":
|
|
209
|
+
continue
|
|
210
|
+
want = str(gated.get("input_hash") or "")
|
|
211
|
+
have = str(gate.get("input_hash") or "")
|
|
212
|
+
if want and have and want != have:
|
|
213
|
+
continue
|
|
214
|
+
idx = candidate
|
|
215
|
+
break
|
|
216
|
+
|
|
217
|
+
if idx is None:
|
|
218
|
+
# A response with no recorded request still belongs in the pack.
|
|
219
|
+
gates.append({
|
|
220
|
+
"correlation_id": corr,
|
|
221
|
+
"source_app": _source_app(event),
|
|
222
|
+
"requested_at": None,
|
|
223
|
+
"tool": gated.get("tool"),
|
|
224
|
+
"input_hash": gated.get("input_hash"),
|
|
225
|
+
"decision": decision,
|
|
226
|
+
"decided_at": event.get("timestamp_utc"),
|
|
227
|
+
"reason": reason,
|
|
228
|
+
"inferred": inferred,
|
|
229
|
+
"orphan_response": True,
|
|
230
|
+
})
|
|
231
|
+
else:
|
|
232
|
+
gates[idx].update({
|
|
233
|
+
"decision": decision,
|
|
234
|
+
"decided_at": event.get("timestamp_utc"),
|
|
235
|
+
"reason": reason,
|
|
236
|
+
"inferred": inferred,
|
|
237
|
+
})
|
|
238
|
+
return gates
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _extract_detections(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
242
|
+
found: list[dict[str, Any]] = []
|
|
243
|
+
for event in events:
|
|
244
|
+
if _action(event).get("type") != "detection":
|
|
245
|
+
continue
|
|
246
|
+
detection = event.get("detection")
|
|
247
|
+
if not isinstance(detection, dict):
|
|
248
|
+
continue
|
|
249
|
+
found.append({
|
|
250
|
+
"ts": event.get("timestamp_utc"),
|
|
251
|
+
"correlation_id": event.get("correlation_id"),
|
|
252
|
+
"rule_id": detection.get("rule_id"),
|
|
253
|
+
"title": detection.get("title"),
|
|
254
|
+
"severity": detection.get("severity"),
|
|
255
|
+
"summary": detection.get("summary"),
|
|
256
|
+
"tactic_ids": detection.get("tactic_ids"),
|
|
257
|
+
"technique_ids": detection.get("technique_ids"),
|
|
258
|
+
"event_ids": detection.get("event_ids"),
|
|
259
|
+
"first_seen_utc": detection.get("first_seen_utc"),
|
|
260
|
+
"last_seen_utc": detection.get("last_seen_utc"),
|
|
261
|
+
})
|
|
262
|
+
return found
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _file_sha256(path: Path) -> dict[str, Any]:
|
|
266
|
+
if not path.is_file():
|
|
267
|
+
return {"path": str(path), "sha256": None, "present": False}
|
|
268
|
+
return {
|
|
269
|
+
"path": str(path),
|
|
270
|
+
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
|
271
|
+
"present": True,
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _controls_snapshot() -> dict[str, Any]:
|
|
276
|
+
"""The enforcement configuration in force — the control-state evidence.
|
|
277
|
+
|
|
278
|
+
Replaces the old drivers.json snapshot, which described demo MCP drivers
|
|
279
|
+
that a recorder-only install does not have.
|
|
280
|
+
"""
|
|
281
|
+
return {
|
|
282
|
+
"dlp": {
|
|
283
|
+
"mode": settings.dlp_mode,
|
|
284
|
+
"manifest": _file_sha256(Path(settings.dlp_rules_path)),
|
|
285
|
+
},
|
|
286
|
+
"tool_policy": {
|
|
287
|
+
"mode": settings.tool_policy_mode,
|
|
288
|
+
"manifest": _file_sha256(Path(settings.tool_policy_path)),
|
|
289
|
+
},
|
|
290
|
+
"detection": {
|
|
291
|
+
"off_hours_enabled": settings.detect_off_hours,
|
|
292
|
+
},
|
|
293
|
+
"operator_id": settings.operator_id.strip() or "local",
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _trail_chain_state() -> dict[str, Any]:
|
|
298
|
+
"""Bind the pack to a verifiable chain position.
|
|
299
|
+
|
|
300
|
+
Without this a pack is an unanchored JSON blob; with it, a reviewer can run
|
|
301
|
+
`agentmetry verify --trail` and confirm the trail still matches the state
|
|
302
|
+
this pack was drawn from.
|
|
303
|
+
"""
|
|
304
|
+
trail_path = Path(settings.audit_export_path)
|
|
305
|
+
try:
|
|
306
|
+
from agentmetry.core.audit.trail_chain import verify_trail_file
|
|
307
|
+
|
|
308
|
+
result = verify_trail_file(trail_path)
|
|
309
|
+
return {
|
|
310
|
+
"path": str(trail_path),
|
|
311
|
+
"verified": result.ok,
|
|
312
|
+
"message": result.message,
|
|
313
|
+
"head_seq": result.head_seq,
|
|
314
|
+
"head_sha256": result.head_sha256,
|
|
315
|
+
"lines_chained": result.lines_chained,
|
|
316
|
+
"lines_legacy": result.lines_legacy,
|
|
317
|
+
}
|
|
318
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
319
|
+
return {"path": str(trail_path), "verified": False, "message": str(exc)}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _attach_dispositions(detections: list[dict[str, Any]]) -> dict[str, int]:
|
|
323
|
+
"""Stamp each detection with the triage state in force, and count them.
|
|
324
|
+
|
|
325
|
+
Read from the disposition index rather than the events in this period on
|
|
326
|
+
purpose: a detection that fired in June and was closed in July is closed,
|
|
327
|
+
and a pack that showed it as untriaged would misrepresent the control.
|
|
328
|
+
"""
|
|
329
|
+
from agentmetry.core.audit.detection.disposition import DEFAULT_STATUS, get_disposition_store
|
|
330
|
+
|
|
331
|
+
store = get_disposition_store()
|
|
332
|
+
counts: Counter[str] = Counter()
|
|
333
|
+
for detection in detections:
|
|
334
|
+
current = store.get(
|
|
335
|
+
str(detection.get("correlation_id") or ""),
|
|
336
|
+
str(detection.get("rule_id") or ""),
|
|
337
|
+
)
|
|
338
|
+
detection["disposition"] = current
|
|
339
|
+
counts[current["status"] if current else DEFAULT_STATUS] += 1
|
|
340
|
+
return dict(counts)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _summarize(
|
|
344
|
+
events: list[dict[str, Any]],
|
|
345
|
+
tool_calls: list[dict[str, Any]],
|
|
346
|
+
approvals: list[dict[str, Any]],
|
|
347
|
+
detections: list[dict[str, Any]],
|
|
348
|
+
disposition_counts: dict[str, int],
|
|
349
|
+
) -> dict[str, Any]:
|
|
350
|
+
from agentmetry.core.audit.detection.disposition import CLOSED_STATUSES
|
|
351
|
+
|
|
352
|
+
decisions = Counter(a.get("decision") for a in approvals)
|
|
353
|
+
triaged = sum(n for status, n in disposition_counts.items() if status != "new")
|
|
354
|
+
return {
|
|
355
|
+
"event_count": len(events),
|
|
356
|
+
"tool_calls": sum(1 for t in tool_calls if not t["denied"]),
|
|
357
|
+
"tool_denials": sum(1 for t in tool_calls if t["denied"]),
|
|
358
|
+
"sessions": len({e.get("correlation_id") for e in events if e.get("correlation_id")}),
|
|
359
|
+
"agents": dict(Counter(_source_app(e) for e in events if _source_app(e))),
|
|
360
|
+
"approval_gates": len(approvals),
|
|
361
|
+
"approvals_granted": decisions.get("granted", 0),
|
|
362
|
+
"approvals_denied": decisions.get("denied", 0),
|
|
363
|
+
"approvals_pending": decisions.get("pending", 0),
|
|
364
|
+
"approvals_inferred": sum(1 for a in approvals if a.get("inferred")),
|
|
365
|
+
"detections": len(detections),
|
|
366
|
+
"detections_by_severity": dict(Counter(d.get("severity") for d in detections)),
|
|
367
|
+
"detections_by_rule": dict(Counter(d.get("rule_id") for d in detections)),
|
|
368
|
+
"detections_by_disposition": disposition_counts,
|
|
369
|
+
"detections_triaged": triaged,
|
|
370
|
+
"detections_untriaged": disposition_counts.get("new", 0),
|
|
371
|
+
"detections_closed": sum(
|
|
372
|
+
n for status, n in disposition_counts.items() if status in CLOSED_STATUSES
|
|
373
|
+
),
|
|
374
|
+
"dlp_hits": dict(
|
|
375
|
+
Counter(t["dlp_rule_id"] for t in tool_calls if t.get("dlp_rule_id"))
|
|
376
|
+
),
|
|
377
|
+
"tool_policy_hits": dict(
|
|
378
|
+
Counter(t["tool_policy_rule_id"] for t in tool_calls if t.get("tool_policy_rule_id"))
|
|
379
|
+
),
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _integrity_hash(body: dict[str, Any]) -> str:
|
|
384
|
+
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"), default=str)
|
|
385
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
_BODY_KEYS = (
|
|
389
|
+
"events",
|
|
390
|
+
"tool_calls",
|
|
391
|
+
"approvals",
|
|
392
|
+
"detections",
|
|
393
|
+
"dispositions",
|
|
394
|
+
"controls",
|
|
395
|
+
"compliance_mapping",
|
|
396
|
+
"summary",
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def build_evidence_pack(
|
|
401
|
+
from_date: date,
|
|
402
|
+
to_date: date,
|
|
403
|
+
*,
|
|
404
|
+
trail_db: Any | None = None,
|
|
405
|
+
include_raw_events: bool = True,
|
|
406
|
+
) -> dict[str, Any]:
|
|
407
|
+
"""Build a complete evidence pack dict (includes integrity hash in meta)."""
|
|
408
|
+
start_ts, end_ts = date_range_to_timestamps(from_date, to_date)
|
|
409
|
+
|
|
410
|
+
if trail_db is None:
|
|
411
|
+
from agentmetry.core.audit.trail_db import get_trail_db
|
|
412
|
+
|
|
413
|
+
trail_db = get_trail_db()
|
|
414
|
+
events = trail_db.read_between(start_ts, end_ts)
|
|
415
|
+
|
|
416
|
+
tool_calls = _extract_tool_calls(events)
|
|
417
|
+
approvals = _extract_approvals(events)
|
|
418
|
+
detections = _extract_detections(events)
|
|
419
|
+
disposition_counts = _attach_dispositions(detections)
|
|
420
|
+
|
|
421
|
+
body = {
|
|
422
|
+
"events": events if include_raw_events else [],
|
|
423
|
+
"tool_calls": tool_calls,
|
|
424
|
+
"approvals": approvals,
|
|
425
|
+
"detections": detections,
|
|
426
|
+
# The decisions made in this period, in the order they were made. The
|
|
427
|
+
# `detections` entries above carry the state currently in force; this
|
|
428
|
+
# is the audit trail of how it got there.
|
|
429
|
+
"dispositions": extract_dispositions(events),
|
|
430
|
+
"controls": _controls_snapshot(),
|
|
431
|
+
"compliance_mapping": dict(_COMPLIANCE_MAPPING),
|
|
432
|
+
"summary": _summarize(
|
|
433
|
+
events, tool_calls, approvals, detections, disposition_counts
|
|
434
|
+
),
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
pack = {
|
|
438
|
+
"meta": {
|
|
439
|
+
"schema_version": SCHEMA_VERSION,
|
|
440
|
+
# An auditor reading this pack in 2028 needs to know which build
|
|
441
|
+
# produced it: rules, redaction, and mappings all move between
|
|
442
|
+
# versions. Provenance, not decoration.
|
|
443
|
+
"producer": f"agentmetry/{__version__}",
|
|
444
|
+
"exported_at": datetime.now(timezone.utc).isoformat(),
|
|
445
|
+
"date_from": from_date.isoformat(),
|
|
446
|
+
"date_to": to_date.isoformat(),
|
|
447
|
+
"query_start_ts": start_ts,
|
|
448
|
+
"query_end_ts": end_ts,
|
|
449
|
+
"source": "audit_trail",
|
|
450
|
+
"raw_events_included": include_raw_events,
|
|
451
|
+
"trail_chain": _trail_chain_state(),
|
|
452
|
+
},
|
|
453
|
+
**body,
|
|
454
|
+
}
|
|
455
|
+
pack["meta"]["integrity_sha256"] = _integrity_hash(body)
|
|
456
|
+
return pack
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def write_evidence_pack(pack: dict[str, Any], output: Path) -> Path:
|
|
460
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
461
|
+
output.write_text(
|
|
462
|
+
json.dumps(pack, indent=2, default=str) + "\n",
|
|
463
|
+
encoding="utf-8",
|
|
464
|
+
)
|
|
465
|
+
return output
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def default_export_path(
|
|
469
|
+
from_date: date, to_date: date, vault_path: Path | None = None
|
|
470
|
+
) -> Path:
|
|
471
|
+
"""Where an export lands by default.
|
|
472
|
+
|
|
473
|
+
Keeps the documented vault archive location when a vault exists, and falls
|
|
474
|
+
back to `data/exports/` next to the trail when it does not — a recorder-only
|
|
475
|
+
install has no vault, and compliance exports must still have a home.
|
|
476
|
+
"""
|
|
477
|
+
name = f"evidence-{from_date.isoformat()}_to_{to_date.isoformat()}.json"
|
|
478
|
+
vault = Path(vault_path) if vault_path else Path(settings.vault_path)
|
|
479
|
+
if vault.is_dir():
|
|
480
|
+
return vault / "30-Archive" / "exports" / name
|
|
481
|
+
return Path(settings.audit_export_path).parent / "exports" / name
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def verify_evidence_pack(pack: dict[str, Any]) -> tuple[bool, str]:
|
|
485
|
+
"""Return (ok, message). Recomputes integrity_sha256 over the body."""
|
|
486
|
+
meta = pack.get("meta") or {}
|
|
487
|
+
stored = meta.get("integrity_sha256")
|
|
488
|
+
if not stored:
|
|
489
|
+
return False, "missing meta.integrity_sha256"
|
|
490
|
+
|
|
491
|
+
body = {key: pack.get(key, [] if key != "controls" else {}) for key in _BODY_KEYS}
|
|
492
|
+
# compliance_mapping and summary default to dicts, not lists.
|
|
493
|
+
for key in ("compliance_mapping", "summary"):
|
|
494
|
+
if not isinstance(body.get(key), dict):
|
|
495
|
+
body[key] = {}
|
|
496
|
+
|
|
497
|
+
expected = _integrity_hash(body)
|
|
498
|
+
if expected != stored:
|
|
499
|
+
return False, f"integrity mismatch (expected {expected[:16]}…, got {stored[:16]}…)"
|
|
500
|
+
return True, "integrity verified"
|