xml-sec 0.1.14

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
//! 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,
};

/// 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 SIGNATURE_REFERENCES: &str = "signature references";
    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 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 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 {
    /// 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 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,
    },
    /// 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 RSA key falls outside the operation's configured 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 modulus width.
        minimum_bits: usize,
        /// Non-configurable implementation ceiling.
        maximum_bits: usize,
        /// Observed normalized modulus width.
        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,
    },
}

/// RSA strength and structural requirements for outbound cryptographic operations.
#[cfg(any(feature = "xmldsig", feature = "xmlenc"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RsaKeyPolicy {
    /// Minimum mathematical RSA modulus bit length accepted for new output.
    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> {
        if self.minimum_modulus_bits == 0 || !self.minimum_modulus_bits.is_multiple_of(64) {
            return Err(PolicyViolation::InvalidResourceLimit {
                resource: "minimum DSA modulus bits",
                requirement: "minimum must be a nonzero multiple of 64 bits",
                actual: self.minimum_modulus_bits,
            });
        }
        ResourcePolicy::within(
            "minimum DSA modulus bits",
            self.minimum_modulus_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> {
        if self.minimum_modulus_bits == 0 || !self.minimum_modulus_bits.is_multiple_of(8) {
            return Err(PolicyViolation::InvalidResourceLimit {
                resource: "minimum RSA modulus bits",
                requirement: "minimum must be a nonzero whole-byte width",
                actual: self.minimum_modulus_bits,
            });
        }
        ResourcePolicy::within(
            "minimum RSA modulus bits",
            self.minimum_modulus_bits,
            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",
            })?;
        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,
            });
        }
        if exponent.is_empty() || exponent.len() > 8 {
            return Err(PolicyViolation::InvalidKeyMaterial {
                operation,
                key_type: "RSA",
                reason: "public exponent has invalid encoding",
            });
        }
        let mut exponent_bytes = [0_u8; 8];
        exponent_bytes[8 - exponent.len()..].copy_from_slice(exponent);
        let exponent = u64::from_be_bytes(exponent_bytes);
        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.len())
    }
}

/// 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 references in one signature or manifest.
    pub max_references: 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 and certificate candidates inspected by one operation.
    pub max_key_candidates: 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 entries materialized in one exact node set.
    pub max_node_set_entries: usize,
    /// Maximum owned string bytes in one materialized node set.
    pub max_node_set_owned_string_bytes: usize,
    /// Maximum cumulative owned node-set string bytes per operation.
    pub max_node_set_cumulative_owned_string_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_references: crate::hard_limits::SIGNATURE_REFERENCE_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_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: crate::hard_limits::NODE_SET_ENTRY_CEILING,
            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,
        }
    }
}

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::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::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::KEY_CANDIDATES,
                self.max_key_candidates,
                crate::hard_limits::KEY_CANDIDATE_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)?;
        }
        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"))]
    pub(crate) 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(())
    }

    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,
}

/// 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,
}

/// 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,
}

#[cfg(feature = "xmldsig")]
impl Default for UriPolicy {
    fn default() -> Self {
        Self {
            references: UriTypeSet::SAME_DOCUMENT,
            retrieval_methods: 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,
}

#[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,
        }
    }
}

/// 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>),
}

/// X.509 and key-resolution decisions for verification.
#[cfg(feature = "xmldsig")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyTrustPolicy {
    /// 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>,
    /// 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 {
            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(),
            rsa_keys: RsaKeyPolicy::default(),
            dsa_keys: DsaKeyPolicy::default(),
            allowed_extended_key_usages: HashSet::new(),
            check_crls: false,
            verification_time: None,
        }
    }
}

#[cfg(feature = "xmldsig")]
impl KeyTrustPolicy {
    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 direct `<Object>/<Manifest>` references.
#[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 {
    /// Allowed signature methods; `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>>,
    /// 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 {
    /// Validate the complete snapshot against implementation hard ceilings.
    pub fn validate(&self) -> Result<(), PolicyViolation> {
        self.resources.validate()?;
        self.key_trust.validate()
    }

    /// Enforce the signature algorithm after key resolution.
    pub fn check_signature_algorithm(
        &self,
        algorithm: SignatureAlgorithm,
    ) -> Result<(), PolicyViolation> {
        if matches!(
            algorithm,
            SignatureAlgorithm::RsaSha1
                | SignatureAlgorithm::DsaSha1
                | SignatureAlgorithm::HmacSha1
        ) && !self
            .key_trust
            .allowed_legacy_signature_algorithms
            .contains(&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))
        {
            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 {
    /// Allowed signing methods; `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>>,
    /// ECDSA `SignatureValue` wire representation emitted by signing.
    pub ecdsa_signature_value_encoding: EcdsaSignatureValueEncoding,
    /// RSA requirements enforced before producing a signature.
    pub rsa_keys: RsaKeyPolicy,
    /// Reference URI permissions. External URIs remain unsupported until the
    /// caller supplies request-scoped external bytes through the signing API.
    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> {
        self.resources.validate()?;
        self.rsa_keys.validate()
    }
}

/// Immutable policy snapshot for XMLEnc encryption.
#[cfg(feature = "xmlenc")]
#[derive(Debug, Clone, Default)]
pub struct EncryptionPolicy {
    /// 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,
    /// 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> {
        self.resources.validate()?;
        self.rsa_keys.validate()
    }
}

/// Immutable policy snapshot for XMLEnc decryption.
#[cfg(feature = "xmlenc")]
#[derive(Debug, Clone, Default)]
pub struct DecryptionPolicy {
    /// 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>>,
    /// 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> {
        self.resources.validate()
    }
}

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

    #[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::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::SIGNATURE_REFERENCES,
                crate::hard_limits::SIGNATURE_REFERENCE_CEILING,
                |p| &mut p.max_references,
            ),
            (
                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::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::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_references: 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_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,
        };

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

    #[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,
        ];
        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 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
        )));
    }
}