crtx-ledger 0.1.0

Append-only event log, hash chain, trace assembly, and audit records.
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
//! TUF-rooted Rekor trust bundle (ADR 0013 Mechanism C trust channel).
//!
//! This module pins the **trusted_root.json** Sigstore TUF artifact used to
//! verify Rekor `SignedEntryTimestamp` payloads. Council Decision #1 (TUF
//! trust root channel, fail-closed when stale > 30 days) is the operator
//! contract enforced here:
//!
//! 1. A known-good `trusted_root.json` snapshot is embedded into the binary
//!    via [`include_bytes!`] so that the verifier can decide what counts as
//!    valid Rekor public keys even when the operator has never run
//!    `cortex audit anchor refresh-trust`. The snapshot date is recorded
//!    in [`EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`].
//! 2. Operators may stage a fresher cached `trusted_root.json` on disk via
//!    [`TrustedRoot::load_cached`]. The CLI exposes this through the
//!    `cortex audit anchor refresh-trust` subcommand.
//! 3. [`TrustedRoot::is_stale_at`] returns `true` when an
//!    operator-supplied freshness anchor (build-time snapshot date for
//!    the embedded path, file mtime for the cached refresh path) is
//!    older than `max_age` at the supplied `now`. Default operator
//!    policy is 30 days. Anchor selection is the explicit
//!    [`TrustRootStalenessAnchor`] caller argument — the
//!    [`Self::metadata_signed_at`]-derived field is NOT a freshness
//!    proxy (Bug J + 2026-05-15 portfolio-extension footnote on ADR
//!    0013).
//!
//! ## What this module does **not** do
//!
//! - It does not verify TUF metadata signatures. The embedded snapshot is
//!   trusted on the first build; subsequent refresh is structurally
//!   validated (parse + currency) but the cryptographic chain-of-trust
//!   over the TUF root → snapshot → targets path is an operator action
//!   gated by the live HTTP refresh flow.
//! - It does not perform any I/O outside [`TrustedRoot::load_cached`]
//!   (read) and [`TrustedRoot::write_atomic`] (write). Both are isolated
//!   to file paths the CLI passes in.
//! - It does not consume the Rekor public key bytes. Rekor signature
//!   verification is deferred per
//!   `docs/design/DESIGN_external_anchor_authority.md` §Residual risk.
//!   This slice unlocks the *channel* through which keys will be
//!   distributed, not the verification of an individual entry.
//!
//! ## Cosign GHSA-whqx-f9j3-ch6m mitigation
//!
//! The trust root channel is the load-bearing primitive for the Cosign
//! advisory class: a verifier that hard-codes Rekor public keys cannot
//! follow key rotation, and a verifier that fetches keys without TUF
//! semantics can be tricked into accepting attacker-controlled keys.
//! Cortex's mitigation is the same as Sigstore's: ship a TUF-validated
//! `trusted_root.json` with explicit operator-driven refresh, and refuse
//! to mark anchor evidence authoritative when the trust root has aged
//! past the operator's risk-acceptance window. Subject binding stays
//! enforced at the verifier path (see
//! [`crate::external_sink::verify_external_receipts`]).

use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Raw bytes for the embedded `trusted_root.json` snapshot.
///
/// Fetched from
/// `https://tuf-repo-cdn.sigstore.dev/targets/<hash>.trusted_root.json` on
/// the snapshot date below. SHA-256 of the embedded bytes:
/// `6494e21ea73fa7ee769f85f57d5a3e6a08725eae1e38c755fc3517c9e6bc0b66`.
///
/// The embed targets the binary at build time; serde validation happens at
/// the [`TrustedRoot::embedded`] boundary so a corrupted embed cannot
/// silently produce a usable `TrustedRoot`.
pub const TRUSTED_ROOT_JSON: &[u8] =
    include_bytes!("embedded/sigstore_trusted_root_2026-05-12.json");

/// Operator-visible date the embedded `trusted_root.json` snapshot was
/// pulled. Used by diagnostics so an operator can correlate a stale
/// embedded root with the public Sigstore TUF history.
///
/// **F2 closure (Finding 3 in
/// `docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md`).** This constant
/// USED to be a hand-written sibling literal next to
/// [`TRUSTED_ROOT_JSON`]'s `include_bytes!("embedded/sigstore_trusted_root_YYYY-MM-DD.json")`
/// argument. A snapshot refresh that bumped the filename but forgot to
/// bump the constant would silently anchor the 30-day freshness gate to
/// the stale capture date. The value is now derived at build time by
/// `crates/cortex-ledger/build.rs` from the embedded snapshot's
/// filename, so the two literals cannot drift independently. Mutating
/// the filename to something that does not match
/// `sigstore_trusted_root_YYYY-MM-DD.json`, or dropping the snapshot
/// altogether, fails the build with a hard error.
pub const EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE: &str = env!("EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE");

/// Default operator policy: a trusted root older than this is fail-closed
/// for the external-anchor authority path. Operators may override the
/// policy through the verify command's `--max-trust-root-age-days` flag
/// (slice 4) when their risk-acceptance window differs.
pub const DEFAULT_MAX_TRUST_ROOT_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);

/// Tolerance window for future-dated freshness anchors before they are
/// treated as a bypass attempt.
///
/// Prior F3 closure (CODE_REVIEW_2026-05-12_post_fd779d7.md): a
/// future-dated cache `mtime` (e.g. via `touch -d 2099-01-01`) used to
/// silently pass the freshness gate because `now - mtime` went negative
/// and the `> max_age` comparison stayed false indefinitely. Refusing on
/// any future mtime would be too strict (filesystem clock drift between
/// hosts is real); instead we permit a small skew and refuse anything
/// beyond it as
/// [`TrustRootStalenessError::CacheFutureDated`] /
/// [`STABLE_INVARIANT_TRUSTED_ROOT_CACHE_FUTURE_DATED`].
pub const TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE: Duration = Duration::from_secs(60);

/// Stable invariant emitted when a trusted-root cache file's `mtime` is
/// dated more than [`TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE`] ahead of
/// wall-clock at the freshness check. See
/// [`TrustRootStalenessError::CacheFutureDated`].
pub const STABLE_INVARIANT_TRUSTED_ROOT_CACHE_FUTURE_DATED: &str =
    "audit.verify.trusted_root.cache_future_dated";

/// Stable invariant emitted when an external-anchor receipt verifier
/// refuses to mark anchor authority authoritative because the cached
/// trusted_root.json has aged past
/// [`DEFAULT_MAX_TRUST_ROOT_AGE`]. CLI diagnostics and JSON envelopes
/// surface this exact token so dashboards and grep-based wrappers can
/// distinguish "trust root stale" from "receipt parse failure".
///
/// Retained as a back-compat catch-all that is emitted ALONGSIDE the
/// branch-specific token (see [`TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT`]
/// and [`TRUSTED_ROOT_CACHE_STALE_INVARIANT`]) so existing dashboards do
/// not break.
pub const TRUSTED_ROOT_STALE_INVARIANT: &str = "audit.verify.trusted_root.stale_beyond_max_age";

/// Stable invariant emitted when the embedded trusted_root.json snapshot
/// is older than [`DEFAULT_MAX_TRUST_ROOT_AGE`]. Anchor is the explicit
/// [`EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`] constant — NOT the Sigstore
/// tlog signing-key activation date inside the JSON.
///
/// ADR 0013 footnote (2026-05-12 clarification on Council Decision #1)
/// codifies the anchor field-choice that closes Bug J. The 2026-05-15
/// portfolio-extension footnote extends that fix to ALL trust-root
/// freshness call sites, not just the production-restore drill path.
pub const TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT: &str = "audit.verify.trusted_root.snapshot_stale";

/// Stable invariant emitted when a cached `trusted_root.json` written by
/// `cortex audit refresh-trust` is older (by file mtime) than
/// [`DEFAULT_MAX_TRUST_ROOT_AGE`]. Anchor is the cache file's
/// modification time — NOT the Sigstore tlog signing-key activation
/// date.
pub const TRUSTED_ROOT_CACHE_STALE_INVARIANT: &str = "audit.verify.trusted_root.cache_stale";

/// Stable invariant emitted by [`crate::external_sink::verify_external_receipts`] when the
/// operator-supplied `trusted_root.json` (cache or embedded) cannot be
/// parsed at all. Distinguished from `audit.verify.trusted_root.stale_beyond_max_age`
/// so operators see whether to refresh or to debug the file shape.
pub const TRUSTED_ROOT_PARSE_INVARIANT: &str = "audit.verify.trusted_root.parse_error";

/// Stable status emitted by the trusted-root channel when the active root
/// is the embedded snapshot rather than a cached operator refresh.
pub const EMBEDDED_ROOT_STATUS: &str = "embedded_snapshot";
/// Stable status emitted by the trusted-root channel when the active root
/// is a cached `trusted_root.json` written by `cortex audit anchor refresh-trust`.
pub const CACHED_ROOT_STATUS: &str = "operator_cached";

/// Stable invariant emitted when [`TrustedRoot::rekor_verifying_key`]
/// refuses a Rekor receipt because no transparency-log instance in the
/// trusted root declares a `logId.keyId` matching the receipt's
/// `body.logID`.
///
/// Closes BH-3 (Finding 3 in
/// `docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md`): the previous
/// "latest activation wins" selector verified entries against the wrong
/// key when `trusted_root.json` carried multiple historical tlogs
/// (key-rotation case) or a newly-added attacker-mirror tlog (Cosign
/// GHSA-whqx-f9j3-ch6m class). The verifier now requires log-bound
/// selection — no silent fall-back to "latest" is permitted.
pub const REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT: &str =
    "rekor.trusted_root.tlog_logid_no_match";

/// Parsed Sigstore `trusted_root.json` (v0.1 `protobuf-go` JSON shape).
///
/// Only the fields cortex needs are deserialised. Unknown fields are
/// preserved as `serde_json::Value` so a refresh from a slightly newer
/// schema still round-trips.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrustedRoot {
    /// Media type from the Sigstore protobuf descriptor.
    /// Example: `application/vnd.dev.sigstore.trustedroot+json;version=0.1`.
    #[serde(rename = "mediaType")]
    pub media_type: String,
    /// Rekor transparency log declarations. Cortex enforces a non-empty
    /// list at parse time; an empty array fails closed.
    #[serde(default)]
    pub tlogs: Vec<TransparencyLogInstance>,
    /// Fulcio certificate authority declarations. Cortex does not consume
    /// these on the trust path today; they are kept so the cached file is
    /// a faithful copy and so a future signature verifier can use them.
    #[serde(rename = "certificateAuthorities", default)]
    pub certificate_authorities: serde_json::Value,
    /// Certificate transparency log declarations. Same posture as
    /// `certificateAuthorities` above.
    #[serde(default)]
    pub ctlogs: serde_json::Value,
    /// RFC 3161 timestamp authority declarations.
    #[serde(rename = "timestampAuthorities", default)]
    pub timestamp_authorities: serde_json::Value,
}

/// Single Rekor transparency log entry inside `trusted_root.json`.
///
/// The full Sigstore protobuf has additional metadata; cortex's slice 1
/// trust-channel path only consumes the activation date and the key
/// bytes, so the rest is captured as `serde_json::Value` and round-tripped
/// without interpretation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransparencyLogInstance {
    /// Rekor API base URL.
    #[serde(rename = "baseUrl")]
    pub base_url: String,
    /// `logId.keyId` base64; opaque to cortex today.
    #[serde(rename = "logId", default)]
    pub log_id: serde_json::Value,
    /// Hash algorithm declaration; opaque to cortex today.
    #[serde(rename = "hashAlgorithm", default)]
    pub hash_algorithm: serde_json::Value,
    /// Public key envelope; opaque except for `validFor.start`.
    #[serde(rename = "publicKey")]
    pub public_key: TransparencyLogPublicKey,
    /// Rekor log shard identity (`log_index`, `tree_size`, etc.); opaque
    /// to cortex today.
    #[serde(default)]
    pub log_index: serde_json::Value,
    /// Tree-id metadata; opaque to cortex today.
    #[serde(rename = "treeId", default)]
    pub tree_id: serde_json::Value,
    /// Catch-all so a refresh from a newer schema does not drop fields.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Sigstore public-key envelope inside [`TransparencyLogInstance`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransparencyLogPublicKey {
    /// Base64 DER public key bytes; opaque on the trust-channel path
    /// today.
    #[serde(rename = "rawBytes", default)]
    pub raw_bytes: Option<String>,
    /// Sigstore protobuf `KeyDetails` enum string (e.g.
    /// `PKIX_ECDSA_P256_SHA_256`, `PKIX_ED25519`). Cortex emits this in
    /// diagnostics so operators can correlate the active key shape.
    #[serde(rename = "keyDetails", default)]
    pub key_details: Option<String>,
    /// Activation window for the key. `start` is the canonical "trust
    /// root signed at" proxy cortex uses for staleness checks.
    #[serde(rename = "validFor", default)]
    pub valid_for: ValidityPeriod,
    /// Catch-all for unmodelled fields.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Activation window emitted by Sigstore protobufs.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidityPeriod {
    /// Inclusive start of the window. RFC 3339; required by Sigstore.
    #[serde(default)]
    pub start: Option<DateTime<Utc>>,
    /// Inclusive end of the window. Absent means "still active".
    #[serde(default)]
    pub end: Option<DateTime<Utc>>,
}

/// Caller-selected freshness anchor used by [`TrustedRoot::is_stale_at`].
///
/// Bug J fix + 2026-05-15 portfolio extension on ADR 0013 footnote:
/// every trust-root freshness gate in Cortex MUST anchor against an
/// operator-meaningful datum, not the Sigstore tlog signing-key
/// activation date inside the JSON. The two operator-meaningful
/// anchors are:
///
/// - **Embedded snapshot path** ([`Self::EmbeddedSnapshotDate`]) — the
///   build-time date Cortex captured the embedded snapshot, parsed
///   from [`EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`]. Fresh until 30 days
///   past that release date.
/// - **Cached refresh path** ([`Self::CacheFileMtime`]) — the
///   filesystem modification time of the cache file written by
///   `cortex audit refresh-trust`. Fresh until 30 days past the last
///   operator-driven refresh.
///
/// Callers select the variant by inspecting whether they have a
/// readable cache file at the configured cache path. The verifier
/// helpers in [`crate::external_sink::verify_external_receipts_with_options`]
/// and the production-restore drill follow the same convention.
#[derive(Debug)]
pub enum TrustRootStalenessAnchor<'a> {
    /// Anchor against the build-time embedded snapshot date.
    /// `snapshot_iso_date` defaults to [`EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`]
    /// at construction via [`Self::embedded_snapshot()`].
    EmbeddedSnapshotDate {
        /// `YYYY-MM-DD` string for the embedded snapshot date. Parsed
        /// at anchor-resolution time so a malformed constant fails
        /// loud rather than silently treating the root as stale.
        snapshot_iso_date: &'a str,
    },
    /// Anchor against a cache file's modification time.
    CacheFileMtime {
        /// Path to the cache file written by
        /// `cortex audit refresh-trust`. The file MUST exist and be
        /// readable; missing/unreadable files surface as
        /// [`TrustRootStalenessError`] so callers can distinguish a
        /// missing cache (fall back to embedded) from an unreadable
        /// cache (operator-actionable I/O error).
        cache_path: &'a Path,
    },
}

impl<'a> TrustRootStalenessAnchor<'a> {
    /// Build the embedded-snapshot anchor anchored to the
    /// build-time [`EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`] constant.
    #[must_use]
    pub const fn embedded_snapshot() -> Self {
        Self::EmbeddedSnapshotDate {
            snapshot_iso_date: EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE,
        }
    }

    /// Build the cache-file-mtime anchor at the supplied path.
    #[must_use]
    pub const fn cache_file_mtime(cache_path: &'a Path) -> Self {
        Self::CacheFileMtime { cache_path }
    }

    /// Short, stable label used in [`TrustRootStalenessError::CacheFutureDated`]
    /// diagnostics so the operator transcript names which anchor source
    /// resolved to a future timestamp.
    fn diagnostic_label(&self) -> String {
        match self {
            Self::EmbeddedSnapshotDate { snapshot_iso_date } => {
                format!("embedded_snapshot_date={snapshot_iso_date}")
            }
            Self::CacheFileMtime { cache_path } => {
                format!("cache_file_mtime path={}", cache_path.display())
            }
        }
    }

    /// Resolve the anchor into a wall-clock timestamp. `_now` is
    /// reserved for potential future anchors (e.g. fixture-injected
    /// clocks) but not used today.
    fn resolve(&self, _now: DateTime<Utc>) -> Result<DateTime<Utc>, TrustRootStalenessError> {
        match self {
            Self::EmbeddedSnapshotDate { snapshot_iso_date } => {
                let date =
                    NaiveDate::parse_from_str(snapshot_iso_date, "%Y-%m-%d").map_err(|err| {
                        TrustRootStalenessError::MalformedEmbeddedSnapshotDate {
                            observed: (*snapshot_iso_date).to_string(),
                            reason: err.to_string(),
                        }
                    })?;
                let utc = date
                    .and_hms_opt(0, 0, 0)
                    .ok_or(TrustRootStalenessError::EmbeddedSnapshotMidnightConstruction)?
                    .and_utc();
                Ok(utc)
            }
            Self::CacheFileMtime { cache_path } => {
                let meta = std::fs::metadata(cache_path).map_err(|source| {
                    TrustRootStalenessError::CacheMetadata {
                        path: cache_path.to_path_buf(),
                        source,
                    }
                })?;
                let mtime =
                    meta.modified()
                        .map_err(|source| TrustRootStalenessError::CacheMtime {
                            path: cache_path.to_path_buf(),
                            source,
                        })?;
                Ok(DateTime::<Utc>::from(mtime))
            }
        }
    }
}

/// Errors produced while resolving a [`TrustRootStalenessAnchor`].
///
/// These surface to the CLI when the caller's selected anchor source
/// is structurally unavailable (e.g. unreadable cache file). They are
/// **not** the "trust root is stale" branch — that is the `Ok(true)`
/// return of [`TrustedRoot::is_stale_at`].
#[derive(Debug, Error)]
pub enum TrustRootStalenessError {
    /// `EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE` constant did not parse as
    /// `YYYY-MM-DD`. Build-time bug — surfaces to operators only when
    /// a fresh build is mis-tagged.
    #[error(
        "EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE `{observed}` is not RFC 3339 YYYY-MM-DD: {reason}"
    )]
    MalformedEmbeddedSnapshotDate {
        /// The observed snapshot-date string that failed to parse.
        observed: String,
        /// Underlying chrono parse error message.
        reason: String,
    },
    /// `NaiveDate::and_hms_opt(0,0,0)` failed; not actually reachable
    /// for any well-formed date but retained so the anchor resolver
    /// can fail closed rather than panic.
    #[error("EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE midnight construction failed")]
    EmbeddedSnapshotMidnightConstruction,
    /// `std::fs::metadata` on the cache file failed (file missing,
    /// unreadable permissions, etc.).
    #[error("cannot stat trusted_root.json cache `{path}`: {source}", path = path.display())]
    CacheMetadata {
        /// Cache path the caller supplied.
        path: PathBuf,
        /// Underlying I/O failure.
        source: std::io::Error,
    },
    /// File metadata was read but `modified()` was unsupported / failed.
    #[error("cannot read mtime on trusted_root.json cache `{path}`: {source}", path = path.display())]
    CacheMtime {
        /// Cache path the caller supplied.
        path: PathBuf,
        /// Underlying I/O failure.
        source: std::io::Error,
    },
    /// The resolved freshness anchor is dated more than the operator
    /// tolerance ahead of wall-clock.
    ///
    /// Prior F3 closure: a future-dated cache `mtime` (e.g. set via
    /// `touch -d 2099-01-01`) used to silently pass the freshness gate
    /// because the `now - mtime > max_age` comparison goes false for a
    /// negative duration. The check is now fail-closed: any anchor more
    /// than [`TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE`] in the future
    /// surfaces this error and the caller MUST refuse the operation with
    /// [`STABLE_INVARIANT_TRUSTED_ROOT_CACHE_FUTURE_DATED`].
    #[error(
        "trusted_root anchor `{anchor}` is dated {anchor_ts} which is more than {tolerance_seconds}s ahead of now={now}: \
         refusing freshness gate (future-dated bypass guard)"
    )]
    CacheFutureDated {
        /// Diagnostic label naming the anchor source (`embedded_snapshot_date=…`
        /// or `cache_file_mtime path=…`).
        anchor: String,
        /// Resolved anchor timestamp (the future-dated value).
        anchor_ts: DateTime<Utc>,
        /// Wall-clock at the check.
        now: DateTime<Utc>,
        /// Tolerance window expressed in seconds (matches
        /// [`TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE`]).
        tolerance_seconds: u64,
    },
}

impl TrustedRoot {
    /// Parse the embedded snapshot. Panics only when the embedded JSON is
    /// structurally invalid — which is a build-time bug, not a runtime
    /// failure mode.
    ///
    /// Operators MUST NOT rely on the embedded root staying fresh; it is
    /// the fail-closed floor that exists so verifying with a brand-new
    /// data directory does not silently degrade. Refresh is an operator
    /// action.
    pub fn embedded() -> Result<Self, TrustedRootParseError> {
        Self::parse_bytes(TRUSTED_ROOT_JSON)
    }

    /// Parse a `trusted_root.json` payload supplied as raw bytes.
    pub fn parse_bytes(bytes: &[u8]) -> Result<Self, TrustedRootParseError> {
        let root: Self =
            serde_json::from_slice(bytes).map_err(|source| TrustedRootParseError::Malformed {
                reason: source.to_string(),
            })?;
        root.validate()?;
        Ok(root)
    }

    /// Read a cached `trusted_root.json` off disk. Missing files return
    /// `Ok(None)` so callers can fall back to [`Self::embedded`]; parse
    /// failures fail closed.
    pub fn load_cached(path: impl AsRef<Path>) -> Result<Option<Self>, TrustedRootIoError> {
        let path = path.as_ref();
        let bytes = match std::fs::read(path) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(source) => {
                return Err(TrustedRootIoError::Read {
                    path: path.to_path_buf(),
                    source,
                });
            }
        };
        Self::parse_bytes(&bytes)
            .map(Some)
            .map_err(|source| TrustedRootIoError::Parse {
                path: path.to_path_buf(),
                source,
            })
    }

    /// Validate the structural invariants cortex enforces on every
    /// `trusted_root.json`:
    ///
    /// - `mediaType` is non-empty and starts with the Sigstore
    ///   `application/vnd.dev.sigstore.trustedroot+json` prefix so a
    ///   misrouted file (e.g. `targets.json`, `timestamp.json`) cannot be
    ///   silently accepted.
    /// - At least one tlog is declared; an empty list cannot witness
    ///   anything and is treated as a hard parse failure rather than as
    ///   "trust nothing".
    /// - Every tlog has a parseable activation start.
    pub fn validate(&self) -> Result<(), TrustedRootParseError> {
        if !self
            .media_type
            .starts_with("application/vnd.dev.sigstore.trustedroot+json")
        {
            return Err(TrustedRootParseError::WrongMediaType {
                observed: self.media_type.clone(),
            });
        }
        if self.tlogs.is_empty() {
            return Err(TrustedRootParseError::EmptyTlogs);
        }
        for (index, tlog) in self.tlogs.iter().enumerate() {
            if tlog.base_url.is_empty() {
                return Err(TrustedRootParseError::MissingBaseUrl { tlog_index: index });
            }
            if tlog.public_key.valid_for.start.is_none() {
                return Err(TrustedRootParseError::MissingValidityStart { tlog_index: index });
            }
        }
        Ok(())
    }

    /// Latest tlog activation timestamp across every transparency log in
    /// the root. Used as the proxy for "this trust root was signed at"
    /// — a fresher activation entry means the trust root saw at least
    /// one signing-key rotation event after that date.
    ///
    /// Returns `None` only when validation was skipped or every tlog
    /// lacked a start (which `validate` would have rejected).
    #[must_use]
    pub fn metadata_signed_at(&self) -> Option<DateTime<Utc>> {
        self.tlogs
            .iter()
            .filter_map(|tlog| tlog.public_key.valid_for.start)
            .max()
    }

    /// Return `true` when `now - anchor` exceeds `max_age`, where the
    /// `anchor` is the explicit freshness datum the caller selected via
    /// [`TrustRootStalenessAnchor`].
    ///
    /// Bug J + 2026-05-15 portfolio-extension fix: callers MUST pass an
    /// explicit anchor source rather than letting the implementation
    /// fall through to [`Self::metadata_signed_at`] — the latter is the
    /// Sigstore tlog signing-key activation date, which rotates rarely
    /// (months/years) and would make every release immediately stale
    /// under a 30-day policy. The correct anchors are documented on
    /// [`TrustRootStalenessAnchor`].
    ///
    /// Returns `Err(TrustRootStalenessError)` only when the anchor
    /// source cannot be resolved (e.g. cache file unreadable,
    /// embedded snapshot date constant is malformed). I/O failures on
    /// the cache file are reported verbatim so callers can map them to
    /// the correct CLI exit code; they are NOT silently treated as
    /// stale.
    pub fn is_stale_at(
        &self,
        now: DateTime<Utc>,
        max_age: Duration,
        anchor: TrustRootStalenessAnchor<'_>,
    ) -> Result<bool, TrustRootStalenessError> {
        let anchor_ts = anchor.resolve(now)?;
        // Prior F3 closure: refuse a future-dated freshness anchor before
        // any direction-sensitive comparison. The bug used to be
        //   let age = now.signed_duration_since(anchor_ts);
        //   age > max_age
        // returning false when `anchor_ts > now` (the `Duration` goes
        // negative). An operator who runs `touch -d 2099-01-01` on the
        // cached `trusted_root.json` would then bypass the staleness
        // window indefinitely. We allow a small tolerance for legitimate
        // wall-clock skew (e.g. between an NFS server and the host) and
        // refuse anything beyond it as a hard error so callers can map
        // the case to a stable invariant.
        let tolerance = chrono::Duration::from_std(TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE)
            .unwrap_or_default();
        if anchor_ts > now + tolerance {
            return Err(TrustRootStalenessError::CacheFutureDated {
                anchor: anchor.diagnostic_label(),
                anchor_ts,
                now,
                tolerance_seconds: TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE.as_secs(),
            });
        }
        // F3 closure: use saturating millisecond arithmetic instead of
        // chrono's `now - anchor_ts` subtraction, which can produce
        // unexpected values near i64::MIN/MAX (e.g. an adversarially
        // crafted anchor near DateTime::MIN could underflow the i64
        // millisecond counter and produce a large positive duration that
        // falsely reports "not stale"). `saturating_sub` clamps to i64::MAX
        // (always-stale) on underflow and to 0 (not-stale) on overflow,
        // both of which are safe failure modes for this gate.
        let age_ms = now
            .timestamp_millis()
            .saturating_sub(anchor_ts.timestamp_millis());
        let max_age_ms = chrono::Duration::from_std(max_age)
            .unwrap_or(chrono::Duration::MAX)
            .num_milliseconds();
        Ok(age_ms > max_age_ms)
    }

    /// Convenience alias for [`Self::is_stale_at`] with the default
    /// operator policy ([`DEFAULT_MAX_TRUST_ROOT_AGE`]). Used by the
    /// Rekor live adapter (council Decision #2) to keep the call sites
    /// readable.
    pub fn is_stale(
        &self,
        now: DateTime<Utc>,
        anchor: TrustRootStalenessAnchor<'_>,
    ) -> Result<bool, TrustRootStalenessError> {
        self.is_stale_at(now, DEFAULT_MAX_TRUST_ROOT_AGE, anchor)
    }

    /// Convenience alias for [`Self::embedded`]. Used by the Rekor live
    /// adapter (council Decision #2) which was authored against the
    /// pre-merge shim API before Decision #1 landed.
    pub fn from_embedded() -> Result<Self, TrustedRootParseError> {
        Self::embedded()
    }

    /// Construct a single-tlog `TrustedRoot` from a fixture
    /// ECDSA P-256 SubjectPublicKeyInfo PEM. Test-only path used by
    /// adapter unit tests that synthesise their own Rekor receipts with
    /// a deterministic signing seed and need a matching verifying key
    /// out of the trust root. Activation is pinned to `signed_at` so
    /// the staleness gate can be exercised deterministically.
    ///
    /// `log_id` is the `logId.keyId` string the constructed tlog will
    /// declare. BH-3 fix
    /// (`docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md` Finding 3)
    /// requires log-bound key selection; pass the same string the
    /// fixture's Rekor receipt declares as `body.logID` so
    /// [`Self::rekor_verifying_key`] resolves the fixture key.
    #[cfg(any(test, feature = "test-support"))]
    pub fn from_fixture_rekor_pem(
        pem: &str,
        signed_at: DateTime<Utc>,
        log_id: &str,
    ) -> Result<Self, TrustedRootKeyError> {
        use base64::Engine;
        use p256::pkcs8::{DecodePublicKey, EncodePublicKey};

        let key = p256::ecdsa::VerifyingKey::from_public_key_pem(pem).map_err(|source| {
            TrustedRootKeyError::DecodeKey {
                reason: source.to_string(),
            }
        })?;
        let encoded = key
            .to_public_key_der()
            .map_err(|source| TrustedRootKeyError::DecodeKey {
                reason: source.to_string(),
            })?;
        let raw_b64 = base64::engine::general_purpose::STANDARD.encode(encoded.as_bytes());
        Ok(Self {
            media_type: "application/vnd.dev.sigstore.trustedroot+json;version=0.1".to_string(),
            tlogs: vec![TransparencyLogInstance {
                base_url: "https://rekor.test.fixture".to_string(),
                log_id: serde_json::json!({ "keyId": log_id }),
                hash_algorithm: serde_json::Value::String("SHA2_256".to_string()),
                public_key: TransparencyLogPublicKey {
                    raw_bytes: Some(raw_b64),
                    key_details: Some("PKIX_ECDSA_P256_SHA_256".to_string()),
                    valid_for: ValidityPeriod {
                        start: Some(signed_at),
                        end: None,
                    },
                    extra: serde_json::Map::new(),
                },
                log_index: serde_json::Value::Null,
                tree_id: serde_json::Value::Null,
                extra: serde_json::Map::new(),
            }],
            ctlogs: serde_json::Value::Null,
            certificate_authorities: serde_json::Value::Null,
            timestamp_authorities: serde_json::Value::Null,
        })
    }

    /// Best-effort signed-at accessor for the staleness gate.
    ///
    /// Falls back to the Unix epoch when no tlog activation is parseable —
    /// trust-root validation refuses that case earlier, so the fallback is
    /// only reachable when the operator deliberately constructs a trust
    /// root with no tlog. Callers that need to distinguish "no activation"
    /// from a real timestamp should use [`Self::metadata_signed_at`].
    #[must_use]
    pub fn signed_at(&self) -> DateTime<Utc> {
        self.metadata_signed_at()
            .unwrap_or_else(|| DateTime::<Utc>::from_timestamp(0, 0).expect("epoch is valid"))
    }

    /// Return the parsed ECDSA P-256 verifying key for the Rekor
    /// `SignedEntryTimestamp` signature **bound to the receipt's
    /// `body.logID`**.
    ///
    /// BH-3 fix (Finding 3 in
    /// `docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md`,
    /// Cosign GHSA-whqx-f9j3-ch6m class). The selector finds the tlog
    /// whose `logId.keyId` byte-decodes to the same value as the
    /// receipt's `body.logID`, then returns that tlog's ECDSA P-256
    /// public key. It does **not** silently fall back to a "latest
    /// activation" tlog when the logId is unknown — Sigstore's
    /// `trusted_root.json` declares multiple historical tlogs during
    /// rotation, each with a distinct `logId` and key; an entry signed
    /// by an older tlog (or a newly-added attacker-controlled tlog
    /// that wins the activation-date race) would otherwise be verified
    /// against the wrong key.
    ///
    /// Encoding: Sigstore's `logId.keyId` is base64 of the raw bytes
    /// (typically SHA-256(public_key_der)); Rekor's REST API returns
    /// `body.logID` as the same bytes in lowercase hex. The match
    /// function decodes both sides to bytes (preferring hex then
    /// base64 for the receipt, base64 then raw for the tlog id) and
    /// compares any pair for equality. Fixture log-ids that are
    /// neither hex nor base64 (e.g. the literal `"fixture-log-id"`
    /// used in unit tests) are matched on raw byte equality so the
    /// fixture surface keeps working without inflating the production
    /// matching rules.
    ///
    /// Fails closed with [`TrustedRootKeyError::TlogLogIdNoMatch`]
    /// (carrying the stable invariant
    /// [`REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT`]) when no
    /// declared tlog matches the receipt's logId, and with the
    /// existing [`TrustedRootKeyError`] variants when the matched
    /// tlog's `rawBytes` is missing or does not decode as DER
    /// SubjectPublicKeyInfo.
    pub fn rekor_verifying_key(
        &self,
        receipt_log_id: &str,
    ) -> Result<p256::ecdsa::VerifyingKey, TrustedRootKeyError> {
        use p256::pkcs8::DecodePublicKey;

        // 1. Filter to tlogs declaring ECDSA P-256 — Cortex does not
        //    yet accept Ed25519 Rekor signatures, so we must NOT pick
        //    an Ed25519 tlog even if its logId happened to match.
        let ecdsa_tlogs = self
            .tlogs
            .iter()
            .filter(|tlog| {
                tlog.public_key
                    .key_details
                    .as_deref()
                    .is_some_and(|details| details.contains("ECDSA_P256"))
            })
            .collect::<Vec<_>>();
        if ecdsa_tlogs.is_empty() {
            return Err(TrustedRootKeyError::NoEcdsaP256Tlog);
        }

        // 2. Of those, find the one whose `logId.keyId` matches the
        //    receipt's `body.logID`. No silent fall-back to "latest
        //    activation" — refusal is the explicit Cosign mitigation.
        let tlog = ecdsa_tlogs
            .into_iter()
            .find(|tlog| {
                tlog_log_id_key_id(&tlog.log_id)
                    .as_deref()
                    .is_some_and(|tlog_key_id| log_id_matches(tlog_key_id, receipt_log_id))
            })
            .ok_or_else(|| TrustedRootKeyError::TlogLogIdNoMatch {
                invariant: REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT,
                receipt_log_id: receipt_log_id.to_string(),
                tlog_log_ids: self
                    .tlogs
                    .iter()
                    .filter_map(|tlog| tlog_log_id_key_id(&tlog.log_id))
                    .collect(),
            })?;

        // 3. Decode the matched tlog's DER SPKI to a typed P-256
        //    VerifyingKey. Same fail-closed semantics as the previous
        //    implementation for the remaining branches.
        use base64::Engine;
        let raw_b64 = tlog
            .public_key
            .raw_bytes
            .as_deref()
            .ok_or(TrustedRootKeyError::MissingRawBytes)?;
        let der = base64::engine::general_purpose::STANDARD
            .decode(raw_b64)
            .map_err(|source| TrustedRootKeyError::Base64 {
                reason: source.to_string(),
            })?;
        p256::ecdsa::VerifyingKey::from_public_key_der(&der).map_err(|source| {
            TrustedRootKeyError::DecodeKey {
                reason: source.to_string(),
            }
        })
    }

    /// Atomically install this trusted root at `path`.
    ///
    /// Writes to a sibling temp file then renames into place so a partial
    /// write cannot leave a half-written trust root on disk for the next
    /// verify call to load.
    pub fn write_atomic(&self, path: impl AsRef<Path>) -> Result<(), TrustedRootIoError> {
        let path = path.as_ref();
        let parent = path.parent().unwrap_or_else(|| Path::new("."));
        std::fs::create_dir_all(parent).map_err(|source| TrustedRootIoError::Write {
            path: path.to_path_buf(),
            source,
        })?;
        let temp = path.with_extension("json.tmp");
        let body = serde_json::to_vec(self).map_err(|source| TrustedRootIoError::Serialize {
            path: path.to_path_buf(),
            source,
        })?;
        {
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&temp)
                .map_err(|source| TrustedRootIoError::Write {
                    path: temp.clone(),
                    source,
                })?;
            file.write_all(&body)
                .map_err(|source| TrustedRootIoError::Write {
                    path: temp.clone(),
                    source,
                })?;
            file.sync_all()
                .map_err(|source| TrustedRootIoError::Write {
                    path: temp.clone(),
                    source,
                })?;
        }
        std::fs::rename(&temp, path).map_err(|source| TrustedRootIoError::Write {
            path: path.to_path_buf(),
            source,
        })
    }
}

/// Bundle returned by [`active_trusted_root`] describing which root is in
/// force for the current verification call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveTrustedRoot {
    /// Parsed trust root currently in force.
    pub root: TrustedRoot,
    /// Stable status token: [`EMBEDDED_ROOT_STATUS`] when the embedded
    /// snapshot is in force, [`CACHED_ROOT_STATUS`] when a cached file
    /// was loaded.
    pub status: &'static str,
    /// Cache path that was inspected. `None` when the caller did not
    /// supply one.
    pub cache_path: Option<PathBuf>,
}

/// Resolve the active trusted root for verification: cached file if
/// present and parseable, embedded snapshot otherwise. The embedded
/// snapshot is the fail-closed floor.
pub fn active_trusted_root(
    cache_path: Option<&Path>,
) -> Result<ActiveTrustedRoot, TrustedRootIoError> {
    if let Some(path) = cache_path {
        if let Some(root) = TrustedRoot::load_cached(path)? {
            return Ok(ActiveTrustedRoot {
                root,
                status: CACHED_ROOT_STATUS,
                cache_path: Some(path.to_path_buf()),
            });
        }
    }
    let root = TrustedRoot::embedded().map_err(|source| TrustedRootIoError::Parse {
        path: PathBuf::from("<embedded>"),
        source,
    })?;
    Ok(ActiveTrustedRoot {
        root,
        status: EMBEDDED_ROOT_STATUS,
        cache_path: cache_path.map(Path::to_path_buf),
    })
}

/// Errors produced while parsing a `trusted_root.json` payload.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum TrustedRootParseError {
    /// Bytes did not parse as JSON in the Sigstore trust-root shape.
    #[error("malformed trusted_root.json: {reason}")]
    Malformed {
        /// Underlying serde decode message.
        reason: String,
    },
    /// `mediaType` did not start with the Sigstore trust-root prefix.
    #[error("trusted_root.json mediaType `{observed}` is not application/vnd.dev.sigstore.trustedroot+json")]
    WrongMediaType {
        /// `mediaType` value observed in the payload.
        observed: String,
    },
    /// Trust root declared zero Rekor tlogs.
    #[error("trusted_root.json has no Rekor tlogs declared")]
    EmptyTlogs,
    /// Trust root declared a tlog with no Rekor `baseUrl`.
    #[error("trusted_root.json tlog at index {tlog_index} is missing baseUrl")]
    MissingBaseUrl {
        /// Zero-based tlog index in the payload.
        tlog_index: usize,
    },
    /// Trust root declared a tlog with no `validFor.start` timestamp.
    #[error("trusted_root.json tlog at index {tlog_index} is missing publicKey.validFor.start")]
    MissingValidityStart {
        /// Zero-based tlog index in the payload.
        tlog_index: usize,
    },
}

/// Errors produced when reading or writing a cached trust root.
#[derive(Debug, Error)]
pub enum TrustedRootIoError {
    /// Cache file could not be read off disk.
    #[error("failed to read trusted_root.json {path:?}: {source}")]
    Read {
        /// Cache path that was being read.
        path: PathBuf,
        /// Underlying I/O failure.
        source: std::io::Error,
    },
    /// Cache file existed but did not parse.
    #[error("invalid trusted_root.json {path:?}: {source}")]
    Parse {
        /// Cache path that was being parsed.
        path: PathBuf,
        /// Underlying parse failure.
        source: TrustedRootParseError,
    },
    /// Cache file could not be serialised before write.
    #[error("failed to serialise trusted_root.json for {path:?}: {source}")]
    Serialize {
        /// Cache path that was being written.
        path: PathBuf,
        /// Underlying serde encode failure.
        source: serde_json::Error,
    },
    /// Cache file could not be written to disk.
    #[error("failed to write trusted_root.json {path:?}: {source}")]
    Write {
        /// Cache path that was being written.
        path: PathBuf,
        /// Underlying I/O failure.
        source: std::io::Error,
    },
}

/// Errors when extracting a typed Rekor verifying key from the active
/// trusted root.
#[derive(Debug, Error)]
pub enum TrustedRootKeyError {
    /// No transparency-log instance in the trusted root declared an
    /// ECDSA P-256 key. Cortex does not (yet) accept Ed25519 Rekor
    /// signatures.
    #[error("trusted_root.json has no ECDSA P-256 tlog entry")]
    NoEcdsaP256Tlog,
    /// No transparency-log instance declared a `logId.keyId` that
    /// matches the Rekor receipt's `body.logID`. Closes BH-3
    /// (`docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md` Finding 3,
    /// Cosign GHSA-whqx-f9j3-ch6m class). Refusal is structural — there
    /// is no silent fall-back to the latest-activated tlog.
    #[error(
        "{invariant}: trusted_root.json has no tlog whose logId.keyId matches Rekor receipt logID `{receipt_log_id}` (declared tlogs: {})",
        tlog_log_ids.join(", ")
    )]
    TlogLogIdNoMatch {
        /// Stable invariant token, equal to
        /// [`REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT`].
        invariant: &'static str,
        /// `body.logID` from the Rekor receipt that failed to bind.
        receipt_log_id: String,
        /// The tlog `logId.keyId` values declared in the trusted root,
        /// preserved verbatim from the JSON so operators can correlate
        /// with the Sigstore TUF history. Empty when every tlog
        /// omitted `logId.keyId`.
        tlog_log_ids: Vec<String>,
    },
    /// The selected tlog declared no `rawBytes` field for its
    /// `publicKey`. The verifier refuses to fall back to inferring keys
    /// from other channels.
    #[error("trusted_root.json tlog publicKey is missing rawBytes")]
    MissingRawBytes,
    /// `rawBytes` was present but did not decode as base64.
    #[error("trusted_root.json tlog publicKey rawBytes is not base64: {reason}")]
    Base64 {
        /// Underlying base64 decode failure.
        reason: String,
    },
    /// The decoded DER bytes did not parse as a P-256 SubjectPublicKeyInfo.
    #[error("trusted_root.json tlog publicKey did not decode as P-256 SPKI: {reason}")]
    DecodeKey {
        /// Underlying p256/pkcs8 failure.
        reason: String,
    },
}

/// Project a [`TransparencyLogInstance::log_id`] JSON value to its
/// `keyId` string, or `None` if the tlog declared no `logId.keyId`.
///
/// Sigstore's protobuf-go JSON encodes `LogId` as
/// `{"keyId": "<base64>"}`; we round-trip via `serde_json::Value` to
/// avoid binding the field shape on the trust-channel path. Returns
/// `None` for missing / non-string `keyId` rather than failing closed
/// here — the no-match branch in [`TrustedRoot::rekor_verifying_key`]
/// surfaces the verifier-visible refusal.
fn tlog_log_id_key_id(log_id: &serde_json::Value) -> Option<String> {
    log_id
        .as_object()?
        .get("keyId")
        .and_then(serde_json::Value::as_str)
        .map(str::to_string)
}

/// Match a trusted-root tlog `logId.keyId` against a Rekor receipt
/// `body.logID`. Returns `true` when the two encode the same byte
/// sequence.
///
/// Decoding rules (BH-3 fix + post-fd779d7 base64-url widening):
/// - The tlog side is canonically base64 per Sigstore's protobuf-JSON
///   shape. Both STANDARD (`+/`, padded) and URL-safe (`-_`, padded
///   or unpadded) alphabets are accepted, because proto3 JSON encodes
///   binary fields as URL-safe base64 (RFC 7515 §2) — the doctrine
///   reference cited by the previous docstring. Raw bytes equality
///   is also accepted for fixtures that pre-date the BH-3 fix and
///   stash a human-readable string.
/// - The receipt side is canonically lowercase hex per Rekor's REST
///   API; we also accept STANDARD and URL-safe base64 for receipt
///   sources that emit the protobuf-JSON shape, and raw bytes
///   equality for fixtures.
///
/// Match holds when ANY candidate byte vector on the tlog side equals
/// ANY candidate byte vector on the receipt side.
fn log_id_matches(tlog_key_id: &str, receipt_log_id: &str) -> bool {
    use base64::Engine;
    let b64_std = base64::engine::general_purpose::STANDARD;
    let b64_url = base64::engine::general_purpose::URL_SAFE;
    let b64_url_nopad = base64::engine::general_purpose::URL_SAFE_NO_PAD;

    let mut tlog_candidates: Vec<Vec<u8>> = Vec::with_capacity(4);
    if let Ok(bytes) = b64_std.decode(tlog_key_id) {
        tlog_candidates.push(bytes);
    }
    if let Ok(bytes) = b64_url.decode(tlog_key_id) {
        tlog_candidates.push(bytes);
    }
    if let Ok(bytes) = b64_url_nopad.decode(tlog_key_id) {
        tlog_candidates.push(bytes);
    }
    tlog_candidates.push(tlog_key_id.as_bytes().to_vec());

    let mut receipt_candidates: Vec<Vec<u8>> = Vec::with_capacity(5);
    if let Ok(bytes) = decode_lowercase_hex(receipt_log_id) {
        receipt_candidates.push(bytes);
    }
    if let Ok(bytes) = b64_std.decode(receipt_log_id) {
        receipt_candidates.push(bytes);
    }
    if let Ok(bytes) = b64_url.decode(receipt_log_id) {
        receipt_candidates.push(bytes);
    }
    if let Ok(bytes) = b64_url_nopad.decode(receipt_log_id) {
        receipt_candidates.push(bytes);
    }
    receipt_candidates.push(receipt_log_id.as_bytes().to_vec());

    for tlog_bytes in &tlog_candidates {
        for receipt_bytes in &receipt_candidates {
            if tlog_bytes == receipt_bytes {
                return true;
            }
        }
    }
    false
}

/// Decode a lowercase ASCII hex string to bytes. Returns `Err(())` on
/// any non-hex character or odd length. Kept local to this module so
/// the BH-3 matcher does not pull a hex decoder transitively into the
/// trust-channel path.
fn decode_lowercase_hex(s: &str) -> Result<Vec<u8>, ()> {
    if s.is_empty() || s.len() % 2 != 0 {
        return Err(());
    }
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(s.len() / 2);
    for chunk in bytes.chunks_exact(2) {
        let hi = hex_nibble(chunk[0])?;
        let lo = hex_nibble(chunk[1])?;
        out.push((hi << 4) | lo);
    }
    Ok(out)
}

fn hex_nibble(b: u8) -> Result<u8, ()> {
    match b {
        b'0'..=b'9' => Ok(b - b'0'),
        b'a'..=b'f' => Ok(10 + b - b'a'),
        _ => Err(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;
    use tempfile::tempdir;

    #[test]
    fn embedded_root_parses_and_has_rekor_tlogs() {
        let root = TrustedRoot::embedded().expect("embedded root parses");
        assert!(root
            .media_type
            .starts_with("application/vnd.dev.sigstore.trustedroot+json"));
        assert!(!root.tlogs.is_empty(), "embedded root must declare tlogs");
        let signed_at = root
            .metadata_signed_at()
            .expect("embedded root has a validity start");
        // Sanity floor: the embedded snapshot must carry a tlog
        // activation after the Sigstore v1 launch.
        let v1_launch = Utc.with_ymd_and_hms(2021, 1, 1, 0, 0, 0).unwrap();
        assert!(
            signed_at >= v1_launch,
            "tlog start {signed_at} predates v1 launch"
        );
    }

    fn embedded_snapshot_anchor_date() -> DateTime<Utc> {
        NaiveDate::parse_from_str(EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE, "%Y-%m-%d")
            .expect("EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE parses")
            .and_hms_opt(0, 0, 0)
            .expect("midnight is valid")
            .and_utc()
    }

    #[test]
    fn fresh_root_is_not_stale_within_30_days_against_embedded_snapshot_anchor() {
        let root = TrustedRoot::embedded().unwrap();
        let anchor = embedded_snapshot_anchor_date();
        let now = anchor + chrono::Duration::days(29);
        let stale = root
            .is_stale_at(
                now,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::embedded_snapshot(),
            )
            .expect("anchor resolves");
        assert!(!stale);
    }

    #[test]
    fn root_is_stale_after_31_days_against_embedded_snapshot_anchor() {
        let root = TrustedRoot::embedded().unwrap();
        let anchor = embedded_snapshot_anchor_date();
        let now = anchor + chrono::Duration::days(31);
        let stale = root
            .is_stale_at(
                now,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::embedded_snapshot(),
            )
            .expect("anchor resolves");
        assert!(stale);
    }

    #[test]
    fn cache_mtime_anchor_resolves_to_file_mtime() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("trusted_root.json");
        let root = TrustedRoot::embedded().unwrap();
        root.write_atomic(&path).unwrap();
        let now = Utc::now();
        let old_mtime = now - chrono::Duration::days(40);
        let mtime_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(old_mtime.timestamp() as u64);
        std::fs::File::options()
            .write(true)
            .open(&path)
            .unwrap()
            .set_modified(mtime_systemtime)
            .expect("set mtime");
        let stale = root
            .is_stale_at(
                now,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::cache_file_mtime(&path),
            )
            .expect("anchor resolves");
        assert!(stale, "40-day-old cache must be stale");
    }

    #[test]
    fn cache_mtime_anchor_fails_loud_when_cache_missing() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("does-not-exist.json");
        let root = TrustedRoot::embedded().unwrap();
        let err = root
            .is_stale_at(
                Utc::now(),
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::cache_file_mtime(&path),
            )
            .unwrap_err();
        assert!(matches!(err, TrustRootStalenessError::CacheMetadata { .. }));
    }

    // -----------------------------------------------------------------
    // Prior F3 closure
    // (`docs/reviews/CODE_REVIEW_2026-05-12_post_fd779d7.md`):
    // a future-dated cache `mtime` (e.g. via `touch -d 2099-01-01`)
    // used to bypass the freshness gate because `now - mtime` went
    // negative and the `> max_age` comparison stayed false
    // indefinitely. `is_stale_at` now refuses with
    // `TrustRootStalenessError::CacheFutureDated` when the anchor
    // is more than [`TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE`]
    // ahead of `now`.
    // -----------------------------------------------------------------

    fn write_cache_with_systemtime(path: &Path, mtime: std::time::SystemTime) {
        let root = TrustedRoot::embedded().unwrap();
        root.write_atomic(path).unwrap();
        std::fs::File::options()
            .write(true)
            .open(path)
            .unwrap()
            .set_modified(mtime)
            .expect("set mtime");
    }

    #[test]
    fn cache_mtime_anchor_refuses_far_future_dated_cache() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("trusted_root.json");
        let now = Utc::now();
        // 70 years ahead — the original Bug 3 attack shape
        // (`touch -d 2099-01-01`).
        let future = now + chrono::Duration::days(365 * 70);
        let future_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(future.timestamp() as u64);
        write_cache_with_systemtime(&path, future_systemtime);
        let root = TrustedRoot::embedded().unwrap();
        let err = root
            .is_stale_at(
                now,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::cache_file_mtime(&path),
            )
            .unwrap_err();
        match err {
            TrustRootStalenessError::CacheFutureDated {
                anchor,
                tolerance_seconds,
                ..
            } => {
                assert!(
                    anchor.contains("cache_file_mtime"),
                    "diagnostic label must name the cache_file_mtime anchor: got {anchor}"
                );
                assert_eq!(
                    tolerance_seconds,
                    TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE.as_secs(),
                );
            }
            other => panic!("expected CacheFutureDated, got {other:?}"),
        }
    }

    #[test]
    fn cache_mtime_anchor_tolerates_small_clock_skew() {
        // The future-dated guard allows a small tolerance for legitimate
        // wall-clock skew between an NFS server and the host. An mtime
        // that is `TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE / 2` ahead
        // of `now` must still pass.
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("trusted_root.json");
        let now = Utc::now();
        let half_tolerance = chrono::Duration::seconds(
            (TRUSTED_ROOT_CACHE_FUTURE_MTIME_TOLERANCE.as_secs() / 2) as i64,
        );
        let skewed = now + half_tolerance;
        let skewed_systemtime = std::time::SystemTime::UNIX_EPOCH
            + std::time::Duration::from_secs(skewed.timestamp() as u64);
        write_cache_with_systemtime(&path, skewed_systemtime);
        let root = TrustedRoot::embedded().unwrap();
        let stale = root
            .is_stale_at(
                now,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::cache_file_mtime(&path),
            )
            .expect("small skew must not trigger the future-dated guard");
        // A fresh-mtime cache must NOT be reported as stale.
        assert!(!stale);
    }

    // ---------------------------------------------------------------
    // F3 closure (new finding, adversarial review post-fd779d7):
    // chrono Duration arithmetic near i64 overflow can produce
    // unexpected values. `is_stale_at` now uses saturating millisecond
    // arithmetic instead of `now - anchor_ts`. Drive the boundary by
    // constructing an anchor_ts that is exactly at `now`; the saturated
    // age_ms must be 0 and the root must NOT be reported as stale.
    // ---------------------------------------------------------------
    #[test]
    fn is_stale_at_saturates_instead_of_panic_on_backward_clock() {
        // Scenario: anchor_ts == now (age_ms == 0 after saturating_sub).
        // Stale must return false regardless of max_age.
        let root = TrustedRoot::embedded().unwrap();
        let anchor_date = embedded_snapshot_anchor_date();
        // Set now == anchor so the saturated age is 0 ms.
        let now = anchor_date;
        let stale = root
            .is_stale_at(
                now,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::embedded_snapshot(),
            )
            .expect("anchor resolves");
        assert!(
            !stale,
            "age_ms == 0 must never be stale; saturating_sub must clamp at 0 not wrap"
        );

        // Edge: anchor very slightly in the past (1 ms) — within the
        // max-age window — must also be not-stale.
        let just_before = anchor_date - chrono::Duration::milliseconds(1);
        let stale_edge = root
            .is_stale_at(
                anchor_date,
                DEFAULT_MAX_TRUST_ROOT_AGE,
                TrustRootStalenessAnchor::EmbeddedSnapshotDate {
                    snapshot_iso_date: EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE,
                },
            )
            .expect("anchor resolves");
        // `anchor_date - anchor_date` == 0 ms < 30d → not stale
        assert!(!stale_edge);
        let _ = just_before; // suppress unused-variable warning
    }

    #[test]
    fn trusted_root_cache_future_dated_invariant_token_is_stable() {
        assert_eq!(
            STABLE_INVARIANT_TRUSTED_ROOT_CACHE_FUTURE_DATED,
            "audit.verify.trusted_root.cache_future_dated"
        );
    }

    // 2026-05-15 portfolio-extension wave 2 invariant-coverage audit: pin the
    // stable invariant strings emitted by the three trusted-root staleness
    // branches so a string-level dashboards-and-grep regression is caught at
    // unit-test time, not from a flaky end-to-end consumer. The actual emit
    // sites live in `cortex-cli`'s audit verify path
    // (`crates/cortex-cli/src/cmd/audit.rs`), but the invariant constants are
    // the carrier identity that downstream wrappers key on.
    #[test]
    fn trusted_root_staleness_invariant_tokens_are_stable() {
        assert_eq!(
            TRUSTED_ROOT_STALE_INVARIANT,
            "audit.verify.trusted_root.stale_beyond_max_age"
        );
        assert_eq!(
            TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT,
            "audit.verify.trusted_root.snapshot_stale"
        );
        assert_eq!(
            TRUSTED_ROOT_CACHE_STALE_INVARIANT,
            "audit.verify.trusted_root.cache_stale"
        );
        // The branch-specific tokens MUST NOT collide with the generic
        // back-compat token; consumers route on the branch-specific token
        // FIRST and fall back to the generic one for legacy dashboards.
        assert_ne!(
            TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT, TRUSTED_ROOT_STALE_INVARIANT,
            "snapshot_stale token must differ from the generic back-compat token"
        );
        assert_ne!(
            TRUSTED_ROOT_CACHE_STALE_INVARIANT, TRUSTED_ROOT_STALE_INVARIANT,
            "cache_stale token must differ from the generic back-compat token"
        );
        assert_ne!(
            TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT, TRUSTED_ROOT_CACHE_STALE_INVARIANT,
            "snapshot_stale and cache_stale tokens must be distinct branches"
        );
    }

    // 2026-05-15 wave-2 invariant-coverage audit: drive the embedded-snapshot
    // staleness predicate to fire, then assert the invariant constant the
    // audit-verify CLI emit site keys on
    // (`crates/cortex-cli/src/cmd/audit.rs::1138`) carries the stable token.
    // CLI-level integration emit requires `Utc::now() > snapshot+30d`, which
    // is not driveable from a deterministic test; this unit test pins the
    // emit precondition (is_stale returns true) AND the surface string the
    // CLI feeds to `eprintln!` so a string-level regression cannot land
    // silently.
    #[test]
    fn embedded_snapshot_stale_emit_precondition_pins_invariant_token() {
        let root = TrustedRoot::embedded().expect("embedded root parses");
        let anchor = embedded_snapshot_anchor_date();
        // Drive the same condition the CLI audit-verify emit site checks:
        // `TrustedRoot::embedded().is_stale(now, embedded_snapshot())`. Use
        // a far-future `now` so the staleness predicate must fire even when
        // the embedded snapshot has just been refreshed.
        let now = anchor + chrono::Duration::days(31);
        let stale = root
            .is_stale(now, TrustRootStalenessAnchor::embedded_snapshot())
            .expect("anchor resolves");
        assert!(
            stale,
            "embedded snapshot must be stale once now > snapshot+30d"
        );
        // Pin the surface string the CLI emit site feeds to `eprintln!` so
        // a refactor that renames the constant breaks at unit-test time.
        assert_eq!(
            TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT, "audit.verify.trusted_root.snapshot_stale",
            "CLI audit-verify emit site keys on this exact stable token"
        );
        // The CLI emit site surfaces BOTH the branch-specific token and the
        // legacy generic token so existing dashboards keep working. Pin
        // that companion token here as well.
        assert_eq!(
            TRUSTED_ROOT_STALE_INVARIANT,
            "audit.verify.trusted_root.stale_beyond_max_age"
        );
    }

    // 2026-05-15 wave-2 invariant-coverage audit, negative companion: when
    // the embedded snapshot is fresh (now within snapshot+30d), the
    // staleness predicate MUST return false so the CLI emit site does NOT
    // surface the `snapshot_stale` invariant. Pairs with
    // `embedded_snapshot_stale_emit_precondition_pins_invariant_token`.
    #[test]
    fn embedded_snapshot_not_stale_emit_precondition_holds_within_30d() {
        let root = TrustedRoot::embedded().expect("embedded root parses");
        let anchor = embedded_snapshot_anchor_date();
        let now = anchor + chrono::Duration::days(29);
        let stale = root
            .is_stale(now, TrustRootStalenessAnchor::embedded_snapshot())
            .expect("anchor resolves");
        assert!(
            !stale,
            "embedded snapshot must NOT be stale within snapshot+30d; \
             CLI emit site for `{TRUSTED_ROOT_SNAPSHOT_STALE_INVARIANT}` must stay silent"
        );
    }

    #[test]
    fn parse_rejects_wrong_media_type() {
        let body = serde_json::json!({
            "mediaType": "application/json",
            "tlogs": [],
        });
        let err = TrustedRoot::parse_bytes(body.to_string().as_bytes()).unwrap_err();
        assert!(matches!(err, TrustedRootParseError::WrongMediaType { .. }));
    }

    #[test]
    fn parse_rejects_empty_tlogs() {
        let body = serde_json::json!({
            "mediaType": "application/vnd.dev.sigstore.trustedroot+json;version=0.1",
            "tlogs": [],
        });
        let err = TrustedRoot::parse_bytes(body.to_string().as_bytes()).unwrap_err();
        assert_eq!(err, TrustedRootParseError::EmptyTlogs);
    }

    #[test]
    fn parse_rejects_tlog_without_validity_start() {
        let body = serde_json::json!({
            "mediaType": "application/vnd.dev.sigstore.trustedroot+json;version=0.1",
            "tlogs": [{
                "baseUrl": "https://rekor.sigstore.dev",
                "publicKey": {
                    "rawBytes": "AAAA",
                    "validFor": {}
                }
            }]
        });
        let err = TrustedRoot::parse_bytes(body.to_string().as_bytes()).unwrap_err();
        assert!(matches!(
            err,
            TrustedRootParseError::MissingValidityStart { tlog_index: 0 }
        ));
    }

    #[test]
    fn load_cached_returns_none_for_missing_path() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("does-not-exist.json");
        let result = TrustedRoot::load_cached(&path).expect("missing path returns Ok(None)");
        assert!(result.is_none());
    }

    #[test]
    fn load_cached_returns_some_for_valid_file() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("trusted_root.json");
        let root = TrustedRoot::embedded().unwrap();
        root.write_atomic(&path).unwrap();
        let loaded = TrustedRoot::load_cached(&path).unwrap().unwrap();
        assert_eq!(loaded.media_type, root.media_type);
    }

    #[test]
    fn write_atomic_replaces_existing_file() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("trusted_root.json");
        std::fs::write(&path, b"old garbage").unwrap();
        let root = TrustedRoot::embedded().unwrap();
        root.write_atomic(&path).unwrap();
        let loaded = TrustedRoot::load_cached(&path).unwrap().unwrap();
        assert_eq!(loaded.media_type, root.media_type);
    }

    #[test]
    fn active_trusted_root_prefers_cache_then_embedded() {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("trusted_root.json");

        let active = active_trusted_root(Some(&path)).expect("missing cache falls back");
        assert_eq!(active.status, EMBEDDED_ROOT_STATUS);
        assert_eq!(active.cache_path.as_deref(), Some(path.as_path()));

        let root = TrustedRoot::embedded().unwrap();
        root.write_atomic(&path).unwrap();
        let active = active_trusted_root(Some(&path)).unwrap();
        assert_eq!(active.status, CACHED_ROOT_STATUS);
    }

    #[test]
    fn missing_embedded_snapshot_date_constant_fails_loud() {
        // The anchor-resolution path surfaces a typed error rather than
        // silently treating the root as stale when the constant is
        // malformed. Build-time guard.
        let root = TrustedRoot::embedded().unwrap();
        let anchor = TrustRootStalenessAnchor::EmbeddedSnapshotDate {
            snapshot_iso_date: "not-a-date",
        };
        let err = root
            .is_stale_at(Utc::now(), DEFAULT_MAX_TRUST_ROOT_AGE, anchor)
            .unwrap_err();
        assert!(matches!(
            err,
            TrustRootStalenessError::MalformedEmbeddedSnapshotDate { .. }
        ));
    }

    // ---------------------------------------------------------------
    // F2 pin: embedded snapshot date constant must match the embedded
    // `include_bytes!` filename.
    //
    // The constant is now derived at build time by `build.rs` from the
    // filename. These tests are the runtime restatement of the
    // invariant — they enumerate `src/external_sink/embedded/*.json` at
    // test time and assert exactly one matches
    // `sigstore_trusted_root_YYYY-MM-DD.json` AND the embedded date
    // string equals [`EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`].
    //
    // `cargo test` runs with CWD = the crate root, so the relative path
    // resolves identically to the build script's `read_dir`.
    // ---------------------------------------------------------------

    fn discover_embedded_snapshot_filename() -> (String, String) {
        // Returns (filename, date).
        let dir = std::path::Path::new("src/external_sink/embedded");
        let mut matches: Vec<(String, String)> = Vec::new();
        for entry in std::fs::read_dir(dir)
            .expect("embedded directory readable from crate-root CWD during cargo test")
        {
            let entry = entry.expect("read_dir entry");
            let name_os = entry.file_name();
            let name = match name_os.to_str() {
                Some(s) => s.to_string(),
                None => continue,
            };
            if let Some(date_and_suffix) = name.strip_prefix("sigstore_trusted_root_") {
                if let Some(date) = date_and_suffix.strip_suffix(".json") {
                    matches.push((name.clone(), date.to_string()));
                }
            }
        }
        assert_eq!(
            matches.len(),
            1,
            "embedded directory must contain exactly one sigstore_trusted_root_YYYY-MM-DD.json, found: {matches:?}"
        );
        matches.into_iter().next().unwrap()
    }

    #[test]
    fn embedded_snapshot_date_constant_matches_embedded_filename() {
        // F2 pin: the build-derived constant equals the date encoded in
        // the on-disk filename. If the filename is bumped without the
        // build rerunning (or vice versa), this assert fails.
        let (filename, date) = discover_embedded_snapshot_filename();
        assert_eq!(
            EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE, date,
            "EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE = `{EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE}` but embedded filename `{filename}` encodes date `{date}`"
        );
    }

    #[test]
    fn embedded_filename_pin_is_documented() {
        // Inert pin: documents that the constant is derived from the
        // filename via `build.rs`. If `EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE`
        // ever stops compiling, this test name is the breadcrumb to the
        // build script.
        assert!(
            EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE.len() == 10
                && EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE.as_bytes()[4] == b'-'
                && EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE.as_bytes()[7] == b'-',
            "EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE must be YYYY-MM-DD; got `{EMBEDDED_TRUSTED_ROOT_SNAPSHOT_DATE}`"
        );
    }

    // ---------------------------------------------------------------
    // BH-3: rekor_verifying_key MUST be log-bound (Cosign
    // GHSA-whqx-f9j3-ch6m mitigation). Test the matcher and the
    // selector contract directly.
    // ---------------------------------------------------------------

    /// Synthesize a trust root with a chosen log_id keyId for testing
    /// the log-bound selector. Uses a deterministic ECDSA P-256 PEM so
    /// the test does not need a fixture file.
    fn synth_trust_root_with_log_id(log_id_key_id: &str, signed_at: DateTime<Utc>) -> TrustedRoot {
        // A throwaway ECDSA P-256 public key in PEM form. Generated
        // offline and pinned here so the test has no live key-gen
        // dependency. The bytes do not need to verify any signature —
        // we only exercise the selector logic.
        const PEM: &str = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE38RLcWzg03IUsJCRqVqTfrIsrZ16\n9knDnAIDtWs7oSxtQ7vlFDJwBMsFiyufFcxRRXotLozXlslNcujXkKAdzQ==\n-----END PUBLIC KEY-----\n";
        TrustedRoot::from_fixture_rekor_pem(PEM, signed_at, log_id_key_id)
            .expect("fixture key parses")
    }

    #[test]
    fn rekor_verifying_key_returns_key_for_matching_logid() {
        let signed_at = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let root = synth_trust_root_with_log_id("my-fixture-log-id", signed_at);
        // Same raw string on both sides: matches via the raw-bytes
        // fallback branch.
        root.rekor_verifying_key("my-fixture-log-id")
            .expect("matching log_id resolves to a verifying key");
    }

    #[test]
    fn rekor_verifying_key_refuses_when_no_tlog_matches_receipt_logid() {
        let signed_at = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let root = synth_trust_root_with_log_id("trust-root-log-id", signed_at);
        let err = root
            .rekor_verifying_key("a-different-receipt-log-id")
            .unwrap_err();
        match err {
            TrustedRootKeyError::TlogLogIdNoMatch {
                invariant,
                receipt_log_id,
                tlog_log_ids,
            } => {
                assert_eq!(invariant, REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT);
                assert_eq!(receipt_log_id, "a-different-receipt-log-id");
                assert_eq!(tlog_log_ids, vec!["trust-root-log-id".to_string()]);
            }
            other => panic!("expected TlogLogIdNoMatch, got {other:?}"),
        }
    }

    #[test]
    fn rekor_verifying_key_does_not_silently_fall_back_to_latest_when_logid_unknown() {
        // Construct a multi-tlog trust root: a recent (would-win the
        // "latest activation" race) one with a non-matching log_id and
        // an older one with the matching log_id. The selector MUST
        // pick the matching one — and if the matching one is removed,
        // it MUST refuse, NOT silently fall back to "latest".
        let old = Utc.with_ymd_and_hms(2021, 1, 1, 0, 0, 0).unwrap();
        let recent = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
        let matching_log_id = "matching-log-id";
        let _decoy_log_id = "decoy-but-newer-log-id";

        // First, baseline: matching log_id present + decoy → matches,
        // verifying key returned.
        let mut root = synth_trust_root_with_log_id(matching_log_id, old);
        // Append the decoy tlog (recent activation, different log_id).
        const PEM2: &str = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE38RLcWzg03IUsJCRqVqTfrIsrZ16\n9knDnAIDtWs7oSxtQ7vlFDJwBMsFiyufFcxRRXotLozXlslNcujXkKAdzQ==\n-----END PUBLIC KEY-----\n";
        let decoy_root =
            TrustedRoot::from_fixture_rekor_pem(PEM2, recent, "decoy-but-newer-log-id")
                .expect("decoy tlog parses");
        root.tlogs.extend(decoy_root.tlogs);
        // Matching path: still resolves.
        root.rekor_verifying_key(matching_log_id)
            .expect("log-bound selector picks the matching (older) tlog despite a newer decoy");

        // Now: drop the matching tlog, leave only the decoy. Receipt
        // logId still references the now-absent log_id. The selector
        // MUST refuse, NOT fall back to the decoy on activation date.
        let only_decoy = TrustedRoot {
            media_type: root.media_type.clone(),
            tlogs: root
                .tlogs
                .iter()
                .filter(|tlog| tlog_log_id_key_id(&tlog.log_id).as_deref() != Some(matching_log_id))
                .cloned()
                .collect(),
            certificate_authorities: root.certificate_authorities.clone(),
            ctlogs: root.ctlogs.clone(),
            timestamp_authorities: root.timestamp_authorities.clone(),
        };
        assert_eq!(
            only_decoy.tlogs.len(),
            1,
            "decoy-only root must have exactly one tlog"
        );
        let err = only_decoy.rekor_verifying_key(matching_log_id).unwrap_err();
        assert!(
            matches!(
                err,
                TrustedRootKeyError::TlogLogIdNoMatch {
                    invariant: REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT,
                    ..
                }
            ),
            "selector silently fell back to a non-matching tlog instead of refusing; got {err:?}"
        );
    }

    #[test]
    fn log_id_matches_decodes_hex_against_base64() {
        // Realistic Sigstore case: the trust root's logId.keyId is
        // base64-encoded raw bytes; the Rekor receipt's logID is the
        // same bytes in lowercase hex. The matcher must equate them.
        use base64::Engine;
        let key_id_bytes: [u8; 32] = [
            0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
            0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x10, 0x20, 0x30, 0x40,
            0x50, 0x60, 0x70, 0x80,
        ];
        let b64 = base64::engine::general_purpose::STANDARD.encode(key_id_bytes);
        let hex: String = key_id_bytes.iter().map(|b| format!("{b:02x}")).collect();
        assert!(log_id_matches(&b64, &hex));
        // And a deliberate mismatch must not match.
        let mut tampered = key_id_bytes;
        tampered[0] ^= 0x01;
        let tampered_hex: String = tampered.iter().map(|b| format!("{b:02x}")).collect();
        assert!(!log_id_matches(&b64, &tampered_hex));
    }

    /// post-fd779d7 LOW closure: proto3-JSON receipts encode binary
    /// fields with URL-safe base64 (RFC 7515 §2 — `-_` alphabet),
    /// not STANDARD base64 (`+/`). The matcher must accept both
    /// alphabets so a tlog `keyId` carried over a protobuf-JSON wire
    /// path matches a receipt `logID` carried over either wire path.
    /// Bytes containing `0x3e` (`>` in raw) encode to a `+` (STANDARD)
    /// or a `-` (URL-safe), which makes them a faithful regression
    /// fixture for the difference between the two alphabets.
    #[test]
    fn log_id_matches_accepts_url_safe_base64_both_sides() {
        use base64::Engine;
        // Bytes chosen so STANDARD and URL-safe encodings differ
        // (the `0x3e`/`0x3f` nibble combos exercise both `+/` and
        // `-_` alphabets distinctly).
        let key_id_bytes: [u8; 32] = [
            0xfb, 0xff, 0xbf, 0xfe, 0x3e, 0x3f, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
            0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50,
            0x60, 0x70, 0x80, 0x90,
        ];
        let b64_std = base64::engine::general_purpose::STANDARD.encode(key_id_bytes);
        let b64_url = base64::engine::general_purpose::URL_SAFE.encode(key_id_bytes);
        let b64_url_nopad = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(key_id_bytes);
        let hex: String = key_id_bytes.iter().map(|b| format!("{b:02x}")).collect();

        // Sanity: STANDARD and URL-safe encodings must actually differ
        // for these bytes (otherwise this test would be vacuous).
        assert_ne!(
            b64_std, b64_url,
            "fixture bytes were chosen so the two alphabets differ; if they match the test is vacuous",
        );

        // tlog side STANDARD vs receipt side URL-safe.
        assert!(log_id_matches(&b64_std, &b64_url));
        // tlog side URL-safe vs receipt side STANDARD.
        assert!(log_id_matches(&b64_url, &b64_std));
        // tlog side URL-safe (no padding) vs receipt side hex.
        assert!(log_id_matches(&b64_url_nopad, &hex));
        // tlog side URL-safe vs receipt side URL-safe (no padding).
        assert!(log_id_matches(&b64_url, &b64_url_nopad));

        // Tampered URL-safe receipt still refuses.
        let mut tampered = key_id_bytes;
        tampered[0] ^= 0x01;
        let tampered_url = base64::engine::general_purpose::URL_SAFE.encode(tampered);
        assert!(!log_id_matches(&b64_std, &tampered_url));
    }
}