-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_verify.py
More file actions
2023 lines (1802 loc) · 75.7 KB
/
Copy pathtest_verify.py
File metadata and controls
2023 lines (1802 loc) · 75.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Comprehensive tests for ai_identity_verify.py.
Uses only unittest (stdlib). Covers:
- HMAC computation with known test vectors
- Report verification (valid / tampered)
- Chain verification (valid / broken / empty)
- Missing environment variable handling
- JSON and human-readable output modes
- Edge cases (empty chain, single entry, cost_estimate_usd null)
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import io
import json
import os
import sys
import tempfile
import unittest
from typing import Any
from unittest.mock import patch
# Import the CLI module from the same directory
sys.path.insert(0, os.path.dirname(__file__))
import contextlib
import ai_identity_verify as cli
# ── Test constants ──────────────────────────────────────────────────────
TEST_HMAC_KEY = "test-secret-key-for-verification"
TEST_HMAC_KEY_BYTES = TEST_HMAC_KEY.encode("utf-8")
TEST_AGENT_ID = "550e8400-e29b-41d4-a716-446655440000"
TEST_REPORT_ID = "fr-a1b2c3d4-20260310"
TEST_GENERATED_AT = "2026-04-08T21:10:37+00:00"
# ── Helpers ─────────────────────────────────────────────────────────────
def _make_report_signature(
report_id: str = TEST_REPORT_ID,
generated_at: str = TEST_GENERATED_AT,
chain_valid: bool = True,
total_entries: int = 3,
entries_verified: int = 3,
key: bytes = TEST_HMAC_KEY_BYTES,
) -> str:
"""Compute a report signature the same way the server does."""
payload = json.dumps(
{
"entries_verified": entries_verified,
"chain_valid": chain_valid,
"generated_at": generated_at,
"report_id": report_id,
"total_entries": total_entries,
},
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
return hmac.new(key, payload, hashlib.sha256).hexdigest()
def _make_entry_hash(
agent_id: str,
endpoint: str,
method: str,
decision: str,
cost_estimate_usd: Any,
latency_ms: Any,
request_metadata: dict,
created_at: str,
prev_hash: str,
key: bytes = TEST_HMAC_KEY_BYTES,
) -> str:
"""Compute an entry hash the same way the server does."""
payload = {
"agent_id": str(agent_id),
"cost_estimate_usd": str(cost_estimate_usd) if cost_estimate_usd is not None else None,
"created_at": created_at,
"decision": decision,
"endpoint": endpoint,
"latency_ms": latency_ms,
"method": method,
"prev_hash": prev_hash,
"request_metadata": request_metadata,
}
message = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hmac.new(key, message, hashlib.sha256).hexdigest()
def _build_chain(count: int = 3) -> list[dict[str, Any]]:
"""Build a valid chain of audit entries."""
entries = []
prev_hash = "GENESIS"
for i in range(count):
created_at = f"2026-04-08T10:{i:02d}:00+00:00"
cost = 0.001 * (i + 1) if i % 2 == 0 else None
latency = 50 + i * 10
metadata = {"status_code": 200, "model": "gpt-4"}
entry_hash = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/v1/chat/completions",
method="POST",
decision="allow",
cost_estimate_usd=cost,
latency_ms=latency,
request_metadata=metadata,
created_at=created_at,
prev_hash=prev_hash,
)
entries.append(
{
"id": i + 1,
"agent_id": TEST_AGENT_ID,
"endpoint": "/v1/chat/completions",
"method": "POST",
"decision": "allow",
"cost_estimate_usd": cost,
"latency_ms": latency,
"request_metadata": metadata,
"created_at": created_at,
"entry_hash": entry_hash,
"prev_hash": prev_hash,
}
)
prev_hash = entry_hash
return entries
def _build_partial_chain(count: int = 3, start_id: int = 50) -> list[dict[str, Any]]:
"""Build a valid partial chain (first entry does NOT start at GENESIS).
Simulates an export that starts mid-chain, e.g. from entry #50.
"""
# Create a fake "previous hash" that would come from the entry before the export
fake_prev = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/v1/chat/completions",
method="POST",
decision="allow",
cost_estimate_usd=0.001,
latency_ms=40,
request_metadata={"status_code": 200},
created_at="2026-04-08T09:59:00+00:00",
prev_hash="GENESIS",
)
entries = []
prev_hash = fake_prev
for i in range(count):
created_at = f"2026-04-08T10:{i:02d}:00+00:00"
cost = 0.001 * (i + 1) if i % 2 == 0 else None
latency = 50 + i * 10
metadata = {"status_code": 200, "model": "gpt-4"}
entry_id = start_id + i
entry_hash = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/v1/chat/completions",
method="POST",
decision="allow",
cost_estimate_usd=cost,
latency_ms=latency,
request_metadata=metadata,
created_at=created_at,
prev_hash=prev_hash,
)
entries.append(
{
"id": entry_id,
"agent_id": TEST_AGENT_ID,
"endpoint": "/v1/chat/completions",
"method": "POST",
"decision": "allow",
"cost_estimate_usd": cost,
"latency_ms": latency,
"request_metadata": metadata,
"created_at": created_at,
"entry_hash": entry_hash,
"prev_hash": prev_hash,
}
)
prev_hash = entry_hash
return entries
def _build_report(entries: list[dict[str, Any]] | None = None) -> dict[str, Any]:
"""Build a valid ForensicsReportResponse-shaped dict."""
if entries is None:
entries = _build_chain(3)
total = len(entries)
sig = _make_report_signature(
total_entries=total,
entries_verified=total,
)
return {
"report_id": TEST_REPORT_ID,
"generated_at": TEST_GENERATED_AT,
"events": entries,
"chain_verification": {
"valid": True,
"chain_valid": True,
"total_entries": total,
"entries_verified": total,
"message": "Chain integrity verified",
},
"report_signature": sig,
}
def _write_json(data: Any) -> str:
"""Write data to a temporary JSON file, returning the path."""
fd, path = tempfile.mkstemp(suffix=".json")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f)
return path
def _run_cmd(argv: list[str], env_key: str = TEST_HMAC_KEY) -> tuple[int, str, str]:
"""Run the CLI main() capturing stdout/stderr and return (exit_code, stdout, stderr)."""
env_patch = {"AI_IDENTITY_HMAC_KEY": env_key} if env_key else {}
stdout = io.StringIO()
stderr = io.StringIO()
with (
patch.dict(os.environ, env_patch, clear=False),
patch("sys.stdout", stdout),
patch("sys.stderr", stderr),
):
# Remove key if env_key is explicitly empty string
if env_key == "":
os.environ.pop("AI_IDENTITY_HMAC_KEY", None)
try:
code = cli.main(argv)
except SystemExit as e:
code = e.code if e.code is not None else 0
return code, stdout.getvalue(), stderr.getvalue()
# ── Test: Known HMAC test vectors ───────────────────────────────────────
class TestHMACVectors(unittest.TestCase):
"""Verify that HMAC computations produce expected deterministic output."""
def test_report_signature_known_vector(self):
"""Compute a report signature and verify it matches a known value."""
sig = _make_report_signature(
report_id="test-report-001",
generated_at="2026-01-01T00:00:00+00:00",
chain_valid=True,
total_entries=10,
entries_verified=10,
key=b"known-test-key",
)
# Recompute the same way
payload = json.dumps(
{
"entries_verified": 10,
"chain_valid": True,
"generated_at": "2026-01-01T00:00:00+00:00",
"report_id": "test-report-001",
"total_entries": 10,
},
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
expected = hmac.new(b"known-test-key", payload, hashlib.sha256).hexdigest()
self.assertEqual(sig, expected)
# Deterministic — same inputs always produce same output
sig2 = _make_report_signature(
report_id="test-report-001",
generated_at="2026-01-01T00:00:00+00:00",
chain_valid=True,
total_entries=10,
entries_verified=10,
key=b"known-test-key",
)
self.assertEqual(sig, sig2)
def test_entry_hash_known_vector(self):
"""Compute an entry hash and verify deterministic output."""
h1 = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/test",
method="GET",
decision="allow",
cost_estimate_usd=None,
latency_ms=42,
request_metadata={},
created_at="2026-01-01T00:00:00+00:00",
prev_hash="GENESIS",
)
h2 = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/test",
method="GET",
decision="allow",
cost_estimate_usd=None,
latency_ms=42,
request_metadata={},
created_at="2026-01-01T00:00:00+00:00",
prev_hash="GENESIS",
)
self.assertEqual(h1, h2)
self.assertEqual(len(h1), 64) # SHA-256 hex digest
def test_different_key_produces_different_hash(self):
"""Different HMAC keys produce different results."""
h1 = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/test",
method="GET",
decision="allow",
cost_estimate_usd=None,
latency_ms=10,
request_metadata={},
created_at="2026-01-01T00:00:00+00:00",
prev_hash="GENESIS",
key=b"key-one",
)
h2 = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/test",
method="GET",
decision="allow",
cost_estimate_usd=None,
latency_ms=10,
request_metadata={},
created_at="2026-01-01T00:00:00+00:00",
prev_hash="GENESIS",
key=b"key-two",
)
self.assertNotEqual(h1, h2)
def test_canonical_sort_order(self):
"""Canonical payload sorts keys alphabetically."""
payload = cli._canonical_entry_payload(
{
"agent_id": TEST_AGENT_ID,
"endpoint": "/v1/test",
"method": "POST",
"decision": "allow",
"cost_estimate_usd": 0.05,
"latency_ms": 100,
"request_metadata": {"a": 1},
"created_at": "2026-01-01T00:00:00+00:00",
},
"GENESIS",
)
decoded = json.loads(payload)
keys = list(decoded.keys())
self.assertEqual(keys, sorted(keys))
def test_cost_estimate_string_conversion(self):
"""cost_estimate_usd is converted to string in payload."""
payload = cli._canonical_entry_payload(
{
"agent_id": TEST_AGENT_ID,
"endpoint": "/test",
"method": "GET",
"decision": "allow",
"cost_estimate_usd": 0.123,
"latency_ms": None,
"request_metadata": {},
"created_at": "2026-01-01T00:00:00+00:00",
},
"GENESIS",
)
decoded = json.loads(payload)
self.assertEqual(decoded["cost_estimate_usd"], "0.123")
def test_cost_estimate_null_stays_null(self):
"""cost_estimate_usd=None stays null in payload."""
payload = cli._canonical_entry_payload(
{
"agent_id": TEST_AGENT_ID,
"endpoint": "/test",
"method": "GET",
"decision": "allow",
"cost_estimate_usd": None,
"latency_ms": None,
"request_metadata": {},
"created_at": "2026-01-01T00:00:00+00:00",
},
"GENESIS",
)
decoded = json.loads(payload)
self.assertIsNone(decoded["cost_estimate_usd"])
# ── Test: Report verification ───────────────────────────────────────────
class TestReportVerification(unittest.TestCase):
"""Test the report subcommand."""
def test_valid_report(self):
"""A correctly signed report returns exit code 0."""
report = _build_report()
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "report", path])
self.assertEqual(code, 0)
self.assertIn("VALID", out)
finally:
os.unlink(path)
def test_valid_report_json_output(self):
"""JSON output for a valid report includes signature_valid=true."""
report = _build_report()
path = _write_json(report)
try:
code, out, err = _run_cmd(["--json", "report", path])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertEqual(result["result"], "valid")
self.assertTrue(result["details"]["signature_valid"])
finally:
os.unlink(path)
def test_tampered_report_id(self):
"""Changing the report_id invalidates the signature."""
report = _build_report()
report["report_id"] = "tampered-id"
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "report", path])
self.assertEqual(code, 1)
self.assertIn("INVALID", out)
finally:
os.unlink(path)
def test_tampered_entries_count(self):
"""Changing total_entries invalidates the signature."""
report = _build_report()
report["chain_verification"]["total_entries"] = 9999
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "report", path])
self.assertEqual(code, 1)
finally:
os.unlink(path)
def test_tampered_signature(self):
"""A corrupted signature string is detected."""
report = _build_report()
report["report_signature"] = "0" * 64
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "report", path])
self.assertEqual(code, 1)
finally:
os.unlink(path)
def test_tampered_chain_valid_flag(self):
"""Flipping chain_valid from true to false is detected."""
report = _build_report()
report["chain_verification"]["chain_valid"] = False
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "report", path])
self.assertEqual(code, 1)
finally:
os.unlink(path)
def test_wrong_hmac_key(self):
"""Using the wrong HMAC key produces an invalid result."""
report = _build_report()
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "report", path], env_key="wrong-key")
self.assertEqual(code, 1)
finally:
os.unlink(path)
def test_missing_fields(self):
"""A JSON file missing required fields exits with code 2."""
path = _write_json({"some": "data"})
try:
code, out, err = _run_cmd(["report", path])
self.assertEqual(code, 2)
self.assertIn("missing", err.lower())
finally:
os.unlink(path)
def test_verbose_shows_hashes(self):
"""Verbose mode shows expected and actual hashes."""
report = _build_report()
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "--verbose", "report", path])
self.assertEqual(code, 0)
self.assertIn("Expected:", out)
self.assertIn("Got:", out)
finally:
os.unlink(path)
# ── Test: Chain verification ────────────────────────────────────────────
class TestChainVerification(unittest.TestCase):
"""Test the chain subcommand."""
def test_valid_chain(self):
"""A valid chain returns exit code 0."""
entries = _build_chain(5)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("CHAIN INTACT", out)
self.assertIn("5/5", out)
finally:
os.unlink(path)
def test_valid_chain_json(self):
"""JSON output for a valid chain."""
entries = _build_chain(3)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertEqual(result["result"], "valid")
self.assertTrue(result["details"]["chain_intact"])
self.assertEqual(result["details"]["entries_verified"], 3)
finally:
os.unlink(path)
def test_tampered_entry_hash(self):
"""Tampering with an entry_hash breaks the chain."""
entries = _build_chain(5)
entries[2]["entry_hash"] = "0" * 64 # corrupt middle entry
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
self.assertIn("2/5", out) # only first 2 verified
finally:
os.unlink(path)
def test_tampered_entry_data(self):
"""Changing an entry's data field breaks the chain at that entry."""
entries = _build_chain(5)
entries[1]["decision"] = "deny" # tamper with data
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
self.assertIn("1/5", out) # only first entry verified
finally:
os.unlink(path)
def test_tampered_prev_hash(self):
"""Changing prev_hash breaks the chain."""
entries = _build_chain(3)
entries[1]["prev_hash"] = "bad" * 21 + "x" # wrong prev link
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
finally:
os.unlink(path)
def test_deleted_entry(self):
"""Removing an entry from the middle breaks the chain."""
entries = _build_chain(5)
del entries[2] # remove middle entry
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
finally:
os.unlink(path)
def test_empty_chain(self):
"""An empty chain returns exit code 0."""
path = _write_json([])
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
finally:
os.unlink(path)
def test_single_entry_chain(self):
"""A single valid entry chain verifies correctly."""
entries = _build_chain(1)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("1/1", out)
finally:
os.unlink(path)
def test_chain_in_report_envelope(self):
"""Chain command extracts entries from a report-shaped JSON."""
report = _build_report(_build_chain(3))
path = _write_json(report)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("CHAIN INTACT", out)
finally:
os.unlink(path)
def test_wrong_key_breaks_chain(self):
"""Using the wrong HMAC key breaks chain verification."""
entries = _build_chain(3)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path], env_key="wrong-key")
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
finally:
os.unlink(path)
def test_chain_json_broken(self):
"""JSON output for a broken chain includes break_at details."""
entries = _build_chain(5)
entries[3]["decision"] = "deny"
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 1)
result = json.loads(out)
self.assertEqual(result["result"], "broken")
self.assertFalse(result["details"]["chain_intact"])
self.assertIn("break_at", result["details"])
self.assertEqual(result["details"]["break_at"]["index"], 3)
finally:
os.unlink(path)
# ── Test: Per-org chain verification ──────────────────────────────────
def _build_org_chain(
count: int = 3, start_seq: int = 1, start_prev: str = "GENESIS"
) -> list[dict[str, Any]]:
"""Build a valid per-org chain (uses prev_hash_org/entry_hash_org/org_chain_seq).
Mirrors what the forensics bundle exports after Phase 1 of the per-org
migration. start_seq=1 + start_prev=GENESIS means the export covers
the org's first row; otherwise simulates a time-windowed slice.
"""
entries = []
prev_hash_org = start_prev
for i in range(count):
seq = start_seq + i
created_at = f"2026-04-08T10:{i:02d}:00+00:00"
cost = 0.001 * (i + 1) if i % 2 == 0 else None
latency = 50 + i * 10
metadata = {"status_code": 200, "model": "gpt-4"}
# entry_hash_org uses the same canonical-form math as entry_hash,
# just with prev_hash_org substituted into the prev_hash slot.
entry_hash_org = _make_entry_hash(
agent_id=TEST_AGENT_ID,
endpoint="/v1/chat/completions",
method="POST",
decision="allow",
cost_estimate_usd=cost,
latency_ms=latency,
request_metadata=metadata,
created_at=created_at,
prev_hash=prev_hash_org,
)
entries.append(
{
"id": i + 1,
"agent_id": TEST_AGENT_ID,
"endpoint": "/v1/chat/completions",
"method": "POST",
"decision": "allow",
"cost_estimate_usd": cost,
"latency_ms": latency,
"request_metadata": metadata,
"created_at": created_at,
# Per-org chain fields — CLI prefers these when present
"prev_hash_org": prev_hash_org,
"entry_hash_org": entry_hash_org,
"org_chain_seq": seq,
# Global chain fields kept so legacy --global path still works
"entry_hash": entry_hash_org,
"prev_hash": prev_hash_org,
}
)
prev_hash_org = entry_hash_org
return entries
class TestPerOrgChainVerification(unittest.TestCase):
"""Per-org chain verification — sequence-gap detection + linkage."""
def test_valid_per_org_chain(self):
entries = _build_org_chain(5)
path = _write_json(entries)
try:
code, out, _ = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("CHAIN INTACT", out)
self.assertIn("Per-org", out)
finally:
os.unlink(path)
def test_per_org_used_by_default_when_fields_present(self):
"""Exports with per-org fields should auto-route to per-org verify."""
entries = _build_org_chain(3)
path = _write_json(entries)
try:
code, out, _ = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertEqual(result["details"]["mode"], "per-org")
finally:
os.unlink(path)
def test_sequence_gap_detected(self):
"""Deleting a middle entry shows up as a sequence gap — the per-org
completeness proof the global chain couldn't deliver."""
entries = _build_org_chain(5)
del entries[2] # seq=3 disappears
path = _write_json(entries)
try:
code, out, _ = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
self.assertIn("sequence gap", out)
finally:
os.unlink(path)
def test_tampered_entry_hash_org_detected(self):
entries = _build_org_chain(4)
entries[2]["entry_hash_org"] = "0" * 64
path = _write_json(entries)
try:
code, out, _ = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("CHAIN BROKEN", out)
finally:
os.unlink(path)
def test_partial_window_starts_at_arbitrary_seq(self):
"""Time-windowed exports start at seq=N, not 1. Linkage anchors at
the first entry's prev_hash_org."""
entries = _build_org_chain(3, start_seq=42, start_prev="a" * 64)
path = _write_json(entries)
try:
code, out, _ = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("42 → 44", out)
finally:
os.unlink(path)
def test_global_flag_forces_legacy_verify(self):
"""--global skips per-org and uses the legacy global chain path."""
entries = _build_org_chain(3)
path = _write_json(entries)
try:
code, out, _ = _run_cmd(["--no-color", "chain", "--global", path])
self.assertEqual(code, 0)
# Legacy "Full" mode label, not per-org
self.assertNotIn("Per-org", out)
finally:
os.unlink(path)
class TestPartialChainVerification(unittest.TestCase):
"""Test partial chain verification (entries not starting from genesis)."""
def test_single_entry_valid(self):
"""A single valid partial entry returns exit code 0 and ENTRY VERIFIED."""
entries = _build_partial_chain(count=1, start_id=96)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("ENTRY VERIFIED", out)
self.assertIn("1/1", out)
self.assertIn("Partial", out)
self.assertIn("entry #96", out)
self.assertIn("Entry hash matches HMAC computation", out)
self.assertIn("Chain linkage cannot be fully verified", out)
finally:
os.unlink(path)
def test_single_entry_tampered(self):
"""A tampered single partial entry returns exit code 1 and ENTRY TAMPERED."""
entries = _build_partial_chain(count=1, start_id=96)
entries[0]["decision"] = "deny" # tamper with data
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("ENTRY TAMPERED", out)
self.assertIn("0/1", out)
self.assertIn("Entry #96", out)
finally:
os.unlink(path)
def test_multi_entry_partial_chain_valid(self):
"""A valid multi-entry partial chain returns exit code 0 and PARTIAL CHAIN INTACT."""
entries = _build_partial_chain(count=5, start_id=50)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 0)
self.assertIn("PARTIAL CHAIN INTACT", out)
self.assertIn("5/5", out)
self.assertIn("Partial", out)
self.assertIn("entry #50", out)
self.assertIn("All entry hashes valid and chain linkage", out)
finally:
os.unlink(path)
def test_multi_entry_partial_chain_tampered(self):
"""A tampered entry in a partial chain returns exit code 1."""
entries = _build_partial_chain(count=5, start_id=50)
entries[2]["entry_hash"] = "0" * 64 # corrupt middle entry
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--no-color", "chain", path])
self.assertEqual(code, 1)
self.assertIn("TAMPERED", out)
finally:
os.unlink(path)
def test_partial_chain_json_output(self):
"""JSON output for partial chain includes mode=partial."""
entries = _build_partial_chain(count=3, start_id=50)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertEqual(result["result"], "partial_valid")
self.assertEqual(result["details"]["mode"], "partial")
self.assertTrue(result["details"]["chain_intact"])
self.assertEqual(result["details"]["entries_verified"], 3)
self.assertEqual(result["details"]["partial_start_entry"], 50)
finally:
os.unlink(path)
def test_single_entry_tampered_json_output(self):
"""JSON output for a tampered partial entry includes mode=partial and tampered info."""
entries = _build_partial_chain(count=1, start_id=96)
entries[0]["decision"] = "deny"
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 1)
result = json.loads(out)
self.assertEqual(result["result"], "entry_tampered")
self.assertEqual(result["details"]["mode"], "partial")
self.assertFalse(result["details"]["chain_intact"])
self.assertEqual(result["details"]["entries_verified"], 0)
self.assertIn("tampered_entries", result["details"])
finally:
os.unlink(path)
def test_full_chain_still_works(self):
"""A full chain (starting at GENESIS) still works with the existing logic."""
entries = _build_chain(5)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertEqual(result["details"]["mode"], "full")
self.assertTrue(result["details"]["chain_intact"])
finally:
os.unlink(path)
def test_full_chain_broken_still_detected(self):
"""A broken full chain is still detected correctly."""
entries = _build_chain(5)
entries[2]["decision"] = "deny"
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 1)
result = json.loads(out)
self.assertEqual(result["details"]["mode"], "full")
self.assertEqual(result["result"], "broken")
finally:
os.unlink(path)
def test_expected_prev_hash_valid_anchor(self):
"""--expected-prev-hash matches the first entry's prev_hash: anchor_verified=True, exit 0."""
entries = _build_partial_chain(count=3, start_id=50)
known_prev = entries[0]["prev_hash"]
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path, "--expected-prev-hash", known_prev])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertTrue(result["details"]["anchor_verified"])
self.assertEqual(result["result"], "partial_valid")
finally:
os.unlink(path)
def test_expected_prev_hash_wrong_anchor(self):
"""--expected-prev-hash mismatch: anchor_verified=False, exit 1 even if entries are valid."""
entries = _build_partial_chain(count=3, start_id=50)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path, "--expected-prev-hash", "a" * 64])
self.assertEqual(code, 1)
result = json.loads(out)
self.assertFalse(result["details"]["anchor_verified"])
finally:
os.unlink(path)
def test_expected_prev_hash_not_supplied(self):
"""Without --expected-prev-hash, anchor_verified is absent from output."""
entries = _build_partial_chain(count=2, start_id=10)
path = _write_json(entries)
try:
code, out, err = _run_cmd(["--json", "chain", path])
self.assertEqual(code, 0)
result = json.loads(out)
self.assertNotIn("anchor_verified", result["details"])
finally:
os.unlink(path)
# ── Test: Environment variable handling ─────────────────────────────────
class TestEnvVarHandling(unittest.TestCase):
"""Test missing/empty HMAC key behaviour."""
def test_missing_env_var_report(self):
"""Missing AI_IDENTITY_HMAC_KEY exits with code 2 and clear message."""
report = _build_report()
path = _write_json(report)
try:
env = os.environ.copy()
env.pop("AI_IDENTITY_HMAC_KEY", None)
stdout = io.StringIO()
stderr = io.StringIO()
with (
patch.dict(os.environ, env, clear=True),
patch("sys.stdout", stdout),
patch("sys.stderr", stderr),
):
try:
cli.main(["report", path])
except SystemExit as e:
code = e.code
self.assertEqual(code, 2)
self.assertIn("AI_IDENTITY_HMAC_KEY", stderr.getvalue())
finally:
os.unlink(path)
def test_missing_env_var_chain(self):
"""Missing key for chain command also exits with code 2."""
entries = _build_chain(1)
path = _write_json(entries)
try:
env = os.environ.copy()
env.pop("AI_IDENTITY_HMAC_KEY", None)
stderr = io.StringIO()
with (
patch.dict(os.environ, env, clear=True),
patch("sys.stdout", io.StringIO()),
patch("sys.stderr", stderr),
):
try:
cli.main(["chain", path])
except SystemExit as e:
code = e.code
self.assertEqual(code, 2)
self.assertIn("AI_IDENTITY_HMAC_KEY", stderr.getvalue())
finally:
os.unlink(path)
# ── Test: CLI argument parsing ──────────────────────────────────────────
class TestCLIParsing(unittest.TestCase):
"""Test CLI argument parsing edge cases."""
def test_no_command_shows_help(self):
"""No subcommand exits with code 2."""
code, out, err = _run_cmd([])
self.assertEqual(code, 2)