xml-sec 0.1.23

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

#[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
use std::collections::HashSet;
#[cfg(feature = "xmldsig")]
use std::time::SystemTime;

#[cfg(feature = "xmldsig")]
use crate::xmldsig::{DigestAlgorithm, SignatureAlgorithm, UriTypeSet, XPathHereSemantics};
#[cfg(feature = "xmlenc")]
use crate::xmlenc::{
    DataEncryptionAlgorithm, KeyTransportAlgorithm, KeyWrapAlgorithm, OaepDigestAlgorithm,
};

#[cfg(feature = "xmldsig")]
mod key_establishment;
#[cfg(feature = "xmldsig")]
pub use key_establishment::{
    KemContentAuthentication, KeyAgreementAlgorithm, KeyDerivationAlgorithm, KeyEstablishmentPolicy,
};

#[cfg(feature = "xmldsig")]
mod profiles;
#[cfg(feature = "xmldsig")]
pub use profiles::{
    CompiledPolicies, PolicyCompileContext, PolicyCompiler, PolicyProfile, PolicySet,
    PolicyValidity, SignatureConstraints,
};

/// Permission for the unbounded parameterized RSA-PSS family.
/// Exact permissions continue to use the signature algorithm allowlist.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RsaPssPermission {
    /// No additional family grant; existing allowlists and secure defaults apply.
    #[default]
    ExactOnly,
    /// Permit supported parameterized tuples using non-legacy hashes only.
    SecureSupported,
    /// Permit every supported tuple; capability and key restrictions still apply.
    AllSupported,
}

#[cfg(feature = "xmldsig")]
impl RsaPssPermission {
    fn permits(self, algorithm: SignatureAlgorithm) -> bool {
        matches!(algorithm, SignatureAlgorithm::RsaPss(_))
            && (self == Self::AllSupported
                || (self == Self::SecureSupported && algorithm.signing_allowed()))
    }
}

/// Canonical diagnostics for limits represented by [`ResourcePolicy`].
///
/// Validation and every enforcement point use the same names so callers can
/// match typed policy violations without operation-specific string drift.
pub(crate) mod resource_name {
    pub const XML_NODES: &str = "XML nodes";
    pub const XML_DEPTH: &str = "XML element depth";
    pub const XML_NAMESPACE_BINDINGS: &str = "XML namespace bindings";
    pub const SIGNATURE_REFERENCES: &str = "signature references";
    #[cfg(feature = "xmlenc")]
    pub const ENCRYPTION_REFERENCES: &str = "encryption key references";
    pub const VERIFICATION_SIGNATURES: &str = "verification signatures";
    pub const REFERENCE_TRANSFORMS: &str = "reference transforms";
    pub const XML_BASE_COMPONENTS: &str = "XML Base components";
    pub const XML_BASE_RESOLUTION_BYTES: &str = "XML Base resolution bytes";
    pub const CANONICALIZED_BYTES: &str = "canonicalized bytes";
    pub const EXTERNAL_RESOURCE_BYTES: &str = "external resource bytes";
    pub const AGGREGATE_EXTERNAL_RESOURCE_BYTES: &str = "aggregate external resource bytes";
    pub const ENCRYPTION_PLAINTEXT_BYTES: &str = "encryption plaintext bytes";
    #[cfg(feature = "xmlenc")]
    pub const AGGREGATE_ENCRYPTION_CIPHER_VALUE_BYTES: &str =
        "aggregate encryption CipherValue bytes";
    pub const XML_DOCUMENT: &str = "XML document";
    pub const XML_PARSE_WORK_BYTES: &str = "cumulative XML parse-work bytes";
    pub const ENCRYPTION_RECIPIENTS: &str = "encryption recipients";
    pub const ENCRYPTION_METADATA_BYTES: &str = "encryption metadata bytes";
    pub const KEY_CANDIDATES: &str = "key candidates";
    pub const KEY_IMPORT_KDF_WORK: &str = "key import KDF work";
    pub const KEY_IMPORT_KDF_MEMORY: &str = "key import KDF memory bytes";
    pub const X509_WORK: &str = "X.509 work";
    pub const X509_WORKSPACE_BYTES: &str = "X.509 workspace bytes";
    #[cfg(feature = "xmldsig")]
    pub const KEY_ESTABLISHMENT_HASH_BLOCKS: &str = "key establishment hash blocks";
    #[cfg(feature = "xmldsig")]
    pub const KEY_ESTABLISHMENT_OWNED_BYTES: &str = "key establishment owned bytes";
    #[cfg(feature = "xmldsig")]
    pub const DH_MODULUS_BITS: &str = "DH modulus bits";
    #[cfg(feature = "xmldsig")]
    pub const DH_SUBGROUP_BITS: &str = "DH subgroup bits";
    #[cfg(feature = "xmldsig")]
    pub const KEY_ESTABLISHMENT_MODULAR_WORK: &str = "key establishment modular work";
    pub const KEY_INFO_REFERENCE_DEPTH: &str = "KeyInfoReference depth";
    pub const BASE64_TRANSFORM_INPUT_BYTES: &str = "Base64 transform input bytes";
    pub const BASE64_TRANSFORM_OUTPUT_BYTES: &str = "Base64 transform output bytes";
    pub const XPATH_EXPRESSIONS: &str = "XPath expressions";
    pub const XPATH_EXPRESSION_BYTES: &str = "XPath expression bytes";
    pub const XPATH_EXPRESSION_COMPLEXITY: &str = "XPath expression complexity";
    pub const XPATH_CONTEXT_EVALUATIONS: &str = "XPath context evaluations";
    pub const XPATH_EVALUATION_WORK: &str = "XPath evaluation work";
    pub const XPATH_MIRROR_STRING_BYTES: &str = "XPath mirror string bytes";
    pub const XPATH_STRING_WORK_BYTES: &str = "XPath string-processing work bytes";
    pub const XPATH_NAMESPACE_BINDINGS: &str = "XPath namespace bindings";
    pub const XPATH_NAMESPACE_BYTES: &str = "XPath namespace bytes";
    pub const XPATH_FILTERS: &str = "XPath filters";
    pub const NODE_SET_FILTER_WORK: &str = "node-set filter work";
    pub const OPC_WORKSPACE_BYTES: &str = "OPC workspace bytes";
    pub const OPC_PARAMETER_BYTES: &str = "OPC parameter bytes";
    pub const NODE_SET_ENTRIES: &str = "node-set entries";
    pub const NODE_SET_OWNED_STRING_BYTES: &str = "node-set owned string bytes";
    pub const NODE_SET_CUMULATIVE_OWNED_STRING_BYTES: &str =
        "cumulative node-set owned string bytes";
}

/// A typed rejection produced by an operation policy.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PolicyViolation {
    /// Contradictory policy layers or an unavailable compiled requirement.
    #[error("policy compilation failed: {reason}")]
    Configuration {
        /// Stable, non-secret diagnostic.
        reason: &'static str,
    },
    /// The immutable operation policy forbids executing Manifest references.
    #[cfg(feature = "xmldsig")]
    #[error("Manifest reference processing is disabled by policy")]
    ManifestProcessingDisabled,
    /// Untrusted XML does not satisfy the selected signature profile.
    #[cfg(feature = "xmldsig")]
    #[error("{profile:?} signature profile rejects document: {reason}")]
    SignatureProfile {
        /// Compiled protocol constraint being enforced.
        profile: SignatureConstraints,
        /// Stable, non-secret explanation of the document defect.
        reason: &'static str,
    },
    /// An explicitly authorized exception is not valid at operation time.
    #[error("policy authorization is outside its validity interval")]
    AuthorizationExpired,
    /// An algorithm is outside the operation allowlist.
    #[error("{operation} policy rejects algorithm {algorithm}")]
    Algorithm {
        /// Operation evaluating the algorithm.
        operation: &'static str,
        /// Stable algorithm URI or diagnostic name.
        algorithm: String,
    },
    /// An HMAC output length is outside the operation's configured bounds.
    #[cfg(feature = "xmldsig")]
    #[error("HMAC output length must be between {minimum} and {maximum} bits: got {actual}")]
    HmacOutputLength {
        /// Minimum output length selected by policy.
        minimum: usize,
        /// Full output width of the selected HMAC algorithm.
        maximum: usize,
        /// Parsed output length.
        actual: usize,
    },
    /// An input exceeds a configured resource ceiling.
    #[error("{resource} exceeds policy maximum {maximum}: got {actual}")]
    ResourceLimit {
        /// Resource whose consumption was rejected.
        resource: &'static str,
        /// Effective policy ceiling.
        maximum: usize,
        /// Observed consumption.
        actual: usize,
    },
    /// An import exceeded a resource ceiling, but its parser did not expose the measured value.
    #[error("{resource} exceeds policy maximum {maximum}")]
    ResourceLimitExceeded {
        /// Resource whose consumption was rejected.
        resource: &'static str,
        /// Effective policy ceiling.
        maximum: usize,
    },
    /// A protected import supplied zero or too many KDF iterations; the parser did not expose the count.
    #[error("key import KDF iterations must be between 1 and {maximum}")]
    KdfIterationsOutsideLimit {
        /// Effective iteration ceiling.
        maximum: usize,
    },
    /// A configured resource limit violates a structural policy requirement.
    #[error("{resource} has invalid policy limit {actual}: {requirement}")]
    InvalidResourceLimit {
        /// Resource whose configured limit was rejected.
        resource: &'static str,
        /// Required property of the configured limit.
        requirement: &'static str,
        /// Rejected configured value.
        actual: usize,
    },
    /// The selected key source or trust mode is disallowed.
    #[error("key/trust policy rejected the operation: {reason}")]
    KeyTrust {
        /// Non-secret reason suitable for diagnostics.
        reason: &'static str,
    },
    /// XML parser behavior is disallowed.
    #[error("XML input policy rejected the operation: {reason}")]
    XmlInput {
        /// Non-secret reason suitable for diagnostics.
        reason: &'static str,
    },
    /// A URI class is outside the operation policy.
    #[error("{operation} URI policy rejected the operation: {reason}")]
    Uri {
        /// Operation evaluating the URI.
        operation: &'static str,
        /// Non-sensitive reason suitable for diagnostics.
        reason: &'static str,
    },
    /// An asymmetric key/domain falls outside the operation's strength range.
    #[error(
        "{operation} policy requires {key_type} keys between {minimum_bits} and {maximum_bits} bits: got {actual_bits}"
    )]
    KeySize {
        /// Operation evaluating the key.
        operation: &'static str,
        /// Stable key-family diagnostic.
        key_type: &'static str,
        /// Configured minimum width of the named key/domain component.
        minimum_bits: usize,
        /// Effective maximum, bounded by the implementation ceiling.
        maximum_bits: usize,
        /// Observed normalized width of the named key/domain component.
        actual_bits: usize,
    },
    /// RSA key material is structurally invalid.
    #[error("{operation} policy rejects invalid {key_type} key material: {reason}")]
    InvalidKeyMaterial {
        /// Operation evaluating the key.
        operation: &'static str,
        /// Stable key-family diagnostic.
        key_type: &'static str,
        /// Non-secret structural rejection reason.
        reason: &'static str,
    },
}

/// HMAC key-strength and truncation requirements shared by signing and verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HmacPolicy {
    /// Minimum caller-owned secret length in bits.
    pub minimum_key_bits: usize,
    /// Minimum emitted or accepted MAC length in bits.
    pub minimum_output_bits: usize,
}

#[cfg(feature = "xmldsig")]
impl Default for HmacPolicy {
    fn default() -> Self {
        Self {
            minimum_key_bits: 128,
            minimum_output_bits: 128,
        }
    }
}

#[cfg(feature = "xmldsig")]
impl HmacPolicy {
    pub(crate) fn validate(self) -> Result<(), PolicyViolation> {
        if self.minimum_key_bits == 0 || self.minimum_output_bits == 0 {
            return Err(PolicyViolation::KeyTrust {
                reason: "HMAC minimum key and output lengths must be nonzero",
            });
        }
        Ok(())
    }

    pub(crate) fn validate_key_bytes(self, key_bytes: usize) -> Result<(), PolicyViolation> {
        self.validate_key_bits(key_bytes.saturating_mul(8))
    }

    pub(crate) fn validate_key_bits(self, key_bits: usize) -> Result<(), PolicyViolation> {
        if key_bits < self.minimum_key_bits {
            return Err(PolicyViolation::InvalidKeyMaterial {
                operation: "HMAC",
                key_type: "symmetric",
                reason: "secret is shorter than the configured minimum",
            });
        }
        Ok(())
    }

    pub(crate) fn validate_output(
        self,
        algorithm: SignatureAlgorithm,
        selected_bits: usize,
    ) -> Result<(), PolicyViolation> {
        let maximum = algorithm
            .hmac_output_bits()
            .ok_or_else(|| PolicyViolation::Algorithm {
                operation: "HMAC",
                algorithm: algorithm.uri().to_owned(),
            })?;
        // XMLDSig 1.1 section 4.4.2 makes this a protocol floor, not a
        // deployment preference: truncation is at least 80 bits and at least
        // half the underlying digest width. Caller policy may only tighten it.
        // https://www.w3.org/TR/2013/REC-xmldsig-core1-20130411/#sec-SignatureMethod
        let minimum = self.minimum_output_bits.max(80).max(maximum / 2);
        if selected_bits < minimum || selected_bits > maximum {
            return Err(PolicyViolation::HmacOutputLength {
                minimum,
                maximum,
                actual: selected_bits,
            });
        }
        Ok(())
    }
}

/// RSA strength and structural requirements for cryptographic operations.
#[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RsaKeyPolicy {
    /// Minimum mathematical RSA modulus bit length accepted by the operation.
    pub minimum_modulus_bits: usize,
}

/// DSA strength requirements for legacy signature verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DsaKeyPolicy {
    /// Minimum prime-modulus width accepted for DSA verification.
    pub minimum_modulus_bits: usize,
}

#[cfg(feature = "xmldsig")]
impl Default for DsaKeyPolicy {
    fn default() -> Self {
        Self {
            minimum_modulus_bits: 2048,
        }
    }
}

#[cfg(feature = "xmldsig")]
impl DsaKeyPolicy {
    /// Validate the configured minimum against the implementation ceiling.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        validate_modulus_minimum(
            "minimum DSA modulus bits",
            self.minimum_modulus_bits,
            64,
            "minimum must be a nonzero multiple of 64 bits",
            crate::hard_limits::DSA_MODULUS_BIT_CEILING,
        )
    }

    pub(crate) fn validate_modulus_bits(&self, actual_bits: usize) -> Result<(), PolicyViolation> {
        self.validate()?;
        if !(self.minimum_modulus_bits..=crate::hard_limits::DSA_MODULUS_BIT_CEILING)
            .contains(&actual_bits)
        {
            return Err(PolicyViolation::KeySize {
                operation: "verification",
                key_type: "DSA",
                minimum_bits: self.minimum_modulus_bits,
                maximum_bits: crate::hard_limits::DSA_MODULUS_BIT_CEILING,
                actual_bits,
            });
        }
        Ok(())
    }
}

#[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
impl Default for RsaKeyPolicy {
    fn default() -> Self {
        Self {
            minimum_modulus_bits: 2048,
        }
    }
}

#[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
impl RsaKeyPolicy {
    /// Validate the configured minimum against the implementation ceiling.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        validate_modulus_minimum(
            "minimum RSA modulus bits",
            self.minimum_modulus_bits,
            8,
            "minimum must be a nonzero whole-byte width",
            crate::hard_limits::RSA_MODULUS_BIT_CEILING,
        )
    }

    pub(crate) fn validate_components(
        &self,
        operation: &'static str,
        modulus: &[u8],
        exponent: &[u8],
    ) -> Result<usize, PolicyViolation> {
        self.validate()?;
        let modulus = modulus
            .iter()
            .position(|byte| *byte != 0)
            .map(|start| &modulus[start..])
            .ok_or(PolicyViolation::InvalidKeyMaterial {
                operation,
                key_type: "RSA",
                reason: "modulus is zero",
            })?;
        let modulus_bits = modulus
            .len()
            .checked_mul(8)
            .and_then(|width| width.checked_sub(modulus[0].leading_zeros() as usize))
            .ok_or(PolicyViolation::InvalidKeyMaterial {
                operation,
                key_type: "RSA",
                reason: "modulus width overflows",
            })?;
        let exponent = if exponent.is_empty() || exponent.len() > 8 {
            None
        } else {
            let mut bytes = [0_u8; 8];
            bytes[8 - exponent.len()..].copy_from_slice(exponent);
            Some(u64::from_be_bytes(bytes))
        };
        self.validate_public_metadata(operation, modulus_bits, exponent)
    }

    pub(crate) fn validate_public_metadata(
        &self,
        operation: &'static str,
        modulus_bits: usize,
        exponent: Option<u64>,
    ) -> Result<usize, PolicyViolation> {
        self.validate()?;
        if modulus_bits == 0 {
            return Err(PolicyViolation::InvalidKeyMaterial {
                operation,
                key_type: "RSA",
                reason: "modulus is zero",
            });
        }
        if !(self.minimum_modulus_bits..=crate::hard_limits::RSA_MODULUS_BIT_CEILING)
            .contains(&modulus_bits)
        {
            return Err(PolicyViolation::KeySize {
                operation,
                key_type: "RSA",
                minimum_bits: self.minimum_modulus_bits,
                maximum_bits: crate::hard_limits::RSA_MODULUS_BIT_CEILING,
                actual_bits: modulus_bits,
            });
        }
        let exponent = exponent.ok_or(PolicyViolation::InvalidKeyMaterial {
            operation,
            key_type: "RSA",
            reason: "public exponent has invalid encoding",
        })?;
        if !(3..=((1_u64 << 33) - 1)).contains(&exponent) || exponent % 2 == 0 {
            return Err(PolicyViolation::InvalidKeyMaterial {
                operation,
                key_type: "RSA",
                reason: "public exponent is outside the supported odd range",
            });
        }
        Ok(modulus_bits.div_ceil(8))
    }
}

#[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
fn validate_modulus_minimum(
    resource: &'static str,
    minimum_bits: usize,
    alignment_bits: usize,
    requirement: &'static str,
    ceiling: usize,
) -> Result<(), PolicyViolation> {
    if minimum_bits == 0 || !minimum_bits.is_multiple_of(alignment_bits) {
        return Err(PolicyViolation::InvalidResourceLimit {
            resource,
            requirement,
            actual: minimum_bits,
        });
    }
    ResourcePolicy::within(resource, minimum_bits, ceiling)
}

/// Resource ceilings shared by parsing, transforms, and cryptographic output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourcePolicy {
    /// Maximum XML nodes in one parsed document.
    pub max_xml_nodes: usize,
    /// Maximum element nesting depth in one parsed document.
    pub max_xml_depth: usize,
    /// Maximum namespace prefixes simultaneously bound while parsing XML.
    /// Node and depth limits alone do not bound declarations on one element.
    pub max_xml_namespace_bindings: usize,
    /// Maximum references in one signature or manifest.
    pub max_references: usize,
    /// Maximum signatures examined and retained in one verification request.
    pub max_signatures: usize,
    /// Maximum transforms in one reference.
    pub max_transforms_per_reference: usize,
    /// Maximum inherited `xml:base` components in one URI resolution.
    pub max_xml_base_components: usize,
    /// Maximum cumulative bytes processed while resolving `xml:base` URIs.
    pub max_xml_base_resolution_bytes: usize,
    /// Maximum canonical bytes retained across one signature operation.
    pub max_canonicalized_bytes: usize,
    /// Maximum decoded external resource bytes.
    pub max_external_resource_bytes: usize,
    /// Maximum bytes in the complete external map and cumulatively dereferenced.
    pub max_external_resource_total_bytes: usize,
    /// Maximum XMLEnc plaintext bytes.
    pub max_encryption_plaintext_bytes: usize,
    /// Maximum caller-owned XML bytes accepted by any document operation.
    pub max_xml_document_bytes: usize,
    /// Maximum cumulative XML bytes parsed by one operation.
    pub max_xml_parse_work_bytes: usize,
    /// Maximum independently wrapped recipients.
    pub max_encryption_recipients: usize,
    /// Maximum caller-controlled XMLEnc metadata bytes per field.
    pub max_encryption_metadata_bytes: usize,
    /// Maximum key-source expansion work and concrete key or certificate
    /// candidates inspected by one operation stage.
    pub max_key_candidates: usize,
    /// Maximum cumulative work charged by the shared certificate mechanism
    /// in a processing session, across its candidates and nested decodes.
    pub max_x509_work: usize,
    /// Maximum live allocation capacity retained by the shared certificate
    /// mechanism, including path search, Name processing and CRL evaluation.
    pub max_x509_workspace_bytes: usize,
    /// Maximum aggregate PBKDF2/PKCS#12 hash rounds or conservative scrypt work
    /// during key import, including PKCS#8 password-hashing work units.
    pub max_key_import_kdf_work: usize,
    /// Maximum estimated scrypt or PKCS#12 KDF workspace bytes during key import.
    pub max_key_import_kdf_memory_bytes: usize,
    /// Maximum nested `KeyInfoReference` dereference depth.
    pub max_key_info_reference_depth: usize,
    /// Maximum bytes accepted by Base64 transforms before decoding.
    pub max_base64_transform_input_bytes: usize,
    /// Maximum cumulative bytes emitted by Base64 transforms in one operation.
    pub max_base64_transform_output_bytes: usize,
    /// Maximum XPath expressions evaluated by one signature operation.
    pub max_xpath_expressions: usize,
    /// Maximum UTF-8 bytes in one XPath expression.
    pub max_xpath_expression_bytes: usize,
    /// Maximum structural complexity accepted for one XPath expression.
    pub max_xpath_expression_complexity: usize,
    /// Maximum context-node evaluations for one ordinary XPath transform.
    pub max_xpath_context_evaluations: usize,
    /// Maximum conservative XPath node-evaluation work per operation.
    pub max_xpath_evaluation_work: usize,
    /// Maximum source strings copied into the XPath mirror.
    pub max_xpath_mirror_string_bytes: usize,
    /// Maximum conservative XPath string-processing work per operation.
    pub max_xpath_string_work_bytes: usize,
    /// Maximum namespace bindings captured by one XPath expression.
    pub max_xpath_namespace_bindings: usize,
    /// Maximum aggregate namespace prefix and URI bytes per XPath expression.
    pub max_xpath_namespace_bytes: usize,
    /// Maximum filters in one XPath Filter 2.0 transform.
    pub max_xpath_filters: usize,
    /// Maximum cumulative node-set entries visited by filtering transforms.
    pub max_node_set_filter_work: usize,
    /// Maximum tree, attribute and namespace nodes in one exact node set,
    /// whether it is stored as a document range or explicitly. Defaults to
    /// 262,144; callers may raise it to the absolute ceiling of 524,288.
    pub max_node_set_entries: usize,
    /// Maximum attribute and namespace name bytes covered by one node set.
    pub max_node_set_owned_string_bytes: usize,
    /// Maximum cumulative node-set name bytes per operation.
    pub max_node_set_cumulative_owned_string_bytes: usize,
    /// Maximum cumulative OPC parameter allocations retained during signature parsing.
    pub max_opc_parameter_bytes: usize,
    /// Maximum cumulative OPC normalization workspace allocations during execution.
    pub max_opc_workspace_bytes: usize,
}

impl Default for ResourcePolicy {
    fn default() -> Self {
        Self {
            max_xml_nodes: crate::hard_limits::XML_DOCUMENT_NODE_CEILING as usize,
            max_xml_depth: crate::hard_limits::XML_DOCUMENT_DEPTH_CEILING,
            max_xml_namespace_bindings: crate::hard_limits::XML_NAMESPACE_BINDING_CEILING,
            max_references: crate::hard_limits::SIGNATURE_REFERENCE_CEILING,
            max_signatures: crate::hard_limits::VERIFICATION_SIGNATURE_CEILING,
            max_transforms_per_reference: crate::hard_limits::REFERENCE_TRANSFORM_CEILING,
            max_xml_base_components: crate::hard_limits::XML_BASE_COMPONENT_CEILING,
            max_xml_base_resolution_bytes: crate::hard_limits::XML_BASE_RESOLUTION_BYTE_CEILING,
            max_canonicalized_bytes: crate::hard_limits::CANONICALIZED_SIGNATURE_DATA_BYTE_CEILING,
            max_external_resource_bytes: crate::hard_limits::EXTERNAL_RESOURCE_BYTE_CEILING,
            max_external_resource_total_bytes:
                crate::hard_limits::EXTERNAL_RESOURCE_TOTAL_BYTE_CEILING,
            max_encryption_plaintext_bytes: crate::hard_limits::ENCRYPTION_PLAINTEXT_BYTE_CEILING,
            max_xml_document_bytes: crate::hard_limits::XML_DOCUMENT_BYTE_CEILING,
            max_xml_parse_work_bytes: crate::hard_limits::XML_PARSE_WORK_BYTE_CEILING,
            max_encryption_recipients: crate::hard_limits::ENCRYPTION_RECIPIENT_CEILING,
            max_encryption_metadata_bytes: crate::hard_limits::ENCRYPTION_METADATA_BYTE_CEILING,
            max_key_candidates: crate::hard_limits::KEY_CANDIDATE_CEILING,
            max_x509_work: crate::hard_limits::X509_WORK_CEILING,
            max_x509_workspace_bytes: crate::hard_limits::X509_WORKSPACE_BYTE_CEILING,
            max_key_import_kdf_work: crate::hard_limits::KEY_IMPORT_KDF_WORK_CEILING as usize,
            max_key_import_kdf_memory_bytes: crate::hard_limits::KEY_IMPORT_KDF_MEMORY_CEILING,
            max_key_info_reference_depth: crate::hard_limits::KEY_INFO_REFERENCE_DEPTH_CEILING,
            max_base64_transform_input_bytes:
                crate::hard_limits::BASE64_TRANSFORM_INPUT_BYTE_CEILING,
            max_base64_transform_output_bytes:
                crate::hard_limits::BASE64_TRANSFORM_OUTPUT_BYTE_CEILING,
            max_xpath_expressions: crate::hard_limits::XPATH_EXPRESSION_COUNT_CEILING,
            max_xpath_expression_bytes: crate::hard_limits::XPATH_EXPRESSION_BYTE_CEILING,
            max_xpath_expression_complexity:
                crate::hard_limits::XPATH_EXPRESSION_COMPLEXITY_CEILING,
            max_xpath_context_evaluations: crate::hard_limits::XPATH_CONTEXT_EVALUATION_CEILING,
            max_xpath_evaluation_work: crate::hard_limits::XPATH_EVALUATION_WORK_CEILING,
            max_xpath_mirror_string_bytes: crate::hard_limits::XPATH_MIRROR_STRING_BYTE_CEILING,
            max_xpath_string_work_bytes: crate::hard_limits::XPATH_STRING_WORK_BYTE_CEILING,
            max_xpath_namespace_bindings: crate::hard_limits::XPATH_NAMESPACE_BINDING_CEILING,
            max_xpath_namespace_bytes: crate::hard_limits::XPATH_NAMESPACE_BYTE_CEILING,
            max_xpath_filters: crate::hard_limits::XPATH_FILTER_COUNT_CEILING,
            max_node_set_filter_work: crate::hard_limits::NODE_SET_FILTER_WORK_CEILING,
            max_node_set_entries: 262_144,
            max_node_set_owned_string_bytes: crate::hard_limits::NODE_SET_OWNED_STRING_BYTE_CEILING,
            max_node_set_cumulative_owned_string_bytes:
                crate::hard_limits::NODE_SET_CUMULATIVE_OWNED_STRING_BYTE_CEILING,
            max_opc_workspace_bytes: crate::hard_limits::OPC_WORKSPACE_BYTE_CEILING,
            max_opc_parameter_bytes: crate::hard_limits::OPC_PARAMETER_BYTE_CEILING,
        }
    }
}

impl ResourcePolicy {
    /// Validate policy values against non-configurable implementation ceilings.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        Self::within(
            resource_name::XML_NODES,
            self.max_xml_nodes,
            crate::hard_limits::XML_DOCUMENT_NODE_CEILING as usize,
        )?;
        Self::within(
            resource_name::XML_DEPTH,
            self.max_xml_depth,
            crate::hard_limits::XML_DOCUMENT_DEPTH_CEILING,
        )?;
        Self::within(
            resource_name::XML_NAMESPACE_BINDINGS,
            self.max_xml_namespace_bindings,
            crate::hard_limits::XML_NAMESPACE_BINDING_CEILING,
        )?;
        Self::within(
            resource_name::CANONICALIZED_BYTES,
            self.max_canonicalized_bytes,
            crate::hard_limits::CANONICALIZED_SIGNATURE_DATA_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::SIGNATURE_REFERENCES,
            self.max_references,
            crate::hard_limits::SIGNATURE_REFERENCE_CEILING,
        )?;
        Self::within(
            resource_name::VERIFICATION_SIGNATURES,
            self.max_signatures,
            crate::hard_limits::VERIFICATION_SIGNATURE_CEILING,
        )?;
        Self::within(
            resource_name::REFERENCE_TRANSFORMS,
            self.max_transforms_per_reference,
            crate::hard_limits::REFERENCE_TRANSFORM_CEILING,
        )?;
        Self::within(
            resource_name::XML_BASE_COMPONENTS,
            self.max_xml_base_components,
            crate::hard_limits::XML_BASE_COMPONENT_CEILING,
        )?;
        Self::within(
            resource_name::XML_BASE_RESOLUTION_BYTES,
            self.max_xml_base_resolution_bytes,
            crate::hard_limits::XML_BASE_RESOLUTION_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::XML_DOCUMENT,
            self.max_xml_document_bytes,
            crate::hard_limits::XML_DOCUMENT_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::XML_PARSE_WORK_BYTES,
            self.max_xml_parse_work_bytes,
            crate::hard_limits::XML_PARSE_WORK_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::EXTERNAL_RESOURCE_BYTES,
            self.max_external_resource_bytes,
            crate::hard_limits::EXTERNAL_RESOURCE_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::AGGREGATE_EXTERNAL_RESOURCE_BYTES,
            self.max_external_resource_total_bytes,
            crate::hard_limits::EXTERNAL_RESOURCE_TOTAL_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::ENCRYPTION_PLAINTEXT_BYTES,
            self.max_encryption_plaintext_bytes,
            crate::hard_limits::ENCRYPTION_PLAINTEXT_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::ENCRYPTION_RECIPIENTS,
            self.max_encryption_recipients,
            crate::hard_limits::ENCRYPTION_RECIPIENT_CEILING,
        )?;
        Self::within(
            resource_name::ENCRYPTION_METADATA_BYTES,
            self.max_encryption_metadata_bytes,
            crate::hard_limits::ENCRYPTION_METADATA_BYTE_CEILING,
        )?;
        for (resource, selected, ceiling) in [
            (
                resource_name::X509_WORK,
                self.max_x509_work,
                crate::hard_limits::X509_WORK_CEILING,
            ),
            (
                resource_name::X509_WORKSPACE_BYTES,
                self.max_x509_workspace_bytes,
                crate::hard_limits::X509_WORKSPACE_BYTE_CEILING,
            ),
            (
                resource_name::KEY_CANDIDATES,
                self.max_key_candidates,
                crate::hard_limits::KEY_CANDIDATE_CEILING,
            ),
            (
                resource_name::KEY_IMPORT_KDF_WORK,
                self.max_key_import_kdf_work,
                crate::hard_limits::KEY_IMPORT_KDF_WORK_CEILING as usize,
            ),
            (
                resource_name::KEY_IMPORT_KDF_MEMORY,
                self.max_key_import_kdf_memory_bytes,
                crate::hard_limits::KEY_IMPORT_KDF_MEMORY_CEILING,
            ),
            (
                resource_name::KEY_INFO_REFERENCE_DEPTH,
                self.max_key_info_reference_depth,
                crate::hard_limits::KEY_INFO_REFERENCE_DEPTH_CEILING,
            ),
            (
                resource_name::BASE64_TRANSFORM_INPUT_BYTES,
                self.max_base64_transform_input_bytes,
                crate::hard_limits::BASE64_TRANSFORM_INPUT_BYTE_CEILING,
            ),
            (
                resource_name::BASE64_TRANSFORM_OUTPUT_BYTES,
                self.max_base64_transform_output_bytes,
                crate::hard_limits::BASE64_TRANSFORM_OUTPUT_BYTE_CEILING,
            ),
            (
                resource_name::XPATH_EXPRESSIONS,
                self.max_xpath_expressions,
                crate::hard_limits::XPATH_EXPRESSION_COUNT_CEILING,
            ),
            (
                resource_name::XPATH_EXPRESSION_BYTES,
                self.max_xpath_expression_bytes,
                crate::hard_limits::XPATH_EXPRESSION_BYTE_CEILING,
            ),
            (
                resource_name::XPATH_EXPRESSION_COMPLEXITY,
                self.max_xpath_expression_complexity,
                crate::hard_limits::XPATH_EXPRESSION_COMPLEXITY_CEILING,
            ),
            (
                resource_name::XPATH_CONTEXT_EVALUATIONS,
                self.max_xpath_context_evaluations,
                crate::hard_limits::XPATH_CONTEXT_EVALUATION_CEILING,
            ),
            (
                resource_name::XPATH_EVALUATION_WORK,
                self.max_xpath_evaluation_work,
                crate::hard_limits::XPATH_EVALUATION_WORK_CEILING,
            ),
            (
                resource_name::XPATH_MIRROR_STRING_BYTES,
                self.max_xpath_mirror_string_bytes,
                crate::hard_limits::XPATH_MIRROR_STRING_BYTE_CEILING,
            ),
            (
                resource_name::XPATH_STRING_WORK_BYTES,
                self.max_xpath_string_work_bytes,
                crate::hard_limits::XPATH_STRING_WORK_BYTE_CEILING,
            ),
            (
                resource_name::XPATH_NAMESPACE_BINDINGS,
                self.max_xpath_namespace_bindings,
                crate::hard_limits::XPATH_NAMESPACE_BINDING_CEILING,
            ),
            (
                resource_name::XPATH_NAMESPACE_BYTES,
                self.max_xpath_namespace_bytes,
                crate::hard_limits::XPATH_NAMESPACE_BYTE_CEILING,
            ),
            (
                resource_name::XPATH_FILTERS,
                self.max_xpath_filters,
                crate::hard_limits::XPATH_FILTER_COUNT_CEILING,
            ),
            (
                resource_name::NODE_SET_FILTER_WORK,
                self.max_node_set_filter_work,
                crate::hard_limits::NODE_SET_FILTER_WORK_CEILING,
            ),
            (
                resource_name::NODE_SET_ENTRIES,
                self.max_node_set_entries,
                crate::hard_limits::NODE_SET_ENTRY_CEILING,
            ),
            (
                resource_name::NODE_SET_OWNED_STRING_BYTES,
                self.max_node_set_owned_string_bytes,
                crate::hard_limits::NODE_SET_OWNED_STRING_BYTE_CEILING,
            ),
            (
                resource_name::NODE_SET_CUMULATIVE_OWNED_STRING_BYTES,
                self.max_node_set_cumulative_owned_string_bytes,
                crate::hard_limits::NODE_SET_CUMULATIVE_OWNED_STRING_BYTE_CEILING,
            ),
        ] {
            Self::within(resource, selected, ceiling)?;
        }
        Self::within(
            resource_name::OPC_WORKSPACE_BYTES,
            self.max_opc_workspace_bytes,
            crate::hard_limits::OPC_WORKSPACE_BYTE_CEILING,
        )?;
        Self::within(
            resource_name::OPC_PARAMETER_BYTES,
            self.max_opc_parameter_bytes,
            crate::hard_limits::OPC_PARAMETER_BYTE_CEILING,
        )?;
        Ok(())
    }

    pub(crate) fn validate_xml_document_len(&self, actual: usize) -> Result<(), PolicyViolation> {
        if actual > self.max_xml_document_bytes {
            return Err(PolicyViolation::ResourceLimit {
                resource: resource_name::XML_DOCUMENT,
                maximum: self.max_xml_document_bytes,
                actual,
            });
        }
        Ok(())
    }

    #[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
    /// Reject aggregate key-candidate work beyond this policy snapshot.
    pub fn validate_key_candidates(&self, actual: usize) -> Result<(), PolicyViolation> {
        if actual > self.max_key_candidates {
            return Err(PolicyViolation::ResourceLimit {
                resource: resource_name::KEY_CANDIDATES,
                maximum: self.max_key_candidates,
                actual,
            });
        }
        Ok(())
    }

    /// Reject `KeyInfoReference` traversal beyond this policy snapshot.
    #[cfg(feature = "xmldsig")]
    pub fn validate_key_info_reference_depth(&self, actual: usize) -> Result<(), PolicyViolation> {
        if actual > self.max_key_info_reference_depth {
            return Err(PolicyViolation::ResourceLimit {
                resource: resource_name::KEY_INFO_REFERENCE_DEPTH,
                maximum: self.max_key_info_reference_depth,
                actual,
            });
        }
        Ok(())
    }

    pub(crate) fn effective_xml_nodes(&self) -> u32 {
        u32::try_from(self.max_xml_nodes)
            .unwrap_or(crate::hard_limits::XML_DOCUMENT_NODE_CEILING)
            .min(crate::hard_limits::XML_DOCUMENT_NODE_CEILING)
    }

    #[cfg(feature = "xmldsig")]
    pub(crate) fn effective_canonicalized_bytes(&self) -> usize {
        self.max_canonicalized_bytes
            .min(crate::hard_limits::CANONICALIZED_SIGNATURE_DATA_BYTE_CEILING)
    }

    #[cfg(feature = "xmldsig")]
    pub(crate) fn effective_xml_base_components(&self) -> usize {
        self.max_xml_base_components
            .min(crate::hard_limits::XML_BASE_COMPONENT_CEILING)
    }

    #[cfg(feature = "xmldsig")]
    pub(crate) fn effective_xml_base_resolution_bytes(&self) -> usize {
        self.max_xml_base_resolution_bytes
            .min(crate::hard_limits::XML_BASE_RESOLUTION_BYTE_CEILING)
    }

    fn within(
        resource: &'static str,
        selected: usize,
        ceiling: usize,
    ) -> Result<(), PolicyViolation> {
        if selected > ceiling {
            return Err(PolicyViolation::ResourceLimit {
                resource,
                maximum: ceiling,
                actual: selected,
            });
        }
        Ok(())
    }

    #[cfg(feature = "xmldsig")]
    fn nonzero_within(
        resource: &'static str,
        selected: usize,
        ceiling: usize,
    ) -> Result<(), PolicyViolation> {
        if selected == 0 {
            return Err(PolicyViolation::InvalidResourceLimit {
                resource,
                requirement: "limit must be nonzero",
                actual: selected,
            });
        }
        Self::within(resource, selected, ceiling)
    }
}

/// XML parsing decisions shared by all operation policies.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct XmlInputPolicy {
    /// Permit bounded internal DTD declarations. External resolution stays off.
    pub allow_internal_dtd: bool,
}

/// Trusted edition of relationship selection and normalization.
/// This is not an OPC package-conformance profile: signature placement and
/// package-wide part identity constraints require a package validator.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum OpcRelationshipEdition {
    /// ECMA-376 Part 2 (2012), including libxmlsec1's case-sensitive selection.
    Ecma2012,
    /// ECMA-376 Part 2 (2021) section 10.6, ASCII-insensitive selection.
    #[default]
    Ecma2021,
}

/// XMLDSig transform and canonicalization decisions shared by signing and verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SameDocumentIdSemantics {
    /// Require bare fragment identifiers to satisfy the XML NCName grammar.
    #[default]
    Specification,
    /// Apply libxmlsec1's default barename compatibility grammar.
    ///
    /// Registered non-NCName values are accepted unless a single quote makes
    /// them unrepresentable in the donor's single-quoted XPointer expression.
    /// The resulting node set retains barename semantics and excludes comments.
    XmlSecBarename,
    /// Resolve the fragment text directly as an ID, including non-NCName values.
    ///
    /// This reproduces libxmlsec1's explicit Visa3D compatibility flag.
    XmlSecVisa3d,
}

/// Wire representation used for ECDSA `SignatureValue` bytes.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum EcdsaSignatureValueEncoding {
    /// XMLDSig fixed-width `r || s` representation.
    #[default]
    XmlDsig,
    /// ASN.1 DER `SEQUENCE(INTEGER(r), INTEGER(s))` compatibility representation.
    XmlSecAsn1Der,
}

/// XMLDSig transform and canonicalization decisions shared by signing and verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TransformPolicy {
    /// Allowed transform and canonicalization URIs; `None` accepts every implemented algorithm.
    pub allowed_algorithms: Option<HashSet<String>>,
    /// Node selected for the XPath `here()` extension function.
    pub xpath_here_semantics: XPathHereSemantics,
    /// Interpretation of bare same-document ID fragments.
    pub same_document_id_semantics: SameDocumentIdSemantics,
    /// Trusted normalization edition, not package validation; never inferred from XML.
    pub opc_relationship_edition: OpcRelationshipEdition,
}

/// URI-class decisions shared by XMLDSig reference and key retrieval processing.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UriPolicy {
    /// URI classes accepted by SignedInfo and Manifest references.
    pub references: UriTypeSet,
    /// URI classes accepted by RetrievalMethod processing.
    pub retrieval_methods: UriTypeSet,
    /// URI classes accepted by XMLDSig 1.1 `KeyInfoReference` processing.
    pub key_info_references: UriTypeSet,
}

#[cfg(feature = "xmldsig")]
impl Default for UriPolicy {
    fn default() -> Self {
        Self {
            references: UriTypeSet::SAME_DOCUMENT,
            retrieval_methods: UriTypeSet::SAME_DOCUMENT,
            key_info_references: UriTypeSet::SAME_DOCUMENT,
        }
    }
}

/// KeyInfo sources an XMLDSig verification operation is permitted to trust.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeySourcePolicy {
    /// Permit a caller-supplied pre-resolved key.
    pub preset_key: bool,
    /// Permit keys selected by document `KeyName`.
    pub key_name: bool,
    /// Permit public keys embedded in `KeyValue`.
    pub key_value: bool,
    /// Permit public keys embedded in `DEREncodedKeyValue`.
    pub der_encoded_key_value: bool,
    /// Permit certificates and selectors embedded in `X509Data`.
    pub x509_data: bool,
    /// Permit `KeyInfoReference` indirection to another bounded `KeyInfo`.
    pub key_info_reference: bool,
}

#[cfg(feature = "xmldsig")]
impl Default for KeySourcePolicy {
    fn default() -> Self {
        Self {
            preset_key: true,
            key_name: true,
            key_value: true,
            der_encoded_key_value: true,
            x509_data: true,
            key_info_reference: true,
        }
    }
}

/// An RFC 5280 extended-key-purpose identifier accepted for XML signing.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExtendedKeyPurpose {
    /// TLS server authentication (`id-kp-serverAuth`).
    ServerAuth,
    /// TLS client authentication (`id-kp-clientAuth`).
    ClientAuth,
    /// Executable code signing (`id-kp-codeSigning`).
    CodeSigning,
    /// Email protection (`id-kp-emailProtection`).
    EmailProtection,
    /// Trusted timestamping (`id-kp-timeStamping`).
    TimeStamping,
    /// OCSP response signing (`id-kp-OCSPSigning`).
    OcspSigning,
    /// Application-defined purpose represented as OID arcs.
    Other(Vec<u64>),
}

/// Whether verification must establish signer authorization in addition to mathematics.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum VerificationTrustMode {
    /// Require path validation or an explicit caller trust declaration.
    #[default]
    RequireTrustedKey,
    /// Check mathematical validity without authenticating the signer.
    CryptographicOnly,
}

/// X.509 and key-resolution decisions for verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyTrustPolicy {
    /// Whether mathematical validity alone is sufficient for the operation.
    pub mode: VerificationTrustMode,
    /// Require embedded or selected certificates to chain to a configured anchor.
    pub verify_x509_chains: bool,
    /// Maximum validated path depth.
    pub max_x509_chain_depth: usize,
    /// Maximum complete or partial signature-valid path states generated.
    pub max_x509_candidate_paths: usize,
    /// Legacy signature algorithms explicitly permitted for verification.
    pub allowed_legacy_signature_algorithms: HashSet<SignatureAlgorithm>,
    /// Independent legacy-hash permission for parameterized RSA-PSS verification.
    pub parameterized_rsa_pss: RsaPssPermission,
    /// Certificate and CRL signature permissions, independent of XML signatures.
    /// `None` permits supported classical algorithms but rejects PQ algorithms;
    /// Explicit permissions select either an exact allowlist (including PSS
    /// parameters) or all provider-supported algorithms for compatibility.
    pub certificate_signature_algorithms: Option<CertificateSignatureAlgorithms>,
    /// RSA requirements enforced for resolved verification keys and issuer keys.
    pub rsa_keys: RsaKeyPolicy,
    /// DSA requirements enforced for resolved verification keys.
    pub dsa_keys: DsaKeyPolicy,
    /// Purposes accepted when any certificate in a path carries ExtendedKeyUsage.
    ///
    /// An empty set accepts only paths whose certificates omit ExtendedKeyUsage
    /// or use `anyExtendedKeyUsage`; it does not treat TLS/code-signing purposes
    /// as a generic authorization for XML signatures.
    pub allowed_extended_key_usages: HashSet<ExtendedKeyPurpose>,
    /// Authenticate and enforce embedded CRLs during path validation.
    /// Requires [`Self::verify_x509_chains`].
    pub check_crls: bool,
    /// Verification time override; `None` selects the system clock.
    pub verification_time: Option<SystemTime>,
}

#[cfg(feature = "xmldsig")]
impl Default for KeyTrustPolicy {
    fn default() -> Self {
        Self {
            mode: VerificationTrustMode::RequireTrustedKey,
            verify_x509_chains: false,
            max_x509_chain_depth: crate::hard_limits::X509_CHAIN_DEPTH_CEILING,
            max_x509_candidate_paths: crate::hard_limits::X509_CANDIDATE_PATH_CEILING,
            allowed_legacy_signature_algorithms: HashSet::new(),
            parameterized_rsa_pss: RsaPssPermission::ExactOnly,
            certificate_signature_algorithms: None,
            rsa_keys: RsaKeyPolicy::default(),
            dsa_keys: DsaKeyPolicy::default(),
            allowed_extended_key_usages: HashSet::new(),
            check_crls: false,
            verification_time: None,
        }
    }
}

#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, PartialEq, Eq)]
/// Explicit certificate/CRL permissions, independent of XML signature methods.
pub enum CertificateSignatureAlgorithms {
    /// Permit any algorithm the selected provider implements, including PQ.
    /// This is an explicit compatibility opt-in, not a provider fallback.
    AllSupported,
    /// Permit only exact algorithms, including every RSA-PSS parameter.
    Allowlist(HashSet<crate::provider::X509SignatureAlgorithm>),
}

#[cfg(feature = "xmldsig")]
impl KeyTrustPolicy {
    pub(crate) fn check_certificate_signature_algorithm(
        algorithm: crate::provider::X509SignatureAlgorithm,
        allowed: Option<&CertificateSignatureAlgorithms>,
    ) -> Result<(), PolicyViolation> {
        // This is deployment permission, not a PKIX syntax requirement.
        // Algorithm parameters are validated before this gate; compiled
        // provider capability is checked only after permission is established.
        let permitted = match allowed {
            Some(CertificateSignatureAlgorithms::AllSupported) => true,
            Some(CertificateSignatureAlgorithms::Allowlist(allowed)) => {
                allowed.contains(&algorithm)
            }
            None => !matches!(
                algorithm,
                crate::provider::X509SignatureAlgorithm::PostQuantum(_)
            ),
        };
        if !permitted {
            return Err(PolicyViolation::Algorithm {
                operation: "certificate/CRL verification",
                algorithm: algorithm
                    .oid()
                    .map_or_else(|| format!("{algorithm:?}"), str::to_owned),
            });
        }
        Ok(())
    }

    pub(crate) fn validate(&self) -> Result<(), PolicyViolation> {
        if self.check_crls && !self.verify_x509_chains {
            return Err(PolicyViolation::KeyTrust {
                reason: "CRL checking requires X.509 chain validation",
            });
        }
        if self
            .allowed_extended_key_usages
            .iter()
            .any(|purpose| match purpose {
                ExtendedKeyPurpose::Other(arcs) => {
                    arcs.len() < 2 || arcs[0] > 2 || (arcs[0] < 2 && arcs[1] > 39)
                }
                _ => false,
            })
        {
            return Err(PolicyViolation::KeyTrust {
                reason: "custom extended key purposes must contain valid OID arcs",
            });
        }
        self.rsa_keys.validate()?;
        self.dsa_keys.validate()?;
        ResourcePolicy::nonzero_within(
            "X.509 chain depth",
            self.max_x509_chain_depth,
            crate::hard_limits::X509_CHAIN_DEPTH_CEILING,
        )?;
        ResourcePolicy::nonzero_within(
            "X.509 candidate paths",
            self.max_x509_candidate_paths,
            crate::hard_limits::X509_CANDIDATE_PATH_CEILING,
        )
    }
}

/// Whether an XMLDSig operation evaluates Manifest references. Verification
/// requires original authenticated coverage; signing populates direct Object/Manifest digests.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ManifestProcessing {
    /// Leave Manifest reference values untouched and perform no Manifest work.
    #[default]
    Ignore,
    /// Evaluate Manifest references under the operation's shared resource policy.
    Process,
}

/// Immutable policy snapshot for XMLDSig verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Default)]
pub struct VerificationPolicy {
    /// Explicitly authorized lifetime; checked again at operation entry.
    pub validity: Option<PolicyValidity>,
    /// XML Security requirements, not application protocol validation.
    pub signature_constraints: SignatureConstraints,
    /// Shared key-establishment permissions and cumulative operation limits.
    pub key_establishment: KeyEstablishmentPolicy,
    /// Family permission selected by the caller, never derived from document input.
    /// Legacy hashes additionally require the independent key-trust permission.
    pub parameterized_rsa_pss: RsaPssPermission,
    /// Exact signature methods, supplemented by `parameterized_rsa_pss`.
    /// `None` accepts every implemented method subject to
    /// independent gates such as [`KeyTrustPolicy::allowed_legacy_signature_algorithms`].
    pub signature_algorithms: Option<HashSet<SignatureAlgorithm>>,
    /// Allowed reference digest methods; `None` accepts every implemented method.
    pub digest_algorithms: Option<HashSet<DigestAlgorithm>>,
    /// HMAC secret and output-length requirements.
    pub hmac: HmacPolicy,
    /// Required ECDSA `SignatureValue` wire representation.
    pub ecdsa_signature_value_encoding: EcdsaSignatureValueEncoding,
    /// Key and certificate trust rules.
    pub key_trust: KeyTrustPolicy,
    /// KeyInfo source permissions.
    pub key_sources: KeySourcePolicy,
    /// Reference and key-retrieval URI permissions.
    pub uris: UriPolicy,
    /// Transform and canonicalization permissions.
    pub transforms: TransformPolicy,
    /// Whether authenticated Manifest references are processed.
    pub manifest_processing: ManifestProcessing,
    /// XML parser rules.
    pub xml: XmlInputPolicy,
    /// Resource ceilings.
    pub resources: ResourcePolicy,
}

#[cfg(feature = "xmldsig")]
impl VerificationPolicy {
    pub(crate) fn check_digest_algorithm(
        &self,
        algorithm: DigestAlgorithm,
    ) -> Result<(), PolicyViolation> {
        if self
            .digest_algorithms
            .as_ref()
            .map_or(!algorithm.requires_explicit_permission(), |allowed| {
                allowed.contains(&algorithm)
            })
        {
            Ok(())
        } else {
            Err(PolicyViolation::Algorithm {
                operation: "verification",
                algorithm: algorithm.uri().to_owned(),
            })
        }
    }
    /// Validate the complete snapshot against implementation hard ceilings.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        if let Some(validity) = &self.validity {
            validity.validate_at(SystemTime::now())?;
        }
        if self.signature_constraints != SignatureConstraints::General
            && self.key_trust.mode == VerificationTrustMode::CryptographicOnly
        {
            return Err(PolicyViolation::Configuration {
                reason: "target coverage requires trusted-key verification",
            });
        }
        self.resources.validate()?;
        self.key_establishment.validate()?;
        self.key_trust.validate()?;
        self.hmac.validate()
    }

    /// Enforce the signature algorithm after key resolution.
    pub fn check_signature_algorithm(
        &self,
        algorithm: SignatureAlgorithm,
    ) -> Result<(), PolicyViolation> {
        if (matches!(algorithm, SignatureAlgorithm::PostQuantum(_))
            || algorithm.requires_explicit_permission())
            && !self
                .signature_algorithms
                .as_ref()
                .is_some_and(|allowed| allowed.contains(&algorithm))
        {
            return Err(PolicyViolation::Algorithm {
                operation: "verification",
                algorithm: algorithm.uri().to_owned(),
            });
        }
        if (algorithm.uses_legacy_pss_hash()
            || matches!(
                algorithm,
                SignatureAlgorithm::RsaSha1
                    | SignatureAlgorithm::DsaSha1
                    | SignatureAlgorithm::HmacSha1
                    | SignatureAlgorithm::EcdsaSha1
            ))
            && !self
                .key_trust
                .allowed_legacy_signature_algorithms
                .contains(&algorithm)
            && !self.key_trust.parameterized_rsa_pss.permits(algorithm)
        {
            return Err(PolicyViolation::Algorithm {
                operation: "verification",
                algorithm: algorithm.uri().to_string(),
            });
        }
        if self
            .signature_algorithms
            .as_ref()
            .is_some_and(|allowed| !allowed.contains(&algorithm))
            && !self.parameterized_rsa_pss.permits(algorithm)
        {
            return Err(PolicyViolation::Algorithm {
                operation: "verification",
                algorithm: algorithm.uri().to_string(),
            });
        }
        Ok(())
    }
}

/// Immutable policy snapshot for XMLDSig signing.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, Default)]
pub struct SigningPolicy {
    /// Explicitly authorized lifetime; checked again at operation entry.
    pub validity: Option<PolicyValidity>,
    /// XML Security requirements, not application protocol validation.
    pub signature_constraints: SignatureConstraints,
    /// Shared key-establishment permissions and cumulative operation limits.
    pub key_establishment: KeyEstablishmentPolicy,
    /// Explicit parameterized RSA-PSS family permission, including legacy hashes.
    pub parameterized_rsa_pss: RsaPssPermission,
    /// Exact signing methods, supplemented by `parameterized_rsa_pss`.
    /// `None` uses the implemented secure defaults.
    pub signature_algorithms: Option<HashSet<SignatureAlgorithm>>,
    /// Allowed reference digest methods; `None` uses the implemented secure defaults.
    pub digest_algorithms: Option<HashSet<DigestAlgorithm>>,
    /// HMAC secret and output-length requirements.
    pub hmac: HmacPolicy,
    /// ECDSA `SignatureValue` wire representation emitted by signing.
    pub ecdsa_signature_value_encoding: EcdsaSignatureValueEncoding,
    /// RSA requirements enforced before producing a signature.
    pub rsa_keys: RsaKeyPolicy,
    /// DSA requirements enforced before producing a signature.
    pub dsa_keys: DsaKeyPolicy,
    /// Reference URI permissions. External URIs resolve only from caller-supplied
    /// request bytes and never enable filesystem or network access.
    pub uris: UriPolicy,
    /// Transform and canonicalization permissions.
    pub transforms: TransformPolicy,
    /// Whether direct `<Object>/<Manifest>` reference digests are populated.
    pub manifest_processing: ManifestProcessing,
    /// XML parser rules.
    pub xml: XmlInputPolicy,
    /// Resource ceilings.
    pub resources: ResourcePolicy,
}

#[cfg(feature = "xmldsig")]
impl SigningPolicy {
    /// Validate the complete snapshot before signing work begins.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        if let Some(validity) = &self.validity {
            validity.validate_at(SystemTime::now())?;
        }
        self.resources.validate()?;
        self.key_establishment.validate()?;
        self.rsa_keys.validate()?;
        self.dsa_keys.validate()?;
        self.hmac.validate()
    }

    pub(crate) fn check_signature_algorithm(
        &self,
        algorithm: SignatureAlgorithm,
    ) -> Result<(), PolicyViolation> {
        if self.parameterized_rsa_pss.permits(algorithm) {
            return Ok(());
        }
        check_signing_algorithm(
            self.signature_algorithms.as_ref(),
            algorithm,
            algorithm.signing_allowed(),
            algorithm.uri(),
        )
    }

    pub(crate) fn check_digest_algorithm(
        &self,
        algorithm: DigestAlgorithm,
    ) -> Result<(), PolicyViolation> {
        check_signing_algorithm(
            self.digest_algorithms.as_ref(),
            algorithm,
            algorithm.signing_allowed(),
            algorithm.uri(),
        )
    }
}

#[cfg(feature = "xmldsig")]
fn check_signing_algorithm<T: Eq + std::hash::Hash>(
    allowlist: Option<&HashSet<T>>,
    algorithm: T,
    default_allowed: bool,
    uri: &str,
) -> Result<(), PolicyViolation> {
    if allowlist.map_or(default_allowed, |allowed| allowed.contains(&algorithm)) {
        Ok(())
    } else {
        Err(PolicyViolation::Algorithm {
            operation: "signing",
            algorithm: uri.to_owned(),
        })
    }
}

/// Enforce the shared content-cipher permission contract before dispatch.
#[cfg(feature = "xmlenc")]
pub(crate) fn check_content_algorithm(
    allowlist: Option<&HashSet<DataEncryptionAlgorithm>>,
    algorithm: DataEncryptionAlgorithm,
    operation: &'static str,
) -> Result<(), PolicyViolation> {
    if allowlist.map_or(!algorithm.requires_explicit_permission(), |allowed| {
        allowed.contains(&algorithm)
    }) {
        Ok(())
    } else {
        Err(PolicyViolation::Algorithm {
            operation,
            algorithm: algorithm.uri().to_owned(),
        })
    }
}

/// Immutable policy snapshot for XMLEnc encryption.
#[cfg(feature = "xmlenc")]
#[derive(Debug, Clone, Default)]
pub struct EncryptionPolicy {
    /// Explicitly authorized lifetime; checked again at operation entry.
    pub validity: Option<PolicyValidity>,
    /// Allowed content-encryption algorithms.
    pub data_algorithms: Option<HashSet<DataEncryptionAlgorithm>>,
    /// Allowed RSA key-transport algorithms.
    pub key_transport_algorithms: Option<HashSet<KeyTransportAlgorithm>>,
    /// Allowed symmetric key-wrap algorithms.
    pub key_wrap_algorithms: Option<HashSet<KeyWrapAlgorithm>>,
    /// Allowed OAEP digest algorithms.
    pub oaep_digests: Option<HashSet<OaepDigestAlgorithm>>,
    /// RSA requirements enforced when producing OAEP key transport.
    pub rsa_keys: RsaKeyPolicy,
    /// Shared agreement/KDF permission and cumulative work requirements.
    pub key_establishment: KeyEstablishmentPolicy,
    /// XML parser rules.
    pub xml: XmlInputPolicy,
    /// Resource ceilings.
    pub resources: ResourcePolicy,
}

#[cfg(feature = "xmlenc")]
impl EncryptionPolicy {
    /// Validate the complete snapshot before outbound encryption work begins.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        if let Some(validity) = &self.validity {
            validity.validate_at(SystemTime::now())?;
        }
        self.resources.validate()?;
        self.key_establishment.validate()?;
        self.rsa_keys.validate()
    }
}

/// Immutable policy snapshot for XMLEnc decryption.
#[cfg(feature = "xmlenc")]
#[derive(Debug, Clone, Default)]
pub struct DecryptionPolicy {
    /// Explicitly authorized lifetime; checked again at operation entry.
    pub validity: Option<PolicyValidity>,
    /// URI-class permissions for ciphertext and indirect key references.
    pub uris: UriPolicy,
    /// Shared transform permissions and same-document reference semantics.
    pub transforms: TransformPolicy,
    /// Allowed content-decryption algorithms.
    pub data_algorithms: Option<HashSet<DataEncryptionAlgorithm>>,
    /// Allowed RSA key-transport algorithms accepted on input.
    pub key_transport_algorithms: Option<HashSet<KeyTransportAlgorithm>>,
    /// Allowed symmetric key-wrap algorithms accepted on input.
    pub key_wrap_algorithms: Option<HashSet<KeyWrapAlgorithm>>,
    /// Allowed OAEP digest algorithms accepted on input.
    pub oaep_digests: Option<HashSet<OaepDigestAlgorithm>>,
    /// RSA requirements enforced before OAEP recovery; defaults to 2048 bits.
    /// Legacy input requires an explicit caller-selected lower minimum.
    pub rsa_keys: RsaKeyPolicy,
    /// Shared agreement/KDF permission and cumulative work requirements.
    pub key_establishment: KeyEstablishmentPolicy,
    /// XML parser rules.
    pub xml: XmlInputPolicy,
    /// Resource ceilings.
    pub resources: ResourcePolicy,
}

#[cfg(feature = "xmlenc")]
impl DecryptionPolicy {
    /// Validate the complete snapshot before inbound decryption work begins.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        if let Some(validity) = &self.validity {
            validity.validate_at(SystemTime::now())?;
        }
        self.resources.validate()?;
        self.key_establishment.validate()?;
        self.rsa_keys.validate()
    }
}

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

    #[cfg(all(feature = "legacy-algorithms", feature = "xmldsig"))]
    #[test]
    fn legacy_digest_permission_is_explicit_and_operation_local() {
        // Capability does not imply acceptance, and permission for one digest
        // or operation must never enable another digest or operation.
        for algorithm in [DigestAlgorithm::Md5, DigestAlgorithm::Ripemd160] {
            assert!(
                VerificationPolicy::default()
                    .check_digest_algorithm(algorithm)
                    .is_err()
            );
            assert!(
                SigningPolicy::default()
                    .check_digest_algorithm(algorithm)
                    .is_err()
            );
            let verification = VerificationPolicy {
                digest_algorithms: Some(HashSet::from([algorithm])),
                ..VerificationPolicy::default()
            };
            let signing = SigningPolicy {
                digest_algorithms: Some(HashSet::from([algorithm])),
                ..SigningPolicy::default()
            };
            assert!(verification.check_digest_algorithm(algorithm).is_ok());
            assert!(signing.check_digest_algorithm(algorithm).is_ok());
            assert!(
                verification
                    .check_digest_algorithm(DigestAlgorithm::Sha256)
                    .is_err()
            );
            assert!(
                signing
                    .check_digest_algorithm(DigestAlgorithm::Sha256)
                    .is_err()
            );
        }
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn certificate_permissions_keep_exact_pss_and_compatibility_distinct() {
        use crate::provider::X509SignatureAlgorithm;
        use crate::xmldsig::{DigestAlgorithm, PqAlgorithm};
        // Compatibility permission cannot impose an arbitrary PSS salt list;
        // exact allowlists must still distinguish every parameter tuple.
        let exact = X509SignatureAlgorithm::RsaPss {
            digest: DigestAlgorithm::Sha256,
            mgf_digest: DigestAlgorithm::Sha256,
            salt_len: 32,
        };
        let allowed = CertificateSignatureAlgorithms::Allowlist(HashSet::from([exact]));
        assert!(
            KeyTrustPolicy::check_certificate_signature_algorithm(exact, Some(&allowed)).is_ok()
        );
        for salt_len in [0, 17, 64, 255] {
            let method = X509SignatureAlgorithm::RsaPss {
                digest: DigestAlgorithm::Sha256,
                mgf_digest: DigestAlgorithm::Sha256,
                salt_len,
            };
            assert!(
                KeyTrustPolicy::check_certificate_signature_algorithm(method, Some(&allowed))
                    .is_err()
            );
            assert!(
                KeyTrustPolicy::check_certificate_signature_algorithm(
                    method,
                    Some(&CertificateSignatureAlgorithms::AllSupported)
                )
                .is_ok()
            );
        }
        let pq = X509SignatureAlgorithm::PostQuantum(PqAlgorithm::MlDsa44);
        assert!(KeyTrustPolicy::check_certificate_signature_algorithm(pq, None).is_err());
        assert!(
            KeyTrustPolicy::check_certificate_signature_algorithm(
                pq,
                Some(&CertificateSignatureAlgorithms::AllSupported)
            )
            .is_ok()
        );
    }

    #[test]
    fn resource_policy_cannot_exceed_implementation_ceiling() {
        let policy = ResourcePolicy {
            max_xml_nodes: 100_001,
            ..ResourcePolicy::default()
        };
        assert!(matches!(
            policy.validate(),
            Err(PolicyViolation::ResourceLimit {
                resource: resource_name::XML_NODES,
                maximum: 100_000,
                actual: 100_001,
            })
        ));
    }

    #[test]
    fn xml_parse_work_policy_cannot_exceed_implementation_ceiling() {
        let policy = ResourcePolicy {
            max_xml_parse_work_bytes: crate::hard_limits::XML_PARSE_WORK_BYTE_CEILING
                .saturating_add(1),
            ..ResourcePolicy::default()
        };

        assert_eq!(
            policy.validate(),
            Err(PolicyViolation::ResourceLimit {
                resource: resource_name::XML_PARSE_WORK_BYTES,
                maximum: crate::hard_limits::XML_PARSE_WORK_BYTE_CEILING,
                actual: crate::hard_limits::XML_PARSE_WORK_BYTE_CEILING.saturating_add(1),
            })
        );
    }

    #[test]
    fn every_resource_policy_field_obeys_its_hard_ceiling() {
        // Each public tuning knob is only a stricter operational limit; none
        // may raise the implementation's allocation ceiling. Exact diagnostics
        // also catch a field accidentally paired with another field's ceiling.
        type Case = (&'static str, usize, fn(&mut ResourcePolicy) -> &mut usize);
        let cases: &[Case] = &[
            (
                resource_name::X509_WORK,
                crate::hard_limits::X509_WORK_CEILING,
                |p| &mut p.max_x509_work,
            ),
            (
                resource_name::X509_WORKSPACE_BYTES,
                crate::hard_limits::X509_WORKSPACE_BYTE_CEILING,
                |p| &mut p.max_x509_workspace_bytes,
            ),
            (
                resource_name::XML_NODES,
                crate::hard_limits::XML_DOCUMENT_NODE_CEILING as usize,
                |p| &mut p.max_xml_nodes,
            ),
            (
                resource_name::XML_DEPTH,
                crate::hard_limits::XML_DOCUMENT_DEPTH_CEILING,
                |p| &mut p.max_xml_depth,
            ),
            (
                resource_name::XML_NAMESPACE_BINDINGS,
                crate::hard_limits::XML_NAMESPACE_BINDING_CEILING,
                |p| &mut p.max_xml_namespace_bindings,
            ),
            (
                resource_name::SIGNATURE_REFERENCES,
                crate::hard_limits::SIGNATURE_REFERENCE_CEILING,
                |p| &mut p.max_references,
            ),
            (
                resource_name::VERIFICATION_SIGNATURES,
                crate::hard_limits::VERIFICATION_SIGNATURE_CEILING,
                |p| &mut p.max_signatures,
            ),
            (
                resource_name::REFERENCE_TRANSFORMS,
                crate::hard_limits::REFERENCE_TRANSFORM_CEILING,
                |p| &mut p.max_transforms_per_reference,
            ),
            (
                resource_name::XML_BASE_COMPONENTS,
                crate::hard_limits::XML_BASE_COMPONENT_CEILING,
                |p| &mut p.max_xml_base_components,
            ),
            (
                resource_name::XML_BASE_RESOLUTION_BYTES,
                crate::hard_limits::XML_BASE_RESOLUTION_BYTE_CEILING,
                |p| &mut p.max_xml_base_resolution_bytes,
            ),
            (
                resource_name::CANONICALIZED_BYTES,
                crate::hard_limits::CANONICALIZED_SIGNATURE_DATA_BYTE_CEILING,
                |p| &mut p.max_canonicalized_bytes,
            ),
            (
                resource_name::EXTERNAL_RESOURCE_BYTES,
                crate::hard_limits::EXTERNAL_RESOURCE_BYTE_CEILING,
                |p| &mut p.max_external_resource_bytes,
            ),
            (
                resource_name::AGGREGATE_EXTERNAL_RESOURCE_BYTES,
                crate::hard_limits::EXTERNAL_RESOURCE_TOTAL_BYTE_CEILING,
                |p| &mut p.max_external_resource_total_bytes,
            ),
            (
                resource_name::ENCRYPTION_PLAINTEXT_BYTES,
                crate::hard_limits::ENCRYPTION_PLAINTEXT_BYTE_CEILING,
                |p| &mut p.max_encryption_plaintext_bytes,
            ),
            (
                resource_name::XML_DOCUMENT,
                crate::hard_limits::XML_DOCUMENT_BYTE_CEILING,
                |p| &mut p.max_xml_document_bytes,
            ),
            (
                resource_name::XML_PARSE_WORK_BYTES,
                crate::hard_limits::XML_PARSE_WORK_BYTE_CEILING,
                |p| &mut p.max_xml_parse_work_bytes,
            ),
            (
                resource_name::ENCRYPTION_RECIPIENTS,
                crate::hard_limits::ENCRYPTION_RECIPIENT_CEILING,
                |p| &mut p.max_encryption_recipients,
            ),
            (
                resource_name::ENCRYPTION_METADATA_BYTES,
                crate::hard_limits::ENCRYPTION_METADATA_BYTE_CEILING,
                |p| &mut p.max_encryption_metadata_bytes,
            ),
            (
                resource_name::KEY_CANDIDATES,
                crate::hard_limits::KEY_CANDIDATE_CEILING,
                |p| &mut p.max_key_candidates,
            ),
            (
                resource_name::KEY_IMPORT_KDF_WORK,
                crate::hard_limits::KEY_IMPORT_KDF_WORK_CEILING as usize,
                |p| &mut p.max_key_import_kdf_work,
            ),
            (
                resource_name::KEY_IMPORT_KDF_MEMORY,
                crate::hard_limits::KEY_IMPORT_KDF_MEMORY_CEILING,
                |p| &mut p.max_key_import_kdf_memory_bytes,
            ),
            (
                resource_name::KEY_INFO_REFERENCE_DEPTH,
                crate::hard_limits::KEY_INFO_REFERENCE_DEPTH_CEILING,
                |p| &mut p.max_key_info_reference_depth,
            ),
            (
                resource_name::BASE64_TRANSFORM_INPUT_BYTES,
                crate::hard_limits::BASE64_TRANSFORM_INPUT_BYTE_CEILING,
                |p| &mut p.max_base64_transform_input_bytes,
            ),
            (
                resource_name::BASE64_TRANSFORM_OUTPUT_BYTES,
                crate::hard_limits::BASE64_TRANSFORM_OUTPUT_BYTE_CEILING,
                |p| &mut p.max_base64_transform_output_bytes,
            ),
            (
                resource_name::XPATH_EXPRESSIONS,
                crate::hard_limits::XPATH_EXPRESSION_COUNT_CEILING,
                |p| &mut p.max_xpath_expressions,
            ),
            (
                resource_name::XPATH_EXPRESSION_BYTES,
                crate::hard_limits::XPATH_EXPRESSION_BYTE_CEILING,
                |p| &mut p.max_xpath_expression_bytes,
            ),
            (
                resource_name::XPATH_EXPRESSION_COMPLEXITY,
                crate::hard_limits::XPATH_EXPRESSION_COMPLEXITY_CEILING,
                |p| &mut p.max_xpath_expression_complexity,
            ),
            (
                resource_name::XPATH_CONTEXT_EVALUATIONS,
                crate::hard_limits::XPATH_CONTEXT_EVALUATION_CEILING,
                |p| &mut p.max_xpath_context_evaluations,
            ),
            (
                resource_name::XPATH_EVALUATION_WORK,
                crate::hard_limits::XPATH_EVALUATION_WORK_CEILING,
                |p| &mut p.max_xpath_evaluation_work,
            ),
            (
                resource_name::XPATH_MIRROR_STRING_BYTES,
                crate::hard_limits::XPATH_MIRROR_STRING_BYTE_CEILING,
                |p| &mut p.max_xpath_mirror_string_bytes,
            ),
            (
                resource_name::XPATH_STRING_WORK_BYTES,
                crate::hard_limits::XPATH_STRING_WORK_BYTE_CEILING,
                |p| &mut p.max_xpath_string_work_bytes,
            ),
            (
                resource_name::XPATH_NAMESPACE_BINDINGS,
                crate::hard_limits::XPATH_NAMESPACE_BINDING_CEILING,
                |p| &mut p.max_xpath_namespace_bindings,
            ),
            (
                resource_name::XPATH_NAMESPACE_BYTES,
                crate::hard_limits::XPATH_NAMESPACE_BYTE_CEILING,
                |p| &mut p.max_xpath_namespace_bytes,
            ),
            (
                resource_name::XPATH_FILTERS,
                crate::hard_limits::XPATH_FILTER_COUNT_CEILING,
                |p| &mut p.max_xpath_filters,
            ),
            (
                resource_name::NODE_SET_FILTER_WORK,
                crate::hard_limits::NODE_SET_FILTER_WORK_CEILING,
                |p| &mut p.max_node_set_filter_work,
            ),
            (
                resource_name::OPC_PARAMETER_BYTES,
                crate::hard_limits::OPC_PARAMETER_BYTE_CEILING,
                |p| &mut p.max_opc_parameter_bytes,
            ),
            (
                resource_name::OPC_WORKSPACE_BYTES,
                crate::hard_limits::OPC_WORKSPACE_BYTE_CEILING,
                |p| &mut p.max_opc_workspace_bytes,
            ),
            (
                resource_name::NODE_SET_ENTRIES,
                crate::hard_limits::NODE_SET_ENTRY_CEILING,
                |p| &mut p.max_node_set_entries,
            ),
            (
                resource_name::NODE_SET_OWNED_STRING_BYTES,
                crate::hard_limits::NODE_SET_OWNED_STRING_BYTE_CEILING,
                |p| &mut p.max_node_set_owned_string_bytes,
            ),
            (
                resource_name::NODE_SET_CUMULATIVE_OWNED_STRING_BYTES,
                crate::hard_limits::NODE_SET_CUMULATIVE_OWNED_STRING_BYTE_CEILING,
                |p| &mut p.max_node_set_cumulative_owned_string_bytes,
            ),
        ];

        for &(resource, ceiling, field) in cases {
            let mut policy = ResourcePolicy::default();
            let actual = ceiling.saturating_add(1);
            *field(&mut policy) = actual;
            assert_eq!(
                policy.validate(),
                Err(PolicyViolation::ResourceLimit {
                    resource,
                    maximum: ceiling,
                    actual,
                }),
                "wrong hard-ceiling validation for {resource}",
            );
        }
    }

    #[test]
    fn resource_policy_accepts_zero_as_a_deny_all_ceiling() {
        // Zero is a valid policy decision for resources that an operation can
        // avoid consuming; runtime checks must reject only actual non-zero use.
        let policy = ResourcePolicy {
            max_xml_nodes: 0,
            max_xml_depth: 0,
            max_xml_namespace_bindings: 0,
            max_references: 0,
            max_signatures: 0,
            max_transforms_per_reference: 0,
            max_xml_base_components: 0,
            max_xml_base_resolution_bytes: 0,
            max_canonicalized_bytes: 0,
            max_external_resource_bytes: 0,
            max_external_resource_total_bytes: 0,
            max_encryption_plaintext_bytes: 0,
            max_xml_document_bytes: 0,
            max_xml_parse_work_bytes: 0,
            max_encryption_recipients: 0,
            max_encryption_metadata_bytes: 0,
            max_key_candidates: 0,
            max_x509_work: 0,
            max_x509_workspace_bytes: 0,
            max_key_import_kdf_work: 0,
            max_key_import_kdf_memory_bytes: 0,
            max_key_info_reference_depth: 0,
            max_base64_transform_input_bytes: 0,
            max_base64_transform_output_bytes: 0,
            max_xpath_expressions: 0,
            max_xpath_expression_bytes: 0,
            max_xpath_expression_complexity: 0,
            max_xpath_context_evaluations: 0,
            max_xpath_evaluation_work: 0,
            max_xpath_mirror_string_bytes: 0,
            max_xpath_string_work_bytes: 0,
            max_xpath_namespace_bindings: 0,
            max_xpath_namespace_bytes: 0,
            max_xpath_filters: 0,
            max_node_set_filter_work: 0,
            max_node_set_entries: 0,
            max_node_set_owned_string_bytes: 0,
            max_node_set_cumulative_owned_string_bytes: 0,
            max_opc_workspace_bytes: 0,
            max_opc_parameter_bytes: 0,
        };

        assert_eq!(policy.validate(), Ok(()));
    }

    #[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
    #[test]
    fn node_set_policy_has_headroom_above_its_default() {
        let mut policy = ResourcePolicy::default();
        assert_eq!(policy.max_node_set_entries, 262_144);
        assert_eq!(policy.validate(), Ok(()));

        policy.max_node_set_entries = 524_288;
        assert_eq!(policy.validate(), Ok(()));

        policy.max_node_set_entries = 524_289;
        assert_eq!(
            policy.validate(),
            Err(PolicyViolation::ResourceLimit {
                resource: resource_name::NODE_SET_ENTRIES,
                maximum: 524_288,
                actual: 524_289,
            })
        );
    }

    #[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
    #[test]
    fn rsa_key_policy_enforces_structure_range_and_explicit_relaxation() {
        let secure = RsaKeyPolicy::default();
        assert!(matches!(
            secure.validate_components("test", &[0x80; 128], &[1, 0, 1]),
            Err(PolicyViolation::KeySize {
                minimum_bits: 2048,
                maximum_bits: 8192,
                actual_bits: 1024,
                ..
            })
        ));
        let mut short_2048_width = [0_u8; 256];
        short_2048_width[0] = 1;
        assert!(matches!(
            secure.validate_components("test", &short_2048_width, &[1, 0, 1]),
            Err(PolicyViolation::KeySize {
                minimum_bits: 2048,
                actual_bits: 2041,
                ..
            })
        ));
        assert!(matches!(
            secure.validate_components("test", &[1; 1025], &[1, 0, 1]),
            Err(PolicyViolation::KeySize {
                actual_bits: 8193,
                ..
            })
        ));
        assert!(matches!(
            secure.validate_components("test", &[0x80; 256], &[2]),
            Err(PolicyViolation::InvalidKeyMaterial { .. })
        ));
        assert_eq!(
            secure.validate_components("test", &[0x80; 256], &[0x80, 0, 0, 1]),
            Ok(256),
            "normalized RSA components encode the exponent as unsigned bytes"
        );

        let compatibility = RsaKeyPolicy {
            minimum_modulus_bits: 1024,
        };
        assert_eq!(
            compatibility.validate_components("test", &[0x80; 128], &[1, 0, 1]),
            Ok(128)
        );
        assert!(
            RsaKeyPolicy {
                minimum_modulus_bits: 2047,
            }
            .validate()
            .is_err()
        );
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn mandatory_x509_limits_report_the_nonzero_requirement() {
        // A lower-bound violation must not be reported as exceeding the upper
        // ceiling: that diagnostic points callers toward the wrong correction.
        let policy = KeyTrustPolicy {
            max_x509_chain_depth: 0,
            ..KeyTrustPolicy::default()
        };

        let error = policy.validate().expect_err("zero depth must be rejected");
        assert!(
            error.to_string().contains("must be nonzero"),
            "unexpected lower-bound diagnostic: {error}"
        );
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn custom_extended_key_purposes_require_valid_oid_arcs() {
        // The typed policy rejects impossible OIDs when the immutable snapshot
        // is validated instead of silently making the purpose unmatchable.
        let mut policy = KeyTrustPolicy::default();
        policy
            .allowed_extended_key_usages
            .insert(ExtendedKeyPurpose::Other(vec![1, 40, 7]));

        assert!(matches!(
            policy.validate(),
            Err(PolicyViolation::KeyTrust {
                reason: "custom extended key purposes must contain valid OID arcs",
            })
        ));
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn crl_checking_requires_x509_chain_validation() {
        // CRLs authenticate through the validated issuer path. Accepting this
        // combination would advertise a security control the resolver skips.
        let policy = KeyTrustPolicy {
            check_crls: true,
            ..KeyTrustPolicy::default()
        };

        assert!(matches!(
            policy.validate(),
            Err(PolicyViolation::KeyTrust {
                reason: "CRL checking requires X.509 chain validation"
            })
        ));
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn legacy_signature_algorithms_require_independent_policy_opt_ins() {
        let legacy = [
            SignatureAlgorithm::RsaSha1,
            SignatureAlgorithm::DsaSha1,
            SignatureAlgorithm::HmacSha1,
            SignatureAlgorithm::EcdsaSha1,
        ];
        let mut policy = VerificationPolicy::default();

        for algorithm in legacy {
            assert!(matches!(
                policy.check_signature_algorithm(algorithm),
                Err(PolicyViolation::Algorithm { .. })
            ));
            policy
                .key_trust
                .allowed_legacy_signature_algorithms
                .insert(algorithm);
            assert_eq!(policy.check_signature_algorithm(algorithm), Ok(()));
            policy
                .key_trust
                .allowed_legacy_signature_algorithms
                .remove(&algorithm);
        }
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn dsa_key_policy_enforces_configured_minimum_and_hard_ceiling() {
        let policy = DsaKeyPolicy::default();

        assert!(matches!(
            policy.validate_modulus_bits(1024),
            Err(PolicyViolation::KeySize {
                key_type: "DSA",
                minimum_bits: 2048,
                maximum_bits: 3072,
                actual_bits: 1024,
                ..
            })
        ));
        assert_eq!(policy.validate_modulus_bits(2048), Ok(()));
        assert!(matches!(
            policy.validate_modulus_bits(4096),
            Err(PolicyViolation::KeySize {
                key_type: "DSA",
                minimum_bits: 2048,
                maximum_bits: 3072,
                actual_bits: 4096,
                ..
            })
        ));
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn hmac_output_policy_cannot_weaken_the_xmldsig_floor() {
        // Caller policy may tighten but cannot weaken XMLDSig section 4.4.2:
        // truncation is at least 80 bits and at least half the digest width.
        let compatibility = HmacPolicy {
            minimum_key_bits: 40,
            minimum_output_bits: 40,
        };

        assert_eq!(
            compatibility.validate_output(SignatureAlgorithm::HmacSha1, 80),
            Ok(())
        );
        assert!(matches!(
            compatibility.validate_output(SignatureAlgorithm::HmacSha1, 72),
            Err(PolicyViolation::HmacOutputLength { minimum: 80, .. })
        ));
        assert!(matches!(
            compatibility.validate_output(SignatureAlgorithm::HmacSha256, 120),
            Err(PolicyViolation::HmacOutputLength { minimum: 128, .. })
        ));
    }

    #[cfg(feature = "xmldsig")]
    #[test]
    fn documented_xmldsig_limits_match_hard_limits() {
        // Public deployment guidance must change in the same commit as the
        // implementation ceilings from which these values are derived.
        let docs = include_str!("../docs/xmldsig.md");
        let mib = 1024 * 1024;
        assert!(docs.contains(&format!(
            "Individual resources are limited to {} MiB",
            crate::hard_limits::EXTERNAL_RESOURCE_BYTE_CEILING / mib
        )));
        assert!(docs.contains(&format!(
            "complete map to {} MiB",
            crate::hard_limits::EXTERNAL_RESOURCE_TOTAL_BYTE_CEILING / mib
        )));
        assert!(docs.contains(&format!(
            "ceilings are {} components and {} MiB per operation",
            crate::hard_limits::XML_BASE_COMPONENT_CEILING,
            crate::hard_limits::XML_BASE_RESOLUTION_BYTE_CEILING / mib
        )));
    }
}