rite-sdk 0.7.0

Backend traits and domain types for the Rite cryptographic key ceremony toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
//! Data types shared between the runtime and backend implementations.
//!
//! These types form the vocabulary of the backend interface: key specifications,
//! algorithm identifiers, attestation evidence, and hardware-specific metadata.

use serde::{Deserialize, Serialize};
use std::fmt;

use crate::backend::BackendError;
use crate::key_material::PublicKeyDer;

/// Opaque key identifier (backend-specific).
///
/// This is an opaque reference to a key managed by a backend. The internal
/// format is backend-specific (e.g., `"slot_9c"` for `YubiKey` PIV, UUID for
/// software backend).
///
/// Ceremony DSL never interprets the contents of a `KeyId`; it is purely a
/// reference that gets passed back to the backend.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct KeyId(String);

impl KeyId {
    /// Create a new `KeyId` from a string.
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Return the `KeyId` as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for KeyId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for KeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for KeyId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for KeyId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// Metadata returned after key generation or import.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyMetadata {
    /// Opaque backend-specific key identifier.
    pub key_id: KeyId,
    /// Key algorithm.
    pub algorithm: KeyAlgorithm,
    /// Human-readable label.
    pub label: String,
    /// Public key, if the backend exports one.
    pub public_key: Option<PublicKeyDer>,
    /// Key check value, for a symmetric key.
    ///
    /// The counterpart of `public_key`: what the key answers to in the
    /// transcript and in the room. `None` for an asymmetric key, which is
    /// named by its public half.
    pub check_value: Option<KeyCheckValue>,
    /// Attestation evidence (if backend supports attestation).
    pub attestation: Option<Attestation>,
}

/// What a symmetric key answers to, in place of a public key.
///
/// AES-CMAC over a 16-byte zero block under the key, leftmost three bytes, as
/// specified for AES keys in ANSI X9.24-1 Annex A and used by TR-31. It is
/// what an HSM displays and what custodians read back, so a transcript
/// carrying it records the value the room checked rather than a parallel one
/// only Rite can compute.
///
/// Three bytes, not a digest of the key. A full-length hash of a secret is
/// what rite#126 removed from the transcript, and a reader cannot tell by
/// looking whether such a value came from a 256-bit key or a 4-digit PIN. The
/// truncation here is the part that makes it evident.
///
/// Renders as `cmac-aes:763cbc`. The method is in the string because the
/// older convention of encrypting a zero block in ECB is still in use and
/// gives a different answer for the same key.
///
/// ```
/// use rite_sdk::KeyCheckValue;
///
/// // A backend computes the CMAC; this keeps the leftmost bytes of it.
/// let cmac = [0x76, 0x3c, 0xbc, 0xde, 0x81, 0xdf, 0x91, 0x31];
/// let kcv = KeyCheckValue::from_cmac(&cmac)?;
///
/// assert_eq!(kcv.to_string(), "cmac-aes:763cbc");
/// assert_eq!(kcv.as_bytes(), &[0x76, 0x3c, 0xbc]);
///
/// // It round-trips through the string a transcript records.
/// assert_eq!("cmac-aes:763cbc".parse::<KeyCheckValue>()?, kcv);
/// // Uppercase hex is a different string for the same bytes, so it is not one.
/// assert!("cmac-aes:763CBC".parse::<KeyCheckValue>().is_err());
/// # Ok::<(), rite_sdk::ParseError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct KeyCheckValue([u8; Self::LEN]);

impl KeyCheckValue {
    /// Bytes kept from the CMAC output.
    pub const LEN: usize = 3;

    /// The name this construction goes by, and the string's prefix.
    pub const METHOD: &'static str = "cmac-aes";

    /// Keep the leftmost bytes of a CMAC output.
    ///
    /// # Errors
    ///
    /// If `cmac` is shorter than [`Self::LEN`], which no AES-CMAC is.
    pub fn from_cmac(cmac: &[u8]) -> Result<Self, ParseError> {
        cmac.get(..Self::LEN)
            .and_then(|head| head.try_into().ok())
            .map(Self)
            .ok_or_else(|| ParseError(format!("a CMAC of {} bytes", cmac.len())))
    }

    /// The kept bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; Self::LEN] {
        &self.0
    }
}

impl fmt::Display for KeyCheckValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:", Self::METHOD)?;
        for byte in self.0 {
            write!(f, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl std::str::FromStr for KeyCheckValue {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let hex = s
            .strip_prefix(Self::METHOD)
            .and_then(|rest| rest.strip_prefix(':'))
            // Lowercase only, so the string a `KeyCheckValue` parses from is
            // the string it renders back to and two records of one key
            // compare as text.
            .filter(|hex| {
                hex.len() == 2 * Self::LEN
                    && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
            })
            .ok_or_else(|| ParseError(s.to_owned()))?;
        let (pairs, _) = hex.as_bytes().as_chunks::<2>();
        let mut bytes = [0u8; Self::LEN];
        for (byte, pair) in bytes.iter_mut().zip(pairs) {
            let pair = std::str::from_utf8(pair).map_err(|_| ParseError(s.to_owned()))?;
            *byte = u8::from_str_radix(pair, 16).map_err(|_| ParseError(s.to_owned()))?;
        }
        Ok(Self(bytes))
    }
}

impl From<KeyCheckValue> for String {
    fn from(kcv: KeyCheckValue) -> String {
        kcv.to_string()
    }
}

impl TryFrom<String> for KeyCheckValue {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// Key algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
#[non_exhaustive]
pub enum KeyAlgorithm {
    /// RSA 2048-bit key.
    Rsa2048,
    /// RSA 4096-bit key.
    Rsa4096,
    /// ECDSA with P-256 curve (secp256r1).
    EcdsaP256,
    /// ECDSA with P-384 curve (secp384r1).
    EcdsaP384,
    /// Ed25519 (`EdDSA`).
    Ed25519,
    /// ML-DSA-44, module-lattice signature at NIST security category 2 (FIPS 204).
    MlDsa44,
    /// ML-DSA-65, module-lattice signature at NIST security category 3 (FIPS 204).
    MlDsa65,
    /// ML-DSA-87, module-lattice signature at NIST security category 5 (FIPS 204).
    MlDsa87,
    /// ML-KEM-512, module-lattice KEM at NIST security category 1 (FIPS 203).
    ///
    /// A KEM encapsulates, it does not sign. Such a key can receive a wrap and
    /// nothing else.
    MlKem512,
    /// ML-KEM-768, module-lattice KEM at NIST security category 3 (FIPS 203).
    MlKem768,
    /// ML-KEM-1024, module-lattice KEM at NIST security category 5 (FIPS 203).
    MlKem1024,
    /// AES 128-bit symmetric key.
    Aes128,
    /// AES 256-bit symmetric key.
    Aes256,
}

impl KeyAlgorithm {
    /// The signature algorithm to use with this key unless told otherwise.
    ///
    /// `None` for symmetric keys, which sign nothing.
    ///
    /// A key algorithm does not always determine a signature algorithm: RSA
    /// keys work with both PKCS#1 v1.5 and PSS, and this picks v1.5 for
    /// interoperability. Everywhere else the pairing is forced, either by the
    /// curve's matching digest strength (RFC 5480) or by the scheme naming its
    /// own digest (Ed25519, ML-DSA).
    #[must_use]
    pub fn default_sign_algorithm(self) -> Option<SignAlgorithm> {
        match self {
            KeyAlgorithm::Rsa2048 | KeyAlgorithm::Rsa4096 => Some(SignAlgorithm::RsaPkcs1Sha256),
            KeyAlgorithm::EcdsaP256 => Some(SignAlgorithm::EcdsaSha256),
            KeyAlgorithm::EcdsaP384 => Some(SignAlgorithm::EcdsaSha384),
            KeyAlgorithm::Ed25519 => Some(SignAlgorithm::Ed25519),
            KeyAlgorithm::MlDsa44 => Some(SignAlgorithm::MlDsa44),
            KeyAlgorithm::MlDsa65 => Some(SignAlgorithm::MlDsa65),
            KeyAlgorithm::MlDsa87 => Some(SignAlgorithm::MlDsa87),
            KeyAlgorithm::MlKem512
            | KeyAlgorithm::MlKem768
            | KeyAlgorithm::MlKem1024
            | KeyAlgorithm::Aes128
            | KeyAlgorithm::Aes256 => None,
        }
    }

    /// Whether a key of this algorithm can be the recipient of a wrap.
    ///
    /// A recipient has to be able to receive a content-encryption key, by key
    /// transport, key agreement, or encapsulation. A signature algorithm can
    /// do none of the three, however good a key it otherwise is, and this
    /// answers the question before a ceremony reaches the wrap step.
    #[must_use]
    pub fn can_receive_wrap(self) -> bool {
        match self {
            KeyAlgorithm::Rsa2048
            | KeyAlgorithm::Rsa4096
            | KeyAlgorithm::EcdsaP256
            | KeyAlgorithm::EcdsaP384
            | KeyAlgorithm::MlKem512
            | KeyAlgorithm::MlKem768
            | KeyAlgorithm::MlKem1024 => true,

            // Ed25519 and ML-DSA sign and nothing else. A symmetric key is a
            // pre-shared KEK, which is a different recipient form than the
            // ones Rite produces.
            KeyAlgorithm::Ed25519
            | KeyAlgorithm::MlDsa44
            | KeyAlgorithm::MlDsa65
            | KeyAlgorithm::MlDsa87
            | KeyAlgorithm::Aes128
            | KeyAlgorithm::Aes256 => false,
        }
    }

    /// Whether a key of this algorithm is one secret with no public half.
    ///
    /// ```
    /// use rite_sdk::KeyAlgorithm;
    ///
    /// assert!(KeyAlgorithm::Aes256.is_symmetric());
    /// assert_eq!(KeyAlgorithm::Aes256.key_bytes(), Some(32));
    ///
    /// assert!(!KeyAlgorithm::EcdsaP256.is_symmetric());
    /// assert_eq!(KeyAlgorithm::EcdsaP256.key_bytes(), None);
    /// ```
    ///
    /// This is the discriminator for everything that assumes a keypair: there
    /// is no public key to export, no SPKI to fingerprint, and no certificate
    /// to issue. A backend answers for such a key with a
    /// [`KeyCheckValue`](crate::KeyCheckValue) instead.
    #[must_use]
    pub fn is_symmetric(self) -> bool {
        self.key_bytes().is_some()
    }

    /// The length of the secret, for an algorithm whose key is raw bytes.
    ///
    /// `None` for an asymmetric algorithm, whose key has no single length a
    /// caller could ask for.
    #[must_use]
    pub fn key_bytes(self) -> Option<usize> {
        match self {
            KeyAlgorithm::Aes128 => Some(16),
            KeyAlgorithm::Aes256 => Some(32),
            KeyAlgorithm::Rsa2048
            | KeyAlgorithm::Rsa4096
            | KeyAlgorithm::EcdsaP256
            | KeyAlgorithm::EcdsaP384
            | KeyAlgorithm::Ed25519
            | KeyAlgorithm::MlDsa44
            | KeyAlgorithm::MlDsa65
            | KeyAlgorithm::MlDsa87
            | KeyAlgorithm::MlKem512
            | KeyAlgorithm::MlKem768
            | KeyAlgorithm::MlKem1024 => None,
        }
    }
}

impl fmt::Display for KeyAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyAlgorithm::Rsa2048 => write!(f, "RSA-2048"),
            KeyAlgorithm::Rsa4096 => write!(f, "RSA-4096"),
            KeyAlgorithm::EcdsaP256 => write!(f, "ECDSA-P256"),
            KeyAlgorithm::EcdsaP384 => write!(f, "ECDSA-P384"),
            KeyAlgorithm::Ed25519 => write!(f, "Ed25519"),
            KeyAlgorithm::MlDsa44 => write!(f, "ML-DSA-44"),
            KeyAlgorithm::MlDsa65 => write!(f, "ML-DSA-65"),
            KeyAlgorithm::MlDsa87 => write!(f, "ML-DSA-87"),
            KeyAlgorithm::MlKem512 => write!(f, "ML-KEM-512"),
            KeyAlgorithm::MlKem768 => write!(f, "ML-KEM-768"),
            KeyAlgorithm::MlKem1024 => write!(f, "ML-KEM-1024"),
            KeyAlgorithm::Aes128 => write!(f, "AES-128"),
            KeyAlgorithm::Aes256 => write!(f, "AES-256"),
        }
    }
}

/// Error returned when parsing an SDK algorithm identifier from a string fails.
///
/// Shared across all algorithm enums in this crate.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown value: {0:?}")]
pub struct ParseError(String);

impl std::str::FromStr for KeyAlgorithm {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "RSA-2048" => Ok(Self::Rsa2048),
            "RSA-4096" => Ok(Self::Rsa4096),
            "ECDSA-P256" => Ok(Self::EcdsaP256),
            "ECDSA-P384" => Ok(Self::EcdsaP384),
            "Ed25519" => Ok(Self::Ed25519),
            "ML-DSA-44" => Ok(Self::MlDsa44),
            "ML-DSA-65" => Ok(Self::MlDsa65),
            "ML-DSA-87" => Ok(Self::MlDsa87),
            "ML-KEM-512" => Ok(Self::MlKem512),
            "ML-KEM-768" => Ok(Self::MlKem768),
            "ML-KEM-1024" => Ok(Self::MlKem1024),
            "AES-128" => Ok(Self::Aes128),
            "AES-256" => Ok(Self::Aes256),
            _ => Err(ParseError(s.to_owned())),
        }
    }
}

impl From<KeyAlgorithm> for String {
    fn from(a: KeyAlgorithm) -> String {
        a.to_string()
    }
}

impl TryFrom<String> for KeyAlgorithm {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

bitflags::bitflags! {
    /// Key usage flags. Maps to PKCS#11 `CKA_SIGN`, `CKA_VERIFY`, etc.
    ///
    /// PIV ignores these (slot determines usage). PKCS#11 requires them at creation.
    /// Using bitflags rather than 7 bools: more compact for serialization, makes
    /// set operations natural, and avoids nonsensical bool combinations.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct KeyUsages: u8 {
        /// Key may be used to sign data.
        const SIGN    = 0b0000_0001;
        /// Key may be used to verify signatures.
        const VERIFY  = 0b0000_0010;
        /// Key may be used to encrypt data.
        const ENCRYPT = 0b0000_0100;
        /// Key may be used to decrypt data.
        const DECRYPT = 0b0000_1000;
        /// Key may be used to wrap other keys.
        const WRAP    = 0b0001_0000;
        /// Key may be used to unwrap other keys.
        const UNWRAP  = 0b0010_0000;
        /// Key may be used to derive other keys.
        const DERIVE  = 0b0100_0000;
    }
}

impl KeyUsages {
    /// Every usage, paired with the name a ceremony writes for it.
    ///
    /// The names are PKCS#11 vocabulary. They say what a key is permitted to do
    /// at the token, which is a different question from the `KeyUsage`
    /// extension a certificate carries.
    pub const NAMED: [(&'static str, KeyUsages); 7] = [
        ("sign", KeyUsages::SIGN),
        ("verify", KeyUsages::VERIFY),
        ("encrypt", KeyUsages::ENCRYPT),
        ("decrypt", KeyUsages::DECRYPT),
        ("wrap", KeyUsages::WRAP),
        ("unwrap", KeyUsages::UNWRAP),
        ("derive", KeyUsages::DERIVE),
    ];

    /// Look up a single usage by its ceremony name.
    ///
    /// Named to avoid colliding with the bitflags-generated `from_name`,
    /// which matches on the `SCREAMING_CASE` constant names instead.
    #[must_use]
    pub fn usage_named(name: &str) -> Option<Self> {
        Self::NAMED
            .iter()
            .find(|(candidate, _)| *candidate == name)
            .map(|(_, usage)| *usage)
    }

    /// The names of the usages in this set, in declaration order.
    #[must_use]
    pub fn names(self) -> Vec<&'static str> {
        Self::NAMED
            .iter()
            .filter(|(_, usage)| self.contains(*usage))
            .map(|(name, _)| *name)
            .collect()
    }

    /// Every usage name a ceremony may write, for a message listing what is
    /// available.
    #[must_use]
    pub fn all_names() -> Vec<&'static str> {
        Self::NAMED.iter().map(|(name, _)| *name).collect()
    }

    /// The usages in this set as one phrase, for an error message.
    #[must_use]
    pub fn describe(self) -> String {
        let names = self.names();
        if names.is_empty() {
            "nothing".to_string()
        } else {
            names.join(", ")
        }
    }
}

/// Security and usage policy for a generated or imported key.
///
/// Backends that cannot honour a requested policy MUST return
/// `BackendError::OperationNotPermitted` rather than silently ignoring it.
/// For example, a PIV backend receiving `extractable: true` must reject it
/// because PIV keys are always non-extractable by hardware design.
// Each bool maps directly to a named PKCS#11 boolean attribute (CKA_TOKEN,
// CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_WRAP_WITH_TRUSTED). Converting these
// to two-variant enums would add type noise with no semantic benefit.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyPolicy {
    /// Key persists after session ends. Always `true` for PIV. `CKA_TOKEN` in PKCS#11.
    pub persistent: bool,
    /// Key material never revealed in plaintext. Always `true` for PIV. `CKA_SENSITIVE`.
    pub sensitive: bool,
    /// Key can be wrapped and exported. Always `false` for PIV. `CKA_EXTRACTABLE`.
    pub extractable: bool,
    /// Key can only be wrapped by a `CKA_TRUSTED` wrapping key. PKCS#11 `CKA_WRAP_WITH_TRUSTED`.
    pub wrap_with_trusted_only: bool,
    /// What operations this key is permitted to perform.
    pub usages: KeyUsages,
}

impl KeyPolicy {
    /// Refuse an operation this policy does not allow.
    ///
    /// The policy is what the ceremony asked for at generation. A token
    /// enforces it itself; a software backend has no token, so it calls this.
    ///
    /// # Errors
    ///
    /// Returns [`BackendError::OperationNotPermitted`] when `usage` is absent
    /// from the policy, naming what the key may do instead.
    pub fn require(&self, usage: KeyUsages, operation: &str) -> Result<(), BackendError> {
        if self.usages.contains(usage) {
            return Ok(());
        }
        Err(BackendError::OperationNotPermitted(format!(
            "this key may not {operation}: its policy allows {}. \
             Declare the usage under `policy:` on the step that generates it.",
            self.usages.describe()
        )))
    }
}

impl KeyPolicy {
    /// What a key of this algorithm may do when the ceremony says nothing.
    ///
    /// A generation step should call this rather than [`Default`], which is
    /// the signing default and gives a symmetric key two usages it can never
    /// have. Rite holds a symmetric key as a key-encryption key and nothing
    /// else, so wrap and unwrap is the whole of what one is for here.
    ///
    /// ```
    /// use rite_sdk::{KeyAlgorithm, KeyPolicy, KeyUsages};
    ///
    /// let signing = KeyPolicy::default_for(KeyAlgorithm::EcdsaP256);
    /// assert_eq!(signing.usages, KeyUsages::SIGN | KeyUsages::VERIFY);
    ///
    /// let kek = KeyPolicy::default_for(KeyAlgorithm::Aes256);
    /// assert_eq!(kek.usages, KeyUsages::WRAP | KeyUsages::UNWRAP);
    ///
    /// // Everything else is the restrictive default either way.
    /// assert!(!kek.extractable);
    /// ```
    #[must_use]
    pub fn default_for(algorithm: KeyAlgorithm) -> Self {
        if algorithm.is_symmetric() {
            Self {
                usages: KeyUsages::WRAP | KeyUsages::UNWRAP,
                ..Self::default()
            }
        } else {
            Self::default()
        }
    }
}

impl Default for KeyPolicy {
    /// Most secure configuration for ceremony signing keys:
    /// persistent=true, sensitive=true, extractable=false, sign+verify only.
    fn default() -> Self {
        Self {
            persistent: true,
            sensitive: true,
            extractable: false,
            wrap_with_trusted_only: false,
            usages: KeyUsages::SIGN | KeyUsages::VERIFY,
        }
    }
}

/// Full specification for key generation or import.
///
/// Replaces the `(algorithm, label, slot_hint)` triplet with a structured type
/// that can carry PKCS#11 policy attributes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeySpec {
    /// Key algorithm.
    pub algorithm: KeyAlgorithm,
    /// Human-readable label.
    pub label: String,
    /// Security and usage policy.
    pub policy: KeyPolicy,
    /// Backend-specific location hint.
    /// PIV: "9c" maps to Signature slot. PKCS#11: slot index or partition label.
    /// Software: ignored.
    pub location_hint: Option<String>,
}

/// PKCS#11 key security attributes read from an HSM after key generation.
///
/// Records HSM-managed attribute state as evidence of key provenance and
/// policy compliance in the ceremony transcript.
// Each bool maps directly to a named PKCS#11 boolean attribute (CKA_ALWAYS_SENSITIVE,
// CKA_NEVER_EXTRACTABLE, CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_WRAP_WITH_TRUSTED).
// These are distinct concepts; collapsing them into enums would obscure the PKCS#11 semantics.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeySecurityAttributes {
    /// Key was ALWAYS sensitive: never had `CKA_SENSITIVE=false` since creation.
    /// This is the primary provenance indicator for PKCS#11 keys.
    pub always_sensitive: bool,
    /// Key was NEVER extractable: never had `CKA_EXTRACTABLE=true` since creation.
    pub never_extractable: bool,
    /// Current value of `CKA_SENSITIVE`.
    pub sensitive: bool,
    /// Current value of `CKA_EXTRACTABLE`.
    pub extractable: bool,
    /// Key can only be wrapped by a key with `CKA_TRUSTED=true` (`CKA_WRAP_WITH_TRUSTED`).
    pub wrap_with_trusted_only: bool,
    /// What operations this key is permitted to perform (read from key object).
    pub usages: KeyUsages,
}

/// Signature algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
#[non_exhaustive]
pub enum SignAlgorithm {
    /// RSASSA-PKCS1-v1_5 with SHA-256.
    RsaPkcs1Sha256,
    /// RSASSA-PSS with SHA-256.
    RsaPssSha256,
    /// ECDSA with SHA-256.
    EcdsaSha256,
    /// ECDSA with SHA-384.
    EcdsaSha384,
    /// Ed25519 (pure `EdDSA`, no hash function).
    Ed25519,
    /// ML-DSA-44 (pure, no pre-hash). FIPS 204.
    MlDsa44,
    /// ML-DSA-65 (pure, no pre-hash). FIPS 204.
    MlDsa65,
    /// ML-DSA-87 (pure, no pre-hash). FIPS 204.
    MlDsa87,
}

impl SignAlgorithm {
    /// A representative key algorithm for this signature algorithm.
    ///
    /// Used where a signature request must be turned into a concrete key
    /// algorithm: selecting a card algorithm, or minting a stand-in key for a
    /// rehearsal. Keeping that mapping here means those callers cannot drift
    /// apart from each other.
    ///
    /// The mapping is deliberately lossy for RSA: both RSA schemes answer
    /// `Rsa2048`, because a signature algorithm does not name a modulus size.
    /// Use [`accepts_key`](Self::accepts_key) to test whether a key may be used
    /// with this algorithm; the equality `alg.key_algorithm() == key` is not
    /// that test and rejects RSA-4096 keys.
    #[must_use]
    pub fn key_algorithm(self) -> KeyAlgorithm {
        match self {
            SignAlgorithm::RsaPkcs1Sha256 | SignAlgorithm::RsaPssSha256 => KeyAlgorithm::Rsa2048,
            SignAlgorithm::EcdsaSha256 => KeyAlgorithm::EcdsaP256,
            SignAlgorithm::EcdsaSha384 => KeyAlgorithm::EcdsaP384,
            SignAlgorithm::Ed25519 => KeyAlgorithm::Ed25519,
            SignAlgorithm::MlDsa44 => KeyAlgorithm::MlDsa44,
            SignAlgorithm::MlDsa65 => KeyAlgorithm::MlDsa65,
            SignAlgorithm::MlDsa87 => KeyAlgorithm::MlDsa87,
        }
    }

    /// Whether a key of `key_algorithm` may be used with this signature algorithm.
    ///
    /// The compatibility check every signing backend needs, kept in one place.
    /// Curve and parameter set are pinned: ECDSA-SHA256 will not take a P-384
    /// key. Only the RSA schemes span more than one key algorithm, since they
    /// are defined for any modulus size.
    #[must_use]
    pub fn accepts_key(self, key_algorithm: KeyAlgorithm) -> bool {
        match self {
            SignAlgorithm::RsaPkcs1Sha256 | SignAlgorithm::RsaPssSha256 => {
                matches!(key_algorithm, KeyAlgorithm::Rsa2048 | KeyAlgorithm::Rsa4096)
            }
            // Every other scheme pins exactly one key algorithm, already named
            // by `key_algorithm`. Reuse it rather than repeating the pairing.
            SignAlgorithm::EcdsaSha256
            | SignAlgorithm::EcdsaSha384
            | SignAlgorithm::Ed25519
            | SignAlgorithm::MlDsa44
            | SignAlgorithm::MlDsa65
            | SignAlgorithm::MlDsa87 => self.key_algorithm() == key_algorithm,
        }
    }
}

impl fmt::Display for SignAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SignAlgorithm::RsaPkcs1Sha256 => write!(f, "RSA-PKCS1-SHA256"),
            SignAlgorithm::RsaPssSha256 => write!(f, "RSA-PSS-SHA256"),
            SignAlgorithm::EcdsaSha256 => write!(f, "ECDSA-SHA256"),
            SignAlgorithm::EcdsaSha384 => write!(f, "ECDSA-SHA384"),
            SignAlgorithm::Ed25519 => write!(f, "Ed25519"),
            SignAlgorithm::MlDsa44 => write!(f, "ML-DSA-44"),
            SignAlgorithm::MlDsa65 => write!(f, "ML-DSA-65"),
            SignAlgorithm::MlDsa87 => write!(f, "ML-DSA-87"),
        }
    }
}

impl std::str::FromStr for SignAlgorithm {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "RSA-PKCS1-SHA256" => Ok(Self::RsaPkcs1Sha256),
            "RSA-PSS-SHA256" => Ok(Self::RsaPssSha256),
            "ECDSA-SHA256" => Ok(Self::EcdsaSha256),
            "ECDSA-SHA384" => Ok(Self::EcdsaSha384),
            "Ed25519" => Ok(Self::Ed25519),
            "ML-DSA-44" => Ok(Self::MlDsa44),
            "ML-DSA-65" => Ok(Self::MlDsa65),
            "ML-DSA-87" => Ok(Self::MlDsa87),
            _ => Err(ParseError(s.to_owned())),
        }
    }
}

impl From<SignAlgorithm> for String {
    fn from(a: SignAlgorithm) -> String {
        a.to_string()
    }
}

impl TryFrom<String> for SignAlgorithm {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// An ASN.1 object identifier in dotted-decimal form.
///
/// Wrapping evidence is a set of algorithm identifiers read back out of the
/// produced artifact, so the OID is the value that gets recorded. Held as text
/// because that is what a transcript reader compares against a registry.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct Oid(String);

impl Oid {
    /// Parse a dotted-decimal OID.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] unless the value is two or more arcs of decimal
    /// digits separated by dots.
    pub fn new(value: &str) -> Result<Self, ParseError> {
        let arcs: Vec<&str> = value.split('.').collect();
        let well_formed = arcs.len() >= 2
            && arcs
                .iter()
                .all(|arc| !arc.is_empty() && arc.bytes().all(|b| b.is_ascii_digit()));
        if well_formed {
            Ok(Self(value.to_owned()))
        } else {
            Err(ParseError(value.to_owned()))
        }
    }

    /// The dotted-decimal form.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Oid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<Oid> for String {
    fn from(oid: Oid) -> String {
        oid.0
    }
}

impl TryFrom<String> for Oid {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Oid::new(&s)
    }
}

/// Well-known OIDs the wrapping paths produce or check.
pub mod oid {
    /// `rsaEncryption`, RSAES-PKCS1-v1.5 key transport (RFC 8017).
    pub const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
    /// `id-RSAES-OAEP` (RFC 8017).
    pub const RSAES_OAEP: &str = "1.2.840.113549.1.1.7";
    /// `dhSinglePass-stdDH-sha1kdf-scheme`, one-pass ECDH with the X9.63 KDF
    /// over SHA-1 (RFC 5753).
    pub const DH_SINGLE_PASS_STDDH_SHA1KDF: &str = "1.3.133.16.840.63.0.2";
    /// `id-aes256-GCM` (RFC 5084).
    pub const AES_256_GCM: &str = "2.16.840.1.101.3.4.1.46";
    /// `id-aes256-CBC` (RFC 3565).
    pub const AES_256_CBC: &str = "2.16.840.1.101.3.4.1.42";
    /// `id-aes256-wrap`, AES Key Wrap with a 256-bit KEK (RFC 3394).
    pub const AES_256_WRAP: &str = "2.16.840.1.101.3.4.1.45";
    /// `id-aes128-wrap`, AES Key Wrap with a 128-bit KEK (RFC 3394).
    pub const AES_128_WRAP: &str = "2.16.840.1.101.3.4.1.5";
    /// `id-aes256-wrap-pad`, AES Key Wrap with Padding (RFC 5649).
    pub const AES_256_WRAP_PAD: &str = "2.16.840.1.101.3.4.1.48";
    /// `id-aes128-wrap-pad`, AES Key Wrap with Padding (RFC 5649).
    pub const AES_128_WRAP_PAD: &str = "2.16.840.1.101.3.4.1.8";
}

/// How a CMS structure conveys the content-encryption key to its recipient.
///
/// The variants are the `RecipientInfo` CHOICE of RFC 5652 §6.2, plus the
/// KEM alternative RFC 9629 carries inside `OtherRecipientInfo`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RecipientInfoKind {
    /// `KeyTransRecipientInfo`: the CEK is encrypted under the recipient's
    /// public key.
    Ktri,
    /// `KeyAgreeRecipientInfo`: a shared secret is agreed with the recipient's
    /// key, run through a KDF, and used to wrap the CEK.
    Kari,
    /// `KEKRecipientInfo`: the CEK is wrapped under a previously shared
    /// symmetric key.
    Kekri,
    /// `KEMRecipientInfo` (RFC 9629), carried as `OtherRecipientInfo`.
    Kemri,
    /// `PasswordRecipientInfo`.
    Pwri,
    /// An `OtherRecipientInfo` this build does not recognise.
    Ori,
}

impl fmt::Display for RecipientInfoKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RecipientInfoKind::Ktri => write!(f, "ktri"),
            RecipientInfoKind::Kari => write!(f, "kari"),
            RecipientInfoKind::Kekri => write!(f, "kekri"),
            RecipientInfoKind::Kemri => write!(f, "kemri"),
            RecipientInfoKind::Pwri => write!(f, "pwri"),
            RecipientInfoKind::Ori => write!(f, "ori"),
        }
    }
}

/// What a wrap actually did.
///
/// The scheme a step requests names a family. The algorithms inside it move
/// independently: the recipient's key type selects the encapsulation, the
/// content cipher selects the KEK size, and the KDF digest is a library
/// default rather than a property of any key.
///
/// Where the scheme is self-describing this is an observation, re-derivable
/// from the blob alone, which is what makes it evidence. Where it is not, it
/// is what the backend invoked. [`WrapScheme::is_self_describing`] is the
/// difference, and `rite verify` reports the two differently.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WrapDescription {
    /// How the CEK reaches the recipient, for a scheme built on CMS.
    ///
    /// Absent for a raw mechanism, whose output carries no `RecipientInfo`
    /// and no other ASN.1 structure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recipient_info: Option<RecipientInfoKind>,
    /// The key-encryption algorithm: key transport for `ktri`, the
    /// key-agreement scheme for `kari`.
    pub key_encryption_oid: Oid,
    /// The KDF, where the encapsulation derives a KEK.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kdf_oid: Option<Oid>,
    /// The algorithm wrapping the CEK under the derived KEK.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kek_wrap_oid: Option<Oid>,
    /// The content cipher, for schemes that encrypt the key as CMS content.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_encryption_oid: Option<Oid>,
}

impl WrapDescription {
    /// Describe a CMS wrap by its recipient info and key-encryption algorithm.
    #[must_use]
    pub fn new(recipient_info: RecipientInfoKind, key_encryption_oid: Oid) -> Self {
        Self {
            recipient_info: Some(recipient_info),
            key_encryption_oid,
            kdf_oid: None,
            kek_wrap_oid: None,
            content_encryption_oid: None,
        }
    }

    /// Describe a raw mechanism, which has no CMS structure around it.
    #[must_use]
    pub fn raw(key_encryption_oid: Oid) -> Self {
        Self {
            recipient_info: None,
            key_encryption_oid,
            kdf_oid: None,
            kek_wrap_oid: None,
            content_encryption_oid: None,
        }
    }

    /// Record the KDF the encapsulation ran.
    #[must_use]
    pub fn with_kdf(mut self, oid: Oid) -> Self {
        self.kdf_oid = Some(oid);
        self
    }

    /// Record the algorithm that wrapped the CEK under the derived KEK.
    #[must_use]
    pub fn with_kek_wrap(mut self, oid: Oid) -> Self {
        self.kek_wrap_oid = Some(oid);
        self
    }

    /// Record the content cipher.
    #[must_use]
    pub fn with_content_encryption(mut self, oid: Oid) -> Self {
        self.content_encryption_oid = Some(oid);
        self
    }

    /// Whether the CMS content was encrypted under an authenticated cipher.
    ///
    /// True only for AES-256-GCM, the one authenticated cipher Rite writes, so
    /// a foreign blob under another AEAD reads as unauthenticated here. It asks
    /// about a CMS content cipher and nothing else, so it is `false` for every
    /// raw mechanism, including ones that authenticate by other means.
    #[must_use]
    pub fn content_is_authenticated(&self) -> bool {
        self.content_encryption_oid
            .as_ref()
            .is_some_and(|oid| oid.as_str() == oid::AES_256_GCM)
    }
}

/// The wrapping scheme a step requests, or a backend reports.
///
/// A scheme names a container and the parts of it Rite fixes. What varies
/// with the recipient is recorded in [`WrapDescription`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
#[non_exhaustive]
pub enum WrapScheme {
    /// CMS `AuthEnvelopedData` (RFC 5083) with AES-256-GCM content
    /// encryption. Output: CMS `ContentInfo` DER.
    ///
    /// The encapsulation follows the recipient key: RSA takes key transport,
    /// EC takes the RFC 5753 key-agreement path, and a KEM recipient takes the
    /// RFC 9629 key-encapsulation path.
    ///
    /// `CMS-RSA-CBC`, the `EnvelopedData` variant with AES-256-CBC, was
    /// removed. It carried no integrity protection, so unwrapping imported
    /// whatever decrypted; PCI PIN v3.1 requirement 18-3 bans unauthenticated
    /// key encryption. Restoring it would take an authenticated construction
    /// around it, which is what the deployments that do use CBC (X9 TR-34,
    /// AD CS key archival) wrap it in.
    CmsAes256Gcm,
    /// RSAES-OAEP with SHA-256, as raw ciphertext (RFC 8017).
    ///
    /// Output is exactly the modulus size and describes nothing about itself.
    /// The payload ceiling is `k - 2*hLen - 2`: 190 bytes under RSA-2048, 446
    /// under RSA-4096, which fits a symmetric key or an EC private key and
    /// never fits an RSA one. [`Self::RsaAesKeyWrapSha256`] exists for that.
    RsaOaepSha256,
    /// RSA-AES key wrap with SHA-256 (PKCS#11 `CKM_RSA_AES_KEY_WRAP`).
    ///
    /// An ephemeral AES key under RSAES-OAEP, concatenated with the payload
    /// under AES-KWP (RFC 5649). The OAEP part comes first and is exactly the
    /// modulus size, which is how a recipient splits the two.
    ///
    /// This is the shape cloud KMS import expects, and it carries no size
    /// ceiling. The digest is in the name because it is not recoverable from
    /// the bytes and recipients differ: AWS names both `RSA_AES_KEY_WRAP_SHA_256`
    /// and `RSA_AES_KEY_WRAP_SHA_1`, and Azure BYOK specifies SHA-1.
    RsaAesKeyWrapSha256,
    /// AES Key Wrap under a 128-bit KEK (RFC 3394, PKCS#11
    /// `CKM_AES_KEY_WRAP`).
    ///
    /// The payload must be a multiple of 8 bytes and at least 16, which a
    /// PKCS#8 private key is not, so this carries another symmetric key and
    /// little else. [`Self::Aes128Kwp`] has no such rule.
    Aes128Kw,
    /// AES Key Wrap under a 256-bit KEK (RFC 3394).
    Aes256Kw,
    /// AES Key Wrap with Padding under a 128-bit KEK (RFC 5649, PKCS#11
    /// `CKM_AES_KEY_WRAP_KWP`).
    ///
    /// Carries a payload of any length. This is what Thales recommends over
    /// CBC for wrapping, and what `OpenStack` Barbican moved to in 2024 after
    /// its hardcoded `CKM_AES_CBC_PAD` broke against Luna firmware in FIPS
    /// mode.
    Aes128Kwp,
    /// AES Key Wrap with Padding under a 256-bit KEK (RFC 5649).
    Aes256Kwp,
}

impl WrapScheme {
    /// The description this scheme fixes, where it fixes one.
    ///
    /// `None` for a self-describing scheme: what a CMS wrap did follows the
    /// recipient key, so it is read out of the artifact rather than known in
    /// advance. A raw mechanism has no such freedom, which is the same fact
    /// that makes its description an assertion.
    ///
    /// This is the one place that says what a raw scheme produces. A backend
    /// builds its description from here rather than restating the OIDs, and
    /// [`permits`](Self::permits) compares against it, so the two cannot
    /// disagree.
    #[must_use]
    pub fn fixed_description(self) -> Option<WrapDescription> {
        // Constructed directly rather than through the validating `Oid::new`:
        // these are this module's own constants, so there is no input to
        // reject and no error a caller could act on.
        let known = |value: &str| Oid(value.to_owned());
        match self {
            WrapScheme::CmsAes256Gcm => None,
            WrapScheme::RsaOaepSha256 => Some(WrapDescription::raw(known(oid::RSAES_OAEP))),
            WrapScheme::Aes128Kw => Some(WrapDescription::raw(known(oid::AES_128_WRAP))),
            WrapScheme::Aes256Kw => Some(WrapDescription::raw(known(oid::AES_256_WRAP))),
            WrapScheme::Aes128Kwp => Some(WrapDescription::raw(known(oid::AES_128_WRAP_PAD))),
            WrapScheme::Aes256Kwp => Some(WrapDescription::raw(known(oid::AES_256_WRAP_PAD))),
            WrapScheme::RsaAesKeyWrapSha256 => Some(
                WrapDescription::raw(known(oid::RSAES_OAEP))
                    .with_kek_wrap(known(oid::AES_256_WRAP_PAD)),
            ),
        }
    }

    /// The one key algorithm this scheme wraps under, where it names one.
    ///
    /// ```
    /// use rite_sdk::{KeyAlgorithm, WrapScheme};
    ///
    /// assert_eq!(WrapScheme::Aes256Kwp.required_kek(), Some(KeyAlgorithm::Aes256));
    /// // CMS admits a family, so it names none.
    /// assert_eq!(WrapScheme::CmsAes256Gcm.required_kek(), None);
    /// ```
    ///
    /// `None` where the scheme admits a family rather than a single algorithm.
    /// The AES schemes name a KEK size, because the RFC 3394 and RFC 5649
    /// object identifiers are per-size and [`fixed_description`](Self::fixed_description)
    /// has only the scheme to go on. Naming it is also what makes a ceremony
    /// that expects a 256-bit KEK refuse a 128-bit one instead of wrapping
    /// under it in silence.
    #[must_use]
    pub fn required_kek(self) -> Option<KeyAlgorithm> {
        match self {
            WrapScheme::CmsAes256Gcm
            | WrapScheme::RsaOaepSha256
            | WrapScheme::RsaAesKeyWrapSha256 => None,
            WrapScheme::Aes128Kw | WrapScheme::Aes128Kwp => Some(KeyAlgorithm::Aes128),
            WrapScheme::Aes256Kw | WrapScheme::Aes256Kwp => Some(KeyAlgorithm::Aes256),
        }
    }

    /// Whether a key of this algorithm can receive a wrap under this scheme.
    ///
    /// Narrower than [`KeyAlgorithm::can_receive_wrap`], which answers for CMS,
    /// where the recipient key selects the encapsulation. The RSA mechanisms
    /// accept nothing but RSA, and the AES mechanisms nothing but the KEK size
    /// in their name.
    ///
    /// A symmetric key passes here and still cannot arrive as `recipient:`,
    /// since that path takes a public key and a symmetric key has none. An
    /// AES scheme is reachable only under `wrapping_key:`.
    #[must_use]
    pub fn accepts_recipient(self, algorithm: KeyAlgorithm) -> bool {
        match self {
            WrapScheme::CmsAes256Gcm => algorithm.can_receive_wrap(),
            WrapScheme::RsaOaepSha256 | WrapScheme::RsaAesKeyWrapSha256 => match algorithm {
                KeyAlgorithm::Rsa2048 | KeyAlgorithm::Rsa4096 => true,
                KeyAlgorithm::EcdsaP256
                | KeyAlgorithm::EcdsaP384
                | KeyAlgorithm::Ed25519
                | KeyAlgorithm::MlDsa44
                | KeyAlgorithm::MlDsa65
                | KeyAlgorithm::MlDsa87
                | KeyAlgorithm::MlKem512
                | KeyAlgorithm::MlKem768
                | KeyAlgorithm::MlKem1024
                | KeyAlgorithm::Aes128
                | KeyAlgorithm::Aes256 => false,
            },
            WrapScheme::Aes128Kw
            | WrapScheme::Aes256Kw
            | WrapScheme::Aes128Kwp
            | WrapScheme::Aes256Kwp => self.required_kek() == Some(algorithm),
        }
    }

    /// Whether `description` is one this scheme admits.
    ///
    /// The check is what keeps a recorded scheme from contradicting the
    /// artifact it labels. For a self-describing scheme it is a structural
    /// test against what was read out of the bytes; for a raw mechanism the
    /// description is fixed, so equality is the whole test.
    #[must_use]
    pub fn permits(self, description: &WrapDescription) -> bool {
        if let Some(fixed) = self.fixed_description() {
            return *description == fixed;
        }
        // `kekri` joins the three public-key encapsulations: the recipient is
        // a key both sides hold rather than one the wrap reaches by public
        // key, and the container and its guarantees are the same either way.
        let encapsulation_fits = matches!(
            description.recipient_info,
            Some(
                RecipientInfoKind::Ktri
                    | RecipientInfoKind::Kari
                    | RecipientInfoKind::Kemri
                    | RecipientInfoKind::Kekri
            )
        );
        description.content_is_authenticated() && encapsulation_fits
    }

    /// Whether a verifier can re-derive the wrap's algorithms from the bytes.
    ///
    /// This is the line between evidence and assertion. A CMS artifact carries
    /// its own algorithm identifiers, so `rite verify` reads them back and
    /// compares them against the transcript; raw mechanism output carries
    /// nothing, so the recorded algorithms are what the backend reports having
    /// invoked and no offline check can confirm them.
    ///
    /// Matched exhaustively on purpose: a scheme added without answering this
    /// would otherwise default into being treated as evidence.
    #[must_use]
    pub fn is_self_describing(self) -> bool {
        match self {
            WrapScheme::CmsAes256Gcm => true,
            WrapScheme::RsaOaepSha256
            | WrapScheme::RsaAesKeyWrapSha256
            | WrapScheme::Aes128Kw
            | WrapScheme::Aes256Kw
            | WrapScheme::Aes128Kwp
            | WrapScheme::Aes256Kwp => false,
        }
    }

    /// Whether the scheme carries content of any length, as opposed to a key.
    ///
    /// A container encrypts the content under its own key and addresses only
    /// that key to the recipient, so what goes in is arbitrary. A raw mechanism
    /// encrypts the payload directly under the recipient's key, which bounds it
    /// to roughly a key's size.
    ///
    /// A separate question from [`is_self_describing`](Self::is_self_describing),
    /// which draws the same line today. That one asks whether a verifier can
    /// re-derive the algorithms, and this one asks what may be put in. Keeping
    /// them apart is what lets them diverge honestly when a second container
    /// lands.
    ///
    /// Matched exhaustively on purpose: a scheme added without answering this
    /// would otherwise default into accepting a file.
    #[must_use]
    pub fn carries_content(self) -> bool {
        match self {
            WrapScheme::CmsAes256Gcm => true,
            WrapScheme::RsaOaepSha256
            | WrapScheme::RsaAesKeyWrapSha256
            | WrapScheme::Aes128Kw
            | WrapScheme::Aes256Kw
            | WrapScheme::Aes128Kwp
            | WrapScheme::Aes256Kwp => false,
        }
    }
}

impl fmt::Display for WrapScheme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WrapScheme::CmsAes256Gcm => write!(f, "CMS-AES-256-GCM"),
            WrapScheme::RsaOaepSha256 => write!(f, "RSA-OAEP-SHA256"),
            WrapScheme::RsaAesKeyWrapSha256 => write!(f, "RSA-AES-KEY-WRAP-SHA256"),
            WrapScheme::Aes128Kw => write!(f, "AES-128-KW"),
            WrapScheme::Aes256Kw => write!(f, "AES-256-KW"),
            WrapScheme::Aes128Kwp => write!(f, "AES-128-KWP"),
            WrapScheme::Aes256Kwp => write!(f, "AES-256-KWP"),
        }
    }
}

impl std::str::FromStr for WrapScheme {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "CMS-AES-256-GCM" => Ok(Self::CmsAes256Gcm),
            "RSA-OAEP-SHA256" => Ok(Self::RsaOaepSha256),
            "RSA-AES-KEY-WRAP-SHA256" => Ok(Self::RsaAesKeyWrapSha256),
            "AES-128-KW" => Ok(Self::Aes128Kw),
            "AES-256-KW" => Ok(Self::Aes256Kw),
            "AES-128-KWP" => Ok(Self::Aes128Kwp),
            "AES-256-KWP" => Ok(Self::Aes256Kwp),
            _ => Err(ParseError(s.to_owned())),
        }
    }
}

impl From<WrapScheme> for String {
    fn from(a: WrapScheme) -> String {
        a.to_string()
    }
}

impl TryFrom<String> for WrapScheme {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// Bytes in a container, the scheme that produced them, and what that
/// operation actually did.
///
/// The three are constructed together and read together: a scheme that does not
/// admit the description would label the bytes with something the bytes
/// contradict.
///
/// Private, because a container on its own says nothing about what is inside
/// it. [`WrappedKey`] and [`EncryptedData`] are the two public forms, and the
/// difference between them is the claim their step made, not the bytes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "ContainerRepr")]
struct Container {
    scheme: WrapScheme,
    description: WrapDescription,
    data: Vec<u8>,
}

/// Deserialization shape for [`Container`], re-checked on the way in.
#[derive(Deserialize)]
struct ContainerRepr {
    scheme: WrapScheme,
    description: WrapDescription,
    data: Vec<u8>,
}

impl TryFrom<ContainerRepr> for Container {
    type Error = IncoherentContainer;

    fn try_from(repr: ContainerRepr) -> Result<Self, Self::Error> {
        Container::new(repr.scheme, repr.description, repr.data)
    }
}

impl Container {
    fn new(
        scheme: WrapScheme,
        description: WrapDescription,
        data: Vec<u8>,
    ) -> Result<Self, IncoherentContainer> {
        if scheme.permits(&description) {
            Ok(Self {
                scheme,
                description,
                data,
            })
        } else {
            Err(IncoherentContainer {
                scheme,
                description,
            })
        }
    }
}

/// A container was labelled with a scheme its own description contradicts.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("scheme {scheme} does not admit this container: {description:?}")]
pub struct IncoherentContainer {
    /// The scheme the bytes were labelled with.
    pub scheme: WrapScheme,
    /// What the artifact says was done.
    pub description: WrapDescription,
}

/// Give a container newtype the three accessors and the checking constructor.
///
/// Both forms answer the same three questions about their bytes. What they do
/// not share is which steps accept them, which is the whole reason there are
/// two types rather than one.
macro_rules! container_newtype {
    ($name:ident, $what:literal) => {
        impl $name {
            #[doc = concat!("Pair ", $what, " with the scheme and the description of what was done.")]
            ///
            /// # Errors
            ///
            /// Returns [`IncoherentContainer`] if the scheme does not admit the
            /// description.
            pub fn new(
                scheme: WrapScheme,
                description: WrapDescription,
                data: Vec<u8>,
            ) -> Result<Self, IncoherentContainer> {
                Container::new(scheme, description, data).map(Self)
            }

            #[doc = concat!("The scheme ", $what, " went into.")]
            #[must_use]
            pub fn scheme(&self) -> WrapScheme {
                self.0.scheme
            }

            /// What the operation did, read back from the artifact.
            #[must_use]
            pub fn description(&self) -> &WrapDescription {
                &self.0.description
            }

            /// The container's bytes.
            #[must_use]
            pub fn data(&self) -> &[u8] {
                &self.0.data
            }
        }
    };
}

/// A key wrapped for transport.
///
/// Carries a custody claim: this key left a backend under protection. That is
/// what separates it from [`EncryptedData`], which holds the same shape of
/// bytes and claims nothing about custody.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct WrappedKey(Container);

container_newtype!(WrappedKey, "a wrapped key");

/// Encrypted content.
///
/// A distinct type from [`WrappedKey`] deliberately. The bytes of a container
/// are the same whether the content was a key or a document; what differs is
/// the claim the ceremony made about it, so a document that reached the
/// artifact store cannot be handed to a step that installs keys.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EncryptedData(Container);

container_newtype!(EncryptedData, "encrypted content");

/// A content-encryption key in the two forms envelope encryption needs.
///
/// The plaintext is for the caller to encrypt with and drop. The wrapped copy
/// is what the container carries, and only the key-encryption key that produced
/// it opens that again.
///
/// This is what every key-protection device offers instead of a cipher: AWS KMS
/// calls it `GenerateDataKey`, PKCS#11 reaches it with `C_GenerateKey` followed
/// by `C_WrapKey`. The content never crosses the boundary, so a device that
/// protects a key it will not export does not also have to be fast enough to
/// encrypt a file.
pub struct DataKey {
    plaintext: zeroize::Zeroizing<Vec<u8>>,
    wrapped: Vec<u8>,
    protection: KeyProtection,
}

/// How a data key was protected, in terms a container can record.
///
/// A container names the key-encryption algorithm in its own structure, so the
/// caller has to know which one the backend used. Asking the backend is the only
/// way: the protected bytes say nothing about themselves, and what a device does
/// to protect a key is a property of that device rather than of the request.
///
/// Every key-protection API in the field takes this as a parameter on the way
/// back: Azure Key Vault's `unwrapKey` requires `alg`, PKCS#11's `C_UnwrapKey`
/// requires a mechanism, and AWS KMS `Decrypt` requires `EncryptionAlgorithm`
/// for an asymmetric key. A pair of methods without it only works where one
/// implementation is both ends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum KeyProtection {
    /// RFC 3394 AES Key Wrap under a symmetric KEK.
    ///
    /// What a CMS `KEKRecipientInfo` names as `id-aes128-wrap` or
    /// `id-aes256-wrap`, PKCS#11 as `CKM_AES_KEY_WRAP`, and Azure as `A256KW`.
    AesKeyWrap,
    /// RSAES-OAEP with SHA-256, under a public key.
    ///
    /// Azure `RSA-OAEP-256`, PKCS#11 `CKM_RSA_PKCS_OAEP`, AWS
    /// `RSAES_OAEP_SHA_256`.
    RsaOaepSha256,
    /// The provider's own envelope, which names no algorithm and follows no
    /// published format.
    ///
    /// AWS KMS is the case to design for. `GenerateDataKey` returns a
    /// `CiphertextBlob` of up to 6144 bytes for a 32-byte data key, carrying the
    /// key ARN and the encryption context beside the key, and the response names
    /// no algorithm at all. Only `Decrypt` against the same service opens it.
    ///
    /// A standard container cannot carry one. A CMS `KEKRecipientInfo` has to
    /// declare a key-encryption algorithm, and declaring `id-aes256-wrap` over
    /// a blob that is not an AES key wrap would produce an artifact whose own
    /// structure lies about it, which no reader could open and `rite verify`
    /// would report as checked. A step that assembles a container refuses this
    /// by name instead.
    ProviderDefined,
}

impl fmt::Display for KeyProtection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyProtection::AesKeyWrap => write!(f, "AES-KW"),
            KeyProtection::RsaOaepSha256 => write!(f, "RSA-OAEP-SHA256"),
            KeyProtection::ProviderDefined => write!(f, "a provider-defined envelope"),
        }
    }
}

impl KeyProtection {
    /// Whether a standard container can record this protection and a standard
    /// reader can therefore open the result.
    ///
    /// Matched exhaustively on purpose: a protection added without answering
    /// this would otherwise default into being written into a container that
    /// cannot describe it.
    #[must_use]
    pub fn is_nameable_in_a_container(self) -> bool {
        match self {
            KeyProtection::AesKeyWrap | KeyProtection::RsaOaepSha256 => true,
            KeyProtection::ProviderDefined => false,
        }
    }
}

impl std::fmt::Debug for DataKey {
    /// Names the shape and never the key. A data key is a secret with a short
    /// life, and a debug print is the way such a thing ends up in a log.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DataKey")
            .field("plaintext", &format_args!("{} bytes", self.plaintext.len()))
            .field("wrapped", &format_args!("{} bytes", self.wrapped.len()))
            .field("protection", &self.protection)
            .finish()
    }
}

impl DataKey {
    /// Pair a fresh data key with the copy its protector can open, and with
    /// what protected it.
    #[must_use]
    pub fn new(
        plaintext: zeroize::Zeroizing<Vec<u8>>,
        wrapped: Vec<u8>,
        protection: KeyProtection,
    ) -> Self {
        Self {
            plaintext,
            wrapped,
            protection,
        }
    }

    /// The key itself, to encrypt content with.
    #[must_use]
    pub fn plaintext(&self) -> &[u8] {
        &self.plaintext
    }

    /// The same key, protected. This is what goes into the container.
    #[must_use]
    pub fn wrapped(&self) -> &[u8] {
        &self.wrapped
    }

    /// What protected it, which is what a container has to declare and what
    /// opening it again needs.
    #[must_use]
    pub fn protection(&self) -> KeyProtection {
        self.protection
    }
}

/// The kind of attestation evidence a backend can produce.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AttestationKind {
    /// Vendor cert chain proving on-device generation. Independently verifiable
    /// against a public manufacturer root CA.
    /// Examples: `YubiKey` F9 attestation, Thales Luna PKC (Public Key Confirmation).
    HardwareCertChain,
    /// TPM signed quote over PCR values with nonce. Proves platform state.
    TpmQuote,
    /// PKCS#11 attribute flags: `CKA_ALWAYS_SENSITIVE=true` + `CKA_NEVER_EXTRACTABLE=true`.
    /// Trustworthy within the HSM's trust boundary but not independently
    /// cryptographically verifiable.
    Pkcs11Attributes,
}

/// Structured attestation evidence with a discriminant kind.
///
/// The `kind` field tells consumers what they're looking at and how to verify it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Attestation {
    /// What kind of attestation this is.
    pub kind: AttestationKind,
    /// DER-encoded certificate chain. Leaf first, then intermediates, then root (if known).
    /// Empty for `Pkcs11Attributes` kind.
    pub certificates: Vec<Vec<u8>>,
    /// Raw signature bytes (if applicable). None for attribute-based attestation.
    pub signature: Option<Vec<u8>>,
    /// Additional metadata (key attributes, slot info, etc.) for transcript recording.
    pub metadata: serde_json::Value,
}

/// Device information for platform attestation.
///
/// Collected from the system running the ceremony. Machine IDs are hashed
/// (SHA-256) for privacy before inclusion in evidence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceInfo {
    /// System hostname.
    pub hostname: String,
    /// Hashed machine ID (SHA-256, format: "sha256:hexhash").
    /// None if machine ID not available on this platform.
    pub machine_id: Option<String>,
    /// CPU model string.
    pub cpu_model: Option<String>,
    /// Operating system name.
    pub os_name: Option<String>,
    /// Operating system version.
    pub os_version: Option<String>,
    /// Kernel version.
    pub kernel_version: Option<String>,
}

/// PIV key slot identifiers.
///
/// Defined by NIST SP 800-73-5 Part 1, Table 4b ("PIV Card Application Card
/// Command Interface: Key References"). These slot assignments are fixed by
/// the standard and MUST NOT be changed.
///
/// # Standard references
/// - NIST SP 800-73-5 Part 1, §3.1.2: Key References
/// - NIST SP 800-73-5 Part 2, §3.2: GENERAL AUTHENTICATE
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PivSlot {
    /// Slot 9A: PIV Authentication Key.
    /// Used for card/cardholder authentication (e.g. system login).
    /// PIN required once per session.
    /// [NIST SP 800-73-5 Part 1, §3.1.2]
    Authentication,

    /// Slot 9C: Digital Signature Key.
    /// Used for document/code signing. PIN required before EVERY
    /// private key operation ("PIN Always" access rule).
    /// Data to be signed is hashed off-card.
    /// [NIST SP 800-73-5 Part 1, §3.1.2; Part 2, §3.2.4]
    Signature,

    /// Slot 9D: Key Management Key.
    /// Used for key establishment (encryption/decryption).
    /// PIN required once per session.
    /// [NIST SP 800-73-5 Part 1, §3.1.2]
    KeyManagement,

    /// Slot 9E: Card Authentication Key.
    /// Used for physical access (e.g. PIV-enabled door locks).
    /// NO PIN required for private key operations.
    /// [NIST SP 800-73-5 Part 1, §3.1.2]
    CardAuthentication,

    /// Retired Key Management Key slot.
    ///
    /// Holds a previously used Key Management key for decrypting historical
    /// documents. The inner value is an index in `0..=19`, where 0 corresponds
    /// to PIV key reference 0x82 and 19 corresponds to 0x95.
    ///
    /// Construct with [`PivSlot::retired`] to enforce the valid range.
    /// [NIST SP 800-73-5 Part 1, §3.1.2]
    Retired(u8),
}

impl PivSlot {
    /// Create a retired key management slot from an index in `0..=19`.
    ///
    /// Returns `None` if `index` is out of the valid range.
    /// The 20 retired slots correspond to PIV key references 0x82–0x95.
    pub fn retired(index: u8) -> Option<Self> {
        (index <= 19).then_some(Self::Retired(index))
    }
}

/// Unified certificate addressing across backend types.
///
/// PIV addresses certs by slot. PKCS#11 addresses cert objects by `CKA_LABEL` or `CKA_ID`.
/// Both are "find me the cert for this key"; the addressing differs by backend type.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum CertRef {
    /// PIV slot identifier (`PivBackend` and `YubikeyBackend`).
    PivSlot(PivSlot),
    /// Human-readable label string (PKCS#11 `CKA_LABEL`, or software backend).
    Label(String),
    /// Raw binary identifier (PKCS#11 `CKA_ID`, typically SHA-1 of public key).
    RawId(Vec<u8>),
}

/// PIN access policy for PIV private key operations.
///
/// Standard PIV defines fixed PIN policies per slot (see `PivSlot` docs).
/// `YubiKey` extends this with per-key configurable policies.
///
/// # Standard references
/// - NIST SP 800-73-5 Part 2, §3.2: access rules per key reference
/// - Yubico PIV documentation: configurable PIN policies (vendor extension)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PivPinPolicy {
    /// Use the slot's default policy per NIST SP 800-73.
    Default,
    /// No PIN required (vendor extension, not standard PIV).
    Never,
    /// PIN verified once per session.
    Once,
    /// PIN verified before every private key operation ("PIN Always").
    Always,
}

/// Physical touch policy for private key operations.
///
/// This is a vendor extension (Yubico), not part of the NIST PIV standard.
/// Standard PIV cards do not have a touch sensor concept.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PivTouchPolicy {
    /// Use the slot's default touch policy.
    Default,
    /// No touch required.
    Never,
    /// Touch required for every operation.
    Always,
    /// Touch cached for 15 seconds (Yubico-specific).
    Cached,
}

/// Metadata about a populated PIV slot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PivSlotInfo {
    /// The PIV slot identifier.
    pub slot: PivSlot,
    /// Key algorithm in this slot (if known).
    pub algorithm: Option<KeyAlgorithm>,
    /// Whether a certificate is stored in this slot.
    /// PIV associates one X.509 certificate with each key slot.
    /// [NIST SP 800-73-5 Part 1, §3.2]
    pub has_certificate: bool,
    /// Origin of the key in this slot.
    pub origin: PivKeyOrigin,
}

/// Origin of a key in a PIV slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PivKeyOrigin {
    /// Key was generated on the device (GENERATE ASYMMETRIC KEY PAIR command).
    /// [NIST SP 800-73-5 Part 2, §3.1]
    Generated,
    /// Key was imported from external material.
    Imported,
    /// Origin unknown (card doesn't report this information).
    Unknown,
}

/// Device identity information for a PIV-compatible smart card.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PivDeviceInfo {
    /// Device serial number (vendor-specific, not standardized by NIST).
    pub serial: Option<String>,
    /// Firmware version string.
    pub firmware_version: Option<String>,
    /// Form factor description (e.g. "USB-A", "USB-C", "NFC").
    pub form_factor: Option<String>,
}

/// `YubiKey`-specific slot metadata (vendor extension, not NIST PIV).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YubikeySlotMetadata {
    /// PIN policy configured for this slot.
    pub pin_policy: PivPinPolicy,
    /// Touch policy configured for this slot.
    pub touch_policy: PivTouchPolicy,
    /// Origin of the key in this slot.
    pub origin: PivKeyOrigin,
    /// Public key, if the slot reports one.
    pub public_key: Option<PublicKeyDer>,
}

bitflags::bitflags! {
    /// PKCS#11 token capability flags. Maps to the `CKF_*` constants in the PKCS#11 standard.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct Pkcs11TokenFlags: u8 {
        /// Token requires login before cryptographic operations (`CKF_LOGIN_REQUIRED`).
        const LOGIN_REQUIRED      = 0b0000_0001;
        /// User PIN has been initialized: `C_InitPIN` has been called (`CKF_USER_PIN_INITIALIZED`).
        const USER_PIN_INITIALIZED = 0b0000_0010;
        /// Token has been initialized: `C_InitToken` has been called (`CKF_TOKEN_INITIALIZED`).
        const TOKEN_INITIALIZED   = 0b0000_0100;
        /// Token is write-protected (`CKF_WRITE_PROTECTED`).
        const WRITE_PROTECTED     = 0b0000_1000;
    }
}

/// PKCS#11 token information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Pkcs11TokenInfo {
    /// Token label (padded to 32 bytes in PKCS#11, trimmed here).
    pub label: String,
    /// Manufacturer ID.
    pub manufacturer: String,
    /// Token model.
    pub model: String,
    /// Token serial number.
    pub serial: String,
    /// Firmware version string.
    pub firmware_version: String,
    /// Token capability flags.
    pub flags: Pkcs11TokenFlags,
}

/// Opaque PKCS#11 mechanism identifier.
///
/// An enum would be incomplete (hundreds of `CKM_*` values, plus vendor extensions).
/// A string like `"CKM_RSA_PKCS_KEY_PAIR_GEN"` is honest about what we expose.
/// Used only for capability checking ("does this token support X?"), not dispatch.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Pkcs11Mechanism(String);

impl Pkcs11Mechanism {
    /// Create a new `Pkcs11Mechanism` from a `CKM_*` name string.
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    /// Return the mechanism name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Pkcs11Mechanism {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// TPM (Trusted Platform Module) information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TpmInfo {
    /// TPM specification version (e.g., "2.0").
    pub version: String,
    /// TPM manufacturer identifier.
    pub manufacturer: String,
    /// Firmware version (if available).
    pub firmware_version: Option<String>,
}

/// PCR (Platform Configuration Register) value.
///
/// The `value` field encodes both the algorithm and the hash in the format
/// `"algorithm:hexhash"` (e.g., `"sha256:abc123..."`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PcrValue {
    /// PCR index (0-23 typically).
    pub index: u8,
    /// PCR value in the format `"algorithm:hexhash"` (e.g., `"sha256:abc123..."`).
    pub value: String,
}

/// Backend configuration entry from a ceremony file.
///
/// The `provider` field identifies the backend by its self-declared name
/// (e.g., `"software"`, `"yubikey"`). The remaining YAML keys are flattened
/// into `extra` for backend-specific deserialization.
///
/// Each backend crate defines its own config struct and deserializes from
/// `extra` at startup. This inverts the prior design where the model listed
/// concrete backend variants; backends now declare themselves.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendConfig {
    /// Backend provider identifier as a lowercase string (e.g., `"software"`).
    pub provider: String,
    /// Backend-specific configuration key/value pairs.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

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

    #[test]
    fn key_algorithm_serde_roundtrip() {
        // Serde uses Display strings via `serde(into/try_from)`. These are the canonical
        // strings for ceremony YAML `algorithm:` fields and transcripts.
        let cases: &[(KeyAlgorithm, &str)] = &[
            (KeyAlgorithm::Rsa2048, "\"RSA-2048\""),
            (KeyAlgorithm::Rsa4096, "\"RSA-4096\""),
            (KeyAlgorithm::EcdsaP256, "\"ECDSA-P256\""),
            (KeyAlgorithm::EcdsaP384, "\"ECDSA-P384\""),
            (KeyAlgorithm::Ed25519, "\"Ed25519\""),
            (KeyAlgorithm::MlDsa44, "\"ML-DSA-44\""),
            (KeyAlgorithm::MlDsa65, "\"ML-DSA-65\""),
            (KeyAlgorithm::MlDsa87, "\"ML-DSA-87\""),
            (KeyAlgorithm::MlKem512, "\"ML-KEM-512\""),
            (KeyAlgorithm::MlKem768, "\"ML-KEM-768\""),
            (KeyAlgorithm::MlKem1024, "\"ML-KEM-1024\""),
            (KeyAlgorithm::Aes128, "\"AES-128\""),
            (KeyAlgorithm::Aes256, "\"AES-256\""),
        ];
        for &(variant, expected) in cases {
            let serialized = serde_json::to_string(&variant).unwrap();
            assert_eq!(serialized, expected, "serialize {variant:?}");
            let deserialized: KeyAlgorithm = serde_json::from_str(expected).unwrap();
            assert_eq!(deserialized, variant, "deserialize {expected}");
        }
    }

    #[test]
    fn sign_algorithm_serde_roundtrip() {
        // Serde uses Display strings via `serde(into/try_from)`. These are the canonical
        // strings for ceremony YAML `algorithm:` fields and transcripts.
        let cases: &[(SignAlgorithm, &str)] = &[
            (SignAlgorithm::RsaPkcs1Sha256, "\"RSA-PKCS1-SHA256\""),
            (SignAlgorithm::RsaPssSha256, "\"RSA-PSS-SHA256\""),
            (SignAlgorithm::EcdsaSha256, "\"ECDSA-SHA256\""),
            (SignAlgorithm::EcdsaSha384, "\"ECDSA-SHA384\""),
            (SignAlgorithm::Ed25519, "\"Ed25519\""),
            (SignAlgorithm::MlDsa44, "\"ML-DSA-44\""),
            (SignAlgorithm::MlDsa65, "\"ML-DSA-65\""),
            (SignAlgorithm::MlDsa87, "\"ML-DSA-87\""),
        ];
        for &(variant, expected) in cases {
            let serialized = serde_json::to_string(&variant).unwrap();
            assert_eq!(serialized, expected, "serialize {variant:?}");
            let deserialized: SignAlgorithm = serde_json::from_str(expected).unwrap();
            assert_eq!(deserialized, variant, "deserialize {expected}");
        }
    }

    #[test]
    fn sign_algorithm_from_str_rejects_unknown() {
        assert!("RSA-PKCS1-SHA512".parse::<SignAlgorithm>().is_err());
        assert!("".parse::<SignAlgorithm>().is_err());
        assert!(
            "ecdsa-sha256".parse::<SignAlgorithm>().is_err(),
            "must be case-sensitive"
        );
        assert!(
            "ecdsa_sha256".parse::<SignAlgorithm>().is_err(),
            "the snake_case spelling is not accepted"
        );
    }

    /// The default must be a signature algorithm the key can actually perform,
    /// or actions that derive one would hand backends an impossible request.
    #[test]
    fn every_default_sign_algorithm_accepts_its_own_key() {
        let signing_keys = [
            KeyAlgorithm::Rsa2048,
            KeyAlgorithm::Rsa4096,
            KeyAlgorithm::EcdsaP256,
            KeyAlgorithm::EcdsaP384,
            KeyAlgorithm::Ed25519,
            KeyAlgorithm::MlDsa44,
            KeyAlgorithm::MlDsa65,
            KeyAlgorithm::MlDsa87,
        ];
        for key_algorithm in signing_keys {
            let algorithm = key_algorithm
                .default_sign_algorithm()
                .unwrap_or_else(|| panic!("{key_algorithm} must have a default"));
            assert!(
                algorithm.accepts_key(key_algorithm),
                "{key_algorithm} defaults to {algorithm}, which rejects it"
            );
        }

        // Symmetric keys sign nothing.
        assert!(KeyAlgorithm::Aes128.default_sign_algorithm().is_none());
        assert!(KeyAlgorithm::Aes256.default_sign_algorithm().is_none());
    }

    #[test]
    fn sign_algorithm_accepts_key_spans_rsa_sizes_and_pins_everything_else() {
        // RSA signature schemes are defined for any modulus size, so both key
        // sizes are valid. This is what `key_algorithm()` cannot express.
        for algorithm in [SignAlgorithm::RsaPkcs1Sha256, SignAlgorithm::RsaPssSha256] {
            assert!(algorithm.accepts_key(KeyAlgorithm::Rsa2048));
            assert!(algorithm.accepts_key(KeyAlgorithm::Rsa4096));
            assert!(!algorithm.accepts_key(KeyAlgorithm::EcdsaP256));
        }

        // Curves and ML-DSA parameter sets are pinned: a signature algorithm
        // names exactly one key algorithm and rejects its neighbours.
        assert!(SignAlgorithm::EcdsaSha256.accepts_key(KeyAlgorithm::EcdsaP256));
        assert!(!SignAlgorithm::EcdsaSha256.accepts_key(KeyAlgorithm::EcdsaP384));
        assert!(SignAlgorithm::MlDsa65.accepts_key(KeyAlgorithm::MlDsa65));
        assert!(!SignAlgorithm::MlDsa65.accepts_key(KeyAlgorithm::MlDsa87));

        // A signing algorithm never accepts a symmetric key.
        assert!(!SignAlgorithm::Ed25519.accepts_key(KeyAlgorithm::Aes256));
    }

    #[test]
    fn wrap_scheme_serde_roundtrip() {
        // Serde uses Display strings via `serde(into/try_from)`. These strings
        // appear in transcripts.
        let cases: &[(WrapScheme, &str)] = &[
            (WrapScheme::CmsAes256Gcm, "\"CMS-AES-256-GCM\""),
            (WrapScheme::RsaOaepSha256, "\"RSA-OAEP-SHA256\""),
            (
                WrapScheme::RsaAesKeyWrapSha256,
                "\"RSA-AES-KEY-WRAP-SHA256\"",
            ),
            (WrapScheme::Aes128Kw, "\"AES-128-KW\""),
            (WrapScheme::Aes256Kw, "\"AES-256-KW\""),
            (WrapScheme::Aes128Kwp, "\"AES-128-KWP\""),
            (WrapScheme::Aes256Kwp, "\"AES-256-KWP\""),
        ];
        for &(variant, expected) in cases {
            let serialized = serde_json::to_string(&variant).unwrap();
            assert_eq!(serialized, expected, "serialize {variant:?}");
            let deserialized: WrapScheme = serde_json::from_str(expected).unwrap();
            assert_eq!(deserialized, variant, "deserialize {expected}");
        }
    }

    #[test]
    fn wrap_scheme_from_str_rejects_unknown() {
        assert!("CMS-RSA-XTS".parse::<WrapScheme>().is_err());
        assert!("".parse::<WrapScheme>().is_err());
        assert!(
            "cms-aes-256-gcm".parse::<WrapScheme>().is_err(),
            "must be case-sensitive"
        );
        assert!(
            "CMS-RSA-CBC".parse::<WrapScheme>().is_err(),
            "the unauthenticated CBC scheme is gone, not merely undocumented"
        );
    }

    /// A CMS wrap to an RSA recipient, as OpenSSL 3.6 produces it.
    fn cms_ktri_gcm() -> WrapDescription {
        WrapDescription::new(
            RecipientInfoKind::Ktri,
            Oid::new(oid::RSA_ENCRYPTION).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_GCM).unwrap())
    }

    #[test]
    fn oid_rejects_values_that_are_not_dotted_decimal() {
        assert!(Oid::new("2.16.840.1.101.3.4.1.46").is_ok());
        assert!(Oid::new("1.2").is_ok());
        assert!(Oid::new("1").is_err(), "a single arc is not an OID");
        assert!(
            Oid::new("1.2.").is_err(),
            "trailing dot leaves an empty arc"
        );
        assert!(Oid::new("1.2.a").is_err());
        assert!(Oid::new("").is_err());
    }

    #[test]
    fn scheme_admits_only_a_matching_description() {
        assert!(WrapScheme::CmsAes256Gcm.permits(&cms_ktri_gcm()));

        // Same container, CBC content: the scheme fixes GCM, so this is not it.
        let cbc = WrapDescription::new(
            RecipientInfoKind::Ktri,
            Oid::new(oid::RSA_ENCRYPTION).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_CBC).unwrap());
        assert!(!WrapScheme::CmsAes256Gcm.permits(&cbc));

        // A symmetric KEK is the KEKRI encapsulation, which this scheme does
        // produce: the recipient is a key both sides hold rather than one
        // reached by public key, and the container is the same.
        let kekri = WrapDescription::new(
            RecipientInfoKind::Kekri,
            Oid::new(oid::AES_256_WRAP).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_GCM).unwrap());
        assert!(WrapScheme::CmsAes256Gcm.permits(&kekri));

        // The content cipher still has to be authenticated, whichever
        // encapsulation carried the key to it.
        let kekri_cbc = WrapDescription::new(
            RecipientInfoKind::Kekri,
            Oid::new(oid::AES_256_WRAP).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_CBC).unwrap());
        assert!(!WrapScheme::CmsAes256Gcm.permits(&kekri_cbc));

        // A password recipient is not one Rite writes, and admitting it would
        // mean a passphrase had silently stood in for a key.
        let pwri = WrapDescription::new(
            RecipientInfoKind::Pwri,
            Oid::new(oid::AES_256_WRAP).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_GCM).unwrap());
        assert!(!WrapScheme::CmsAes256Gcm.permits(&pwri));
    }

    #[test]
    fn wrapped_key_rejects_a_scheme_its_description_contradicts() {
        let coherent = WrappedKey::new(WrapScheme::CmsAes256Gcm, cms_ktri_gcm(), vec![1, 2, 3]);
        assert!(coherent.is_ok());

        let unauthenticated = WrapDescription::new(
            RecipientInfoKind::Ktri,
            Oid::new(oid::RSA_ENCRYPTION).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_CBC).unwrap());
        let mislabelled = WrappedKey::new(WrapScheme::CmsAes256Gcm, unauthenticated, vec![1, 2, 3]);
        assert!(
            mislabelled.is_err(),
            "bytes must not carry a label they contradict"
        );
    }

    #[test]
    fn wrapped_key_recheck_survives_deserialization() {
        let wrapped =
            WrappedKey::new(WrapScheme::CmsAes256Gcm, cms_ktri_gcm(), vec![9, 9]).unwrap();
        let json = serde_json::to_string(&wrapped).unwrap();
        let back: WrappedKey = serde_json::from_str(&json).unwrap();
        assert_eq!(back.scheme(), WrapScheme::CmsAes256Gcm);
        assert_eq!(back.data(), &[9, 9]);

        // An artifact edited to disagree with itself does not deserialize.
        let tampered = json.replace(oid::AES_256_GCM, oid::AES_256_CBC);
        assert!(serde_json::from_str::<WrappedKey>(&tampered).is_err());
    }

    #[test]
    fn gcm_content_is_the_authenticated_case() {
        assert!(cms_ktri_gcm().content_is_authenticated());
        let cbc = WrapDescription::new(
            RecipientInfoKind::Ktri,
            Oid::new(oid::RSA_ENCRYPTION).unwrap(),
        )
        .with_content_encryption(Oid::new(oid::AES_256_CBC).unwrap());
        assert!(!cbc.content_is_authenticated());
    }

    #[test]
    fn piv_slot_retired_enforces_valid_range() {
        // Indices 0–19 map to PIV key references 0x82–0x95.
        // An out-of-range index would send an invalid reference to PIV hardware.
        assert!(PivSlot::retired(0).is_some(), "index 0 must be valid");
        assert!(
            PivSlot::retired(19).is_some(),
            "index 19 must be valid (last slot 0x95)"
        );
        assert!(
            PivSlot::retired(20).is_none(),
            "index 20 must be rejected (out of range)"
        );
        assert!(
            PivSlot::retired(255).is_none(),
            "index 255 must be rejected"
        );
    }

    #[test]
    fn key_policy_default_is_secure() {
        // The default is documented as the most secure configuration for ceremony signing keys.
        // A regression here (e.g., extractable=true) is a silent security downgrade.
        let policy = KeyPolicy::default();
        assert!(
            policy.persistent,
            "ceremony keys must persist across sessions"
        );
        assert!(policy.sensitive, "ceremony keys must be marked sensitive");
        assert!(
            !policy.extractable,
            "ceremony keys must not be extractable by default"
        );
        assert!(policy.usages.contains(KeyUsages::SIGN));
        assert!(policy.usages.contains(KeyUsages::VERIFY));
        assert!(
            !policy.usages.contains(KeyUsages::ENCRYPT),
            "signing-only default must not permit encryption"
        );
        assert!(
            !policy.usages.contains(KeyUsages::WRAP),
            "signing-only default must not permit wrapping"
        );
    }
}