enclavia-protocol 0.1.0

Shared wire types and Noise+CBOR responder helpers used by the Enclavia server, router, and SDK.
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
//! Per-enclave public upgrade chain: shared types + pure validation.
//!
//! The chain is the user-facing audit trail of every transition an
//! enclave has been through, exposed by the backend as
//! `GET /enclaves/{id}/upgrade-chain` (unauthenticated). The same
//! validation that gates ingest server-side is what an SDK consumer
//! needs to walk the chain and convince themselves it is consistent;
//! both surfaces share this module so behaviour cannot drift.
//!
//! Three link kinds in v1:
//!
//! * [`ChainLinkKind::Boot`] — one per successful boot of a new image
//!   digest. Payload binds `pcrs / image_digest / enclave_id /
//!   booted_at / nonce`. The attestation's `user_data` is
//!   `sha256(payload)` (checked by [`super::attestation::verify_chain_attestation`]).
//! * [`ChainLinkKind::Upgrade`] — emitted by the OLD enclave after the
//!   backend signs and ships a `PrepareUpgrade` control command.
//!   Payload binds `from_pcrs / to_pcrs / image_digest / valid_from /
//!   issued_at / nonce`. The link's `signature` is the backend's
//!   ECDSA P-256 sig over the payload, verifiable against the enclave's
//!   baked-in control pubkey.
//! * [`ChainLinkKind::Revocation`] — emitted by the OLD enclave on a
//!   pre-activation revoke. Payload binds the chain entry id being
//!   cancelled + `issued_at / nonce`. Same signature treatment as
//!   upgrade.
//!
//! Non-upgradable enclaves can only ever produce a single Boot entry
//! (the genesis). [`validate_chain_link`] rejects upgrade / revocation
//! outright on those (no control pubkey to verify against, no upgrade
//! flow), and rejects a second boot that would change `image_digest`.
//!
//! The wire shape diverges slightly from the original issue body, which
//! described the chain as carrying no signature. We include one on
//! upgrade / revocation as defence-in-depth: a forged link injected by
//! a tampered host-side daemon would carry no valid signature.

use base64::Engine as _;
use chrono::{DateTime, Utc};
use p256::ecdsa::{Signature, VerifyingKey, signature::Verifier};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::attestation::{AttestationError, Pcrs, verify_chain_attestation};

/// Kind of a chain entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChainLinkKind {
    Boot,
    Upgrade,
    Revocation,
}

/// One entry in an enclave's public chain. The opaque byte fields are
/// the same shape on the wire (base64 in the API JSON) and at rest
/// (raw bytes in the backend DB) — this struct is the canonical
/// representation either way.
///
/// `id` and `sequence` are assigned by the backend at insert time;
/// in-flight links being validated for the FIRST time will not have
/// them populated. Use [`ChainLink::with_assignment`] to attach them
/// after validation returns [`Outcome::Append`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChainLink {
    /// Backend-assigned UUID. Absent on inbound (pre-ingest) links;
    /// populated on every link returned by the public read endpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<Uuid>,
    /// Per-enclave monotonic ordering, starts at 0. Absent on inbound
    /// links — the backend computes it at validation time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sequence: Option<u64>,
    pub kind: ChainLinkKind,
    /// CBOR-encoded payload. Decode against the kind-specific struct:
    /// [`BootPayload`] / [`UpgradePayload`] / [`RevocationPayload`].
    #[serde(with = "serde_bytes")]
    pub payload: Vec<u8>,
    /// COSE_Sign1 attestation document. `user_data == sha256(payload)`.
    #[serde(with = "serde_bytes")]
    pub attestation: Vec<u8>,
    /// 64-byte raw `r || s` ECDSA P-256 signature over `payload` under
    /// the enclave's control private key. Required for upgrade /
    /// revocation, absent on boot.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "serde_bytes_opt"
    )]
    pub signature: Option<Vec<u8>>,
}

/// `serde_bytes`-like adapter that handles `Option<Vec<u8>>` cleanly.
/// (`serde_bytes` requires Vec<u8> directly; without this, an Option
/// would round-trip through serde's default sequence representation
/// and break interop with the backend's DB-side BYTEA column.)
mod serde_bytes_opt {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, ser: S) -> Result<S::Ok, S::Error> {
        match v {
            Some(bytes) => serde_bytes::Bytes::new(bytes).serialize(ser),
            None => ser.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Option<Vec<u8>>, D::Error> {
        Option::<serde_bytes::ByteBuf>::deserialize(de).map(|o| o.map(|b| b.into_vec()))
    }
}

/// JSON wire shape of a chain link on the public `GET
/// /enclaves/{id}/upgrade-chain` route. The opaque byte fields are
/// carried as base64 strings here (vs. the raw-bytes [`ChainLink`] used
/// at rest and inside the validator). Consumed by the CLI today and,
/// eventually, by the backend + chain-host so all three surfaces share
/// one definition.
///
/// `payload`, `attestation`, and `signature` are standard base64 with
/// padding. Decode them before handing the bytes to [`validate_chain_link`]
/// for re-verification.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChainLinkJson {
    /// Assigned by the backend on insert; absent on the wire shape
    /// `chain-host` sends to the ingest route.
    #[serde(default)]
    pub id: Option<uuid::Uuid>,
    pub kind: ChainLinkKind,
    /// Monotonic per-enclave, starts at 0 for the boot link.
    #[serde(default)]
    pub sequence: Option<i64>,
    /// Base64 of the CBOR-encoded kind-specific payload.
    pub payload: String,
    /// Base64 of the COSE_Sign1 NSM attestation document. `user_data`
    /// is bound to `sha256(payload_bytes)`.
    pub attestation: String,
    /// Base64 of the raw 64-byte ECDSA P-256 r||s signature. Absent on
    /// boot links (they're authenticated by the attestation alone),
    /// required on upgrade/revocation links.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    /// Wall-clock time the backend appended this link. `None` on the
    /// chain-host ingest direction.
    #[serde(default)]
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Payload shape for a [`ChainLinkKind::Boot`] link.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootPayload {
    /// Enclave identifier. Must match the URL path on ingest.
    pub enclave_id: Uuid,
    /// Manifest digest of the Docker image this boot is bound to.
    pub image_digest: String,
    /// PCR0 / PCR1 / PCR2 in raw byte form (48 B each on Nitro).
    pub pcrs: PcrsHex,
    /// Wall-clock time the in-enclave boot path produced this
    /// attestation.
    pub booted_at: DateTime<Utc>,
    /// 32-byte freshly-generated nonce.
    #[serde(with = "serde_bytes")]
    pub nonce: Vec<u8>,
}

/// Payload shape for a [`ChainLinkKind::Upgrade`] link.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpgradePayload {
    pub enclave_id: Uuid,
    pub from_pcrs: PcrsHex,
    pub to_pcrs: PcrsHex,
    pub image_digest: String,
    pub valid_from: DateTime<Utc>,
    pub issued_at: DateTime<Utc>,
    #[serde(with = "serde_bytes")]
    pub nonce: Vec<u8>,
}

/// Payload shape for a [`ChainLinkKind::Revocation`] link.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RevocationPayload {
    pub enclave_id: Uuid,
    /// Chain entry id of the upgrade link this revocation cancels.
    pub revokes: Uuid,
    pub issued_at: DateTime<Utc>,
    #[serde(with = "serde_bytes")]
    pub nonce: Vec<u8>,
}

/// Failure decoding a [`ChainLinkJson`] wire link into a [`ChainLink`].
#[derive(Debug, thiserror::Error)]
pub enum ChainLinkDecodeError {
    /// One of the base64 byte fields did not decode.
    #[error("chain link `{field}` is not valid base64: {source}")]
    Base64 {
        field: &'static str,
        #[source]
        source: base64::DecodeError,
    },
    /// `sequence` was negative. The backend never persists a negative
    /// value; surface it instead of silently coercing, so a misbehaving
    /// source is visible rather than papered over.
    #[error("chain link has a negative sequence {0}")]
    NegativeSequence(i64),
}

impl ChainLinkJson {
    /// Decode the base64 wire fields into the raw-bytes [`ChainLink`] the
    /// validator consumes. `id` carries through; `sequence` narrows
    /// `i64 -> u64` and errors on a negative value rather than coercing.
    ///
    /// This is the single decode path for every consumer of the public
    /// `GET /enclaves/{id}/upgrade-chain` endpoint (the SDK's
    /// trust-upgrades walk and the CLI's `upgrade chain`), so the
    /// base64 handling is defined once in the audited crate rather than
    /// re-implemented per caller.
    pub fn into_chain_link(&self) -> Result<ChainLink, ChainLinkDecodeError> {
        let b64 = base64::engine::general_purpose::STANDARD;
        let decode = |field: &'static str, s: &str| {
            b64.decode(s.as_bytes())
                .map_err(|source| ChainLinkDecodeError::Base64 { field, source })
        };
        let payload = decode("payload", &self.payload)?;
        let attestation = decode("attestation", &self.attestation)?;
        let signature = match self.signature.as_deref() {
            Some(s) => Some(decode("signature", s)?),
            None => None,
        };
        let sequence = match self.sequence {
            Some(s) => {
                Some(u64::try_from(s).map_err(|_| ChainLinkDecodeError::NegativeSequence(s))?)
            }
            None => None,
        };
        Ok(ChainLink {
            id: self.id,
            sequence,
            kind: self.kind,
            payload,
            attestation,
            signature,
        })
    }

    /// Decode into a [`RecordedLink`], carrying `created_at` as the
    /// ingest reference instant for time-dependent rules (revocation
    /// `valid_from`).
    pub fn into_recorded_link(&self) -> Result<RecordedLink, ChainLinkDecodeError> {
        Ok(RecordedLink {
            link: self.into_chain_link()?,
            recorded_at: self.created_at,
        })
    }
}

/// PCRs in hex-string form. Chosen over raw bytes for the wire/CBOR
/// shape because hex strings interop trivially with the existing
/// hex-PCR format the backend already stores; clients walking the
/// chain don't have to deal with byte-vs-string conversion to match
/// what the attestation document carries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PcrsHex {
    // `alias` accepts the lowercase form too: the backend persists the
    // builder's pcr.json verbatim (nitro-cli `PCR0` casing), but a
    // future normalization on the row should not break a consumer
    // deserializing it. Serialization is unchanged (always `PCR0`).
    #[serde(rename = "PCR0", alias = "pcr0")]
    pub pcr0: String,
    #[serde(rename = "PCR1", alias = "pcr1")]
    pub pcr1: String,
    #[serde(rename = "PCR2", alias = "pcr2")]
    pub pcr2: String,
}

impl PcrsHex {
    /// Decode to raw bytes for the attestation verifier.
    pub fn to_pcrs(&self) -> Result<Pcrs, ChainValidationError> {
        let pcr0 =
            hex::decode(&self.pcr0).map_err(|_| ChainValidationError::CorruptStoredPcrHex(0))?;
        let pcr1 =
            hex::decode(&self.pcr1).map_err(|_| ChainValidationError::CorruptStoredPcrHex(1))?;
        let pcr2 =
            hex::decode(&self.pcr2).map_err(|_| ChainValidationError::CorruptStoredPcrHex(2))?;
        Ok(Pcrs { pcr0, pcr1, pcr2 })
    }
}

/// The `validate_chain` context fields carried on the public
/// `GET /enclaves/{id}` response. Deserialized by every consumer that
/// re-walks a chain (the SDK's `trust_upgrades`, the CLI's `upgrade
/// chain`) so the tolerant parsing lives once here instead of being
/// re-implemented per caller.
///
/// Tolerances, matching what the backend actually emits:
/// - `pcrs`: nitro-cli `PCR0` casing or lowercase (see [`PcrsHex`]).
/// - `control_public_key`: the BYTEA column serializes as a JSON array
///   of byte values; a base64 string and `null` (a non-upgradable
///   enclave) are also accepted.
/// - `upgradable`: defaults to `false` when absent.
///
/// These values are corroborating, not load-bearing, in the
/// `trust_upgrades` trust model (a wrong value can only make a genuine
/// chain fail to verify); see [`verify_pcr_descent`].
#[derive(Debug, Clone, Deserialize)]
pub struct EnclaveChainRow {
    pub pcrs: PcrsHex,
    pub image_digest: String,
    #[serde(default, deserialize_with = "deserialize_control_key")]
    pub control_public_key: Option<Vec<u8>>,
    #[serde(default)]
    pub upgradable: bool,
}

/// Accept the `control_public_key` BYTEA in any of the shapes the row
/// can carry: a JSON array of byte values, a base64 string, or
/// null/absent (non-upgradable enclave).
fn deserialize_control_key<'de, D>(de: D) -> Result<Option<Vec<u8>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Raw {
        Bytes(Vec<u8>),
        Base64(String),
    }
    match Option::<Raw>::deserialize(de)? {
        None => Ok(None),
        Some(Raw::Bytes(bytes)) => Ok(Some(bytes)),
        Some(Raw::Base64(s)) => base64::engine::general_purpose::STANDARD
            .decode(s.as_bytes())
            .map(Some)
            .map_err(serde::de::Error::custom),
    }
}

/// Context the validator needs that lives outside the link itself: the
/// enclave's recorded metadata + the chain so far.
///
/// Backend usage: load from DB at ingest. SDK usage: fetch via
/// `GET /enclaves/{id}` and iterate the chain returned from
/// `GET /enclaves/{id}/upgrade-chain`, passing successively longer
/// prefixes as `prior_chain`.
pub struct ChainContext<'a> {
    /// PCR0/1/2 recorded for this enclave at build time. Every link's
    /// attestation document must carry these PCRs.
    pub enclave_pcrs: &'a PcrsHex,
    /// Manifest digest of the Docker image currently pinned to this
    /// enclave row. Boot payloads must reference this digest.
    pub enclave_image_digest: &'a str,
    /// Enclave's 65-byte uncompressed SEC1 ECDSA P-256 control public
    /// key, or None when the enclave was created non-upgradable.
    pub control_public_key: Option<&'a [u8]>,
    /// Whether the enclave was created with the upgradable flag.
    /// Upgrade / revocation links are rejected outright when false.
    pub upgradable: bool,
    /// Existing chain entries, in `sequence` order. May be empty (the
    /// link about to be validated would be genesis).
    pub prior_chain: &'a [ChainLink],
}

/// Validator outcome on a successful check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// The link is well-formed and consistent with the chain. Caller
    /// should append it with this `sequence` number.
    Append {
        /// Sequence number to assign to the new link. The first
        /// genesis boot is 0; subsequent links increment by 1.
        sequence: u64,
    },
    /// The link is a duplicate of an already-active boot (same
    /// `image_digest` as the chain's most recent boot). Caller should
    /// NOT insert it; the existing matching link is still authoritative.
    Dedup,
}

/// All ways a chain link can fail validation.
#[derive(Debug, thiserror::Error)]
pub enum ChainValidationError {
    /// Bottom-line attestation verification (see
    /// [`super::attestation::verify_chain_attestation`]).
    #[error("{0}")]
    Attestation(#[from] AttestationError),
    /// `attestation` byte vec is empty.
    #[error("attestation must be present")]
    EmptyAttestation,
    /// CBOR-decode of `payload` failed against the kind's struct.
    #[error("{kind:?} payload not CBOR-decodable: {msg}")]
    PayloadDecode { kind: ChainLinkKind, msg: String },
    /// `payload.enclave_id` does not match the validator's context.
    #[error("payload enclave_id does not match the URL")]
    EnclaveIdMismatch,
    /// Boot link claims PCRs that disagree with what the backend
    /// recorded post-build.
    #[error("boot payload PCRs do not match the enclave's recorded PCRs")]
    PcrMismatch,
    /// Boot link's `image_digest` disagrees with `enclaves.image_digest`.
    #[error("boot payload image_digest does not match the enclave's pinned digest")]
    ImageDigestMismatch,
    /// Boot link presented a `signature`. Boot links carry no
    /// signature.
    #[error("boot link must not carry a signature")]
    BootHasSignature,
    /// Upgrade / revocation link is missing the `signature` field.
    #[error("{0:?} link must carry a signature")]
    SignatureMissing(ChainLinkKind),
    /// The control_public_key on `enclaves` did not decode as
    /// uncompressed SEC1 P-256. Indicates DB-side drift; user-facing
    /// error class should map to 500.
    #[error("stored control_public_key does not decode as SEC1 P-256: {0}")]
    BadControlPubkey(String),
    /// `signature` is not 64 bytes raw r||s.
    #[error("signature is not 64 bytes raw r||s ECDSA P-256")]
    SignatureShape,
    /// `signature` does not verify against the enclave's control
    /// pubkey.
    #[error("signature does not verify under the enclave's control_public_key")]
    SignatureInvalid,
    /// Upgrade / revocation submitted on a non-upgradable enclave.
    #[error("non-upgradable enclaves cannot record {0:?} links")]
    NonUpgradableSigned(ChainLinkKind),
    /// Boot of a fresh image digest on a non-upgradable enclave.
    #[error("non-upgradable enclaves cannot record a second boot")]
    NonUpgradableSecondBoot,
    /// Upgrade or revocation submitted before any genesis boot exists.
    #[error("first chain entry must be a boot — no upgrade or revocation can precede the genesis")]
    NoGenesisYet,
    /// Revocation's `revokes` does not resolve to any entry on the
    /// chain context.
    #[error("revocation `revokes` does not reference any chain entry on this enclave")]
    RevokeTargetMissing,
    /// Revocation's `revokes` points at a non-upgrade link.
    #[error("revocation can only target an upgrade entry, not a {0:?}")]
    RevokeTargetWrongKind(ChainLinkKind),
    /// Revoked upgrade is past `valid_from`. Pre-activation revoke only.
    #[error("revocation is past the upgrade's valid_from; pre-activation revoke only")]
    RevokePastActivation,
    /// Another revocation on this chain already targets the same
    /// upgrade.
    #[error("upgrade has already been revoked")]
    AlreadyRevoked,
    /// A stored chain entry's payload no longer CBOR-decodes (DB-side
    /// drift). Maps to 500.
    #[error("stored {0:?} payload corrupt: {1}")]
    CorruptStoredPayload(ChainLinkKind, String),
    /// A stored PCR string is not hex (DB-side drift). Maps to 500.
    #[error("stored PCR {0} is not valid hex")]
    CorruptStoredPcrHex(usize),
}

/// Pure validator. No DB access, no clock skew (uses the supplied
/// `now`), no I/O. Backend ingest calls this with `now = Utc::now()`;
/// SDK chain-walkers can pass any reference instant they want for
/// consistency (e.g. the chain GET's response time).
///
/// On `Ok(Outcome::Append { sequence })` the caller should INSERT the
/// link assigning that sequence number. On `Ok(Outcome::Dedup)` the
/// caller should not insert. On `Err(_)` the caller should reject.
pub fn validate_chain_link(
    link: &ChainLink,
    ctx: &ChainContext<'_>,
    now: DateTime<Utc>,
    debug_mode: bool,
) -> Result<Outcome, ChainValidationError> {
    if link.attestation.is_empty() {
        return Err(ChainValidationError::EmptyAttestation);
    }
    let recorded_pcrs = ctx.enclave_pcrs.to_pcrs()?;
    verify_chain_attestation(&link.attestation, &link.payload, &recorded_pcrs, debug_mode)?;

    match link.kind {
        ChainLinkKind::Boot => validate_boot(link, ctx),
        ChainLinkKind::Upgrade | ChainLinkKind::Revocation => validate_signed(link, ctx, now),
    }
}

fn validate_boot(
    link: &ChainLink,
    ctx: &ChainContext<'_>,
) -> Result<Outcome, ChainValidationError> {
    if link.signature.is_some() {
        return Err(ChainValidationError::BootHasSignature);
    }
    let parsed: BootPayload = ciborium::from_reader(link.payload.as_slice()).map_err(|e| {
        ChainValidationError::PayloadDecode {
            kind: ChainLinkKind::Boot,
            msg: e.to_string(),
        }
    })?;
    if parsed.pcrs != *ctx.enclave_pcrs {
        return Err(ChainValidationError::PcrMismatch);
    }
    if parsed.image_digest != ctx.enclave_image_digest {
        return Err(ChainValidationError::ImageDigestMismatch);
    }
    // Cross-link semantics: dedup against the most recent boot
    // anywhere in the chain (not just the tail). The reboot-during-
    // pending-upgrade case lands here with `upgrade` as the tail; the
    // running image hasn't actually changed.
    let last_boot = ctx
        .prior_chain
        .iter()
        .rev()
        .find(|l| l.kind == ChainLinkKind::Boot);
    match last_boot {
        None => {
            // Genesis. Sequence is `prior_chain.len()` so we pick up
            // from whatever's at the tail even if (somehow) a non-boot
            // entry preceded the genesis.
            Ok(Outcome::Append {
                sequence: ctx.prior_chain.len() as u64,
            })
        }
        Some(prev) => {
            let prev_payload: BootPayload = ciborium::from_reader(prev.payload.as_slice())
                .map_err(|e| {
                    ChainValidationError::CorruptStoredPayload(ChainLinkKind::Boot, e.to_string())
                })?;
            if prev_payload.image_digest == parsed.image_digest {
                return Ok(Outcome::Dedup);
            }
            if !ctx.upgradable {
                return Err(ChainValidationError::NonUpgradableSecondBoot);
            }
            Ok(Outcome::Append {
                sequence: ctx.prior_chain.len() as u64,
            })
        }
    }
}

fn validate_signed(
    link: &ChainLink,
    ctx: &ChainContext<'_>,
    now: DateTime<Utc>,
) -> Result<Outcome, ChainValidationError> {
    if !ctx.upgradable {
        return Err(ChainValidationError::NonUpgradableSigned(link.kind));
    }
    let sig_bytes = link
        .signature
        .as_deref()
        .ok_or(ChainValidationError::SignatureMissing(link.kind))?;
    let pubkey_bytes = ctx.control_public_key.ok_or_else(|| {
        ChainValidationError::BadControlPubkey(
            "upgradable enclave is missing control_public_key in context".into(),
        )
    })?;
    let verifying = VerifyingKey::from_sec1_bytes(pubkey_bytes)
        .map_err(|e| ChainValidationError::BadControlPubkey(e.to_string()))?;
    let sig = Signature::from_slice(sig_bytes).map_err(|_| ChainValidationError::SignatureShape)?;
    verifying
        .verify(&link.payload, &sig)
        .map_err(|_| ChainValidationError::SignatureInvalid)?;

    // Payload-shape sanity + per-kind cross-link checks.
    match link.kind {
        ChainLinkKind::Upgrade => {
            let _: UpgradePayload =
                ciborium::from_reader(link.payload.as_slice()).map_err(|e| {
                    ChainValidationError::PayloadDecode {
                        kind: ChainLinkKind::Upgrade,
                        msg: e.to_string(),
                    }
                })?;
        }
        ChainLinkKind::Revocation => {
            let revoke: RevocationPayload = ciborium::from_reader(link.payload.as_slice())
                .map_err(|e| ChainValidationError::PayloadDecode {
                    kind: ChainLinkKind::Revocation,
                    msg: e.to_string(),
                })?;
            // Target lookup, kind check, activation check, double-revoke.
            let target = ctx
                .prior_chain
                .iter()
                .find(|l| l.id == Some(revoke.revokes))
                .ok_or(ChainValidationError::RevokeTargetMissing)?;
            if target.kind != ChainLinkKind::Upgrade {
                return Err(ChainValidationError::RevokeTargetWrongKind(target.kind));
            }
            let target_upgrade: UpgradePayload = ciborium::from_reader(target.payload.as_slice())
                .map_err(|e| {
                ChainValidationError::CorruptStoredPayload(ChainLinkKind::Upgrade, e.to_string())
            })?;
            if target_upgrade.valid_from <= now {
                return Err(ChainValidationError::RevokePastActivation);
            }
            for existing in ctx.prior_chain {
                if existing.kind != ChainLinkKind::Revocation {
                    continue;
                }
                let existing_payload: RevocationPayload =
                    ciborium::from_reader(existing.payload.as_slice()).map_err(|e| {
                        ChainValidationError::CorruptStoredPayload(
                            ChainLinkKind::Revocation,
                            e.to_string(),
                        )
                    })?;
                if existing_payload.revokes == revoke.revokes {
                    return Err(ChainValidationError::AlreadyRevoked);
                }
            }
        }
        ChainLinkKind::Boot => unreachable!("validate_signed not called for boot"),
    };

    // First chain entry must be a boot.
    if ctx.prior_chain.is_empty() {
        return Err(ChainValidationError::NoGenesisYet);
    }
    Ok(Outcome::Append {
        sequence: ctx.prior_chain.len() as u64,
    })
}

// ---------------------------------------------------------------------------
// Full-chain walker
// ---------------------------------------------------------------------------

/// One stored chain link plus its server-assigned ingest time: the
/// input unit for [`validate_chain`].
#[derive(Debug, Clone)]
pub struct RecordedLink {
    pub link: ChainLink,
    /// `created_at` on the stored row. Used as the reference instant
    /// for time-dependent rules: a revocation is judged against the
    /// clock at its ingest, not the verifier's clock: by the time
    /// anyone re-walks the chain, the revoked upgrade's `valid_from`
    /// has usually passed, and judging it "now" would reject a link
    /// that was perfectly valid when the backend recorded it. `None`
    /// falls back to the walk's `now`.
    pub recorded_at: Option<DateTime<Utc>>,
}

/// Result of [`validate_chain`].
#[derive(Debug)]
pub struct ChainWalk {
    /// Per-link outcome, same order as the input links.
    pub outcomes: Vec<Result<Outcome, ChainValidationError>>,
    /// PCRs in force after the walk: the genesis boot's values,
    /// advanced by every verified promotion boot. `None` when the
    /// chain has no usable genesis.
    pub final_pcrs: Option<PcrsHex>,
    /// Image digest in force after the walk (same advancement rule).
    pub final_image_digest: Option<String>,
    /// Whether the walk's final in-force state equals the enclave row
    /// state supplied to [`validate_chain`]. `false` means the chain
    /// does not explain what the row currently records (stale chain,
    /// missing links, or row drift): treat the chain as NOT verified
    /// even if every individual link validated.
    pub tip_matches_row: bool,
}

/// Re-validate a stored chain end-to-end, reconstructing the context
/// each link saw at ingest time.
///
/// The backend validates links incrementally: each arrives while the
/// enclave row still holds the state in force at that moment: the
/// genesis build's PCRs for the genesis boot, the old version's PCRs
/// for upgrade / revocation links (the running enclave attests them),
/// and the new version's PCRs for a promotion boot (the cutover sweep
/// promotes the row before the new enclave boots). A later verifier
/// only has the FINAL row state, so validating every link against it
/// rejects perfectly good history. This walker rebuilds the historical
/// context from the chain itself:
///
/// - The genesis boot anchors the walk on its own attested payload.
///   [`validate_chain_link`] then enforces payload <-> attestation
///   agreement, and in production the AWS Nitro CA signature roots
///   that payload in hardware.
/// - Upgrade / revocation links validate against the in-force state:
///   they are attested by the enclave version running at the time.
/// - A boot whose PCRs match the `to_pcrs` of a prior unrevoked
///   upgrade link (with the same target image digest) is a promotion:
///   it validates against that upgrade's target state, and on success
///   the in-force state advances to it.
/// - Any other boot validates against the in-force state: a
///   same-version reboot dedups, anything else fails the attestation
///   PCR check. A transition no signed upgrade link explains is
///   exactly what this rejects.
///
/// Callers MUST check [`ChainWalk::tip_matches_row`] in addition to
/// the per-link outcomes: it ties the walk's final state to the row,
/// proving the chain accounts for what is currently running.
///
/// `now` is the fallback reference instant for links with no
/// `recorded_at` (e.g. not-yet-ingested candidates).
pub fn validate_chain(
    links: &[RecordedLink],
    row_pcrs: &PcrsHex,
    row_image_digest: &str,
    control_public_key: Option<&[u8]>,
    upgradable: bool,
    now: DateTime<Utc>,
    debug_mode: bool,
) -> ChainWalk {
    let mut outcomes = Vec::with_capacity(links.len());
    let mut prior: Vec<ChainLink> = Vec::with_capacity(links.len());
    // (pcrs, image_digest) in force at the current walk position. Set
    // by the genesis boot, advanced by each verified promotion boot.
    // `None` until a genesis validates; the row state then stands in
    // so later links still get individually validated and reported.
    let mut in_force: Option<(PcrsHex, String)> = None;

    for recorded in links {
        let link = &recorded.link;
        let reference = recorded.recorded_at.unwrap_or(now);

        // Reconstruct the row state this link saw at ingest. `promotes`
        // marks the contexts that advance the in-force state when the
        // link validates (genesis anchor, promotion boot).
        let (ctx_pcrs, ctx_digest, promotes): (PcrsHex, String, bool) = match link.kind {
            ChainLinkKind::Boot if prior.is_empty() => {
                match ciborium::from_reader::<BootPayload, _>(link.payload.as_slice()) {
                    Ok(p) => (p.pcrs, p.image_digest, true),
                    // Undecodable genesis: hand the row state to the
                    // validator so it reports the decode error.
                    Err(_) => (row_pcrs.clone(), row_image_digest.to_owned(), false),
                }
            }
            ChainLinkKind::Boot => {
                match (
                    ciborium::from_reader::<BootPayload, _>(link.payload.as_slice()),
                    in_force.as_ref(),
                ) {
                    (Ok(p), Some((pcrs, digest))) => {
                        if p.pcrs == *pcrs {
                            // Same-version reboot.
                            (pcrs.clone(), digest.clone(), false)
                        } else if let Some(target) =
                            promotion_target(&prior, &p.pcrs, &p.image_digest)
                        {
                            // Promotion boot: ingest saw the row
                            // already promoted to the upgrade target.
                            (target.to_pcrs, target.image_digest, true)
                        } else {
                            // No signed upgrade explains these PCRs;
                            // validate against the in-force state and
                            // fail loudly.
                            (pcrs.clone(), digest.clone(), false)
                        }
                    }
                    (_, Some((pcrs, digest))) => (pcrs.clone(), digest.clone(), false),
                    (_, None) => (row_pcrs.clone(), row_image_digest.to_owned(), false),
                }
            }
            ChainLinkKind::Upgrade | ChainLinkKind::Revocation => match in_force.as_ref() {
                Some((pcrs, digest)) => (pcrs.clone(), digest.clone(), false),
                None => (row_pcrs.clone(), row_image_digest.to_owned(), false),
            },
        };

        let ctx = ChainContext {
            enclave_pcrs: &ctx_pcrs,
            enclave_image_digest: &ctx_digest,
            control_public_key,
            upgradable,
            prior_chain: &prior,
        };
        let outcome = validate_chain_link(link, &ctx, reference, debug_mode);
        if promotes && matches!(outcome, Ok(Outcome::Append { .. })) {
            in_force = Some((ctx_pcrs, ctx_digest));
        }
        outcomes.push(outcome);
        prior.push(link.clone());
    }

    let tip_matches_row = in_force
        .as_ref()
        .is_some_and(|(p, d)| p == row_pcrs && d == row_image_digest);
    let (final_pcrs, final_image_digest) = match in_force {
        Some((p, d)) => (Some(p), Some(d)),
        None => (None, None),
    };
    ChainWalk {
        outcomes,
        final_pcrs,
        final_image_digest,
        tip_matches_row,
    }
}

/// Most recent prior unrevoked upgrade link whose `to_pcrs` and target
/// image digest match the boot being explained. `None` when no signed
/// upgrade accounts for a boot with these measurements.
fn promotion_target(
    prior: &[ChainLink],
    boot_pcrs: &PcrsHex,
    boot_image_digest: &str,
) -> Option<UpgradePayload> {
    let revoked: Vec<Uuid> = prior
        .iter()
        .filter(|l| l.kind == ChainLinkKind::Revocation)
        .filter_map(|l| ciborium::from_reader::<RevocationPayload, _>(l.payload.as_slice()).ok())
        .map(|p| p.revokes)
        .collect();
    prior
        .iter()
        .rev()
        .filter(|l| l.kind == ChainLinkKind::Upgrade)
        .filter(|l| l.id.is_none_or(|id| !revoked.contains(&id)))
        .filter_map(|l| ciborium::from_reader::<UpgradePayload, _>(l.payload.as_slice()).ok())
        .find(|p| p.to_pcrs == *boot_pcrs && p.image_digest == boot_image_digest)
}

// ---------------------------------------------------------------------------
// Pinned-PCR upgrade-descent check (SDK `trust_upgrades`)
// ---------------------------------------------------------------------------

/// Why a live enclave's PCRs could not be shown to descend from the
/// caller's pinned PCRs.
#[derive(Debug, thiserror::Error)]
pub enum PcrDescentError {
    /// The chain produced no usable genesis, so no in-force state could
    /// be established and nothing descends from anything.
    #[error("chain has no valid genesis boot")]
    NoGenesis,
    /// A chain link failed validation (attestation, signature, or
    /// cross-link consistency). The whole chain is rejected: a single
    /// unverifiable link means the history is not a trustworthy account
    /// of how the enclave reached its current measurements.
    #[error("chain link at position {position} failed validation: {source}")]
    LinkInvalid {
        position: usize,
        #[source]
        source: ChainValidationError,
    },
    /// Every link validated, but the pinned PCRs never appear as an
    /// in-force boot state on this chain. The chain may be a perfectly
    /// valid history of a DIFFERENT enclave; it does not start from (or
    /// pass through) the version the caller pinned, so the live
    /// measurements cannot be said to descend from the pinned ones.
    #[error("pinned PCRs are not an in-force state anywhere on this chain")]
    PinnedNotInLineage,
    /// A boot link the walker accepted carries a payload that no longer
    /// CBOR-decodes, or PCR hex that no longer parses. Indicates the
    /// link bytes were mutated between validation and this read; treated
    /// as fatal.
    #[error("validated boot link at position {0} has an unreadable payload")]
    BootPayloadUnreadable(usize),
}

/// Verify that an enclave currently measuring some live PCRs descends,
/// through this enclave's signed upgrade chain, from the PCRs the caller
/// pinned, and return the chain's final (tip) measurements.
///
/// This backs the SDK's `trust_upgrades` mode. When a client pinned a
/// version's PCRs and the enclave has since upgraded, the live
/// attestation no longer matches the pin; this function decides whether
/// to extend trust to the new image by proving the new image is a
/// descendant of the pinned one.
///
/// The caller passes the pinned PCRs plus the enclave's public chain
/// (from `GET /enclaves/{id}/upgrade-chain`) and the validator context
/// (`row_*`, `control_public_key`, `upgradable`) from
/// `GET /enclaves/{id}`. On success it returns the chain's TIP PCRs; the
/// caller MUST then verify the LIVE attestation against exactly those
/// PCRs (e.g. [`crate::attestation::verify_against`]) to bind the
/// verified descendant version to the running Noise session. This
/// function does not see the live attestation and so cannot make that
/// binding itself.
///
/// ## Trust model
///
/// Soundness rests entirely on the per-link AWS Nitro attestations,
/// which `validate_chain` verifies (in production mode); the
/// control-key signatures and the `row_*` / `control_public_key` /
/// `upgradable` context are corroborating, never load-bearing. A
/// dishonest source of any of those can only make a genuine chain FAIL
/// here (a denial), never make a forged transition pass: forging an
/// upgrade link would require a real Nitro document from an enclave
/// measuring the `from` PCRs that voluntarily authorized the `to` PCRs,
/// which is exactly the trust delegation `trust_upgrades` opts into.
///
/// Two independent gates make the result meaningful:
///
/// 1. EVERY link validates. One bad link rejects the whole chain.
/// 2. The pinned PCRs appear as an in-force boot state on the chain.
///    Without this a valid chain belonging to some OTHER enclave would
///    pass; with it, the pinned version is provably part of THIS
///    enclave's measured history. Per-enclave PCRs are unique (the
///    enclave UUID is measured into them), so a single matching
///    in-force state on a fully-validated linear chain places the tip
///    downstream of the pin.
///
/// `debug_mode` must be the SDK's own mode: in production mode a chain
/// of debug (non-CA-signed) links fails attestation and is rejected, so
/// a production client never extends trust through unverifiable history.
// One arg over the lint's threshold: this mirrors `validate_chain`'s
// context (which sits exactly at the limit) plus the pinned anchor.
// Bundling them into a struct would just move the same fields around.
#[allow(clippy::too_many_arguments)]
pub fn verify_pcr_descent(
    pinned: &Pcrs,
    links: &[RecordedLink],
    control_public_key: Option<&[u8]>,
    row_pcrs: &PcrsHex,
    row_image_digest: &str,
    upgradable: bool,
    now: DateTime<Utc>,
    debug_mode: bool,
) -> Result<Pcrs, PcrDescentError> {
    let ChainWalk {
        outcomes,
        final_pcrs,
        ..
    } = validate_chain(
        links,
        row_pcrs,
        row_image_digest,
        control_public_key,
        upgradable,
        now,
        debug_mode,
    );

    // Gate 1: every link must validate. Reject on the first failure so a
    // tampered or unexplained transition can never be papered over by a
    // later good link.
    for (position, outcome) in outcomes.into_iter().enumerate() {
        outcome.map_err(|source| PcrDescentError::LinkInvalid { position, source })?;
    }

    let tip = final_pcrs
        .ok_or(PcrDescentError::NoGenesis)?
        .to_pcrs()
        .map_err(|_| PcrDescentError::BootPayloadUnreadable(0))?;

    // Gate 2: the pinned PCRs must be one of the chain's in-force boot
    // states. Every boot link here was accepted by the walk above (we
    // returned on any failure), so its PCRs are a measured state the
    // enclave genuinely ran; the genesis and each promotion boot are the
    // points where the in-force version changed.
    let mut pinned_in_lineage = false;
    for (position, recorded) in links.iter().enumerate() {
        if recorded.link.kind != ChainLinkKind::Boot {
            continue;
        }
        let payload: BootPayload = ciborium::from_reader(recorded.link.payload.as_slice())
            .map_err(|_| PcrDescentError::BootPayloadUnreadable(position))?;
        let state = payload
            .pcrs
            .to_pcrs()
            .map_err(|_| PcrDescentError::BootPayloadUnreadable(position))?;
        if &state == pinned {
            pinned_in_lineage = true;
        }
    }
    if !pinned_in_lineage {
        return Err(PcrDescentError::PinnedNotInLineage);
    }

    Ok(tip)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::attestation::test_utils::FakeChainAttestation;
    use chrono::Duration;
    use p256::ecdsa::{SigningKey, signature::Signer};

    fn pcrs_hex_from_seed(seed: u8) -> PcrsHex {
        PcrsHex {
            pcr0: hex::encode(vec![seed; 48]),
            pcr1: hex::encode(vec![seed.wrapping_add(1); 48]),
            pcr2: hex::encode(vec![seed.wrapping_add(2); 48]),
        }
    }

    fn keypair() -> (SigningKey, Vec<u8>) {
        let seed: [u8; 32] = core::array::from_fn(|i| (i + 1) as u8);
        let sk = SigningKey::from_slice(&seed).unwrap();
        let pk = sk
            .verifying_key()
            .to_encoded_point(false)
            .as_bytes()
            .to_vec();
        (sk, pk)
    }

    fn boot_link(enclave_id: Uuid, image_digest: &str, pcr_seed: u8) -> ChainLink {
        let payload = BootPayload {
            enclave_id,
            image_digest: image_digest.into(),
            pcrs: pcrs_hex_from_seed(pcr_seed),
            booted_at: chrono::Utc::now(),
            nonce: vec![0x42; 32],
        };
        let mut payload_bytes = Vec::new();
        ciborium::into_writer(&payload, &mut payload_bytes).unwrap();
        let attestation = FakeChainAttestation::for_payload(pcr_seed, &payload_bytes).encode();
        ChainLink {
            id: None,
            sequence: None,
            kind: ChainLinkKind::Boot,
            payload: payload_bytes,
            attestation,
            signature: None,
        }
    }

    fn upgrade_link(
        enclave_id: Uuid,
        image_digest: &str,
        pcr_seed: u8,
        signing: &SigningKey,
        valid_from: DateTime<Utc>,
    ) -> ChainLink {
        let pcrs = pcrs_hex_from_seed(pcr_seed);
        let payload = UpgradePayload {
            enclave_id,
            from_pcrs: pcrs.clone(),
            to_pcrs: pcrs,
            image_digest: image_digest.into(),
            valid_from,
            issued_at: chrono::Utc::now(),
            nonce: vec![0x43; 32],
        };
        let mut payload_bytes = Vec::new();
        ciborium::into_writer(&payload, &mut payload_bytes).unwrap();
        let attestation = FakeChainAttestation::for_payload(pcr_seed, &payload_bytes).encode();
        let sig: Signature = signing.sign(&payload_bytes);
        ChainLink {
            id: None,
            sequence: None,
            kind: ChainLinkKind::Upgrade,
            payload: payload_bytes,
            attestation,
            signature: Some(sig.to_bytes().to_vec()),
        }
    }

    fn revocation_link(
        enclave_id: Uuid,
        revokes: Uuid,
        pcr_seed: u8,
        signing: &SigningKey,
    ) -> ChainLink {
        let payload = RevocationPayload {
            enclave_id,
            revokes,
            issued_at: chrono::Utc::now(),
            nonce: vec![0x44; 32],
        };
        let mut payload_bytes = Vec::new();
        ciborium::into_writer(&payload, &mut payload_bytes).unwrap();
        let attestation = FakeChainAttestation::for_payload(pcr_seed, &payload_bytes).encode();
        let sig: Signature = signing.sign(&payload_bytes);
        ChainLink {
            id: None,
            sequence: None,
            kind: ChainLinkKind::Revocation,
            payload: payload_bytes,
            attestation,
            signature: Some(sig.to_bytes().to_vec()),
        }
    }

    fn ctx<'a>(
        pcrs: &'a PcrsHex,
        digest: &'a str,
        pubkey: Option<&'a [u8]>,
        upgradable: bool,
        chain: &'a [ChainLink],
    ) -> ChainContext<'a> {
        ChainContext {
            enclave_pcrs: pcrs,
            enclave_image_digest: digest,
            control_public_key: pubkey,
            upgradable,
            prior_chain: chain,
        }
    }

    #[test]
    fn boot_genesis_appends_at_zero() {
        let pcrs = pcrs_hex_from_seed(0x10);
        let id = Uuid::new_v4();
        let link = boot_link(id, "sha256:aaa", 0x10);
        let outcome = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:aaa", None, false, &[]),
            chrono::Utc::now(),
            true,
        )
        .unwrap();
        assert_eq!(outcome, Outcome::Append { sequence: 0 });
    }

    #[test]
    fn boot_rejects_pcr_mismatch() {
        let pcrs = pcrs_hex_from_seed(0x11);
        let id = Uuid::new_v4();
        let link = boot_link(id, "sha256:aaa", 0x99);
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:aaa", None, false, &[]),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::Attestation(_)));
    }

    #[test]
    fn boot_rejects_image_digest_mismatch() {
        let pcrs = pcrs_hex_from_seed(0x12);
        let id = Uuid::new_v4();
        let link = boot_link(id, "sha256:DIFFERENT", 0x12);
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:aaa", None, false, &[]),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::ImageDigestMismatch));
    }

    #[test]
    fn boot_dedups_on_same_image_digest() {
        let pcrs = pcrs_hex_from_seed(0x13);
        let id = Uuid::new_v4();
        let first = boot_link(id, "sha256:bbb", 0x13);
        let outcome = validate_chain_link(
            &first,
            &ctx(
                &pcrs,
                "sha256:bbb",
                None,
                false,
                std::slice::from_ref(&first),
            ),
            chrono::Utc::now(),
            true,
        )
        .unwrap();
        assert_eq!(outcome, Outcome::Dedup);
    }

    #[test]
    fn boot_after_pending_upgrade_dedups_against_last_boot() {
        // boot(v1) -> upgrade(v1->v2) -> reboot(v1): dedup.
        let pcrs = pcrs_hex_from_seed(0x14);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let mut chain = vec![boot_link(id, "sha256:v1", 0x14)];
        chain[0].id = Some(Uuid::new_v4());
        chain[0].sequence = Some(0);
        let mut upgrade = upgrade_link(
            id,
            "sha256:v2",
            0x14,
            &sk,
            chrono::Utc::now() + Duration::days(7),
        );
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        chain.push(upgrade);

        let reboot = boot_link(id, "sha256:v1", 0x14);
        let outcome = validate_chain_link(
            &reboot,
            &ctx(&pcrs, "sha256:v1", Some(&pk), true, &chain),
            chrono::Utc::now(),
            true,
        )
        .unwrap();
        assert_eq!(outcome, Outcome::Dedup);
    }

    #[test]
    fn non_upgradable_rejects_second_boot_with_new_digest() {
        let pcrs = pcrs_hex_from_seed(0x15);
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:old", 0x15);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);

        let reboot = boot_link(id, "sha256:new", 0x15);
        let err = validate_chain_link(
            &reboot,
            &ctx(
                &pcrs,
                "sha256:new",
                None,
                false,
                std::slice::from_ref(&genesis),
            ),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::NonUpgradableSecondBoot));
    }

    #[test]
    fn upgrade_rejects_on_non_upgradable() {
        let pcrs = pcrs_hex_from_seed(0x16);
        let (sk, _) = keypair();
        let id = Uuid::new_v4();
        let link = upgrade_link(
            id,
            "sha256:v2",
            0x16,
            &sk,
            chrono::Utc::now() + Duration::days(7),
        );
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:v1", None, false, &[]),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            ChainValidationError::NonUpgradableSigned(ChainLinkKind::Upgrade)
        ));
    }

    #[test]
    fn upgrade_rejects_bad_signature() {
        let pcrs = pcrs_hex_from_seed(0x17);
        let (_sk, pk) = keypair();
        // Sign with a different key.
        let other_seed: [u8; 32] = core::array::from_fn(|i| (i + 99) as u8);
        let other_sk = SigningKey::from_slice(&other_seed).unwrap();
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:v1", 0x17);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);

        let link = upgrade_link(
            id,
            "sha256:v2",
            0x17,
            &other_sk,
            chrono::Utc::now() + Duration::days(7),
        );
        let err = validate_chain_link(
            &link,
            &ctx(
                &pcrs,
                "sha256:v1",
                Some(&pk),
                true,
                std::slice::from_ref(&genesis),
            ),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::SignatureInvalid));
    }

    #[test]
    fn upgrade_rejects_without_genesis() {
        let pcrs = pcrs_hex_from_seed(0x18);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let link = upgrade_link(
            id,
            "sha256:v2",
            0x18,
            &sk,
            chrono::Utc::now() + Duration::days(7),
        );
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:v1", Some(&pk), true, &[]),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::NoGenesisYet));
    }

    #[test]
    fn upgrade_appends_after_genesis() {
        let pcrs = pcrs_hex_from_seed(0x19);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:v1", 0x19);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);

        let link = upgrade_link(
            id,
            "sha256:v2",
            0x19,
            &sk,
            chrono::Utc::now() + Duration::days(7),
        );
        let outcome = validate_chain_link(
            &link,
            &ctx(
                &pcrs,
                "sha256:v1",
                Some(&pk),
                true,
                std::slice::from_ref(&genesis),
            ),
            chrono::Utc::now(),
            true,
        )
        .unwrap();
        assert_eq!(outcome, Outcome::Append { sequence: 1 });
    }

    #[test]
    fn revocation_succeeds_against_pending_upgrade() {
        let pcrs = pcrs_hex_from_seed(0x1a);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:v1", 0x1a);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut upgrade = upgrade_link(
            id,
            "sha256:v2",
            0x1a,
            &sk,
            chrono::Utc::now() + Duration::days(7),
        );
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        let chain = vec![genesis, upgrade.clone()];

        let link = revocation_link(id, upgrade.id.unwrap(), 0x1a, &sk);
        let outcome = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:v1", Some(&pk), true, &chain),
            chrono::Utc::now(),
            true,
        )
        .unwrap();
        assert_eq!(outcome, Outcome::Append { sequence: 2 });
    }

    #[test]
    fn revocation_rejects_unknown_target() {
        let pcrs = pcrs_hex_from_seed(0x1b);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:v1", 0x1b);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let chain = vec![genesis];

        let link = revocation_link(id, Uuid::new_v4(), 0x1b, &sk);
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:v1", Some(&pk), true, &chain),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::RevokeTargetMissing));
    }

    #[test]
    fn revocation_rejects_past_activation() {
        let pcrs = pcrs_hex_from_seed(0x1c);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:v1", 0x1c);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut upgrade = upgrade_link(
            id,
            "sha256:v2",
            0x1c,
            &sk,
            chrono::Utc::now() - Duration::seconds(1),
        );
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        let chain = vec![genesis, upgrade.clone()];

        let link = revocation_link(id, upgrade.id.unwrap(), 0x1c, &sk);
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:v1", Some(&pk), true, &chain),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::RevokePastActivation));
    }

    #[test]
    fn revocation_rejects_double_revoke() {
        let pcrs = pcrs_hex_from_seed(0x1d);
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let mut genesis = boot_link(id, "sha256:v1", 0x1d);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut upgrade = upgrade_link(
            id,
            "sha256:v2",
            0x1d,
            &sk,
            chrono::Utc::now() + Duration::days(7),
        );
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        let mut prior_revoke = revocation_link(id, upgrade.id.unwrap(), 0x1d, &sk);
        prior_revoke.id = Some(Uuid::new_v4());
        prior_revoke.sequence = Some(2);
        let chain = vec![genesis, upgrade.clone(), prior_revoke];

        let link = revocation_link(id, upgrade.id.unwrap(), 0x1d, &sk);
        let err = validate_chain_link(
            &link,
            &ctx(&pcrs, "sha256:v1", Some(&pk), true, &chain),
            chrono::Utc::now(),
            true,
        )
        .unwrap_err();
        assert!(matches!(err, ChainValidationError::AlreadyRevoked));
    }

    // -----------------------------------------------------------------------
    // Full-chain walker
    // -----------------------------------------------------------------------

    /// Upgrade link describing a real version transition: attested by
    /// the OLD enclave (`from_seed`, the version running at confirm
    /// time) and targeting the NEW measurements (`to_seed`). The
    /// single-seed [`upgrade_link`] fixture above keeps from == to,
    /// which never promotes anything.
    fn transition_upgrade_link(
        enclave_id: Uuid,
        target_digest: &str,
        from_seed: u8,
        to_seed: u8,
        signing: &SigningKey,
        valid_from: DateTime<Utc>,
    ) -> ChainLink {
        let payload = UpgradePayload {
            enclave_id,
            from_pcrs: pcrs_hex_from_seed(from_seed),
            to_pcrs: pcrs_hex_from_seed(to_seed),
            image_digest: target_digest.into(),
            valid_from,
            issued_at: chrono::Utc::now(),
            nonce: vec![0x45; 32],
        };
        let mut payload_bytes = Vec::new();
        ciborium::into_writer(&payload, &mut payload_bytes).unwrap();
        let attestation = FakeChainAttestation::for_payload(from_seed, &payload_bytes).encode();
        let sig: Signature = signing.sign(&payload_bytes);
        ChainLink {
            id: None,
            sequence: None,
            kind: ChainLinkKind::Upgrade,
            payload: payload_bytes,
            attestation,
            signature: Some(sig.to_bytes().to_vec()),
        }
    }

    fn recorded(link: ChainLink, at: DateTime<Utc>) -> RecordedLink {
        RecordedLink {
            link,
            recorded_at: Some(at),
        }
    }

    /// The promoted-history shape a real upgrade leaves behind:
    /// boot(v1) -> upgrade(v1->v2) -> boot(v2), walked AFTER promotion
    /// with the row already holding the v2 state. Validating each link
    /// against the final row state would reject the first two; the
    /// walker must reconstruct the per-link historical context.
    #[test]
    fn walk_validates_promoted_history() {
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let now = chrono::Utc::now();

        let mut genesis = boot_link(id, "sha256:v1", 0x20);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut upgrade = transition_upgrade_link(
            id,
            "sha256:v2",
            0x20,
            0x30,
            &sk,
            now - Duration::minutes(10),
        );
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        let mut promo = boot_link(id, "sha256:v2", 0x30);
        promo.id = Some(Uuid::new_v4());
        promo.sequence = Some(2);

        let links = vec![
            recorded(genesis, now - Duration::hours(2)),
            recorded(upgrade, now - Duration::minutes(11)),
            recorded(promo, now - Duration::minutes(9)),
        ];
        let row_pcrs = pcrs_hex_from_seed(0x30);
        let walk = validate_chain(&links, &row_pcrs, "sha256:v2", Some(&pk), true, now, true);

        for (i, outcome) in walk.outcomes.iter().enumerate() {
            assert!(
                matches!(outcome, Ok(Outcome::Append { sequence }) if *sequence == i as u64),
                "link {i}: {outcome:?}"
            );
        }
        assert!(walk.tip_matches_row);
        assert_eq!(walk.final_pcrs, Some(row_pcrs));
        assert_eq!(walk.final_image_digest, Some("sha256:v2".into()));
    }

    /// A boot whose measurements no prior upgrade link explains must
    /// reject, and the in-force tip must NOT advance to it, even when
    /// the enclave row already claims the new state.
    #[test]
    fn walk_rejects_unexplained_transition_boot() {
        let id = Uuid::new_v4();
        let now = chrono::Utc::now();

        let mut genesis = boot_link(id, "sha256:v1", 0x21);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut rogue = boot_link(id, "sha256:v2", 0x31);
        rogue.id = Some(Uuid::new_v4());
        rogue.sequence = Some(1);

        let links = vec![
            recorded(genesis, now - Duration::hours(1)),
            recorded(rogue, now - Duration::minutes(5)),
        ];
        let row_pcrs = pcrs_hex_from_seed(0x31);
        let walk = validate_chain(
            &links,
            &row_pcrs,
            "sha256:v2",
            Some(&[4u8; 65]),
            true,
            now,
            true,
        );

        assert!(matches!(
            walk.outcomes[0],
            Ok(Outcome::Append { sequence: 0 })
        ));
        assert!(walk.outcomes[1].is_err(), "{:?}", walk.outcomes[1]);
        // Tip stays at genesis, which the row no longer matches.
        assert!(!walk.tip_matches_row);
        assert_eq!(walk.final_pcrs, Some(pcrs_hex_from_seed(0x21)));
    }

    /// A boot of a REVOKED upgrade's target must reject: the revocation
    /// strips the upgrade link of its power to explain the transition.
    #[test]
    fn walk_rejects_boot_of_revoked_upgrade() {
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let now = chrono::Utc::now();

        let mut genesis = boot_link(id, "sha256:v1", 0x22);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        // Confirmed for the future, then revoked before activation.
        let mut upgrade =
            transition_upgrade_link(id, "sha256:v2", 0x22, 0x32, &sk, now + Duration::days(7));
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        let mut revoke = revocation_link(id, upgrade.id.unwrap(), 0x22, &sk);
        revoke.id = Some(Uuid::new_v4());
        revoke.sequence = Some(2);
        let mut rogue = boot_link(id, "sha256:v2", 0x32);
        rogue.id = Some(Uuid::new_v4());
        rogue.sequence = Some(3);

        let links = vec![
            recorded(genesis, now - Duration::hours(1)),
            recorded(upgrade, now - Duration::minutes(30)),
            recorded(revoke, now - Duration::minutes(20)),
            recorded(rogue, now - Duration::minutes(5)),
        ];
        let row_pcrs = pcrs_hex_from_seed(0x22);
        let walk = validate_chain(&links, &row_pcrs, "sha256:v1", Some(&pk), true, now, true);

        assert!(walk.outcomes[0].is_ok());
        assert!(walk.outcomes[1].is_ok());
        assert!(walk.outcomes[2].is_ok());
        assert!(walk.outcomes[3].is_err(), "{:?}", walk.outcomes[3]);
        // Still on v1, which the row agrees with.
        assert!(walk.tip_matches_row);
    }

    /// Historical revocations validate against their INGEST clock, not
    /// the verifier's: by walk time the revoked upgrade's `valid_from`
    /// has passed, and judging the revocation "now" would reject a
    /// link the backend legitimately recorded.
    #[test]
    fn walk_accepts_historical_revocation_after_target_activation() {
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let now = chrono::Utc::now();

        let mut genesis = boot_link(id, "sha256:v1", 0x23);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        // valid_from is an hour in the PAST relative to the walk...
        let mut upgrade =
            transition_upgrade_link(id, "sha256:v2", 0x23, 0x33, &sk, now - Duration::hours(1));
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        // ...but the revocation was recorded 30 minutes BEFORE that.
        let mut revoke = revocation_link(id, upgrade.id.unwrap(), 0x23, &sk);
        revoke.id = Some(Uuid::new_v4());
        revoke.sequence = Some(2);

        let links = vec![
            recorded(genesis, now - Duration::hours(3)),
            recorded(upgrade, now - Duration::hours(2)),
            recorded(revoke, now - Duration::minutes(90)),
        ];
        let row_pcrs = pcrs_hex_from_seed(0x23);
        let walk = validate_chain(&links, &row_pcrs, "sha256:v1", Some(&pk), true, now, true);

        assert!(
            walk.outcomes.iter().all(Result::is_ok),
            "{:?}",
            walk.outcomes
        );
        assert!(walk.tip_matches_row);

        // Sanity: the same chain judged entirely at `now` (no recorded
        // ingest times) rejects the revocation as past activation.
        let unstamped: Vec<RecordedLink> = links
            .iter()
            .map(|r| RecordedLink {
                link: r.link.clone(),
                recorded_at: None,
            })
            .collect();
        let walk_now = validate_chain(
            &unstamped,
            &row_pcrs,
            "sha256:v1",
            Some(&pk),
            true,
            now,
            true,
        );
        assert!(matches!(
            walk_now.outcomes[2],
            Err(ChainValidationError::RevokePastActivation)
        ));
    }

    // -----------------------------------------------------------------------
    // verify_pcr_descent (SDK trust_upgrades)
    // -----------------------------------------------------------------------

    /// boot(v1) -> upgrade(v1->v2) -> boot(v2) walked AFTER promotion.
    /// Returns the links plus the v1/v2 seeds and the control pubkey.
    fn two_version_chain(now: DateTime<Utc>) -> (Vec<RecordedLink>, Vec<u8>, u8, u8) {
        let (sk, pk) = keypair();
        let id = Uuid::new_v4();
        let (v1, v2) = (0x20u8, 0x30u8);

        let mut genesis = boot_link(id, "sha256:v1", v1);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut upgrade =
            transition_upgrade_link(id, "sha256:v2", v1, v2, &sk, now - Duration::minutes(10));
        upgrade.id = Some(Uuid::new_v4());
        upgrade.sequence = Some(1);
        let mut promo = boot_link(id, "sha256:v2", v2);
        promo.id = Some(Uuid::new_v4());
        promo.sequence = Some(2);

        let links = vec![
            recorded(genesis, now - Duration::hours(2)),
            recorded(upgrade, now - Duration::minutes(11)),
            recorded(promo, now - Duration::minutes(9)),
        ];
        (links, pk, v1, v2)
    }

    #[test]
    fn descent_pinned_genesis_returns_tip() {
        let now = chrono::Utc::now();
        let (links, pk, v1, v2) = two_version_chain(now);
        let row_pcrs = pcrs_hex_from_seed(v2);
        let pinned = pcrs_hex_from_seed(v1).to_pcrs().unwrap();

        let tip = verify_pcr_descent(
            &pinned,
            &links,
            Some(&pk),
            &row_pcrs,
            "sha256:v2",
            true,
            now,
            true,
        )
        .unwrap();
        // The tip is the v2 measurements the running enclave should show.
        assert_eq!(tip, pcrs_hex_from_seed(v2).to_pcrs().unwrap());
    }

    #[test]
    fn descent_pinned_current_tip_returns_tip() {
        // Pinning the CURRENT (post-upgrade) version is also "in lineage":
        // the tip itself is an in-force boot state.
        let now = chrono::Utc::now();
        let (links, pk, _v1, v2) = two_version_chain(now);
        let row_pcrs = pcrs_hex_from_seed(v2);
        let pinned = pcrs_hex_from_seed(v2).to_pcrs().unwrap();

        let tip = verify_pcr_descent(
            &pinned, &links, Some(&pk), &row_pcrs, "sha256:v2", true, now, true,
        )
        .unwrap();
        assert_eq!(tip, pinned);
    }

    #[test]
    fn descent_rejects_pin_not_in_chain() {
        // A fully-valid chain, but the pinned PCRs belong to neither the
        // genesis nor any promotion: this could be a real chain for a
        // different enclave. Must not extend trust.
        let now = chrono::Utc::now();
        let (links, pk, _v1, v2) = two_version_chain(now);
        let row_pcrs = pcrs_hex_from_seed(v2);
        let stranger = pcrs_hex_from_seed(0x77).to_pcrs().unwrap();

        let err = verify_pcr_descent(
            &stranger, &links, Some(&pk), &row_pcrs, "sha256:v2", true, now, true,
        )
        .unwrap_err();
        assert!(matches!(err, PcrDescentError::PinnedNotInLineage));
    }

    #[test]
    fn descent_rejects_tampered_link() {
        // Flip a byte in the upgrade payload: its attestation binding
        // (user_data == sha256(payload)) breaks, so the link fails and
        // the whole chain is rejected even though the pin matches genesis.
        let now = chrono::Utc::now();
        let (mut links, pk, v1, v2) = two_version_chain(now);
        links[1].link.payload[0] ^= 0xff;
        let row_pcrs = pcrs_hex_from_seed(v2);
        let pinned = pcrs_hex_from_seed(v1).to_pcrs().unwrap();

        let err = verify_pcr_descent(
            &pinned, &links, Some(&pk), &row_pcrs, "sha256:v2", true, now, true,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            PcrDescentError::LinkInvalid { position: 1, .. }
        ));
    }

    #[test]
    fn descent_rejects_unsigned_promotion() {
        // boot(v1) then a promotion boot(v2) with NO upgrade link
        // explaining the transition: the v2 boot fails the attestation
        // PCR check against the in-force v1 state. An attacker cannot
        // jump the measured version without a signed, attested upgrade.
        let now = chrono::Utc::now();
        let (_sk, pk) = keypair();
        let id = Uuid::new_v4();
        let (v1, v2) = (0x20u8, 0x30u8);

        let mut genesis = boot_link(id, "sha256:v1", v1);
        genesis.id = Some(Uuid::new_v4());
        genesis.sequence = Some(0);
        let mut rogue = boot_link(id, "sha256:v2", v2);
        rogue.id = Some(Uuid::new_v4());
        rogue.sequence = Some(1);
        let links = vec![
            recorded(genesis, now - Duration::hours(1)),
            recorded(rogue, now - Duration::minutes(1)),
        ];
        let pinned = pcrs_hex_from_seed(v1).to_pcrs().unwrap();

        let err = verify_pcr_descent(
            &pinned,
            &links,
            Some(&pk),
            &pcrs_hex_from_seed(v1),
            "sha256:v1",
            true,
            now,
            true,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            PcrDescentError::LinkInvalid { position: 1, .. }
        ));
    }

    #[test]
    fn descent_empty_chain_has_no_genesis() {
        let now = chrono::Utc::now();
        let pinned = pcrs_hex_from_seed(0x20).to_pcrs().unwrap();
        let err = verify_pcr_descent(
            &pinned,
            &[],
            None,
            &pcrs_hex_from_seed(0x20),
            "sha256:v1",
            true,
            now,
            true,
        )
        .unwrap_err();
        assert!(matches!(err, PcrDescentError::NoGenesis));
    }

    #[test]
    fn chain_link_json_round_trips_through_decode() {
        // into_chain_link is the SDK/CLI decode path: base64 wire fields
        // back to raw bytes, id/sequence carried, negative sequence
        // dropped.
        let id = Uuid::new_v4();
        let raw = boot_link(id, "sha256:v1", 0x20);
        let b64 = base64::engine::general_purpose::STANDARD;
        let wire = ChainLinkJson {
            id: Some(Uuid::new_v4()),
            kind: ChainLinkKind::Boot,
            sequence: Some(3),
            payload: b64.encode(&raw.payload),
            attestation: b64.encode(&raw.attestation),
            signature: None,
            created_at: None,
        };
        let decoded = wire.into_chain_link().unwrap();
        assert_eq!(decoded.payload, raw.payload);
        assert_eq!(decoded.attestation, raw.attestation);
        assert_eq!(decoded.sequence, Some(3));

        let bad = ChainLinkJson {
            payload: "not base64!!!".into(),
            ..wire.clone()
        };
        assert!(matches!(
            bad.into_chain_link(),
            Err(ChainLinkDecodeError::Base64 { field: "payload", .. })
        ));

        let neg = ChainLinkJson {
            sequence: Some(-1),
            ..wire
        };
        assert!(matches!(
            neg.into_chain_link(),
            Err(ChainLinkDecodeError::NegativeSequence(-1))
        ));
    }

    #[test]
    fn enclave_row_parses_array_control_key_and_pcr_casing() {
        let row = serde_json::json!({
            "upgradable": true,
            "image_digest": "sha256:abc",
            "pcrs": { "PCR0": "00", "PCR1": "11", "PCR2": "22" },
            "control_public_key": [4, 255, 0, 7],
        });
        let parsed: EnclaveChainRow = serde_json::from_value(row).unwrap();
        assert!(parsed.upgradable);
        assert_eq!(parsed.image_digest, "sha256:abc");
        assert_eq!(parsed.pcrs.pcr0, "00");
        assert_eq!(parsed.control_public_key, Some(vec![4u8, 255, 0, 7]));
    }

    #[test]
    fn enclave_row_accepts_base64_control_key_and_lowercase_pcrs() {
        let key = vec![4u8, 1, 2, 3];
        let row = serde_json::json!({
            "upgradable": true,
            "image_digest": "sha256:abc",
            "pcrs": { "pcr0": "aa", "pcr1": "bb", "pcr2": "cc" },
            "control_public_key": base64::engine::general_purpose::STANDARD.encode(&key),
        });
        let parsed: EnclaveChainRow = serde_json::from_value(row).unwrap();
        assert_eq!(parsed.pcrs.pcr1, "bb");
        assert_eq!(parsed.control_public_key, Some(key));
    }

    #[test]
    fn enclave_row_null_control_key_is_non_upgradable_and_upgradable_defaults_false() {
        let row = serde_json::json!({
            "image_digest": "sha256:abc",
            "pcrs": { "PCR0": "00", "PCR1": "11", "PCR2": "22" },
            "control_public_key": null,
        });
        let parsed: EnclaveChainRow = serde_json::from_value(row).unwrap();
        assert_eq!(parsed.control_public_key, None);
        assert!(!parsed.upgradable);
    }

    #[test]
    fn enclave_row_missing_image_digest_errors() {
        let row = serde_json::json!({
            "upgradable": true,
            "pcrs": { "PCR0": "00", "PCR1": "11", "PCR2": "22" },
        });
        assert!(serde_json::from_value::<EnclaveChainRow>(row).is_err());
    }
}