sysknife-daemon 0.2.15

Policy-enforced, audit-logged Linux action daemon for SysKnife
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
//! Forward Ed25519-signed hash chain for the audit log.
//!
//! Each `transactions` row stores `chain_hash` and `prev_chain_hash` columns.
//! On insert, the daemon computes
//!
//! ```text
//! chain_hash = ed25519_sign(ROW_DOMAIN || canonical(immutable_fields) || prev_chain_hash, signing_key)
//! ```
//!
//! The `ROW_DOMAIN` prefix is **part of the signed message**, not decoration:
//! it is what stops a row signature from ever verifying as a checkpoint or
//! approval-receipt signature. An independent verifier that omits it will
//! never reproduce a valid `chain_hash`.
//!
//! and stores both (the signature is hex-encoded; the first row in a chain has
//! `prev_chain_hash = ""`). Ed25519 signatures are deterministic (RFC 8032), so
//! the same content always produces the same `chain_hash`.
//!
//! Verification (`sysknife audit verify`) walks rows in `seq` order and checks
//! each row's signature **with the public key**, reporting the first broken
//! link. Because verification needs only the public key, an auditor or a
//! central log aggregator can verify the chain **without holding the private
//! key** — they cannot forge entries. This is the property a symmetric MAC
//! (the previous HMAC-SHA256 design) could not provide: with an HMAC, the
//! verifier and the forger are the same principal.
//!
//! ## Threat model
//!
//! - **Non-repudiation (asymmetric).** The daemon signs with the private key;
//!   anyone with the exported public key (`<key>.pub`) can verify but not
//!   forge. A compromise of the verifier does not enable forgery.
//! - **Compromised host / root.** An attacker who reads the private key file
//!   can forge *future* entries. Mitigation is to anchor signed checkpoints to
//!   an append-only external sink (see `checkpoint_sink`) so that later
//!   tampering with past entries becomes *detectable* and the tamper window is
//!   bounded to "after compromise".
//! - **Tail truncation** is undetectable by the chain walk alone: an attacker
//!   who deletes the last K rows leaves a still-consistent chain. It is caught
//!   by anchoring signed checkpoints to an independent append-only sink, since
//!   a truncated chain can no longer reproduce a previously anchored
//!   `(seq, chain_tip)` (see `verify_checkpoints` and `checkpoint_sink`). The
//!   best-effort `audit_watermark` journald forward is a lighter complement.
//! - **In-flight modification** between insert and read is mitigated by
//!   computing the signature *before* INSERT and writing it in the same SQL
//!   statement.
//! - **Status mutations are not in the chain.** The mutable `status` field
//!   is intentionally excluded — the chain protects the *authorisation
//!   decision* (immutable fields captured at insert time), not the live
//!   execution state. A future append-only `audit_events` table will
//!   chain status transitions if the threat model demands it.
//!
//! ## Key management
//!
//! The Ed25519 private key (a 32-byte seed) lives in a file. By default the
//! path is `<db_dir>/audit-key` (sibling of the SQLite database, or of
//! whatever directory `sysknife_core::default_database_path` resolves to in
//! production), and the env var `SYSKNIFE_AUDIT_KEY_PATH` overrides it for
//! systemd unit drop-ins (typically `/etc/sysknife/audit-key`). The file is
//! created with mode `0o600` on first daemon start if it does not exist;
//! subsequent runs refuse to start if it is world-readable. The public key is
//! written alongside as `<key>.pub` (hex) for auditors and aggregators.
//!
//! Future epochs (key rotation): each row already carries a `key_id`
//! column. A planned rotation flow appends a checkpoint row signed with the
//! outgoing key whose payload references both public-key fingerprints;
//! verification walks the chain through epoch boundaries by looking up each
//! row's `key_id` in a directory of retired public keys. For now, all rows use
//! `key_id = "v1"` and rotation is manual (delete the chain, regenerate).

use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use sysknife_types::RiskLevel;
use zeroize::Zeroize;

/// Stable identifier for the current key generation. Stored in every row.
/// Tied to the schema, not the key bytes — rotation will introduce `"v2"` etc.
pub const CURRENT_KEY_ID: &str = "v1";

/// Hex-encoded length of an Ed25519 signature (64 raw bytes → 128 hex chars).
pub const HASH_HEX_LEN: usize = 128;

/// Domain-separation tags for Ed25519 signing contexts. They MUST stay distinct
/// and prefix-free so a signature made in one context can never verify in any
/// other. Enforced by the `domain_tags_are_distinct_and_prefix_free` test.
const ROW_DOMAIN: &[u8] = b"sysknife-audit-row-v1\x1f";
const CHECKPOINT_DOMAIN: &[u8] = b"sysknife-checkpoint-v1\x1f";
const APPROVAL_DOMAIN: &[u8] = b"sysknife-approval-receipt-v1\x1f";
const EVENT_DOMAIN: &[u8] = b"sysknife-audit-event-v1\x1f";

/// Row encoding written before the caller-identity migration: no
/// `caller_role`, no `event_tip`. Still verifiable — see [`ChainIdentity`].
pub const CHAIN_VERSION_LEGACY: u32 = 1;
/// Row encoding written by this binary: adds `caller_role` and `event_tip`.
pub const CHAIN_VERSION_CURRENT: u32 = 2;

/// Loaded Ed25519 signing key + its identifier. Construct via
/// [`AuditKey::load_or_generate`].
///
/// `Clone` is intentional: the audit-verify CLI needs to load the key once
/// and share it between the SQLite read-only path and the Postgres pool.
///
/// `Debug` is implemented manually to redact the signing key. A derived
/// `Debug` would dump the private key via any `tracing::debug!("{key:?}")`
/// or `dbg!(key)` site, which would leak the audit secret into journald.
/// We keep `key_id` visible because operators need to identify which key
/// generation a record belongs to when triaging chain breaks.
#[derive(Clone)]
pub struct AuditKey {
    key_id: String,
    signing: SigningKey,
}

impl std::fmt::Debug for AuditKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never render the private key. A derived `Debug` (or printing the
        // signing key) would leak the audit secret into journald via any
        // `tracing::debug!("{key:?}")`. `key_id` is not secret and is kept
        // visible for triaging chain breaks.
        f.debug_struct("AuditKey")
            .field("key_id", &self.key_id)
            .field("signing", &format_args!("<redacted signing key>"))
            .finish()
    }
}

// The `SigningKey` zeroizes its secret scalar on drop (ed25519-dalek `zeroize`
// feature), so no manual `Drop` is needed to keep the private key out of
// post-free memory.

#[derive(Debug, thiserror::Error)]
pub enum AuditKeyError {
    #[error("io error reading audit key {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error(
        "audit key file {path} has unsafe permissions {mode:#o}; \
         tighten with `chmod 600 {path:?}` and restart"
    )]
    UnsafePermissions { path: PathBuf, mode: u32 },
    #[error(
        "audit key file {path} is too short ({len} bytes); \
         expected at least 32 bytes of random material"
    )]
    KeyTooShort { path: PathBuf, len: usize },
}

impl AuditKey {
    /// Load the audit key from `path`. If the file does not exist, generate a
    /// 32-byte cryptographically random key and write it with mode `0o600`.
    ///
    /// On every load (including freshly generated), the file's permissions
    /// are checked: any bit beyond `0o600` for owner-only access is rejected
    /// — a world-readable audit key is a self-defeating audit chain.
    pub fn load_or_generate(path: &Path) -> Result<Self, AuditKeyError> {
        if !path.exists() {
            generate_key_at(path)?;
        }

        let metadata = std::fs::metadata(path).map_err(|e| AuditKeyError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;

        use std::os::unix::fs::PermissionsExt;
        let mode = metadata.permissions().mode() & 0o777;
        if mode & 0o077 != 0 {
            // Group or world bits set — reject.
            return Err(AuditKeyError::UnsafePermissions {
                path: path.to_path_buf(),
                mode,
            });
        }

        let mut key_bytes = std::fs::read(path).map_err(|e| AuditKeyError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
        if key_bytes.len() < 32 {
            return Err(AuditKeyError::KeyTooShort {
                path: path.to_path_buf(),
                len: key_bytes.len(),
            });
        }

        let mut seed = [0u8; 32];
        seed.copy_from_slice(&key_bytes[..32]);
        let signing = SigningKey::from_bytes(&seed);
        seed.zeroize();
        key_bytes.zeroize();

        Ok(Self {
            key_id: CURRENT_KEY_ID.to_string(),
            signing,
        })
    }

    /// Construct a key from a 32-byte seed. For tests only — production builds
    /// always go through [`Self::load_or_generate`] for the permission check.
    #[cfg(test)]
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        let mut seed = [0u8; 32];
        seed.copy_from_slice(&bytes[..32]);
        let signing = SigningKey::from_bytes(&seed);
        seed.zeroize();
        Self {
            key_id: CURRENT_KEY_ID.to_string(),
            signing,
        }
    }

    /// Stable identifier for this key generation.
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Compute the chain signature for `content` linked to `prev_chain_hash`.
    ///
    /// Hex-encoded Ed25519 signature over `canonical(content) || prev_chain_hash`.
    /// Deterministic (RFC 8032): identical inputs always yield the same value.
    pub fn chain_hash(&self, content: &ChainContent, prev_chain_hash: &str) -> String {
        let sig = self.signing.sign(&chain_message(content, prev_chain_hash));
        hex::encode(sig.to_bytes())
    }

    /// The public verifying key for this audit key.
    pub fn verifying_key(&self) -> VerifyingKey {
        self.signing.verifying_key()
    }

    /// Hex-encoded 32-byte Ed25519 public key. Safe to publish; auditors use it
    /// to verify the chain without the ability to forge entries.
    pub fn verifying_key_hex(&self) -> String {
        hex::encode(self.signing.verifying_key().to_bytes())
    }

    /// Derive the bearer receipt for one immutable preview. The signature is
    /// deterministic, so a failed response delivery can be retried without
    /// storing plaintext bearer credentials in the database.
    pub fn approval_receipt(&self, transaction_id: &str, request_hash: &str) -> String {
        // Frame both fields through `push_field` (the same escaping used for
        // chain rows) so the signed message is injective in
        // (transaction_id, request_hash). Raw concatenation with a bare 0x1F
        // would alias distinct inputs if either field ever contained 0x1F;
        // escaping removes that dependency on the callers' value shapes.
        let mut message = APPROVAL_DOMAIN.to_vec();
        push_field(&mut message, "txid", transaction_id);
        push_field(&mut message, "reqhash", request_hash);
        hex::encode(self.signing.sign(&message).to_bytes())
    }

    /// Chain-stored SHA-256 commitment to the deterministic approval receipt.
    pub fn approval_commitment(&self, transaction_id: &str, request_hash: &str) -> String {
        approval_receipt_digest(&self.approval_receipt(transaction_id, request_hash))
    }
}

pub fn approval_receipt_digest(receipt: &str) -> String {
    hex::encode(Sha256::digest(receipt.as_bytes()))
}

/// Message signed for a row: `ROW_DOMAIN || canonical(content) || prev_chain_hash`.
///
/// The leading domain tag separates row signatures from checkpoint signatures
/// so a signature produced in one context can never verify in the other, even
/// if the framed fields were ever to overlap.
fn chain_message(content: &ChainContent, prev_chain_hash: &str) -> Vec<u8> {
    let mut msg = ROW_DOMAIN.to_vec();
    msg.extend_from_slice(&content.canonical_bytes());
    msg.extend_from_slice(prev_chain_hash.as_bytes());
    msg
}

/// Resolve the audit key file path: `$SYSKNIFE_AUDIT_KEY_PATH` if set,
/// otherwise `<db_dir>/audit-key` (sibling of the database). This is the single
/// definition of the key-location precedence documented in the module header;
/// the CLI verify/checkpoint paths resolve through it so they always agree with
/// the daemon on where the key lives.
pub fn resolve_audit_key_path(db_path: &Path) -> PathBuf {
    std::env::var("SYSKNIFE_AUDIT_KEY_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            db_path
                .parent()
                .unwrap_or_else(|| Path::new("."))
                .join("audit-key")
        })
}

/// Generate a 32-byte random key and write it to `path` with mode `0o600`.
/// Parent directory is created with mode `0o700` if missing.
fn generate_key_at(path: &Path) -> Result<(), AuditKeyError> {
    use std::io::Write as _;
    use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};

    if let Some(parent) = path.parent() {
        if !parent.exists() {
            std::fs::DirBuilder::new()
                .recursive(true)
                .mode(0o700)
                .create(parent)
                .map_err(|e| AuditKeyError::Io {
                    path: parent.to_path_buf(),
                    source: e,
                })?;
        }
    }

    let mut bytes = [0u8; 32];
    fill_random(&mut bytes).map_err(|e| AuditKeyError::Io {
        path: path.to_path_buf(),
        source: e,
    })?;

    let mut f = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .map_err(|e| AuditKeyError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
    f.write_all(&bytes).map_err(|e| AuditKeyError::Io {
        path: path.to_path_buf(),
        source: e,
    })?;
    f.sync_all().map_err(|e| AuditKeyError::Io {
        path: path.to_path_buf(),
        source: e,
    })?;

    // Write the public key alongside as `<key>.pub` (hex). Not secret: it lets
    // an auditor or aggregator verify the chain without the private key.
    let signing = SigningKey::from_bytes(&bytes);
    let pub_hex = hex::encode(signing.verifying_key().to_bytes());
    bytes.zeroize();
    let mut pub_path = path.as_os_str().to_os_string();
    pub_path.push(".pub");
    std::fs::write(&pub_path, format!("{pub_hex}\n")).map_err(|e| AuditKeyError::Io {
        path: PathBuf::from(pub_path),
        source: e,
    })?;
    Ok(())
}

/// Fill `buf` with bytes from the kernel CSPRNG via `/dev/urandom`.
fn fill_random(buf: &mut [u8]) -> std::io::Result<()> {
    use std::io::Read as _;
    let mut f = std::fs::File::open("/dev/urandom")?;
    f.read_exact(buf)
}

/// Immutable fields hashed into the chain. Status is intentionally absent —
/// see module docs.
///
/// # Security contract — chain-content immutability
///
/// Every field in this struct is captured **once** at INSERT time and baked
/// into `chain_hash = ed25519_sign(canonical(self) || prev_chain_hash, key)`.
/// After the row is written the hash is a one-time commitment: **no field
/// in this struct may ever be mutated in place**.
///
/// `summary` is the field most likely to attract a future "let me just fix
/// that typo" API. **Do not add an `update_summary` (or similar) function.**
/// If a correction is genuinely needed, choose one of the two safe options:
///
/// 1. **Insert a corrective row** — a new transaction row that references the
///    original `transaction_id` in its own `summary`, leaving the original
///    row and its chain hash untouched.
/// 2. **Extend the chain protocol** — introduce a dedicated amendment record
///    type with its own chain link, so that both the original commitment and
///    the correction are auditable.
///
/// Any other approach silently breaks chain integrity: `verify_chain` will
/// flag the modified row as `Broken` because the stored signature will no
/// longer verify against the row's content.
///
/// The canonical serialisation is stable across SQLite/Postgres backends.
/// Each field is emitted as
///
/// ```text
///     <tag-name> 0x1E <tag-value> 0x1F
/// ```
///
/// where `0x1E` is the *tag/value* separator within a single field and `0x1F`
/// is the *field* separator that terminates the field and introduces the
/// next one. We use the ASCII C0 byte values RS (0x1E) and US (0x1F)
/// because they are guaranteed not to appear in any normal text field, but
/// **our role assignment is the inverse of the ASCII C0 convention**
/// (where RS = "record separator" and US = "unit separator"). The names
/// are kept in the source for byte-level traceability against the canonical
/// buffer, not as a claim about ASCII semantics.
///
/// Inside a value, the four
/// bytes `\\`, NUL, `RS`, `US` are escaped to `\\\\`, `\\0`, `\\1E`, `\\1F`
/// respectively. The escape table is **prefix-free** (every escape starts
/// with `\\`), so any value can be injected without ambiguity. See
/// `push_field` for the implementation and tests for the round-trip.
/// Which generation of the canonical row encoding a row was signed under.
///
/// # Why this is an enum and not two `Option` fields
///
/// Adding a field to [`ChainContent`] changes the signed message, so every row
/// written before the change would re-encode differently and report as
/// `Broken`. Chains already exist in the field, and "delete your audit log to
/// upgrade" is not an acceptable migration for an audit log. The stored
/// `chain_version` column therefore selects the encoding **per row**: legacy
/// rows keep the exact bytes they were signed over, new rows carry the
/// identity fields.
///
/// A downgrade is not a hiding place. Rewriting a `V2` row as `LegacyV1` (to
/// erase `caller_role`) makes verification re-encode it without the identity
/// fields, so the stored signature — made over the `V2` message — no longer
/// verifies and the row reports as `Broken`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainIdentity<'a> {
    /// `chain_version = 1`. Written before the identity migration.
    LegacyV1,
    /// `chain_version = 2`. Binds the row to the authenticated caller and to
    /// the approval-event chain tip at insert time.
    V2 {
        /// Role the daemon resolved for the connection that requested this
        /// action (`SO_PEERCRED` for Unix sockets, token for vsock). Signing
        /// it is what lets an auditor answer "who asked for this".
        caller_role: &'a str,
        /// `chain_hash` of the last [`EventRow`] at insert time, or `""` when
        /// the event chain is empty. This is the cross-chain binding: because
        /// checkpoints anchor the *transaction* chain tip, a committed
        /// `event_tip` transitively anchors the event chain, so deleting
        /// approval events below it becomes detectable.
        event_tip: &'a str,
    },
}

impl ChainIdentity<'_> {
    /// `chain_version` column value for this encoding.
    pub fn version(&self) -> u32 {
        match self {
            Self::LegacyV1 => CHAIN_VERSION_LEGACY,
            Self::V2 { .. } => CHAIN_VERSION_CURRENT,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChainContent<'a> {
    pub seq: u64,
    pub key_id: &'a str,
    pub transaction_id: &'a str,
    pub request_id: &'a str,
    pub request_hash: &'a str,
    pub action_name: &'a str,
    pub risk_level: RiskLevel,
    /// Human-readable description of the planned action.
    ///
    /// **Immutable after insert.** This field is included in the chain hash
    /// (see [`ChainContent`] struct-level doc). It MUST NOT be updated after
    /// the row is written — doing so silently invalidates `chain_hash` and
    /// will be detected as `VerifyOutcome::Broken` by `sysknife audit verify`.
    /// See the struct-level security contract for the only safe correction
    /// strategies.
    pub summary: &'a str,
    /// Signed receipt commitment for daemon-created previews. Legacy/imported
    /// rows may be `None`; serialised as empty for wire compatibility.
    pub approval_id: Option<&'a str>,
    /// JSON-canonical (sorted keys) array of warning strings.
    pub warnings_json: &'a str,
    pub created_at: &'a str,
    /// Encoding generation. See [`ChainIdentity`] for why this is per-row.
    pub identity: ChainIdentity<'a>,
}

impl<'a> ChainContent<'a> {
    /// Stable canonical encoding of every field. Within each field the
    /// `0x1E` byte separates tag from value, and `0x1F` terminates the field;
    /// raw NUL becomes the two-byte escape `\0`.
    pub fn canonical_bytes(&self) -> Vec<u8> {
        let risk_level_str = match self.risk_level {
            RiskLevel::Low => "low",
            RiskLevel::Medium => "medium",
            RiskLevel::High => "high",
        };
        let approval = self.approval_id.unwrap_or("");

        let mut buf = Vec::with_capacity(512);
        // Each field is `tag 0x1E value 0x1F`; tags make the canonical form
        // self-describing for forensics.
        push_field(&mut buf, "seq", &self.seq.to_string());
        push_field(&mut buf, "key_id", self.key_id);
        push_field(&mut buf, "transaction_id", self.transaction_id);
        push_field(&mut buf, "request_id", self.request_id);
        push_field(&mut buf, "request_hash", self.request_hash);
        push_field(&mut buf, "action_name", self.action_name);
        push_field(&mut buf, "risk_level", risk_level_str);
        push_field(&mut buf, "summary", self.summary);
        push_field(&mut buf, "approval_id", approval);
        push_field(&mut buf, "warnings_json", self.warnings_json);
        push_field(&mut buf, "created_at", self.created_at);
        // v2 fields are *appended*, so a legacy row's bytes are unchanged and
        // its signature still verifies. The `chain_version` tag leads the
        // suffix so a future v3 can never alias a v2 message: the two differ
        // in a signed field, not merely in field count.
        if let ChainIdentity::V2 {
            caller_role,
            event_tip,
        } = self.identity
        {
            push_field(
                &mut buf,
                "chain_version",
                &CHAIN_VERSION_CURRENT.to_string(),
            );
            push_field(&mut buf, "caller_role", caller_role);
            push_field(&mut buf, "event_tip", event_tip);
        }
        buf
    }
}

/// Append `tag<RS>value<US>` to `buf`, escaping any byte that could otherwise
/// alias one of the framing characters or another escape sequence.
///
/// The escape table is **prefix-free**: every escape starts with `\` (0x5C)
/// followed by a tag that cannot itself be the start of a different escape.
/// Concretely:
///
/// | Raw byte | Escape       |
/// |---------:|--------------|
/// | `\\`     | `\\\\`       |
/// | `\x00`   | `\\0`        |
/// | `\x1E`   | `\\1E`       |
/// | `\x1F`   | `\\1F`       |
///
/// The `\\` escape MUST come first: without it, a field value containing the
/// literal two-byte sequence `\` + `0` would canonicalise to the same bytes
/// as a raw NUL and produce a chain-signature collision.
fn push_field(buf: &mut Vec<u8>, tag: &str, value: &str) {
    buf.extend_from_slice(tag.as_bytes());
    buf.push(0x1E); // tag/value separator (ASCII RS byte, but used inversely — see ChainContent doc)
    for b in value.bytes() {
        match b {
            b'\\' => buf.extend_from_slice(b"\\\\"),
            0x00 => buf.extend_from_slice(b"\\0"),
            0x1E => buf.extend_from_slice(b"\\1E"),
            0x1F => buf.extend_from_slice(b"\\1F"),
            other => buf.push(other),
        }
    }
    buf.push(0x1F); // field terminator (ASCII US byte, but used inversely — see ChainContent doc)
}

/// Result of `verify_chain`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyOutcome {
    /// Chain is intact across all rows checked.
    Intact { rows_checked: u64 },
    /// One or more rows fail to chain. First broken row is reported.
    Broken {
        rows_checked: u64,
        first_broken_seq: u64,
        first_broken_transaction_id: String,
        expected: String,
        actual: String,
    },
    /// Verification could not be completed (missing key, unreachable storage,
    /// retired key not on disk, etc.). Distinct from `Broken` — callers map
    /// this to exit code 2.
    CannotVerify { reason: String },
}

/// Process exit code for `sysknife audit verify`.
///
/// `0` intact, `1` broken, `2` cannot-verify. The split between 1 and 2
/// matters: a CI pipeline expecting 0 or 1 must not silently pass on a
/// missing key file.
pub fn outcome_to_exit_code(outcome: &VerifyOutcome) -> i32 {
    match outcome {
        VerifyOutcome::Intact { .. } => 0,
        VerifyOutcome::Broken { .. } => 1,
        VerifyOutcome::CannotVerify { .. } => 2,
    }
}

/// One row's worth of chain data, as fetched from the store.
#[derive(Debug, Clone)]
pub struct ChainRow {
    pub seq: u64,
    pub key_id: String,
    pub transaction_id: String,
    pub request_id: String,
    pub request_hash: String,
    pub action_name: String,
    pub risk_level: RiskLevel,
    pub summary: String,
    pub approval_id: Option<String>,
    pub warnings_json: String,
    pub created_at: String,
    pub prev_chain_hash: String,
    pub chain_hash: String,
    /// Which encoding this row was signed under. See [`ChainIdentity`].
    pub chain_version: u32,
    /// `NULL` for legacy rows; required for `chain_version = 2`.
    pub caller_role: Option<String>,
    /// `NULL` for legacy rows; required for `chain_version = 2`. May be the
    /// empty string when the event chain was empty at insert time.
    pub event_tip: Option<String>,
}

/// Why a stored row's columns do not describe a verifiable encoding.
#[derive(Debug)]
pub(crate) enum RowIdentityError {
    /// The row claims an encoding this binary does not know how to reproduce.
    /// Genuinely unverifiable, not evidence of tampering — an older binary
    /// reading a newer chain lands here.
    UnknownVersion(u32),
    /// The row claims `chain_version = 2` but is missing an identity column.
    /// No message can be reconstructed, and the shape is self-contradictory,
    /// so this counts as a detected break rather than an inability to check.
    MissingField(&'static str),
}

impl ChainRow {
    /// Recover the encoding this row was signed under, so a caller can rebuild
    /// the exact message that produced `chain_hash`.
    pub(crate) fn identity(&self) -> Result<ChainIdentity<'_>, RowIdentityError> {
        match self.chain_version {
            CHAIN_VERSION_LEGACY => Ok(ChainIdentity::LegacyV1),
            CHAIN_VERSION_CURRENT => Ok(ChainIdentity::V2 {
                caller_role: self
                    .caller_role
                    .as_deref()
                    .ok_or(RowIdentityError::MissingField("caller_role"))?,
                event_tip: self
                    .event_tip
                    .as_deref()
                    .ok_or(RowIdentityError::MissingField("event_tip"))?,
            }),
            other => Err(RowIdentityError::UnknownVersion(other)),
        }
    }
}

/// Verify a chain using the daemon's key. Verification uses the **public** key
/// (so it proves, but cannot forge) and also asserts every row was written
/// under this key generation (`key_id`).
pub fn verify_chain(key: &AuditKey, rows: &[ChainRow]) -> VerifyOutcome {
    verify_rows(&key.verifying_key(), Some(key.key_id()), rows)
}

/// Verify a chain with only the hex-encoded Ed25519 **public** key. This is the
/// auditor / aggregator path: it proves the chain without the private key and
/// cannot be used to forge entries. `key_id` is not checked — the public key
/// itself identifies the signer.
pub fn verify_chain_with_pubkey(verifying_key_hex: &str, rows: &[ChainRow]) -> VerifyOutcome {
    match parse_verifying_key(verifying_key_hex) {
        Some(vk) => verify_rows(&vk, None, rows),
        None => VerifyOutcome::CannotVerify {
            reason: format!(
                "invalid public key hex ({} chars); expected 64 hex chars of a \
                 32-byte Ed25519 public key",
                verifying_key_hex.len()
            ),
        },
    }
}

fn parse_verifying_key(hex_str: &str) -> Option<VerifyingKey> {
    let bytes = hex::decode(hex_str.trim()).ok()?;
    let arr: [u8; 32] = bytes.try_into().ok()?;
    VerifyingKey::from_bytes(&arr).ok()
}

/// Verify a stored hex signature over a row's message. Any malformed signature
/// (bad hex, wrong length, invalid point) is a failed check, never a panic.
fn signature_ok(vk: &VerifyingKey, msg: &[u8], sig_hex: &str) -> bool {
    let Ok(bytes) = hex::decode(sig_hex) else {
        return false;
    };
    let Ok(arr): Result<[u8; 64], _> = bytes.try_into() else {
        return false;
    };
    vk.verify_strict(msg, &Signature::from_bytes(&arr)).is_ok()
}

/// Walk `rows` in seq order, verifying each row's signature with `vk` and its
/// `prev_chain_hash` linkage. Returns the first break (or `Intact`). When
/// `expect_key_id` is `Some`, every row must carry that `key_id`.
fn verify_rows(vk: &VerifyingKey, expect_key_id: Option<&str>, rows: &[ChainRow]) -> VerifyOutcome {
    let mut last_hash = String::new();
    let mut rows_checked = 0u64;
    for row in rows {
        if let Some(kid) = expect_key_id {
            if row.key_id != kid {
                return VerifyOutcome::CannotVerify {
                    reason: format!(
                        "row seq={} uses key_id={:?} but only {:?} is loaded; \
                         epoch keys not yet supported",
                        row.seq, row.key_id, kid
                    ),
                };
            }
        }
        if row.prev_chain_hash != last_hash {
            return VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq: row.seq,
                first_broken_transaction_id: row.transaction_id.clone(),
                expected: format!("prev_chain_hash={last_hash}"),
                actual: format!("prev_chain_hash={}", row.prev_chain_hash),
            };
        }
        let identity = match row.identity() {
            Ok(identity) => identity,
            Err(RowIdentityError::UnknownVersion(v)) => {
                return VerifyOutcome::CannotVerify {
                    reason: format!(
                        "row seq={} declares chain_version={v}, which this binary cannot \
                         reproduce (it understands {CHAIN_VERSION_LEGACY}..={CHAIN_VERSION_CURRENT}); \
                         verify with a build at least as new as the one that wrote the chain",
                        row.seq
                    ),
                };
            }
            Err(RowIdentityError::MissingField(field)) => {
                return VerifyOutcome::Broken {
                    rows_checked,
                    first_broken_seq: row.seq,
                    first_broken_transaction_id: row.transaction_id.clone(),
                    expected: format!("chain_version={CHAIN_VERSION_CURRENT} row carrying {field}"),
                    actual: format!("{field}=NULL"),
                };
            }
        };
        let content = ChainContent {
            seq: row.seq,
            key_id: &row.key_id,
            transaction_id: &row.transaction_id,
            request_id: &row.request_id,
            request_hash: &row.request_hash,
            action_name: &row.action_name,
            risk_level: row.risk_level,
            summary: &row.summary,
            approval_id: row.approval_id.as_deref(),
            warnings_json: &row.warnings_json,
            created_at: &row.created_at,
            identity,
        };
        let msg = chain_message(&content, &row.prev_chain_hash);
        if !signature_ok(vk, &msg, &row.chain_hash) {
            return VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq: row.seq,
                first_broken_transaction_id: row.transaction_id.clone(),
                expected: "valid ed25519 signature".to_string(),
                actual: row.chain_hash.clone(),
            };
        }
        last_hash = row.chain_hash.clone();
        rows_checked += 1;
    }
    VerifyOutcome::Intact { rows_checked }
}

// ── Approval-event chain ─────────────────────────────────────────────────────

/// A lifecycle event on an approval receipt.
///
/// The `transactions` chain commits to the *authorisation decision* at preview
/// time. It says nothing about whether a human ever approved, whether that
/// approval was spent, or whether it was retracted — those live in
/// `transaction_approvals`, a plain mutable table. Deleting a row from it used
/// to leave `sysknife audit verify` reporting `Intact`, so the record that an
/// approval happened was the one part of the trail an attacker could erase
/// without leaving a mark. These events are chained so that erasure breaks a
/// signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditEventKind {
    /// A receipt was minted for a queued transaction.
    ApprovalGranted,
    /// A receipt was spent to move a transaction into `Running`.
    ApprovalConsumed,
    /// An undelivered receipt was retracted before it could be spent.
    ApprovalRevoked,
}

impl AuditEventKind {
    /// Stored and signed spelling. Stable on the wire — changing one of these
    /// strings invalidates every event signature already written.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::ApprovalGranted => "approval_granted",
            Self::ApprovalConsumed => "approval_consumed",
            Self::ApprovalRevoked => "approval_revoked",
        }
    }
}

/// Immutable content of one approval event, signed into the event chain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventContent<'a> {
    pub seq: u64,
    pub key_id: &'a str,
    pub kind: AuditEventKind,
    pub transaction_id: &'a str,
    /// The receipt digest the event concerns. Binds the event to the specific
    /// receipt, so swapping in a different approval's digest breaks the
    /// signature.
    pub receipt_digest: &'a str,
    pub created_at: &'a str,
}

impl EventContent<'_> {
    /// Canonical encoding, using the same prefix-free field framing as
    /// [`ChainContent::canonical_bytes`].
    pub fn canonical_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(256);
        push_field(&mut buf, "seq", &self.seq.to_string());
        push_field(&mut buf, "key_id", self.key_id);
        push_field(&mut buf, "kind", self.kind.as_str());
        push_field(&mut buf, "transaction_id", self.transaction_id);
        push_field(&mut buf, "receipt_digest", self.receipt_digest);
        push_field(&mut buf, "created_at", self.created_at);
        buf
    }
}

fn event_message(content: &EventContent, prev_chain_hash: &str) -> Vec<u8> {
    let mut msg = EVENT_DOMAIN.to_vec();
    msg.extend_from_slice(&content.canonical_bytes());
    msg.extend_from_slice(prev_chain_hash.as_bytes());
    msg
}

impl AuditKey {
    /// Compute the event-chain signature for `content` linked to
    /// `prev_chain_hash`. Separate domain tag from rows and checkpoints, so an
    /// event signature can never be replayed as a transaction row.
    pub fn event_hash(&self, content: &EventContent, prev_chain_hash: &str) -> String {
        hex::encode(
            self.signing
                .sign(&event_message(content, prev_chain_hash))
                .to_bytes(),
        )
    }
}

/// One approval event as fetched from the store.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventRow {
    pub seq: u64,
    pub key_id: String,
    /// Stored spelling of an [`AuditEventKind`]. Kept as a string so an
    /// unrecognised value read from the database is a verification failure
    /// rather than a deserialisation panic.
    pub kind: String,
    pub transaction_id: String,
    pub receipt_digest: String,
    pub created_at: String,
    pub prev_chain_hash: String,
    pub chain_hash: String,
}

/// Verify the approval-event chain with the daemon's key.
pub fn verify_event_chain(key: &AuditKey, rows: &[EventRow]) -> VerifyOutcome {
    verify_event_rows(&key.verifying_key(), Some(key.key_id()), rows)
}

/// Verify the approval-event chain with only the exported public key.
pub fn verify_event_chain_with_pubkey(verifying_key_hex: &str, rows: &[EventRow]) -> VerifyOutcome {
    match parse_verifying_key(verifying_key_hex) {
        Some(vk) => verify_event_rows(&vk, None, rows),
        None => VerifyOutcome::CannotVerify {
            reason: format!(
                "invalid public key hex ({} chars); expected 64 hex chars of a \
                 32-byte Ed25519 public key",
                verifying_key_hex.len()
            ),
        },
    }
}

fn verify_event_rows(
    vk: &VerifyingKey,
    expect_key_id: Option<&str>,
    rows: &[EventRow],
) -> VerifyOutcome {
    let mut last_hash = String::new();
    let mut rows_checked = 0u64;
    for row in rows {
        if let Some(kid) = expect_key_id {
            if row.key_id != kid {
                return VerifyOutcome::CannotVerify {
                    reason: format!(
                        "event seq={} uses key_id={:?} but only {:?} is loaded; \
                         epoch keys not yet supported",
                        row.seq, row.key_id, kid
                    ),
                };
            }
        }
        if row.prev_chain_hash != last_hash {
            return VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq: row.seq,
                first_broken_transaction_id: row.transaction_id.clone(),
                expected: format!("prev_chain_hash={last_hash}"),
                actual: format!("prev_chain_hash={}", row.prev_chain_hash),
            };
        }
        // An unknown `kind` cannot be re-encoded, so it can never reproduce a
        // valid signature. Report it as the break it is instead of guessing.
        let Some(kind) = parse_event_kind(&row.kind) else {
            return VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq: row.seq,
                first_broken_transaction_id: row.transaction_id.clone(),
                expected: "a known event kind".to_string(),
                actual: format!("kind={:?}", row.kind),
            };
        };
        let content = EventContent {
            seq: row.seq,
            key_id: &row.key_id,
            kind,
            transaction_id: &row.transaction_id,
            receipt_digest: &row.receipt_digest,
            created_at: &row.created_at,
        };
        if !signature_ok(
            vk,
            &event_message(&content, &row.prev_chain_hash),
            &row.chain_hash,
        ) {
            return VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq: row.seq,
                first_broken_transaction_id: row.transaction_id.clone(),
                expected: "valid ed25519 signature".to_string(),
                actual: row.chain_hash.clone(),
            };
        }
        last_hash = row.chain_hash.clone();
        rows_checked += 1;
    }
    VerifyOutcome::Intact { rows_checked }
}

fn parse_event_kind(raw: &str) -> Option<AuditEventKind> {
    // Exhaustive by construction: the match below fails to compile if a
    // variant is added without a spelling here.
    [
        AuditEventKind::ApprovalGranted,
        AuditEventKind::ApprovalConsumed,
        AuditEventKind::ApprovalRevoked,
    ]
    .into_iter()
    .find(|kind| kind.as_str() == raw)
}

/// Result of checking that the transaction chain's committed `event_tip`
/// values are still reproducible from the event chain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingOutcome {
    /// Every committed tip is present in the event chain.
    Consistent { bindings_checked: u64 },
    /// A transaction row committed to an event tip that no longer exists —
    /// approval events were deleted from the end of the event chain, which the
    /// event chain walk alone cannot see.
    MissingEvent {
        transaction_seq: u64,
        event_tip: String,
    },
}

/// Check the cross-chain binding: each `chain_version = 2` transaction row
/// signs the event-chain tip as of its insert, so a later deletion of trailing
/// approval events leaves a tip that can no longer be found.
///
/// This is what extends checkpoint anchoring to the event chain for free: the
/// checkpoints commit to the transaction tip, the transaction rows commit to
/// event tips. Events appended *after* the last transaction row are still
/// unanchored until the next row is written — the same bounded tail exposure
/// the transaction chain has between checkpoints.
pub fn verify_event_binding(tx_rows: &[ChainRow], event_rows: &[EventRow]) -> BindingOutcome {
    let known: std::collections::HashSet<&str> = event_rows
        .iter()
        .map(|row| row.chain_hash.as_str())
        .collect();
    let mut bindings_checked = 0u64;
    for row in tx_rows {
        let Some(tip) = row.event_tip.as_deref() else {
            continue;
        };
        if tip.is_empty() {
            continue;
        }
        if !known.contains(tip) {
            return BindingOutcome::MissingEvent {
                transaction_seq: row.seq,
                event_tip: tip.to_string(),
            };
        }
        bindings_checked += 1;
    }
    BindingOutcome::Consistent { bindings_checked }
}

/// Everything `sysknife audit verify` checks, in one value.
///
/// Three independent questions, deliberately not collapsed into one enum:
/// is the authorisation record intact, is the approval record intact, and do
/// the two still agree. Collapsing them would let a clean transaction chain
/// mask a tampered approval trail in the summary line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuditVerification {
    pub chain: VerifyOutcome,
    pub events: VerifyOutcome,
    pub binding: BindingOutcome,
}

impl AuditVerification {
    /// Worst result across all three checks.
    ///
    /// A detected tamper (`1`) outranks an inability to check (`2`): if the
    /// chain is provably broken, reporting "could not verify" because some
    /// *other* check was inconclusive would understate what is known.
    pub fn exit_code(&self) -> i32 {
        let codes = [
            outcome_to_exit_code(&self.chain),
            outcome_to_exit_code(&self.events),
            binding_outcome_to_exit_code(&self.binding),
        ];
        if codes.contains(&1) {
            1
        } else if codes.contains(&2) {
            2
        } else {
            0
        }
    }
}

/// Run all three checks with the daemon's key.
pub fn verify_all(
    key: &AuditKey,
    tx_rows: &[ChainRow],
    event_rows: &[EventRow],
) -> AuditVerification {
    AuditVerification {
        chain: verify_chain(key, tx_rows),
        events: verify_event_chain(key, event_rows),
        binding: verify_event_binding(tx_rows, event_rows),
    }
}

/// Run all three checks with only the exported public key (the auditor path).
pub fn verify_all_with_pubkey(
    verifying_key_hex: &str,
    tx_rows: &[ChainRow],
    event_rows: &[EventRow],
) -> AuditVerification {
    AuditVerification {
        chain: verify_chain_with_pubkey(verifying_key_hex, tx_rows),
        events: verify_event_chain_with_pubkey(verifying_key_hex, event_rows),
        binding: verify_event_binding(tx_rows, event_rows),
    }
}

/// Exit code for the binding check, on the same scale as
/// [`outcome_to_exit_code`]: a missing event is a detected tamper (`1`).
pub fn binding_outcome_to_exit_code(outcome: &BindingOutcome) -> i32 {
    match outcome {
        BindingOutcome::Consistent { .. } => 0,
        BindingOutcome::MissingEvent { .. } => 1,
    }
}

// ── Signed checkpoints (external anchoring / tail-truncation detection) ──────

/// A signed commitment to the chain tip at a point in time. Periodically
/// emitted and anchored to an independent, append-only sink (a separate
/// database, a WORM store, or an RFC 3161 timestamp) so that a later attempt to
/// rewrite or **truncate** the local chain is detectable: the anchored
/// `(seq, chain_tip)` can no longer be reproduced from the shortened chain.
///
/// This is the Certificate-Transparency "signed checkpoint" idiom. The
/// signature is Ed25519 over the canonical `(seq, chain_tip, created_at)`, so
/// an auditor verifies it with only the public key.
///
/// A `Checkpoint` value carries no validity guarantee on its own: validity is
/// established solely by [`verify_checkpoints`] under the public key. A
/// checkpoint loaded from a sink is untrusted input until verified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checkpoint {
    /// `seq` of the chain tip this checkpoint commits to (the last row at
    /// emit time).
    pub seq: u64,
    /// `chain_hash` of the row at `seq` (the committed chain tip).
    pub chain_tip: String,
    /// RFC 3339 timestamp when the checkpoint was signed.
    pub created_at: String,
    /// Hex Ed25519 signature over `canonical(seq, chain_tip, created_at)`.
    pub signature: String,
}

/// Canonical message signed into a checkpoint. Reuses the prefix-free field
/// framing so the encoding is unambiguous and stable across backends.
fn checkpoint_message(seq: u64, chain_tip: &str, created_at: &str) -> Vec<u8> {
    // Leading domain tag: separates checkpoint signatures from row signatures
    // (see `chain_message`) so the two contexts can never cross-verify.
    let mut buf = CHECKPOINT_DOMAIN.to_vec();
    push_field(&mut buf, "seq", &seq.to_string());
    push_field(&mut buf, "chain_tip", chain_tip);
    push_field(&mut buf, "created_at", created_at);
    buf
}

impl AuditKey {
    /// Sign a checkpoint committing to `(seq, chain_tip)` at `created_at`.
    pub fn sign_checkpoint(&self, seq: u64, chain_tip: &str, created_at: &str) -> Checkpoint {
        let sig = self
            .signing
            .sign(&checkpoint_message(seq, chain_tip, created_at));
        Checkpoint {
            seq,
            chain_tip: chain_tip.to_string(),
            created_at: created_at.to_string(),
            signature: hex::encode(sig.to_bytes()),
        }
    }
}

/// Result of checking anchored checkpoints against the current chain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckpointOutcome {
    /// Every checkpoint's signature is valid and its committed tip is still
    /// present in the chain at the committed `seq`.
    Consistent { checkpoints_checked: u64 },
    /// A checkpoint signature failed to verify under the public key.
    BadSignature { seq: u64 },
    /// A checkpoint commits to a `seq` no longer present in the chain — the
    /// chain has been **truncated** below a previously anchored tip.
    Truncated {
        checkpoint_seq: u64,
        current_max_seq: u64,
    },
    /// A checkpoint's committed `chain_tip` does not match the chain's
    /// `chain_hash` at that `seq` — the chain was **rewritten**.
    TipMismatch {
        seq: u64,
        anchored: String,
        actual: String,
    },
    /// Could not verify (e.g. malformed public key).
    CannotVerify { reason: String },
}

/// Verify anchored `checkpoints` against `rows` (the current chain) with the
/// hex **public** key. Detects truncation (a checkpoint seq no longer in the
/// chain) and rewrite (tip mismatch at a checkpoint seq). `rows` must be in
/// seq order. This is the anti-root guarantee: a host attacker who shortens or
/// edits the local chain cannot reproduce a previously anchored signed tip.
pub fn verify_checkpoints(
    verifying_key_hex: &str,
    rows: &[ChainRow],
    checkpoints: &[Checkpoint],
) -> CheckpointOutcome {
    let vk = match parse_verifying_key(verifying_key_hex) {
        Some(vk) => vk,
        None => {
            return CheckpointOutcome::CannotVerify {
                reason: format!("invalid public key hex ({} chars)", verifying_key_hex.len()),
            };
        }
    };
    // `rows` is seq-sorted (ORDER BY seq ASC in the store; chain build order in
    // tests), so the tip seq is the last element and we can binary-search below.
    let current_max_seq = rows.last().map(|r| r.seq).unwrap_or(0);
    let mut checked = 0u64;
    for cp in checkpoints {
        let msg = checkpoint_message(cp.seq, &cp.chain_tip, &cp.created_at);
        if !signature_ok(&vk, &msg, &cp.signature) {
            return CheckpointOutcome::BadSignature { seq: cp.seq };
        }
        match rows.binary_search_by_key(&cp.seq, |r| r.seq) {
            Ok(idx) if rows[idx].chain_hash == cp.chain_tip => {}
            Ok(idx) => {
                return CheckpointOutcome::TipMismatch {
                    seq: cp.seq,
                    anchored: cp.chain_tip.clone(),
                    actual: rows[idx].chain_hash.clone(),
                };
            }
            Err(_) => {
                return CheckpointOutcome::Truncated {
                    checkpoint_seq: cp.seq,
                    current_max_seq,
                };
            }
        }
        checked += 1;
    }
    CheckpointOutcome::Consistent {
        checkpoints_checked: checked,
    }
}

/// Process exit code for `sysknife audit checkpoint` verification, mirroring
/// [`outcome_to_exit_code`]: `0` consistent, `1` a detected tamper (bad
/// signature / truncation / rewrite), `2` cannot-verify (e.g. malformed public
/// key). The 1-vs-2 split matters for CI exactly as it does for chain verify.
pub fn checkpoint_outcome_to_exit_code(outcome: &CheckpointOutcome) -> i32 {
    match outcome {
        CheckpointOutcome::Consistent { .. } => 0,
        CheckpointOutcome::BadSignature { .. }
        | CheckpointOutcome::Truncated { .. }
        | CheckpointOutcome::TipMismatch { .. } => 1,
        CheckpointOutcome::CannotVerify { .. } => 2,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fixed_key() -> AuditKey {
        AuditKey::from_bytes(vec![0x42; 32])
    }

    fn sample_content<'a>(seq: u64, txid: &'a str) -> ChainContent<'a> {
        ChainContent {
            seq,
            key_id: CURRENT_KEY_ID,
            transaction_id: txid,
            request_id: "req-1",
            request_hash: "hash-abc",
            action_name: "UpdateSystem",
            risk_level: RiskLevel::High,
            summary: "Upgrade",
            approval_id: None,
            warnings_json: "[]",
            created_at: "2026-04-24T12:00:00Z",
            identity: ChainIdentity::V2 {
                caller_role: "Dev",
                event_tip: "",
            },
        }
    }

    // ── chain_hash determinism + linkage ──────────────────────────────────

    #[test]
    fn same_inputs_yield_same_hash() {
        let key = fixed_key();
        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
        let h2 = key.chain_hash(&sample_content(1, "txa"), "");
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), HASH_HEX_LEN);
    }

    #[test]
    fn different_seq_yields_different_hash() {
        let key = fixed_key();
        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
        let h2 = key.chain_hash(&sample_content(2, "txa"), "");
        assert_ne!(h1, h2);
    }

    #[test]
    fn different_prev_hash_yields_different_hash() {
        let key = fixed_key();
        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
        let h2 = key.chain_hash(&sample_content(1, "txa"), "deadbeef");
        assert_ne!(h1, h2);
    }

    #[test]
    fn different_keys_yield_different_hashes() {
        let key1 = AuditKey::from_bytes(vec![0x01; 32]);
        let key2 = AuditKey::from_bytes(vec![0x02; 32]);
        let h1 = key1.chain_hash(&sample_content(1, "txa"), "");
        let h2 = key2.chain_hash(&sample_content(1, "txa"), "");
        assert_ne!(h1, h2);
    }

    // ── canonical encoding stability ──────────────────────────────────────

    #[test]
    fn canonical_bytes_have_stable_field_order() {
        let c = sample_content(1, "txa");
        let bytes = c.canonical_bytes();
        let s = String::from_utf8_lossy(&bytes);
        // Tags must appear in a fixed order.
        let order = [
            "seq",
            "key_id",
            "transaction_id",
            "request_id",
            "request_hash",
            "action_name",
            "risk_level",
            "summary",
            "approval_id",
            "warnings_json",
            "created_at",
        ];
        let mut last_idx = 0;
        for tag in order {
            let idx = s.find(tag).unwrap_or_else(|| panic!("missing {tag}"));
            assert!(idx >= last_idx, "{tag} out of order");
            last_idx = idx;
        }
    }

    #[test]
    fn nul_bytes_in_field_value_are_escaped() {
        let mut c = sample_content(1, "txa");
        let summary = "before\0after";
        c.summary = summary;
        let bytes = c.canonical_bytes();
        // Raw NUL must NOT appear; escape sequence must.
        assert!(!bytes.contains(&0x00));
        assert!(String::from_utf8_lossy(&bytes).contains("before\\0after"));
    }

    /// Backslash-NUL collision regression: an attacker who could craft a
    /// row with `summary = "before\\0after"` (literal backslash + zero) must
    /// NOT produce the same canonical bytes as one with raw `\x00`. Without
    /// the `\\` → `\\\\` escape, the two collide and the attacker can
    /// substitute one for the other while the chain hash matches.
    #[test]
    fn literal_backslash_zero_does_not_collide_with_raw_nul_escape() {
        let mut a = sample_content(1, "txa");
        a.summary = "before\\0after"; // literal backslash + '0'
        let mut b = sample_content(1, "txa");
        b.summary = "before\0after"; // raw NUL
        assert_ne!(
            a.canonical_bytes(),
            b.canonical_bytes(),
            "backslash escape must run before NUL escape to prevent collision"
        );
    }

    fn key_for_collision_test() -> AuditKey {
        AuditKey::from_bytes(vec![0xab; 32])
    }

    #[test]
    fn literal_backslash_zero_chain_hash_differs_from_raw_nul() {
        let key = key_for_collision_test();
        let mut a = sample_content(1, "txa");
        a.summary = "before\\0after";
        let mut b = sample_content(1, "txa");
        b.summary = "before\0after";
        assert_ne!(
            key.chain_hash(&a, ""),
            key.chain_hash(&b, ""),
            "chain signature must distinguish escape from raw byte"
        );
    }

    // ── verify_chain ──────────────────────────────────────────────────────

    /// Materialise the stored row that `content` would produce, so a test
    /// never hand-copies field-by-field and accidentally signs one thing while
    /// storing another.
    fn row_for(content: &ChainContent<'_>, prev: &str, chain_hash: String) -> ChainRow {
        let (chain_version, caller_role, event_tip) = match content.identity {
            ChainIdentity::LegacyV1 => (CHAIN_VERSION_LEGACY, None, None),
            ChainIdentity::V2 {
                caller_role,
                event_tip,
            } => (
                CHAIN_VERSION_CURRENT,
                Some(caller_role.to_string()),
                Some(event_tip.to_string()),
            ),
        };
        ChainRow {
            seq: content.seq,
            key_id: content.key_id.to_string(),
            transaction_id: content.transaction_id.to_string(),
            request_id: content.request_id.to_string(),
            request_hash: content.request_hash.to_string(),
            action_name: content.action_name.to_string(),
            risk_level: content.risk_level,
            summary: content.summary.to_string(),
            approval_id: content.approval_id.map(str::to_string),
            warnings_json: content.warnings_json.to_string(),
            created_at: content.created_at.to_string(),
            prev_chain_hash: prev.to_string(),
            chain_hash,
            chain_version,
            caller_role,
            event_tip,
        }
    }

    fn build_chain(key: &AuditKey, count: usize) -> Vec<ChainRow> {
        let mut rows = Vec::with_capacity(count);
        let mut prev = String::new();
        for i in 0..count {
            let seq = (i + 1) as u64;
            let txid = format!("tx{i}");
            let content = sample_content(seq, &txid);
            let hash = key.chain_hash(&content, &prev);
            rows.push(row_for(&content, &prev, hash.clone()));
            prev = hash;
        }
        rows
    }

    // ── caller identity in the signed content ─────────────────────────────

    #[test]
    fn caller_role_is_covered_by_the_row_signature() {
        // The whole point of the v2 encoding: two rows identical except for
        // who asked must not share a signature, or the chain cannot answer
        // "which role requested this".
        let key = fixed_key();
        let mut dev = sample_content(1, "txa");
        dev.identity = ChainIdentity::V2 {
            caller_role: "Dev",
            event_tip: "",
        };
        let mut boot = sample_content(1, "txa");
        boot.identity = ChainIdentity::V2 {
            caller_role: "Boot",
            event_tip: "",
        };
        assert_ne!(key.chain_hash(&dev, ""), key.chain_hash(&boot, ""));
    }

    #[test]
    fn event_tip_is_covered_by_the_row_signature() {
        let key = fixed_key();
        let mut empty = sample_content(1, "txa");
        empty.identity = ChainIdentity::V2 {
            caller_role: "Dev",
            event_tip: "",
        };
        let mut bound = sample_content(1, "txa");
        bound.identity = ChainIdentity::V2 {
            caller_role: "Dev",
            event_tip: "abc123",
        };
        assert_ne!(key.chain_hash(&empty, ""), key.chain_hash(&bound, ""));
    }

    #[test]
    fn a_legacy_row_written_before_the_migration_still_verifies() {
        // The migration contract. A chain written by v0.2.12 or earlier has no
        // caller_role column; re-encoding those rows with an empty identity
        // would report every historical row as Broken, i.e. an upgrade would
        // look exactly like a compromise.
        let key = fixed_key();
        let mut content = sample_content(1, "tx-legacy");
        content.identity = ChainIdentity::LegacyV1;
        let hash = key.chain_hash(&content, "");
        let row = row_for(&content, "", hash);
        assert_eq!(row.chain_version, CHAIN_VERSION_LEGACY);
        assert_eq!(row.caller_role, None);
        assert_eq!(
            verify_chain(&key, &[row]),
            VerifyOutcome::Intact { rows_checked: 1 }
        );
    }

    #[test]
    fn a_chain_that_spans_the_migration_verifies_end_to_end() {
        // The realistic upgrade shape: old rows, then new rows appended by the
        // upgraded daemon, in one chain.
        let key = fixed_key();
        let mut rows = Vec::new();
        let mut prev = String::new();
        for (i, identity) in [
            ChainIdentity::LegacyV1,
            ChainIdentity::LegacyV1,
            ChainIdentity::V2 {
                caller_role: "Dev",
                event_tip: "",
            },
            ChainIdentity::V2 {
                caller_role: "Boot",
                event_tip: "",
            },
        ]
        .into_iter()
        .enumerate()
        {
            let txid = format!("tx{i}");
            let mut content = sample_content((i + 1) as u64, &txid);
            content.identity = identity;
            let hash = key.chain_hash(&content, &prev);
            rows.push(row_for(&content, &prev, hash.clone()));
            prev = hash;
        }
        assert_eq!(
            verify_chain(&key, &rows),
            VerifyOutcome::Intact { rows_checked: 4 }
        );
    }

    #[test]
    fn downgrading_a_v2_row_to_hide_the_caller_role_breaks_it() {
        // The attack the version column might invite: relabel a v2 row as
        // legacy and drop the identity columns, so verification re-encodes it
        // without caller_role. The stored signature was made over the v2
        // message, so it cannot verify against the shorter one.
        let key = fixed_key();
        let mut rows = build_chain(&key, 2);
        rows[1].chain_version = CHAIN_VERSION_LEGACY;
        rows[1].caller_role = None;
        rows[1].event_tip = None;
        match verify_chain(&key, &rows) {
            VerifyOutcome::Broken {
                first_broken_seq, ..
            } => assert_eq!(first_broken_seq, 2),
            other => panic!("expected Broken, got {other:?}"),
        }
    }

    #[test]
    fn a_v2_row_with_a_nulled_caller_role_is_broken_not_merely_unverifiable() {
        // Nulling the column while leaving chain_version=2 is a
        // self-contradictory row, not an infrastructure problem. It must map
        // to exit code 1 (tamper detected), never 2 (could not check) — a CI
        // gate that treats 2 as "skip" would otherwise wave it through.
        let key = fixed_key();
        let mut rows = build_chain(&key, 1);
        rows[0].caller_role = None;
        let outcome = verify_chain(&key, &rows);
        assert!(matches!(outcome, VerifyOutcome::Broken { .. }));
        assert_eq!(outcome_to_exit_code(&outcome), 1);
    }

    #[test]
    fn a_chain_version_this_binary_does_not_know_is_cannot_verify() {
        // An older binary reading a newer chain genuinely cannot reproduce the
        // message. That is exit 2, distinct from a detected break.
        let key = fixed_key();
        let mut rows = build_chain(&key, 1);
        rows[0].chain_version = CHAIN_VERSION_CURRENT + 1;
        let outcome = verify_chain(&key, &rows);
        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
        assert_eq!(outcome_to_exit_code(&outcome), 2);
    }

    // ── approval-event chain ──────────────────────────────────────────────

    fn event_content<'a>(seq: u64, kind: AuditEventKind, txid: &'a str) -> EventContent<'a> {
        EventContent {
            seq,
            key_id: CURRENT_KEY_ID,
            kind,
            transaction_id: txid,
            receipt_digest: "digest-abc",
            created_at: "2026-04-24T12:00:00Z",
        }
    }

    fn build_event_chain(key: &AuditKey, kinds: &[AuditEventKind]) -> Vec<EventRow> {
        let mut rows = Vec::with_capacity(kinds.len());
        let mut prev = String::new();
        for (i, kind) in kinds.iter().enumerate() {
            let seq = (i + 1) as u64;
            let txid = format!("tx{i}");
            let content = event_content(seq, *kind, &txid);
            let hash = key.event_hash(&content, &prev);
            rows.push(EventRow {
                seq,
                key_id: content.key_id.to_string(),
                kind: content.kind.as_str().to_string(),
                transaction_id: content.transaction_id.to_string(),
                receipt_digest: content.receipt_digest.to_string(),
                created_at: content.created_at.to_string(),
                prev_chain_hash: prev.clone(),
                chain_hash: hash.clone(),
            });
            prev = hash;
        }
        rows
    }

    #[test]
    fn event_kind_spellings_are_stable() {
        // These strings are inside the signed message. Renaming one silently
        // invalidates every event already written.
        assert_eq!(AuditEventKind::ApprovalGranted.as_str(), "approval_granted");
        assert_eq!(
            AuditEventKind::ApprovalConsumed.as_str(),
            "approval_consumed"
        );
        assert_eq!(AuditEventKind::ApprovalRevoked.as_str(), "approval_revoked");
    }

    #[test]
    fn intact_event_chain_verifies() {
        let key = fixed_key();
        let rows = build_event_chain(
            &key,
            &[
                AuditEventKind::ApprovalGranted,
                AuditEventKind::ApprovalConsumed,
            ],
        );
        assert_eq!(
            verify_event_chain(&key, &rows),
            VerifyOutcome::Intact { rows_checked: 2 }
        );
    }

    #[test]
    fn deleting_an_approval_event_from_the_middle_breaks_the_event_chain() {
        // The finding this chain exists for: before it, deleting the record
        // that an approval happened left `audit verify` reporting Intact.
        let key = fixed_key();
        let mut rows = build_event_chain(
            &key,
            &[
                AuditEventKind::ApprovalGranted,
                AuditEventKind::ApprovalConsumed,
                AuditEventKind::ApprovalRevoked,
            ],
        );
        rows.remove(1);
        match verify_event_chain(&key, &rows) {
            VerifyOutcome::Broken {
                first_broken_seq, ..
            } => assert_eq!(first_broken_seq, 3),
            other => panic!("expected Broken, got {other:?}"),
        }
    }

    #[test]
    fn relabelling_a_revocation_as_a_grant_breaks_the_event_chain() {
        let key = fixed_key();
        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalRevoked]);
        rows[0].kind = AuditEventKind::ApprovalGranted.as_str().to_string();
        assert!(matches!(
            verify_event_chain(&key, &rows),
            VerifyOutcome::Broken { .. }
        ));
    }

    #[test]
    fn an_unrecognised_event_kind_is_a_break_not_a_panic() {
        let key = fixed_key();
        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalGranted]);
        rows[0].kind = "approval_unicorned".to_string();
        assert!(matches!(
            verify_event_chain(&key, &rows),
            VerifyOutcome::Broken { .. }
        ));
    }

    #[test]
    fn a_row_signature_cannot_be_replayed_as_an_event_signature() {
        // Domain separation, checked functionally rather than by comparing the
        // tag constants: the tags test proves the bytes differ, this proves the
        // difference actually reaches the verifier.
        let key = fixed_key();
        let content = event_content(1, AuditEventKind::ApprovalGranted, "tx0");
        let event_sig = key.event_hash(&content, "");
        let row_sig = key.chain_hash(&sample_content(1, "tx0"), "");
        assert_ne!(event_sig, row_sig);

        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalGranted]);
        rows[0].chain_hash = row_sig;
        assert!(matches!(
            verify_event_chain(&key, &rows),
            VerifyOutcome::Broken { .. }
        ));
    }

    // ── cross-chain binding ───────────────────────────────────────────────

    #[test]
    fn deleting_the_last_approval_event_is_caught_by_the_transaction_binding() {
        // Truncating the *tail* of the event chain leaves a self-consistent
        // event chain — the walk alone cannot see it. It is caught because a
        // later transaction row signed the tip that no longer exists, and the
        // transaction chain is what checkpoints anchor.
        let key = fixed_key();
        let events = build_event_chain(
            &key,
            &[
                AuditEventKind::ApprovalGranted,
                AuditEventKind::ApprovalConsumed,
            ],
        );
        let mut content = sample_content(1, "tx-after");
        content.identity = ChainIdentity::V2 {
            caller_role: "Dev",
            event_tip: &events[1].chain_hash,
        };
        let hash = key.chain_hash(&content, "");
        let tx_rows = vec![row_for(&content, "", hash)];

        assert_eq!(
            verify_event_binding(&tx_rows, &events),
            BindingOutcome::Consistent {
                bindings_checked: 1
            }
        );

        let truncated = &events[..1];
        assert_eq!(
            verify_event_chain(&key, truncated),
            VerifyOutcome::Intact { rows_checked: 1 },
            "a truncated event chain still walks clean; the binding is the detector"
        );
        match verify_event_binding(&tx_rows, truncated) {
            BindingOutcome::MissingEvent {
                transaction_seq, ..
            } => assert_eq!(transaction_seq, 1),
            other => panic!("expected MissingEvent, got {other:?}"),
        }
    }

    #[test]
    fn legacy_rows_carry_no_binding_to_check() {
        // Rows written before the migration never committed to an event tip.
        // They must not be counted as bindings, and must not fail the check.
        let key = fixed_key();
        let mut content = sample_content(1, "tx-legacy");
        content.identity = ChainIdentity::LegacyV1;
        let hash = key.chain_hash(&content, "");
        let rows = vec![row_for(&content, "", hash)];
        assert_eq!(
            verify_event_binding(&rows, &[]),
            BindingOutcome::Consistent {
                bindings_checked: 0
            }
        );
    }

    #[test]
    fn a_detected_break_outranks_an_inconclusive_check_in_the_exit_code() {
        // If one check proves tampering and another merely cannot run, the
        // command must report the tamper. Reporting 2 ("could not verify")
        // would let a CI gate that treats 2 as a skip wave a broken chain
        // through.
        let verification = AuditVerification {
            chain: VerifyOutcome::Broken {
                rows_checked: 1,
                first_broken_seq: 2,
                first_broken_transaction_id: "tx".to_string(),
                expected: "e".to_string(),
                actual: "a".to_string(),
            },
            events: VerifyOutcome::CannotVerify {
                reason: "no key".to_string(),
            },
            binding: BindingOutcome::Consistent {
                bindings_checked: 0,
            },
        };
        assert_eq!(verification.exit_code(), 1);
    }

    #[test]
    fn a_clean_transaction_chain_does_not_mask_a_broken_event_chain() {
        let verification = AuditVerification {
            chain: VerifyOutcome::Intact { rows_checked: 3 },
            events: VerifyOutcome::Intact { rows_checked: 1 },
            binding: BindingOutcome::MissingEvent {
                transaction_seq: 3,
                event_tip: "abc".to_string(),
            },
        };
        assert_eq!(verification.exit_code(), 1);
    }

    #[test]
    fn all_three_clean_is_exit_zero() {
        let verification = AuditVerification {
            chain: VerifyOutcome::Intact { rows_checked: 3 },
            events: VerifyOutcome::Intact { rows_checked: 2 },
            binding: BindingOutcome::Consistent {
                bindings_checked: 1,
            },
        };
        assert_eq!(verification.exit_code(), 0);
    }

    #[test]
    fn binding_exit_codes_split_clean_from_tampered() {
        assert_eq!(
            binding_outcome_to_exit_code(&BindingOutcome::Consistent {
                bindings_checked: 0
            }),
            0
        );
        assert_eq!(
            binding_outcome_to_exit_code(&BindingOutcome::MissingEvent {
                transaction_seq: 7,
                event_tip: "abc".to_string()
            }),
            1
        );
    }

    #[test]
    fn intact_chain_verifies() {
        let key = fixed_key();
        let rows = build_chain(&key, 5);
        let outcome = verify_chain(&key, &rows);
        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 5 });
        assert_eq!(outcome_to_exit_code(&outcome), 0);
    }

    #[test]
    fn empty_chain_verifies() {
        let key = fixed_key();
        let outcome = verify_chain(&key, &[]);
        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 0 });
    }

    #[test]
    fn tampered_summary_breaks_chain_at_first_offending_row() {
        let key = fixed_key();
        let mut rows = build_chain(&key, 3);
        // Mutate summary on row 1 (seq=2). Hash mismatch should be detected.
        rows[1].summary = "TAMPERED".to_string();
        let outcome = verify_chain(&key, &rows);
        match outcome {
            VerifyOutcome::Broken {
                first_broken_seq, ..
            } => assert_eq!(first_broken_seq, 2),
            other => panic!("expected Broken, got {other:?}"),
        }
    }

    #[test]
    fn deleted_middle_row_breaks_chain_via_prev_hash_mismatch() {
        let key = fixed_key();
        let mut rows = build_chain(&key, 4);
        // Remove row at seq=2 entirely. Row 3's prev_chain_hash now mismatches.
        rows.remove(1);
        let outcome = verify_chain(&key, &rows);
        match outcome {
            VerifyOutcome::Broken {
                first_broken_seq, ..
            } => assert_eq!(
                first_broken_seq, 3,
                "first broken row is the one whose prev_hash refers to deleted row"
            ),
            other => panic!("expected Broken, got {other:?}"),
        }
    }

    #[test]
    fn inserted_forged_row_breaks_chain() {
        // Counterpart to `deleted_middle_row_…`. An attacker who managed to
        // insert a fabricated row between two genuine ones still cannot
        // produce a `chain_hash` that links the insertion back to the prior
        // row's hash, so verification must flag the forgery at the inserted
        // row (or at the immediately following genuine row whose
        // `prev_chain_hash` no longer matches its real predecessor).
        let key = fixed_key();
        let mut rows = build_chain(&key, 3);

        // Splice in a new row between seq=1 and seq=2 with a fabricated hash.
        let forged = ChainRow {
            seq: 2,
            key_id: CURRENT_KEY_ID.to_string(),
            transaction_id: "tx-forged".to_string(),
            request_id: "req-forged".to_string(),
            request_hash: "hash-forged".to_string(),
            action_name: "InstallFlatpak".to_string(),
            risk_level: RiskLevel::Medium,
            summary: "Forged row".to_string(),
            approval_id: None,
            warnings_json: "[]".to_string(),
            created_at: "2026-04-25T13:00:00Z".to_string(),
            // Plausible prev_chain_hash chosen to look intact at boundary.
            prev_chain_hash: rows[0].chain_hash.clone(),
            // Not a valid signature; verification must reject this.
            chain_hash: "0".repeat(HASH_HEX_LEN),
            chain_version: CHAIN_VERSION_CURRENT,
            caller_role: Some("Dev".to_string()),
            event_tip: Some(String::new()),
        };

        // Renumber the genuine seq=2/3 rows so seq is still 1..=4.
        let mut rest: Vec<ChainRow> = rows.split_off(1);
        for r in rest.iter_mut() {
            r.seq += 1;
        }
        rows.push(forged);
        rows.extend(rest);

        // The fixture is deterministic: the forged row sits at seq=2 with a
        // signature that cannot verify, so the walk must stop exactly there.
        // Accepting "2 or 3" let an off-by-one in `verify_rows` pass.
        let outcome = verify_chain(&key, &rows);
        match outcome {
            VerifyOutcome::Broken {
                first_broken_seq, ..
            } => assert_eq!(
                first_broken_seq, 2,
                "the verifier must flag the forged row itself, not a later one"
            ),
            other => panic!("expected Broken, got {other:?}"),
        }
    }

    // ── Ed25519 public-key verification / non-repudiation ─────────────────

    #[test]
    fn signature_verifies_under_exported_public_key() {
        // The auditor path: verify with only the public key.
        let key = fixed_key();
        let rows = build_chain(&key, 4);
        let outcome = verify_chain_with_pubkey(&key.verifying_key_hex(), &rows);
        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 4 });
    }

    #[test]
    fn foreign_public_key_cannot_validate_chain() {
        // Non-repudiation: a different keypair's public key neither validates
        // the chain nor (by construction) could forge it. This is the property
        // the old symmetric HMAC could not provide.
        let signer = AuditKey::from_bytes(vec![0x11; 32]);
        let rows = build_chain(&signer, 3);
        let other = AuditKey::from_bytes(vec![0x22; 32]);
        let outcome = verify_chain_with_pubkey(&other.verifying_key_hex(), &rows);
        assert!(matches!(
            outcome,
            VerifyOutcome::Broken {
                first_broken_seq: 1,
                ..
            }
        ));
    }

    #[test]
    fn verifying_key_hex_is_a_32_byte_public_key() {
        let key = fixed_key();
        let vk_hex = key.verifying_key_hex();
        assert_eq!(
            vk_hex.len(),
            64,
            "32-byte ed25519 public key = 64 hex chars"
        );
        assert!(hex::decode(&vk_hex).is_ok());
    }

    #[test]
    fn malformed_signature_hex_is_broken_not_panic() {
        let key = fixed_key();
        let mut rows = build_chain(&key, 2);
        rows[0].chain_hash = "not-valid-hex!!".to_string();
        let outcome = verify_chain(&key, &rows);
        assert!(matches!(
            outcome,
            VerifyOutcome::Broken {
                first_broken_seq: 1,
                ..
            }
        ));
    }

    #[test]
    fn bad_public_key_hex_yields_cannot_verify() {
        let key = fixed_key();
        let rows = build_chain(&key, 1);
        let outcome = verify_chain_with_pubkey("zz", &rows);
        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
    }

    #[test]
    fn load_or_generate_writes_public_key_sidecar() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit-key");
        let key = AuditKey::load_or_generate(&path).unwrap();
        let pub_path = dir.path().join("audit-key.pub");
        assert!(pub_path.exists(), "public key sidecar must be written");
        let pub_hex = std::fs::read_to_string(&pub_path).unwrap();
        assert_eq!(pub_hex.trim(), key.verifying_key_hex());
    }

    #[test]
    fn wrong_key_id_yields_cannot_verify() {
        let key = fixed_key();
        let mut rows = build_chain(&key, 2);
        rows[0].key_id = "v99".to_string();
        let outcome = verify_chain(&key, &rows);
        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
        assert_eq!(outcome_to_exit_code(&outcome), 2);
    }

    #[test]
    fn exit_code_for_each_outcome() {
        assert_eq!(
            outcome_to_exit_code(&VerifyOutcome::Intact { rows_checked: 0 }),
            0
        );
        assert_eq!(
            outcome_to_exit_code(&VerifyOutcome::Broken {
                rows_checked: 0,
                first_broken_seq: 1,
                first_broken_transaction_id: String::new(),
                expected: String::new(),
                actual: String::new(),
            }),
            1
        );
        assert_eq!(
            outcome_to_exit_code(&VerifyOutcome::CannotVerify {
                reason: String::new()
            }),
            2
        );
    }

    // ── AuditKey file management ──────────────────────────────────────────

    #[test]
    fn load_or_generate_creates_with_0600_mode() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit-key");
        let _key = AuditKey::load_or_generate(&path).unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[test]
    fn load_or_generate_is_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit-key");
        let key1_bytes = {
            let _ = AuditKey::load_or_generate(&path).unwrap();
            std::fs::read(&path).unwrap()
        };
        let _ = AuditKey::load_or_generate(&path).unwrap();
        let key2_bytes = std::fs::read(&path).unwrap();
        assert_eq!(key1_bytes, key2_bytes, "second load must not regenerate");
    }

    #[test]
    fn rejects_world_readable_key_file() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit-key");
        std::fs::write(&path, vec![0u8; 32]).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
        let result = AuditKey::load_or_generate(&path);
        assert!(matches!(
            result,
            Err(AuditKeyError::UnsafePermissions { .. })
        ));
    }

    #[test]
    fn rejects_short_key_file() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit-key");
        std::fs::write(&path, vec![0u8; 8]).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        let result = AuditKey::load_or_generate(&path);
        assert!(matches!(result, Err(AuditKeyError::KeyTooShort { .. })));
    }

    // ── Debug redaction (HI-17 secret hygiene) ────────────────────────────

    /// `Debug` must never expose the Ed25519 private key material, neither raw bytes,
    /// nor their hex encoding. A derived `Debug` would dump the bytes the
    /// moment anyone wrote `tracing::debug!("{key:?}")`.
    #[test]
    fn debug_redacts_key_bytes_and_their_hex_encoding() {
        // Use a distinctive byte pattern so accidental leaks are obvious.
        let raw = (0u8..32).collect::<Vec<u8>>();
        let key = AuditKey::from_bytes(raw.clone());
        let dbg = format!("{key:?}");

        assert!(
            dbg.contains("redacted"),
            "Debug output must contain the literal 'redacted' marker, got: {dbg}"
        );

        // Hex encoding of the bytes must NOT appear, in either case.
        let hex_lower = hex::encode(&raw);
        let hex_upper = hex::encode_upper(&raw);
        assert!(
            !dbg.contains(&hex_lower),
            "Debug output leaks lowercase hex of key bytes: {dbg}"
        );
        assert!(
            !dbg.contains(&hex_upper),
            "Debug output leaks uppercase hex of key bytes: {dbg}"
        );

        // Each individual byte's two-hex-char form must also be absent. This
        // catches the case where a future change splits the bytes across the
        // formatter and prints them piecewise.
        for b in &raw {
            let pair = format!("{b:02x}");
            // 1-byte values 0x00..0x0f render as "00".."0f" — too short to
            // assert against safely (collides with key_id "v1" etc.). Only
            // check 2-char forms that cannot incidentally match the rest of
            // the Debug output.
            if *b >= 0x10 && pair != "1e" && pair != "1f" {
                assert!(
                    !dbg.contains(&pair),
                    "Debug output leaks byte {b:#04x} as {pair:?}: {dbg}"
                );
            }
        }
    }

    /// Operators triaging a chain break need to know which key generation
    /// produced a row. `key_id` is not secret and must remain visible.
    #[test]
    fn debug_preserves_key_id() {
        let key = AuditKey::from_bytes(vec![0xff; 32]);
        let dbg = format!("{key:?}");
        assert!(
            dbg.contains("key_id"),
            "Debug output must label the key_id field: {dbg}"
        );
        assert!(
            dbg.contains(CURRENT_KEY_ID),
            "Debug output must contain the key_id value {CURRENT_KEY_ID:?}: {dbg}"
        );
    }

    // ── signed checkpoints (anti-truncation / anti-rewrite) ───────────────

    #[test]
    fn checkpoint_consistent_with_intact_chain() {
        let key = fixed_key();
        let rows = build_chain(&key, 5);
        let cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
        assert_eq!(
            outcome,
            CheckpointOutcome::Consistent {
                checkpoints_checked: 1
            }
        );
    }

    #[test]
    fn checkpoint_detects_truncation() {
        let key = fixed_key();
        let full = build_chain(&key, 5);
        // Anchor a checkpoint at the tip (seq=5); later the chain is cut to 3.
        let cp = key.sign_checkpoint(5, &full[4].chain_hash, "2026-04-24T12:00:00Z");
        let truncated = &full[..3];
        let outcome = verify_checkpoints(&key.verifying_key_hex(), truncated, &[cp]);
        assert!(matches!(
            outcome,
            CheckpointOutcome::Truncated {
                checkpoint_seq: 5,
                current_max_seq: 3
            }
        ));
    }

    #[test]
    fn checkpoint_detects_rewrite() {
        let key = fixed_key();
        let mut rows = build_chain(&key, 4);
        let cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
        // Rewrite the row at seq=3 after the checkpoint was anchored.
        rows[2].chain_hash = "0".repeat(HASH_HEX_LEN);
        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
        assert!(matches!(
            outcome,
            CheckpointOutcome::TipMismatch { seq: 3, .. }
        ));
    }

    #[test]
    fn checkpoint_bad_signature_detected() {
        let key = fixed_key();
        let rows = build_chain(&key, 3);
        let mut cp = key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z");
        cp.signature = "0".repeat(HASH_HEX_LEN); // not a valid signature
        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
        assert!(matches!(
            outcome,
            CheckpointOutcome::BadSignature { seq: 2 }
        ));
    }

    #[test]
    fn checkpoint_foreign_key_rejected() {
        // A checkpoint signed by one key must not verify under another key.
        let signer = AuditKey::from_bytes(vec![0x11; 32]);
        let rows = build_chain(&signer, 3);
        let cp = signer.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z");
        let other = AuditKey::from_bytes(vec![0x22; 32]);
        let outcome = verify_checkpoints(&other.verifying_key_hex(), &rows, &[cp]);
        assert!(matches!(
            outcome,
            CheckpointOutcome::BadSignature { seq: 2 }
        ));
    }

    #[test]
    fn pubkey_verify_detects_tampered_middle_row() {
        // The core auditor claim: with only the public key, a mutated field in
        // a non-first row is detected at that exact seq.
        let key = fixed_key();
        let mut rows = build_chain(&key, 4);
        rows[2].summary = "TAMPERED".to_string();
        let outcome = verify_chain_with_pubkey(&key.verifying_key_hex(), &rows);
        assert!(matches!(
            outcome,
            VerifyOutcome::Broken {
                first_broken_seq: 3,
                ..
            }
        ));
    }

    #[test]
    fn multiple_checkpoints_all_consistent() {
        let key = fixed_key();
        let rows = build_chain(&key, 5);
        let cps = vec![
            key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z"),
            key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:05:00Z"),
            key.sign_checkpoint(5, &rows[4].chain_hash, "2026-04-24T12:10:00Z"),
        ];
        assert_eq!(
            verify_checkpoints(&key.verifying_key_hex(), &rows, &cps),
            CheckpointOutcome::Consistent {
                checkpoints_checked: 3
            }
        );
    }

    #[test]
    fn middle_checkpoint_failure_is_reported() {
        // Earlier-consistent checkpoints must not mask a later failure.
        let key = fixed_key();
        let mut rows = build_chain(&key, 5);
        let cps = vec![
            key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z"),
            key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:05:00Z"),
            key.sign_checkpoint(5, &rows[4].chain_hash, "2026-04-24T12:10:00Z"),
        ];
        rows[2].chain_hash = "0".repeat(HASH_HEX_LEN); // rewrite what cp #2 commits to
        assert!(matches!(
            verify_checkpoints(&key.verifying_key_hex(), &rows, &cps),
            CheckpointOutcome::TipMismatch { seq: 3, .. }
        ));
    }

    #[test]
    fn checkpoint_created_at_is_signed() {
        // created_at is inside the signed message: backdating invalidates it.
        let key = fixed_key();
        let rows = build_chain(&key, 3);
        let mut cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
        cp.created_at = "2020-01-01T00:00:00Z".to_string();
        assert!(matches!(
            verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]),
            CheckpointOutcome::BadSignature { .. }
        ));
    }

    #[test]
    fn checkpoint_seq_is_signed() {
        // seq is inside the signed message: moving it invalidates the signature.
        let key = fixed_key();
        let rows = build_chain(&key, 3);
        let mut cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
        cp.seq = 2;
        assert!(matches!(
            verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]),
            CheckpointOutcome::BadSignature { seq: 2 }
        ));
    }

    #[test]
    fn checkpoint_detects_full_wipe() {
        // The whole chain deleted: the anchored tip cannot be reproduced.
        let key = fixed_key();
        let full = build_chain(&key, 3);
        let cp = key.sign_checkpoint(3, &full[2].chain_hash, "2026-04-24T12:00:00Z");
        assert!(matches!(
            verify_checkpoints(&key.verifying_key_hex(), &[], &[cp]),
            CheckpointOutcome::Truncated {
                checkpoint_seq: 3,
                current_max_seq: 0
            }
        ));
    }

    #[test]
    fn domain_tags_are_distinct_and_prefix_free() {
        // Security invariant: row and checkpoint signatures can never
        // cross-verify because their signed messages start with distinct,
        // prefix-free domain tags.
        // Checked pairwise over the whole set rather than as a hand-written
        // list: adding a fourth tag to a hand-written list silently leaves the
        // new tag unchecked against the old ones.
        let tags: [(&str, &[u8]); 4] = [
            ("row", ROW_DOMAIN),
            ("checkpoint", CHECKPOINT_DOMAIN),
            ("approval", APPROVAL_DOMAIN),
            ("event", EVENT_DOMAIN),
        ];
        for (i, (name_a, a)) in tags.iter().enumerate() {
            for (name_b, b) in tags.iter().skip(i + 1) {
                assert_ne!(a, b, "{name_a} and {name_b} share a domain tag");
                assert!(!a.starts_with(b), "{name_a} is prefixed by {name_b}");
                assert!(!b.starts_with(a), "{name_b} is prefixed by {name_a}");
            }
        }
    }

    #[test]
    fn approval_receipt_framing_is_injective() {
        // The signed receipt message must be injective in
        // (transaction_id, request_hash). Without `push_field` escaping, the
        // ambiguous pair below would collide because a raw 0x1F separator
        // cannot be distinguished from a 0x1F inside a field value.
        let key = fixed_key();
        let sep = "\u{1f}";
        let a = key.approval_receipt(&format!("tx{sep}b"), "c");
        let b = key.approval_receipt("tx", &format!("b{sep}c"));
        assert_ne!(a, b, "0x1F in a field must not alias distinct receipts");

        // Sanity: the derivation is deterministic (Ed25519, same inputs).
        assert_eq!(
            key.approval_receipt("tx-1", "hash-1"),
            key.approval_receipt("tx-1", "hash-1"),
        );
        // And the commitment is exactly SHA-256 of the receipt.
        assert_eq!(
            key.approval_commitment("tx-1", "hash-1"),
            approval_receipt_digest(&key.approval_receipt("tx-1", "hash-1")),
        );
    }
}