authority-runtime 0.3.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.
@@ -0,0 +1,572 @@
1
+ """
2
+ Compliance Reporting for Authority Runtime
3
+
4
+ Generates audit reports for regulatory compliance (FERPA, SOC 2, HIPAA, etc.)
5
+ from the existing audit trail.
6
+
7
+ Key capability: negative attestation — cryptographic proof that an agent
8
+ NEVER accessed a specific resource during a time period.
9
+ """
10
+
11
+ import csv
12
+ import hashlib
13
+ import io
14
+ import json
15
+ from datetime import datetime, timezone
16
+ from typing import Any, Dict, List, Optional
17
+
18
+ from .storage import EnvelopeStore
19
+
20
+
21
+ class ComplianceReport:
22
+ """
23
+ Generates compliance reports from the Carryall audit trail.
24
+
25
+ Example:
26
+ ```python
27
+ store = EnvelopeStore("./authority.db")
28
+ report = ComplianceReport(store)
29
+
30
+ # Prove financial-aid-agent never accessed health records
31
+ attestation = report.negative_attestation(
32
+ agent_id="financial-aid-agent",
33
+ resource_pattern="slos://vaults/student-health/%",
34
+ start_time="2026-01-01T00:00:00Z",
35
+ end_time="2026-03-01T00:00:00Z",
36
+ )
37
+ print(attestation["result"]) # "CONFIRMED: 0 access events found"
38
+ ```
39
+ """
40
+
41
+ def __init__(self, store: EnvelopeStore):
42
+ self.store = store
43
+
44
+ def agent_access_report(
45
+ self,
46
+ agent_id: str,
47
+ resource_pattern: Optional[str] = None,
48
+ start_time: Optional[str] = None,
49
+ end_time: Optional[str] = None,
50
+ ) -> Dict[str, Any]:
51
+ """
52
+ All accesses by a specific agent, optionally filtered by resource.
53
+
54
+ Returns a structured report showing what the agent accessed, when,
55
+ and with what result.
56
+ """
57
+ entries = self.store.get_audit_trail(
58
+ agent_id=agent_id,
59
+ resource_pattern=resource_pattern,
60
+ start_time=start_time,
61
+ end_time=end_time,
62
+ )
63
+
64
+ resources = self.store.get_distinct_resources_for_agent(
65
+ agent_id=agent_id,
66
+ start_time=start_time,
67
+ end_time=end_time,
68
+ )
69
+
70
+ return {
71
+ "report_type": "agent_access",
72
+ "generated_at": datetime.now(timezone.utc).isoformat(),
73
+ "parameters": {
74
+ "agent_id": agent_id,
75
+ "resource_pattern": resource_pattern,
76
+ "start_time": start_time,
77
+ "end_time": end_time,
78
+ },
79
+ "summary": {
80
+ "total_events": len(entries),
81
+ "successful": sum(1 for e in entries if e["result"] == "success"),
82
+ "blocked": sum(1 for e in entries if e["result"] == "blocked"),
83
+ "distinct_resources": len(resources),
84
+ },
85
+ "resources_accessed": resources,
86
+ "entries": entries,
87
+ }
88
+
89
+ def resource_access_report(
90
+ self,
91
+ resource_pattern: str,
92
+ start_time: Optional[str] = None,
93
+ end_time: Optional[str] = None,
94
+ ) -> Dict[str, Any]:
95
+ """
96
+ All agents that accessed resources matching a pattern.
97
+
98
+ Answers: "Who has touched student records in the last 90 days?"
99
+ """
100
+ agents = self.store.get_distinct_agents_for_resource(
101
+ resource_pattern=resource_pattern,
102
+ start_time=start_time,
103
+ end_time=end_time,
104
+ )
105
+
106
+ total = self.store.count_access_events(
107
+ resource_pattern=resource_pattern,
108
+ start_time=start_time,
109
+ end_time=end_time,
110
+ )
111
+
112
+ return {
113
+ "report_type": "resource_access",
114
+ "generated_at": datetime.now(timezone.utc).isoformat(),
115
+ "parameters": {
116
+ "resource_pattern": resource_pattern,
117
+ "start_time": start_time,
118
+ "end_time": end_time,
119
+ },
120
+ "summary": {
121
+ "total_events": total,
122
+ "distinct_agents": len(agents),
123
+ },
124
+ "agents": agents,
125
+ }
126
+
127
+ def negative_attestation(
128
+ self,
129
+ agent_id: str,
130
+ resource_pattern: str,
131
+ start_time: Optional[str] = None,
132
+ end_time: Optional[str] = None,
133
+ ) -> Dict[str, Any]:
134
+ """
135
+ Prove that an agent NEVER accessed resources matching a pattern.
136
+
137
+ This is the FERPA killer feature. When the count is 0, this is a
138
+ cryptographically-backed attestation that can be presented to auditors.
139
+
140
+ The attestation includes a SHA-256 hash of the query parameters so
141
+ the exact query can be verified later.
142
+
143
+ Returns:
144
+ Dict with:
145
+ - result: "CONFIRMED: 0 access events found" or "FAILED: N events found"
146
+ - count: number of matching events
147
+ - attestation_hash: SHA-256 of query parameters
148
+ - query_parameters: the exact filters used
149
+ """
150
+ count = self.store.count_access_events(
151
+ agent_id=agent_id,
152
+ resource_pattern=resource_pattern,
153
+ start_time=start_time,
154
+ end_time=end_time,
155
+ )
156
+
157
+ # Create deterministic hash of the query for verification
158
+ query_canonical = json.dumps({
159
+ "agent_id": agent_id,
160
+ "resource_pattern": resource_pattern,
161
+ "start_time": start_time,
162
+ "end_time": end_time,
163
+ }, sort_keys=True)
164
+ attestation_hash = hashlib.sha256(query_canonical.encode()).hexdigest()
165
+
166
+ confirmed = count == 0
167
+
168
+ return {
169
+ "report_type": "negative_attestation",
170
+ "generated_at": datetime.now(timezone.utc).isoformat(),
171
+ "result": f"CONFIRMED: 0 access events found" if confirmed
172
+ else f"FAILED: {count} access event(s) found",
173
+ "confirmed": confirmed,
174
+ "count": count,
175
+ "attestation_hash": attestation_hash,
176
+ "query_parameters": {
177
+ "agent_id": agent_id,
178
+ "resource_pattern": resource_pattern,
179
+ "start_time": start_time,
180
+ "end_time": end_time,
181
+ },
182
+ }
183
+
184
+ def scope_usage_report(
185
+ self,
186
+ start_time: Optional[str] = None,
187
+ end_time: Optional[str] = None,
188
+ ) -> Dict[str, Any]:
189
+ """
190
+ Scopes granted vs. actually used — proves least-privilege enforcement.
191
+
192
+ Pulls envelope scopes and compares against actual audit trail actions.
193
+ """
194
+ trail = self.store.get_audit_trail(
195
+ start_time=start_time,
196
+ end_time=end_time,
197
+ )
198
+
199
+ # Group by agent
200
+ agent_scopes: Dict[str, Dict[str, Any]] = {}
201
+ for entry in trail:
202
+ aid = entry["agent_id"]
203
+ if aid not in agent_scopes:
204
+ agent_scopes[aid] = {
205
+ "total_events": 0,
206
+ "actions": set(),
207
+ "resources": set(),
208
+ }
209
+ agent_scopes[aid]["total_events"] += 1
210
+ agent_scopes[aid]["actions"].add(entry["action"])
211
+ if entry.get("resource"):
212
+ agent_scopes[aid]["resources"].add(entry["resource"])
213
+
214
+ # Convert sets to lists for JSON serialization
215
+ agents = {
216
+ aid: {
217
+ "total_events": data["total_events"],
218
+ "distinct_actions": list(data["actions"]),
219
+ "distinct_resources": list(data["resources"]),
220
+ }
221
+ for aid, data in agent_scopes.items()
222
+ }
223
+
224
+ return {
225
+ "report_type": "scope_usage",
226
+ "generated_at": datetime.now(timezone.utc).isoformat(),
227
+ "parameters": {
228
+ "start_time": start_time,
229
+ "end_time": end_time,
230
+ },
231
+ "summary": {
232
+ "total_events": len(trail),
233
+ "distinct_agents": len(agents),
234
+ },
235
+ "agents": agents,
236
+ }
237
+
238
+ def generate_summary(self, report: Dict[str, Any]) -> str:
239
+ """Generate a human-readable summary from any report type."""
240
+ lines = []
241
+ report_type = report.get("report_type", "unknown")
242
+ lines.append(f"Compliance Report: {report_type}")
243
+ lines.append(f"Generated: {report.get('generated_at', 'unknown')}")
244
+ lines.append("")
245
+
246
+ if report_type == "negative_attestation":
247
+ lines.append(f"Result: {report['result']}")
248
+ lines.append(f"Agent: {report['query_parameters']['agent_id']}")
249
+ lines.append(f"Resource Pattern: {report['query_parameters']['resource_pattern']}")
250
+ lines.append(f"Time Range: {report['query_parameters'].get('start_time', 'all')} - {report['query_parameters'].get('end_time', 'now')}")
251
+ lines.append(f"Attestation Hash: {report['attestation_hash']}")
252
+
253
+ elif report_type == "agent_access":
254
+ summary = report["summary"]
255
+ lines.append(f"Agent: {report['parameters']['agent_id']}")
256
+ lines.append(f"Total Events: {summary['total_events']}")
257
+ lines.append(f"Successful: {summary['successful']}")
258
+ lines.append(f"Blocked: {summary['blocked']}")
259
+ lines.append(f"Distinct Resources: {summary['distinct_resources']}")
260
+
261
+ elif report_type == "resource_access":
262
+ summary = report["summary"]
263
+ lines.append(f"Resource Pattern: {report['parameters']['resource_pattern']}")
264
+ lines.append(f"Total Events: {summary['total_events']}")
265
+ lines.append(f"Distinct Agents: {summary['distinct_agents']}")
266
+ if report.get("agents"):
267
+ lines.append("")
268
+ lines.append("Agents:")
269
+ for agent in report["agents"]:
270
+ lines.append(f" - {agent['agent_id']}: {agent['access_count']} accesses")
271
+
272
+ elif report_type == "scope_usage":
273
+ summary = report["summary"]
274
+ lines.append(f"Total Events: {summary['total_events']}")
275
+ lines.append(f"Distinct Agents: {summary['distinct_agents']}")
276
+
277
+ return "\n".join(lines)
278
+
279
+ def export_json(self, report: Dict[str, Any], filepath: str) -> None:
280
+ """Export a report to JSON file."""
281
+ with open(filepath, "w") as f:
282
+ json.dump(report, f, indent=2, default=str)
283
+
284
+ def export_csv(self, entries: List[Dict[str, Any]], filepath: str) -> None:
285
+ """Export audit entries to CSV for spreadsheet review."""
286
+ if not entries:
287
+ with open(filepath, "w") as f:
288
+ f.write("")
289
+ return
290
+
291
+ # Flatten entries for CSV
292
+ fieldnames = [
293
+ "timestamp", "agent_id", "action", "resource", "result",
294
+ "error", "envelope_id", "signature_valid",
295
+ ]
296
+
297
+ with open(filepath, "w", newline="") as f:
298
+ writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction="ignore")
299
+ writer.writeheader()
300
+ for entry in entries:
301
+ writer.writerow(entry)
302
+
303
+ def export_csv_string(self, entries: List[Dict[str, Any]]) -> str:
304
+ """Export audit entries to CSV string."""
305
+ if not entries:
306
+ return ""
307
+
308
+ fieldnames = [
309
+ "timestamp", "agent_id", "action", "resource", "result",
310
+ "error", "envelope_id", "signature_valid",
311
+ ]
312
+
313
+ output = io.StringIO()
314
+ writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction="ignore")
315
+ writer.writeheader()
316
+ for entry in entries:
317
+ writer.writerow(entry)
318
+ return output.getvalue()
319
+
320
+ def generate_full_report(
321
+ self,
322
+ start_time: Optional[str] = None,
323
+ end_time: Optional[str] = None,
324
+ policy_summary: Optional[Dict[str, Any]] = None,
325
+ title: str = "FERPA Compliance Report",
326
+ ) -> Dict[str, Any]:
327
+ """
328
+ Aggregate all report types into a single comprehensive report.
329
+
330
+ Combines:
331
+ - Executive summary (stats)
332
+ - Per-agent access breakdowns
333
+ - Negative attestation matrix (every agent x sensitive vaults)
334
+ - Data classifications from policy (if provided)
335
+ """
336
+ stats = self.store.get_stats()
337
+ trail = self.store.get_audit_trail(start_time=start_time, end_time=end_time)
338
+
339
+ # Collect all unique agents
340
+ agent_ids = set()
341
+ for entry in trail:
342
+ agent_ids.add(entry["agent_id"])
343
+
344
+ # Per-agent reports
345
+ agent_reports = {}
346
+ for agent_id in sorted(agent_ids):
347
+ agent_reports[agent_id] = self.agent_access_report(
348
+ agent_id=agent_id, start_time=start_time, end_time=end_time
349
+ )
350
+
351
+ # Negative attestation matrix: each agent vs sensitive resource patterns
352
+ sensitive_patterns = [
353
+ "slos://vaults/student-health/%",
354
+ "slos://vaults/financial-aid/%",
355
+ ]
356
+ attestations = []
357
+ for agent_id in sorted(agent_ids):
358
+ for pattern in sensitive_patterns:
359
+ attestation = self.negative_attestation(
360
+ agent_id=agent_id,
361
+ resource_pattern=pattern,
362
+ start_time=start_time,
363
+ end_time=end_time,
364
+ )
365
+ attestations.append(attestation)
366
+
367
+ return {
368
+ "report_type": "full_compliance",
369
+ "title": title,
370
+ "generated_at": datetime.now(timezone.utc).isoformat(),
371
+ "time_window": {
372
+ "start": start_time or "all time",
373
+ "end": end_time or "now",
374
+ },
375
+ "executive_summary": {
376
+ "total_agents": stats["envelopes"]["unique_agents"],
377
+ "total_envelopes": stats["envelopes"]["total"],
378
+ "total_events": stats["audit_trail"]["total_actions"],
379
+ "successful": stats["audit_trail"]["successful"],
380
+ "blocked": stats["audit_trail"]["blocked"],
381
+ "signature_failures": stats["audit_trail"]["signature_failures"],
382
+ },
383
+ "agent_reports": agent_reports,
384
+ "attestations": attestations,
385
+ "policy_summary": policy_summary,
386
+ }
387
+
388
+ def render_html(self, report: Dict[str, Any]) -> str:
389
+ """
390
+ Render a full compliance report as self-contained HTML.
391
+
392
+ No external CSS, no JavaScript. Opens in any browser.
393
+ Professional enough to email to legal.
394
+ """
395
+ title = report.get("title", "Compliance Report")
396
+ generated = report.get("generated_at", "")[:19]
397
+ window = report.get("time_window", {})
398
+ summary = report.get("executive_summary", {})
399
+ agent_reports = report.get("agent_reports", {})
400
+ attestations = report.get("attestations", [])
401
+ policy = report.get("policy_summary")
402
+
403
+ # Build HTML sections
404
+ sections = []
405
+
406
+ # Executive summary
407
+ sections.append(self._html_executive_summary(summary))
408
+
409
+ # Per-agent breakdown
410
+ sections.append(self._html_agent_breakdown(agent_reports))
411
+
412
+ # Negative attestations
413
+ sections.append(self._html_attestations(attestations))
414
+
415
+ # Policy / data classification (if available)
416
+ if policy:
417
+ sections.append(self._html_policy_summary(policy))
418
+
419
+ # Metadata
420
+ sections.append(self._html_metadata(report))
421
+
422
+ body = "\n".join(sections)
423
+
424
+ return f"""<!DOCTYPE html>
425
+ <html lang="en">
426
+ <head>
427
+ <meta charset="UTF-8">
428
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
429
+ <title>{_h(title)}</title>
430
+ <style>
431
+ * {{ margin: 0; padding: 0; box-sizing: border-box; }}
432
+ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
433
+ color: #1a1a2e; background: #f8f9fa; line-height: 1.6; padding: 2rem; }}
434
+ .container {{ max-width: 900px; margin: 0 auto; }}
435
+ h1 {{ font-size: 1.8rem; margin-bottom: 0.25rem; color: #1a1a2e; }}
436
+ .subtitle {{ color: #6c757d; margin-bottom: 2rem; font-size: 0.95rem; }}
437
+ h2 {{ font-size: 1.3rem; color: #1a1a2e; margin: 2rem 0 1rem 0;
438
+ border-bottom: 2px solid #dee2e6; padding-bottom: 0.5rem; }}
439
+ table {{ width: 100%; border-collapse: collapse; margin: 1rem 0; }}
440
+ th, td {{ padding: 0.6rem 0.8rem; text-align: left; border-bottom: 1px solid #dee2e6; }}
441
+ th {{ background: #e9ecef; font-weight: 600; font-size: 0.85rem;
442
+ text-transform: uppercase; letter-spacing: 0.03em; color: #495057; }}
443
+ td {{ font-size: 0.9rem; }}
444
+ .stat-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
445
+ gap: 1rem; margin: 1rem 0; }}
446
+ .stat {{ background: white; padding: 1rem; border-radius: 8px;
447
+ border: 1px solid #dee2e6; text-align: center; }}
448
+ .stat-value {{ font-size: 1.8rem; font-weight: 700; color: #1a1a2e; }}
449
+ .stat-label {{ font-size: 0.8rem; color: #6c757d; text-transform: uppercase;
450
+ letter-spacing: 0.05em; }}
451
+ .pass {{ color: #28a745; font-weight: 600; }}
452
+ .fail {{ color: #dc3545; font-weight: 600; }}
453
+ .warn {{ color: #ffc107; font-weight: 600; }}
454
+ .hash {{ font-family: monospace; font-size: 0.78rem; color: #6c757d;
455
+ word-break: break-all; }}
456
+ .badge {{ display: inline-block; padding: 0.15rem 0.5rem; border-radius: 4px;
457
+ font-size: 0.78rem; font-weight: 600; }}
458
+ .badge-green {{ background: #d4edda; color: #155724; }}
459
+ .badge-red {{ background: #f8d7da; color: #721c24; }}
460
+ .badge-yellow {{ background: #fff3cd; color: #856404; }}
461
+ .meta {{ color: #6c757d; font-size: 0.82rem; margin-top: 2rem;
462
+ border-top: 1px solid #dee2e6; padding-top: 1rem; }}
463
+ .meta td {{ border: none; padding: 0.2rem 0.8rem; }}
464
+ </style>
465
+ </head>
466
+ <body>
467
+ <div class="container">
468
+ <h1>{_h(title)}</h1>
469
+ <p class="subtitle">Generated {_h(generated)} UTC &middot; Window: {_h(str(window.get('start', 'all')))} to {_h(str(window.get('end', 'now')))}</p>
470
+ {body}
471
+ </div>
472
+ </body>
473
+ </html>"""
474
+
475
+ def _html_executive_summary(self, summary: dict) -> str:
476
+ total = summary.get("total_events", 0)
477
+ blocked = summary.get("blocked", 0)
478
+ sig_fail = summary.get("signature_failures", 0)
479
+ block_rate = f"{(blocked / total * 100):.1f}%" if total else "0%"
480
+
481
+ return f"""<h2>Executive Summary</h2>
482
+ <div class="stat-grid">
483
+ <div class="stat"><div class="stat-value">{summary.get('total_agents', 0)}</div><div class="stat-label">Agents</div></div>
484
+ <div class="stat"><div class="stat-value">{total}</div><div class="stat-label">Total Events</div></div>
485
+ <div class="stat"><div class="stat-value">{summary.get('successful', 0)}</div><div class="stat-label">Successful</div></div>
486
+ <div class="stat"><div class="stat-value">{blocked}</div><div class="stat-label">Blocked</div></div>
487
+ <div class="stat"><div class="stat-value">{block_rate}</div><div class="stat-label">Block Rate</div></div>
488
+ <div class="stat"><div class="stat-value {'fail' if sig_fail else 'pass'}">{sig_fail}</div><div class="stat-label">Sig Failures</div></div>
489
+ </div>"""
490
+
491
+ def _html_agent_breakdown(self, agent_reports: dict) -> str:
492
+ rows = []
493
+ for agent_id, report in sorted(agent_reports.items()):
494
+ s = report["summary"]
495
+ rows.append(
496
+ f"<tr><td>{_h(agent_id)}</td>"
497
+ f"<td>{s['total_events']}</td>"
498
+ f"<td>{s['successful']}</td>"
499
+ f"<td>{s['blocked']}</td>"
500
+ f"<td>{s['distinct_resources']}</td></tr>"
501
+ )
502
+
503
+ return f"""<h2>Per-Agent Access Breakdown</h2>
504
+ <table>
505
+ <tr><th>Agent ID</th><th>Events</th><th>Successful</th><th>Blocked</th><th>Resources</th></tr>
506
+ {''.join(rows)}
507
+ </table>"""
508
+
509
+ def _html_attestations(self, attestations: list) -> str:
510
+ rows = []
511
+ for a in attestations:
512
+ qp = a.get("query_parameters", {})
513
+ confirmed = a.get("confirmed", False)
514
+ badge = '<span class="badge badge-green">CONFIRMED</span>' if confirmed \
515
+ else f'<span class="badge badge-red">FAILED ({a.get("count", "?")} events)</span>'
516
+
517
+ rows.append(
518
+ f"<tr><td>{_h(qp.get('agent_id', ''))}</td>"
519
+ f"<td>{_h(qp.get('resource_pattern', ''))}</td>"
520
+ f"<td>{badge}</td>"
521
+ f"<td class=\"hash\">{_h(a.get('attestation_hash', '')[:24])}...</td></tr>"
522
+ )
523
+
524
+ return f"""<h2>Negative Attestation Matrix</h2>
525
+ <p>Cryptographic proof of access or non-access for each agent &times; sensitive resource combination.</p>
526
+ <table>
527
+ <tr><th>Agent</th><th>Resource Pattern</th><th>Result</th><th>Hash</th></tr>
528
+ {''.join(rows)}
529
+ </table>"""
530
+
531
+ def _html_policy_summary(self, policy: dict) -> str:
532
+ # Data classifications
533
+ dc_rows = []
534
+ for dc in policy.get("data_classifications", []):
535
+ sens = dc.get("sensitivity", "")
536
+ badge_class = {"restricted": "badge-red", "confidential": "badge-yellow"}.get(sens, "badge-green")
537
+ pii = ", ".join(dc.get("pii_fields", []))
538
+ retention = f"{dc.get('retention_days', 0)} days" if dc.get("retention_days") else "N/A"
539
+ dc_rows.append(
540
+ f"<tr><td>{_h(dc['domain'])}</td>"
541
+ f"<td><span class=\"badge {badge_class}\">{_h(sens)}</span></td>"
542
+ f"<td>{_h(pii)}</td>"
543
+ f"<td>{retention}</td></tr>"
544
+ )
545
+
546
+ dc_section = ""
547
+ if dc_rows:
548
+ dc_section = f"""<h2>Data Classifications</h2>
549
+ <p>Organization: {_h(policy.get('organization', ''))} &middot; Frameworks: {_h(', '.join(policy.get('compliance_frameworks', [])))}</p>
550
+ <table>
551
+ <tr><th>Domain</th><th>Sensitivity</th><th>PII Fields</th><th>Retention</th></tr>
552
+ {''.join(dc_rows)}
553
+ </table>"""
554
+
555
+ return dc_section
556
+
557
+ def _html_metadata(self, report: dict) -> str:
558
+ from . import __version__
559
+ return f"""<table class="meta">
560
+ <tr><td><strong>Report Type</strong></td><td>{_h(report.get('report_type', ''))}</td></tr>
561
+ <tr><td><strong>Generated At</strong></td><td>{_h(report.get('generated_at', ''))}</td></tr>
562
+ <tr><td><strong>Carryall Version</strong></td><td>{_h(__version__)}</td></tr>
563
+ </table>"""
564
+
565
+
566
+ def _h(text: str) -> str:
567
+ """HTML-escape a string."""
568
+ return (str(text)
569
+ .replace("&", "&amp;")
570
+ .replace("<", "&lt;")
571
+ .replace(">", "&gt;")
572
+ .replace('"', "&quot;"))