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
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
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
//! XMLEnc content encryption, key wrapping, and XML generation.

use std::{fmt, sync::Arc};

use base64::{Engine as _, engine::general_purpose::STANDARD};
use quick_xml::{
    Writer,
    events::{BytesEnd, BytesStart, BytesText, Event},
};
use roxmltree::{Document, Node};
use rsa::RsaPublicKey;

use crate::document::{
    DocumentParseSettings, XmlDocument, XmlDocumentError, XmlParseWorkBudget,
    parse_borrowed_with_settings_and_budget,
};
use crate::xml::{is_xml_1_0_character, is_xml_ncname};

use super::types::{XMLDSIG_NS, XMLENC_NS, XMLENC11_NS};
use super::{
    DataEncryptionAlgorithm, DocumentEncryptionOptions, EncryptedDataType, EncryptionRecipient,
    EncryptionResult, KeyWrapAlgorithm, ReplacementMode, RsaOaepParameters, XmlEncError,
    has_single_element_with_boundary_trivia, map_document_error,
};

const XML_WHITESPACE: &[char] = &[' ', '\t', '\n', '\r'];

/// Validate an RSA recipient key against the compiled encryption policy.
///
/// Key registries can use this preflight before selecting a candidate, ensuring
/// ordered searches skip keys that the encryption operation would reject.
pub fn validate_rsa_recipient_key(
    key: &RsaPublicKey,
    policy: &crate::policy::EncryptionPolicy,
) -> Result<(), XmlEncError> {
    validate_key_transport_recipient(key, policy)
}

/// Validate an opaque RSA transport key against the compiled encryption policy.
///
/// The handle's public metadata must identify the exact key used by the
/// selected provider. This preflight lets provider-owned key registries apply
/// the same policy as [`EncryptedDataBuilder`] before selecting a candidate.
pub fn validate_key_transport_recipient(
    key: &dyn crate::provider::KeyTransportKey,
    policy: &crate::policy::EncryptionPolicy,
) -> Result<(), XmlEncError> {
    let modulus = key.rsa_modulus();
    let exponent = key.rsa_exponent();
    policy
        .rsa_keys
        .validate_components("encryption", &modulus, &exponent)?;
    Ok(())
}

/// Builder for complete `EncryptedData` fragments and document replacement.
#[derive(Clone)]
pub struct EncryptedDataBuilder {
    algorithm: DataEncryptionAlgorithm,
    encrypted_type: EncryptedDataType,
    id: Option<String>,
    direct_key: Option<Vec<u8>>,
    direct_key_name: Option<String>,
    recipients: Vec<EncryptionRecipient>,
    policy: crate::policy::EncryptionPolicy,
    provider: Arc<dyn crate::provider::CryptoProvider>,
}

struct GeneratedEncryption {
    result: EncryptionResult,
    xml_nodes: usize,
}

impl fmt::Debug for EncryptedDataBuilder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EncryptedDataBuilder")
            .field("algorithm", &self.algorithm)
            .field("encrypted_type", &self.encrypted_type)
            .field("id", &self.id)
            .field(
                "direct_key",
                &self.direct_key.as_ref().map(|_| "[REDACTED]"),
            )
            .field("direct_key_name", &self.direct_key_name)
            .field("recipients", &self.recipients)
            .field("policy", &self.policy)
            .field("provider", &self.provider.name())
            .finish()
    }
}

impl EncryptedDataBuilder {
    /// Create a builder for a content-encryption algorithm.
    pub fn new(algorithm: DataEncryptionAlgorithm) -> Self {
        Self {
            algorithm,
            encrypted_type: EncryptedDataType::Element,
            id: None,
            direct_key: None,
            direct_key_name: None,
            recipients: Vec::new(),
            policy: crate::policy::EncryptionPolicy::default(),
            provider: Arc::new(crate::provider::RustCryptoProvider),
        }
    }

    /// Replace the complete immutable encryption policy snapshot.
    pub fn policy(mut self, policy: crate::policy::EncryptionPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Select the cryptographic provider for this operation context.
    pub fn provider(mut self, provider: Arc<dyn crate::provider::CryptoProvider>) -> Self {
        self.provider = provider;
        self
    }

    /// Set whether XML encryption covers one element or its child content.
    pub fn encryption_type(mut self, encrypted_type: EncryptedDataType) -> Self {
        self.encrypted_type = encrypted_type;
        self
    }

    /// Set the generated `EncryptedData` identifier.
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Use a caller-managed content key instead of generating and wrapping one.
    pub fn direct_key(mut self, key: impl Into<Vec<u8>>) -> Self {
        self.direct_key = Some(key.into());
        self
    }

    /// Emit a direct `KeyName` hint for a caller-managed content key.
    pub fn direct_key_name(mut self, key_name: impl Into<String>) -> Self {
        self.direct_key_name = Some(key_name.into());
        self
    }

    /// Add one independently wrapped recipient of the generated content key.
    pub fn add_recipient(mut self, recipient: EncryptionRecipient) -> Self {
        self.recipients.push(recipient);
        self
    }

    /// Add an RSA-OAEP recipient using secure XMLEnc 1.1 defaults.
    pub fn recipient_rsa_oaep(self, public_key: RsaPublicKey) -> Self {
        self.add_recipient(EncryptionRecipient::rsa_oaep(public_key))
    }

    /// Add an RSA-OAEP recipient backed by an opaque provider key handle.
    pub fn recipient_key_transport(
        self,
        public_key: Arc<dyn crate::provider::KeyTransportKey>,
    ) -> Self {
        self.add_recipient(EncryptionRecipient::provider_key_transport(public_key))
    }

    /// Add an AES Key Wrap recipient.
    pub fn recipient_aes_kw(self, kek: impl Into<Vec<u8>>, algorithm: KeyWrapAlgorithm) -> Self {
        self.add_recipient(EncryptionRecipient::aes_key_wrap(kek, algorithm))
    }

    /// Encrypt one complete XML element or an XML content fragment.
    pub fn encrypt_xml(&self, xml: &str) -> Result<EncryptionResult, XmlEncError> {
        self.policy.validate()?;
        self.validate_plaintext_len(xml.len())?;
        let parse_budget = XmlParseWorkBudget::from_resources(&self.policy.resources);
        validate_xml_plaintext(xml, &self.encrypted_type, &self.policy, &parse_budget)?;
        let generated = self.encrypt_payload(
            xml.as_bytes(),
            Some(self.encrypted_type.clone()),
            &parse_budget,
        )?;
        validate_standalone_encrypted_data_nodes(
            generated.xml_nodes,
            self.policy.resources.effective_xml_nodes() as usize,
        )?;
        Ok(generated.result)
    }

    /// Encrypt opaque bytes, preserving a configured non-XML `Type` hint.
    ///
    /// Element and Content are XML replacement semantics and are omitted from
    /// binary output. Any other URI remains application metadata.
    pub fn encrypt_binary(&self, data: &[u8]) -> Result<EncryptionResult, XmlEncError> {
        self.policy.validate()?;
        let parse_budget = XmlParseWorkBudget::from_resources(&self.policy.resources);
        let encrypted_type = match &self.encrypted_type {
            EncryptedDataType::Other(uri) => Some(EncryptedDataType::Other(uri.clone())),
            EncryptedDataType::Element | EncryptedDataType::Content => None,
        };
        let generated = self.encrypt_payload(data, encrypted_type, &parse_budget)?;
        validate_standalone_encrypted_data_nodes(
            generated.xml_nodes,
            self.policy.resources.effective_xml_nodes() as usize,
        )?;
        Ok(generated.result)
    }

    /// Encrypt and replace the document root or one element selected by XML ID.
    pub fn encrypt_document(
        &self,
        xml: &str,
        options: DocumentEncryptionOptions<'_>,
    ) -> Result<String, XmlEncError> {
        self.policy.validate()?;
        self.validate_document_len(xml.len())?;
        let parse_budget = XmlParseWorkBudget::from_resources(&self.policy.resources);
        let settings = DocumentParseSettings::from_policy(&self.policy.xml, &self.policy.resources);
        let mut document =
            XmlDocument::parse_with_settings_and_budget(xml.to_owned(), settings, &parse_budget)
                .map_err(|error| map_document_error(error, settings))?;
        self.encrypt_owned_document_with_budget(&mut document, options, &parse_budget)?;
        Ok(document.into_xml())
    }

    /// Encrypt and replace a node in a reusable owned XML document.
    ///
    /// Successful mutation advances the document generation and invalidates
    /// identities captured before this call.
    pub fn encrypt_owned_document(
        &self,
        document: &mut XmlDocument,
        options: DocumentEncryptionOptions<'_>,
    ) -> Result<(), XmlEncError> {
        let parse_budget = XmlParseWorkBudget::from_resources(&self.policy.resources);
        self.encrypt_owned_document_with_budget(document, options, &parse_budget)
    }

    fn encrypt_owned_document_with_budget(
        &self,
        document: &mut XmlDocument,
        options: DocumentEncryptionOptions<'_>,
        parse_budget: &XmlParseWorkBudget,
    ) -> Result<(), XmlEncError> {
        self.policy.validate()?;
        document.validate_operation_policy(&self.policy.xml, &self.policy.resources)?;
        let document_nodes = document.with_view(|view| view.node_count());
        let (target, source, content_boundaries, selected_nodes) = document.with_view(|view| {
            let selected = select_encryption_target(view.document(), options.element_id)?;
            let source = &view.xml()[selected.range()];
            let content_boundaries = match self.encrypted_type {
                EncryptedDataType::Element => {
                    self.validate_plaintext_len(source.len())?;
                    None
                }
                EncryptedDataType::Content => {
                    let boundaries = element_content_boundaries(source)?;
                    self.validate_plaintext_len(boundaries.content.len())?;
                    Some(boundaries)
                }
                EncryptedDataType::Other(_) => None,
            };
            Ok::<_, XmlEncError>((
                view.node_identity(selected),
                source.to_owned(),
                content_boundaries,
                selected.descendants().count(),
            ))
        })?;

        match self.encrypted_type {
            EncryptedDataType::Element => {
                let generated = self.encrypt_payload(
                    source.as_bytes(),
                    Some(EncryptedDataType::Element),
                    parse_budget,
                )?;
                let result = generated.result;
                validate_replacement_document_len(
                    document.as_xml().len(),
                    source.len(),
                    result.encrypted_data_xml.len(),
                    self.policy.resources.max_xml_document_bytes,
                )?;
                validate_replacement_node_counts(
                    document_nodes,
                    selected_nodes,
                    generated.xml_nodes,
                    ReplacementMode::ReplaceElement,
                    self.policy.resources.effective_xml_nodes() as usize,
                )?;
                let settings =
                    DocumentParseSettings::from_policy(&self.policy.xml, &self.policy.resources);
                document
                    .replace_element_with_budget(
                        target,
                        &result.encrypted_data_xml,
                        settings,
                        parse_budget,
                    )
                    .map_err(|error| map_document_error(error, settings))?;
                Ok(())
            }
            EncryptedDataType::Content => {
                let boundaries = content_boundaries.ok_or_else(|| {
                    XmlEncError::InvalidStructure(
                        "content encryption target boundaries are unavailable".into(),
                    )
                })?;
                let plaintext = &source[boundaries.content.clone()];
                let generated = self.encrypt_payload(
                    plaintext.as_bytes(),
                    Some(EncryptedDataType::Content),
                    parse_budget,
                )?;
                let result = generated.result;
                let (removed, inserted) = if boundaries.self_closing {
                    let slash = source[..boundaries.start_tag_end]
                        .rfind('/')
                        .ok_or_else(|| {
                            XmlEncError::InvalidStructure("self-closing tag has no slash".into())
                        })?;
                    (
                        source.len(),
                        slash
                            .saturating_add(result.encrypted_data_xml.len())
                            .saturating_add(boundaries.qualified_name.len())
                            .saturating_add(4),
                    )
                } else {
                    (boundaries.content.len(), result.encrypted_data_xml.len())
                };
                validate_replacement_document_len(
                    document.as_xml().len(),
                    removed,
                    inserted,
                    self.policy.resources.max_xml_document_bytes,
                )?;
                validate_replacement_node_counts(
                    document_nodes,
                    selected_nodes,
                    generated.xml_nodes,
                    ReplacementMode::ReplaceContent,
                    self.policy.resources.effective_xml_nodes() as usize,
                )?;
                let settings =
                    DocumentParseSettings::from_policy(&self.policy.xml, &self.policy.resources);
                document
                    .replace_content_with_budget(
                        target,
                        &result.encrypted_data_xml,
                        settings,
                        parse_budget,
                    )
                    .map_err(|error| map_document_error(error, settings))?;
                Ok(())
            }
            EncryptedDataType::Other(_) => Err(XmlEncError::InvalidEncryptionConfig(
                "document encryption requires Element or Content Type".into(),
            )),
        }
    }

    fn encrypt_payload(
        &self,
        plaintext: &[u8],
        encrypted_type: Option<EncryptedDataType>,
        parse_budget: &XmlParseWorkBudget,
    ) -> Result<GeneratedEncryption, XmlEncError> {
        self.validate_plaintext_len(plaintext.len())?;
        self.validate_configuration()?;

        let content_key = if let Some(key) = &self.direct_key {
            validate_content_key(self.algorithm, key)?;
            key.clone()
        } else {
            random_bytes(self.provider.as_ref(), self.algorithm.key_len())?
        };
        let ciphertext = encrypt_content(
            self.provider.as_ref(),
            self.algorithm,
            &content_key,
            plaintext,
        )?;
        let encrypted_keys = self
            .recipients
            .iter()
            .map(|recipient| wrap_content_key(self.provider.as_ref(), recipient, &content_key))
            .collect::<Result<Vec<_>, _>>()?;
        let encrypted_data_xml = render_encrypted_data(
            self.algorithm,
            encrypted_type.as_ref(),
            self.id.as_deref(),
            self.direct_key_name.as_deref(),
            &encrypted_keys,
            &ciphertext,
        )?;
        self.validate_document_len(encrypted_data_xml.len())?;
        let xml_nodes =
            count_generated_encrypted_data_nodes(&encrypted_data_xml, &self.policy, parse_budget)?;
        let replacement = match encrypted_type {
            Some(EncryptedDataType::Content) => ReplacementMode::ReplaceContent,
            Some(EncryptedDataType::Element | EncryptedDataType::Other(_)) | None => {
                ReplacementMode::ReplaceElement
            }
        };
        Ok(GeneratedEncryption {
            result: EncryptionResult {
                encrypted_data_xml,
                replacement,
            },
            xml_nodes,
        })
    }

    fn validate_configuration(&self) -> Result<(), XmlEncError> {
        self.policy.validate()?;
        if let EncryptedDataType::Other(uri) = &self.encrypted_type {
            self.validate_metadata("EncryptedData Type", Some(uri))?;
        }
        if self
            .policy
            .data_algorithms
            .as_ref()
            .is_some_and(|allowed| !allowed.contains(&self.algorithm))
        {
            return Err(crate::policy::PolicyViolation::Algorithm {
                operation: "encryption",
                algorithm: self.algorithm.to_string(),
            }
            .into());
        }
        if self.recipients.len() > self.policy.resources.max_encryption_recipients {
            return Err(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::ENCRYPTION_RECIPIENTS,
                maximum: self.policy.resources.max_encryption_recipients,
                actual: self.recipients.len(),
            }
            .into());
        }
        let key_candidates = self.recipients.len() + usize::from(self.direct_key.is_some());
        self.policy
            .resources
            .validate_key_candidates(key_candidates)?;
        self.validate_metadata("EncryptedData Id", self.id.as_deref())?;
        if self.id.as_deref().is_some_and(|id| !is_xml_ncname(id)) {
            return Err(XmlEncError::InvalidEncryptionConfig(
                "EncryptedData Id must be an XML NCName".into(),
            ));
        }
        self.validate_key_name("direct KeyName", self.direct_key_name.as_deref())?;
        for recipient in &self.recipients {
            match recipient {
                EncryptionRecipient::RsaOaep {
                    public_key,
                    parameters,
                    recipient,
                    key_name,
                } => {
                    validate_key_transport_recipient(public_key.as_ref(), &self.policy)?;
                    if parameters.algorithm == super::KeyTransportAlgorithm::RsaOaepMgf1p
                        && parameters.mgf_digest != super::OaepDigestAlgorithm::Sha1
                    {
                        return Err(XmlEncError::InvalidEncryptionConfig(
                            "legacy RSA-OAEP fixes MGF1 to SHA-1".into(),
                        ));
                    }
                    if self
                        .policy
                        .key_transport_algorithms
                        .as_ref()
                        .is_some_and(|allowed| !allowed.contains(&parameters.algorithm))
                        || self.policy.oaep_digests.as_ref().is_some_and(|allowed| {
                            !allowed.contains(&parameters.digest)
                                || !allowed.contains(&parameters.mgf_digest)
                        })
                    {
                        return Err(crate::policy::PolicyViolation::Algorithm {
                            operation: "encryption",
                            algorithm: parameters.algorithm.uri().to_string(),
                        }
                        .into());
                    }
                    self.validate_metadata("EncryptedKey Recipient", recipient.as_deref())?;
                    self.validate_key_name("EncryptedKey KeyName", key_name.as_deref())?;
                    self.validate_metadata_len(parameters.label.len())?;
                }
                EncryptionRecipient::AesKeyWrap {
                    kek,
                    algorithm,
                    recipient,
                    key_name,
                } => {
                    if self
                        .policy
                        .key_wrap_algorithms
                        .as_ref()
                        .is_some_and(|allowed| !allowed.contains(algorithm))
                    {
                        return Err(crate::policy::PolicyViolation::Algorithm {
                            operation: "encryption",
                            algorithm: algorithm.uri().to_string(),
                        }
                        .into());
                    }
                    if kek.len() != algorithm.key_len() {
                        return Err(XmlEncError::InvalidEncryptionConfig(format!(
                            "{} requires a {}-byte key-encryption key, got {} bytes",
                            algorithm.uri(),
                            algorithm.key_len(),
                            kek.len()
                        )));
                    }
                    self.validate_metadata("EncryptedKey Recipient", recipient.as_deref())?;
                    self.validate_key_name("EncryptedKey KeyName", key_name.as_deref())?;
                }
            }
        }
        match (self.direct_key.is_some(), self.recipients.is_empty()) {
            (false, true) => Err(XmlEncError::InvalidEncryptionConfig(
                "configure a direct content key or at least one wrapped recipient".into(),
            )),
            (true, false) => Err(XmlEncError::InvalidEncryptionConfig(
                "a direct content key cannot be combined with wrapped recipients".into(),
            )),
            _ if self.direct_key_name.is_some() && self.direct_key.is_none() => {
                Err(XmlEncError::InvalidEncryptionConfig(
                    "direct KeyName requires a direct content key".into(),
                ))
            }
            _ => Ok(()),
        }
    }

    fn validate_metadata(
        &self,
        field: &'static str,
        value: Option<&str>,
    ) -> Result<(), XmlEncError> {
        validate_metadata(
            field,
            value,
            self.policy.resources.max_encryption_metadata_bytes,
        )
    }

    fn validate_key_name(
        &self,
        field: &'static str,
        value: Option<&str>,
    ) -> Result<(), XmlEncError> {
        validate_key_name(
            field,
            value,
            self.policy.resources.max_encryption_metadata_bytes,
        )
    }

    fn validate_metadata_len(&self, actual: usize) -> Result<(), XmlEncError> {
        validate_metadata_len(actual, self.policy.resources.max_encryption_metadata_bytes)
    }

    fn validate_plaintext_len(&self, actual: usize) -> Result<(), XmlEncError> {
        validate_plaintext_len(actual, self.policy.resources.max_encryption_plaintext_bytes)
    }

    fn validate_document_len(&self, actual: usize) -> Result<(), XmlEncError> {
        validate_document_len(actual, self.policy.resources.max_xml_document_bytes)
    }
}

fn validate_metadata(
    field: &'static str,
    value: Option<&str>,
    maximum: usize,
) -> Result<(), XmlEncError> {
    if value.is_some_and(|value| !value.chars().all(is_xml_1_0_character)) {
        return Err(XmlEncError::InvalidEncryptionConfig(format!(
            "{field} contains a character forbidden by XML 1.0"
        )));
    }
    validate_metadata_len(value.map_or(0, str::len), maximum)
}

fn validate_key_name(
    field: &'static str,
    value: Option<&str>,
    maximum: usize,
) -> Result<(), XmlEncError> {
    if value.is_some_and(str::is_empty) {
        return Err(XmlEncError::InvalidEncryptionConfig(format!(
            "{field} must not be empty"
        )));
    }
    validate_metadata(field, value, maximum)
}

fn validate_metadata_len(actual: usize, maximum: usize) -> Result<(), XmlEncError> {
    if actual <= maximum {
        Ok(())
    } else {
        Err(crate::policy::PolicyViolation::ResourceLimit {
            resource: crate::policy::resource_name::ENCRYPTION_METADATA_BYTES,
            maximum,
            actual,
        }
        .into())
    }
}

#[derive(Debug)]
struct WrappedKey {
    algorithm_uri: &'static str,
    oaep: Option<RsaOaepParameters>,
    recipient: Option<String>,
    key_name: Option<String>,
    ciphertext: Vec<u8>,
}

#[derive(Debug)]
struct ContentBoundaries {
    content: std::ops::Range<usize>,
    self_closing: bool,
    qualified_name: String,
    start_tag_end: usize,
}

fn validate_plaintext_len(actual: usize, maximum: usize) -> Result<(), XmlEncError> {
    if actual <= maximum {
        Ok(())
    } else {
        Err(crate::policy::PolicyViolation::ResourceLimit {
            resource: crate::policy::resource_name::ENCRYPTION_PLAINTEXT_BYTES,
            maximum,
            actual,
        }
        .into())
    }
}

fn validate_document_len(actual: usize, maximum: usize) -> Result<(), XmlEncError> {
    if actual > maximum {
        return Err(crate::policy::PolicyViolation::ResourceLimit {
            resource: crate::policy::resource_name::XML_DOCUMENT,
            maximum,
            actual,
        }
        .into());
    }
    Ok(())
}

fn validate_replacement_document_len(
    document_len: usize,
    removed_len: usize,
    inserted_len: usize,
    maximum: usize,
) -> Result<(), XmlEncError> {
    let actual = document_len
        .saturating_sub(removed_len)
        .saturating_add(inserted_len);
    validate_document_len(actual, maximum)
}

fn validate_replacement_node_counts(
    document_nodes: usize,
    selected_nodes: usize,
    inserted_nodes: usize,
    replacement: ReplacementMode,
    maximum: usize,
) -> Result<(), XmlEncError> {
    let removed_nodes = match replacement {
        ReplacementMode::ReplaceElement => selected_nodes,
        ReplacementMode::ReplaceContent => selected_nodes.saturating_sub(1),
    };
    let actual = document_nodes
        .saturating_sub(removed_nodes)
        .saturating_add(inserted_nodes);
    if actual > maximum {
        return Err(crate::policy::PolicyViolation::ResourceLimit {
            resource: crate::policy::resource_name::XML_NODES,
            maximum,
            actual,
        }
        .into());
    }
    Ok(())
}

fn count_generated_encrypted_data_nodes(
    encrypted_data_xml: &str,
    policy: &crate::policy::EncryptionPolicy,
    parse_budget: &XmlParseWorkBudget,
) -> Result<usize, XmlEncError> {
    let maximum_nodes = policy.resources.effective_xml_nodes();
    // The standalone parser adds one document node that is not inserted into
    // the caller's tree. Bound the generated subtree by the active policy while
    // admitting that transient root so exact-fit content replacement remains valid.
    let settings = DocumentParseSettings {
        nodes_limit: maximum_nodes.saturating_add(1),
        ..DocumentParseSettings::from_policy(&policy.xml, &policy.resources)
    };
    let generated =
        parse_borrowed_with_settings_and_budget(encrypted_data_xml, settings, Some(parse_budget))
            .map_err(|error| match error {
            XmlDocumentError::Parse(roxmltree::Error::NodesLimitReached) => {
                XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_NODES,
                    maximum: maximum_nodes as usize,
                    actual: maximum_nodes as usize + 1,
                })
            }
            error => map_document_error(error, settings),
        })?;
    Ok(generated.root_element().descendants().count())
}

fn validate_standalone_encrypted_data_nodes(
    encrypted_data_subtree_nodes: usize,
    maximum: usize,
) -> Result<(), XmlEncError> {
    let actual = encrypted_data_subtree_nodes.saturating_add(1);
    if actual > maximum {
        return Err(crate::policy::PolicyViolation::ResourceLimit {
            resource: crate::policy::resource_name::XML_NODES,
            maximum,
            actual,
        }
        .into());
    }
    Ok(())
}

fn validate_content_key(algorithm: DataEncryptionAlgorithm, key: &[u8]) -> Result<(), XmlEncError> {
    if key.len() == algorithm.key_len() {
        Ok(())
    } else {
        Err(XmlEncError::InvalidKeySize {
            algorithm,
            expected: algorithm.key_len(),
            actual: key.len(),
        })
    }
}

fn random_bytes(
    provider: &dyn crate::provider::CryptoProvider,
    len: usize,
) -> Result<Vec<u8>, XmlEncError> {
    provider.require_capability(crate::provider::ProviderCapability::Random)?;
    let mut bytes = vec![0_u8; len];
    provider.fill_random(&mut bytes)?;
    Ok(bytes)
}

fn encrypt_content(
    provider: &dyn crate::provider::CryptoProvider,
    algorithm: DataEncryptionAlgorithm,
    key: &[u8],
    plaintext: &[u8],
) -> Result<Vec<u8>, XmlEncError> {
    provider.require_capability(crate::provider::ProviderCapability::Encrypt(algorithm))?;
    let ciphertext = provider.encrypt_data(algorithm, key, plaintext)?;
    super::types::validate_ciphertext_framing(algorithm, ciphertext.len())?;
    let expected = algorithm
        .ciphertext_len_for_plaintext(plaintext.len())
        .ok_or(crate::policy::PolicyViolation::ResourceLimit {
            resource: crate::policy::resource_name::ENCRYPTION_PLAINTEXT_BYTES,
            maximum: crate::hard_limits::ENCRYPTION_PLAINTEXT_BYTE_CEILING,
            actual: plaintext.len(),
        })?;
    if ciphertext.len() != expected {
        return Err(crate::provider::ProviderError::InvalidOutputSize {
            operation: crate::provider::ProviderOperation::Encrypt,
            expected,
            actual: ciphertext.len(),
        }
        .into());
    }
    Ok(ciphertext)
}

fn wrap_content_key(
    provider: &dyn crate::provider::CryptoProvider,
    recipient: &EncryptionRecipient,
    content_key: &[u8],
) -> Result<WrappedKey, XmlEncError> {
    match recipient {
        EncryptionRecipient::RsaOaep {
            public_key,
            parameters,
            recipient,
            key_name,
        } => Ok(WrappedKey {
            algorithm_uri: parameters.algorithm.uri(),
            oaep: Some(parameters.clone()),
            recipient: recipient.clone(),
            key_name: key_name.clone(),
            ciphertext: wrap_rsa_oaep(provider, public_key.as_ref(), parameters, content_key)?,
        }),
        EncryptionRecipient::AesKeyWrap {
            kek,
            algorithm,
            recipient,
            key_name,
        } => {
            provider
                .require_capability(crate::provider::ProviderCapability::KeyWrap(*algorithm))?;
            let wrapped = provider.wrap_key(*algorithm, kek, content_key)?;
            let expected = content_key.len() + 8;
            if wrapped.len() != expected {
                return Err(XmlEncError::InvalidWrappedKeyLength {
                    expected,
                    actual: wrapped.len(),
                });
            }
            Ok(WrappedKey {
                algorithm_uri: algorithm.uri(),
                oaep: None,
                recipient: recipient.clone(),
                key_name: key_name.clone(),
                ciphertext: wrapped,
            })
        }
    }
}

fn wrap_rsa_oaep(
    provider: &dyn crate::provider::CryptoProvider,
    public_key: &dyn crate::provider::KeyTransportKey,
    parameters: &RsaOaepParameters,
    content_key: &[u8],
) -> Result<Vec<u8>, XmlEncError> {
    provider.require_capability(crate::provider::ProviderCapability::KeyTransport(
        parameters,
    ))?;
    let ciphertext = provider
        .transport_key(public_key, parameters, content_key)
        .map_err(|error| match error {
            crate::provider::ProviderError::Random(message) => XmlEncError::Rng(message),
            crate::provider::ProviderError::InvalidInput(reason) => {
                XmlEncError::InvalidEncryptionConfig(reason.to_string())
            }
            error => XmlEncError::RsaEncrypt(error.to_string()),
        })?;
    let expected = public_key.rsa_modulus().len();
    if ciphertext.len() != expected {
        return Err(XmlEncError::InvalidWrappedKeyLength {
            expected,
            actual: ciphertext.len(),
        });
    }
    Ok(ciphertext)
}

fn render_encrypted_data(
    algorithm: DataEncryptionAlgorithm,
    encrypted_type: Option<&EncryptedDataType>,
    id: Option<&str>,
    direct_key_name: Option<&str>,
    encrypted_keys: &[WrappedKey],
    ciphertext: &[u8],
) -> Result<String, XmlEncError> {
    let mut writer = Writer::new(Vec::new());
    let mut root = BytesStart::new("xenc:EncryptedData");
    root.push_attribute(("xmlns:xenc", XMLENC_NS));
    root.push_attribute(("xmlns:xenc11", XMLENC11_NS));
    root.push_attribute(("xmlns:ds", XMLDSIG_NS));
    if let Some(id) = id {
        root.push_attribute(("Id", id));
    }
    if let Some(encrypted_type) = encrypted_type {
        let uri = match encrypted_type {
            EncryptedDataType::Element => format!("{XMLENC_NS}Element"),
            EncryptedDataType::Content => format!("{XMLENC_NS}Content"),
            EncryptedDataType::Other(uri) => uri.clone(),
        };
        root.push_attribute(("Type", uri.as_str()));
    }
    write_event(&mut writer, Event::Start(root))?;
    write_empty_with_algorithm(&mut writer, "xenc:EncryptionMethod", algorithm.uri())?;

    if direct_key_name.is_some() || !encrypted_keys.is_empty() {
        write_event(&mut writer, Event::Start(BytesStart::new("ds:KeyInfo")))?;
        if let Some(key_name) = direct_key_name {
            write_text_element(&mut writer, "ds:KeyName", key_name)?;
        }
        for encrypted_key in encrypted_keys {
            write_encrypted_key(&mut writer, encrypted_key)?;
        }
        write_event(&mut writer, Event::End(BytesEnd::new("ds:KeyInfo")))?;
    }

    write_cipher_data(&mut writer, ciphertext)?;
    write_event(&mut writer, Event::End(BytesEnd::new("xenc:EncryptedData")))?;
    String::from_utf8(writer.into_inner())
        .map_err(|error| XmlEncError::XmlSerialize(error.to_string()))
}

fn write_encrypted_key(
    writer: &mut Writer<Vec<u8>>,
    encrypted_key: &WrappedKey,
) -> Result<(), XmlEncError> {
    let mut start = BytesStart::new("xenc:EncryptedKey");
    if let Some(recipient) = encrypted_key.recipient.as_deref() {
        start.push_attribute(("Recipient", recipient));
    }
    write_event(writer, Event::Start(start))?;

    if let Some(parameters) = encrypted_key.oaep.as_ref() {
        let mut method = BytesStart::new("xenc:EncryptionMethod");
        method.push_attribute(("Algorithm", encrypted_key.algorithm_uri));
        write_event(writer, Event::Start(method))?;
        if !parameters.label.is_empty() {
            write_text_element(
                writer,
                "xenc:OAEPparams",
                &STANDARD.encode(&parameters.label),
            )?;
        }
        write_empty_with_algorithm(writer, "ds:DigestMethod", parameters.digest.uri())?;
        if parameters.algorithm == super::KeyTransportAlgorithm::RsaOaep11 {
            write_empty_with_algorithm(writer, "xenc11:MGF", parameters.mgf_digest.mgf_uri())?;
        }
        write_event(writer, Event::End(BytesEnd::new("xenc:EncryptionMethod")))?;
    } else {
        write_empty_with_algorithm(writer, "xenc:EncryptionMethod", encrypted_key.algorithm_uri)?;
    }

    if let Some(key_name) = encrypted_key.key_name.as_deref() {
        write_event(writer, Event::Start(BytesStart::new("ds:KeyInfo")))?;
        write_text_element(writer, "ds:KeyName", key_name)?;
        write_event(writer, Event::End(BytesEnd::new("ds:KeyInfo")))?;
    }
    write_cipher_data(writer, &encrypted_key.ciphertext)?;
    write_event(writer, Event::End(BytesEnd::new("xenc:EncryptedKey")))
}

fn write_cipher_data(writer: &mut Writer<Vec<u8>>, value: &[u8]) -> Result<(), XmlEncError> {
    write_event(writer, Event::Start(BytesStart::new("xenc:CipherData")))?;
    write_text_element(writer, "xenc:CipherValue", &STANDARD.encode(value))?;
    write_event(writer, Event::End(BytesEnd::new("xenc:CipherData")))
}

fn write_empty_with_algorithm(
    writer: &mut Writer<Vec<u8>>,
    name: &str,
    algorithm: &str,
) -> Result<(), XmlEncError> {
    let mut element = BytesStart::new(name);
    element.push_attribute(("Algorithm", algorithm));
    write_event(writer, Event::Empty(element))
}

fn write_text_element(
    writer: &mut Writer<Vec<u8>>,
    name: &str,
    text: &str,
) -> Result<(), XmlEncError> {
    write_event(writer, Event::Start(BytesStart::new(name)))?;
    write_event(writer, Event::Text(BytesText::new(text)))?;
    write_event(writer, Event::End(BytesEnd::new(name)))
}

fn write_event(writer: &mut Writer<Vec<u8>>, event: Event<'_>) -> Result<(), XmlEncError> {
    writer
        .write_event(event)
        .map_err(|error| XmlEncError::XmlSerialize(error.to_string()))
}

fn validate_xml_plaintext(
    xml: &str,
    encrypted_type: &EncryptedDataType,
    policy: &crate::policy::EncryptionPolicy,
    parse_budget: &XmlParseWorkBudget,
) -> Result<(), XmlEncError> {
    let settings = DocumentParseSettings::from_policy(&policy.xml, &policy.resources);
    match encrypted_type {
        EncryptedDataType::Element => {
            let document =
                parse_borrowed_with_settings_and_budget(xml, settings, Some(parse_budget))
                    .map_err(|error| map_document_error(error, settings))?;
            if !has_single_element_with_boundary_trivia(document.root()) {
                return Err(XmlEncError::InvalidStructure(
                    "Element plaintext must contain exactly one element".into(),
                ));
            }
            Ok(())
        }
        EncryptedDataType::Content => {
            const WRAPPER_START: &str = "<xmlsec-content>";
            const WRAPPER_END: &str = "</xmlsec-content>";

            policy.resources.validate_xml_document_len(xml.len())?;
            let wrapped = format!("{WRAPPER_START}{xml}{WRAPPER_END}");
            let wrapper_bytes = WRAPPER_START.len() + WRAPPER_END.len();
            // The wrapper exists only to parse an XML fragment. Its node must
            // not consume the caller-owned byte, node, or depth allowance.
            let wrapped_settings = DocumentParseSettings {
                nodes_limit: settings.nodes_limit.saturating_add(1),
                depth_limit: settings.depth_limit.saturating_add(1),
                max_bytes: settings.max_bytes.saturating_add(wrapper_bytes),
                ..settings
            };
            parse_borrowed_with_settings_and_budget(&wrapped, wrapped_settings, Some(parse_budget))
                .map_err(|error| match error {
                    XmlDocumentError::DocumentTooLarge { actual, .. } => {
                        XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                            resource: crate::policy::resource_name::XML_DOCUMENT,
                            maximum: settings.max_bytes,
                            actual: actual.saturating_sub(wrapper_bytes),
                        })
                    }
                    XmlDocumentError::Parse(roxmltree::Error::NodesLimitReached) => {
                        XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                            resource: crate::policy::resource_name::XML_NODES,
                            maximum: settings.nodes_limit as usize,
                            actual: settings.nodes_limit as usize + 1,
                        })
                    }
                    XmlDocumentError::DocumentTooDeep { actual, .. } => {
                        XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                            resource: crate::policy::resource_name::XML_DEPTH,
                            maximum: settings.depth_limit,
                            actual: actual.saturating_sub(1),
                        })
                    }
                    error => map_document_error(error, wrapped_settings),
                })?;
            Ok(())
        }
        EncryptedDataType::Other(_) => Err(XmlEncError::InvalidEncryptionConfig(
            "encrypt_xml requires Element or Content Type".into(),
        )),
    }
}

fn select_encryption_target<'a, 'input>(
    document: &'a Document<'input>,
    id: Option<&str>,
) -> Result<Node<'a, 'input>, XmlEncError> {
    let Some(id) = id else {
        return Ok(document.root_element());
    };
    let mut matches = document.descendants().filter(|node| {
        node.is_element()
            && ["Id", "ID", "id"]
                .iter()
                .any(|name| node.attribute(*name) == Some(id))
    });
    let selected = matches
        .next()
        .ok_or(XmlEncError::EncryptionTargetNotFound)?;
    if matches.next().is_some() {
        return Err(XmlEncError::AmbiguousEncryptionTarget);
    }
    Ok(selected)
}

fn element_content_boundaries(source: &str) -> Result<ContentBoundaries, XmlEncError> {
    let tag_end = find_start_tag_end(source)?;
    let before_end = source[..tag_end].trim_end_matches(XML_WHITESPACE);
    let self_closing = before_end.ends_with('/');
    let name_end = source[1..]
        .find(|character: char| character.is_ascii_whitespace() || matches!(character, '/' | '>'))
        .map(|index| index + 1)
        .ok_or_else(|| XmlEncError::InvalidStructure("source element has no name".into()))?;
    let qualified_name = source[1..name_end].to_owned();
    if self_closing {
        return Ok(ContentBoundaries {
            content: tag_end..tag_end,
            self_closing: true,
            qualified_name,
            start_tag_end: tag_end,
        });
    }
    // `Node::range()` ends at this element's closing tag, so its `</` marker is
    // necessarily the final one even when child text or CDATA contains `</`.
    let closing_start = source
        .rfind("</")
        .ok_or_else(|| XmlEncError::InvalidStructure("source element has no closing tag".into()))?;
    Ok(ContentBoundaries {
        content: tag_end + 1..closing_start,
        self_closing: false,
        qualified_name,
        start_tag_end: tag_end,
    })
}

fn find_start_tag_end(source: &str) -> Result<usize, XmlEncError> {
    let mut quote = None;
    for (index, character) in source.char_indices() {
        match (quote, character) {
            (Some(expected), actual) if expected == actual => quote = None,
            (None, '\'' | '"') => quote = Some(character),
            (None, '>') => return Ok(index),
            _ => {}
        }
    }
    Err(XmlEncError::InvalidStructure(
        "source element start tag is unterminated".into(),
    ))
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use std::sync::Arc;

    use getrandom::SysRng;
    use getrandom::rand_core::UnwrapErr;
    use rsa::pkcs8::DecodePublicKey as _;
    use rsa::{RsaPrivateKey, RsaPublicKey};

    use super::*;
    use crate::hard_limits::{
        ENCRYPTION_METADATA_BYTE_CEILING as MAX_ENCRYPTION_METADATA_LEN,
        ENCRYPTION_PLAINTEXT_BYTE_CEILING as MAX_ENCRYPTION_PLAINTEXT_LEN,
        ENCRYPTION_RECIPIENT_CEILING as MAX_ENCRYPTION_RECIPIENTS,
        XML_DOCUMENT_BYTE_CEILING as MAX_ENCRYPTION_DOCUMENT_LEN,
    };
    use crate::xmlenc::{
        KekDecryptor, OaepDigestAlgorithm, PrivateKeyDecryptor, SymmetricKeyDecryptor, decrypt,
        decrypt_document, parse_encrypted_data,
    };

    #[derive(Debug)]
    struct OverridingOutputProvider {
        ciphertext: Option<Vec<u8>>,
        wrapped_key: Option<Vec<u8>>,
        transported_key: Option<Vec<u8>>,
        transport_calls: AtomicUsize,
    }

    struct OpaqueTransportKey {
        modulus: Vec<u8>,
        exponent: Vec<u8>,
    }

    impl crate::provider::KeyTransportKey for OpaqueTransportKey {
        fn rsa_modulus(&self) -> std::borrow::Cow<'_, [u8]> {
            std::borrow::Cow::Borrowed(&self.modulus)
        }

        fn rsa_exponent(&self) -> std::borrow::Cow<'_, [u8]> {
            std::borrow::Cow::Borrowed(&self.exponent)
        }

        fn transport_with_provider(
            &self,
            _provider: &dyn crate::provider::CryptoProvider,
            _parameters: &RsaOaepParameters,
            _plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            panic!("custom provider must own transport for its opaque key")
        }
    }

    impl crate::provider::CryptoProvider for OverridingOutputProvider {
        fn name(&self) -> &'static str {
            "overriding-output-test"
        }

        fn supports(&self, capability: crate::provider::ProviderCapability<'_>) -> bool {
            crate::provider::CryptoProvider::supports(
                &crate::provider::RustCryptoProvider,
                capability,
            )
        }

        fn fill_random(&self, output: &mut [u8]) -> Result<(), crate::provider::ProviderError> {
            crate::provider::CryptoProvider::fill_random(
                &crate::provider::RustCryptoProvider,
                output,
            )
        }

        fn derive_key(
            &self,
            parameters: &crate::provider::KdfParameters<'_>,
            secret: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::RustCryptoProvider.derive_key(parameters, secret)
        }

        #[cfg(feature = "xmldsig")]
        fn digest(
            &self,
            algorithm: crate::xmldsig::DigestAlgorithm,
            data: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::CryptoProvider::digest(
                &crate::provider::RustCryptoProvider,
                algorithm,
                data,
            )
        }

        #[cfg(feature = "xmldsig")]
        fn sign(
            &self,
            key: &dyn crate::xmldsig::SigningKey,
            algorithm: crate::xmldsig::SignatureAlgorithm,
            data: &[u8],
        ) -> Result<Vec<u8>, crate::xmldsig::SigningKeyError> {
            crate::provider::CryptoProvider::sign(
                &crate::provider::RustCryptoProvider,
                key,
                algorithm,
                data,
            )
        }

        #[cfg(feature = "xmldsig")]
        fn verify(
            &self,
            key: &dyn crate::xmldsig::VerifyingKey,
            algorithm: crate::xmldsig::SignatureAlgorithm,
            data: &[u8],
            signature: &[u8],
        ) -> Result<bool, crate::xmldsig::DsigError> {
            crate::provider::CryptoProvider::verify(
                &crate::provider::RustCryptoProvider,
                key,
                algorithm,
                data,
                signature,
            )
        }

        fn encrypt_data(
            &self,
            algorithm: DataEncryptionAlgorithm,
            key: &[u8],
            plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            if let Some(ciphertext) = &self.ciphertext {
                return Ok(ciphertext.clone());
            }
            crate::provider::CryptoProvider::encrypt_data(
                &crate::provider::RustCryptoProvider,
                algorithm,
                key,
                plaintext,
            )
        }

        fn decrypt_data(
            &self,
            algorithm: DataEncryptionAlgorithm,
            key: &[u8],
            ciphertext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::CryptoProvider::decrypt_data(
                &crate::provider::RustCryptoProvider,
                algorithm,
                key,
                ciphertext,
            )
        }

        fn wrap_key(
            &self,
            algorithm: KeyWrapAlgorithm,
            kek: &[u8],
            key: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            if let Some(wrapped_key) = &self.wrapped_key {
                return Ok(wrapped_key.clone());
            }
            crate::provider::CryptoProvider::wrap_key(
                &crate::provider::RustCryptoProvider,
                algorithm,
                kek,
                key,
            )
        }

        fn unwrap_key(
            &self,
            algorithm: KeyWrapAlgorithm,
            kek: &[u8],
            wrapped: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::CryptoProvider::unwrap_key(
                &crate::provider::RustCryptoProvider,
                algorithm,
                kek,
                wrapped,
            )
        }

        fn transport_key(
            &self,
            key: &dyn crate::provider::KeyTransportKey,
            parameters: &RsaOaepParameters,
            plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            self.transport_calls.fetch_add(1, Ordering::Relaxed);
            if let Some(transported_key) = &self.transported_key {
                return Ok(transported_key.clone());
            }
            crate::provider::CryptoProvider::transport_key(
                &crate::provider::RustCryptoProvider,
                key,
                parameters,
                plaintext,
            )
        }

        fn recover_key(
            &self,
            key: &dyn crate::provider::KeyRecoveryKey,
            parameters: &RsaOaepParameters,
            ciphertext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::CryptoProvider::recover_key(
                &crate::provider::RustCryptoProvider,
                key,
                parameters,
                ciphertext,
            )
        }
    }

    #[test]
    fn direct_key_round_trips_every_content_algorithm() {
        // All emitted wire layouts must be accepted by the existing independent
        // decrypt path, including empty plaintext and full-block CBC padding.
        for algorithm in [
            DataEncryptionAlgorithm::Aes128Cbc,
            DataEncryptionAlgorithm::Aes256Cbc,
            DataEncryptionAlgorithm::Aes128Gcm,
            DataEncryptionAlgorithm::Aes256Gcm,
        ] {
            for plaintext in [b"".as_slice(), b"sixteen-byte-msg", b"not aligned"] {
                let key = vec![0x31; algorithm.key_len()];
                let encrypted = EncryptedDataBuilder::new(algorithm)
                    .direct_key(key.clone())
                    .direct_key_name("content-key")
                    .encrypt_binary(plaintext)
                    .expect("supported direct encryption must succeed");
                assert_eq!(
                    decrypt(
                        &encrypted.encrypted_data_xml,
                        &SymmetricKeyDecryptor::new(key)
                    )
                    .expect("generated ciphertext must decrypt"),
                    super::super::DecryptedContent::Bytes(plaintext.to_vec())
                );
            }
        }
    }

    #[test]
    fn aes_key_wrap_round_trips_and_preserves_recipient_metadata() {
        let kek = [0x44; 32];
        let encrypted = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .add_recipient(
                EncryptionRecipient::aes_key_wrap(kek, KeyWrapAlgorithm::AesKw256)
                    .recipient("service-a")
                    .key_name("shared-kek"),
            )
            .encrypt_xml("<secret>value</secret>")
            .expect("AES-KW encryption must succeed");
        let parsed = parse_encrypted_data(&encrypted.encrypted_data_xml)
            .expect("generated EncryptedData must parse");
        assert_eq!(
            parsed.encrypted_keys[0].recipient.as_deref(),
            Some("service-a")
        );
        assert_eq!(
            parsed.encrypted_keys[0].key_name.as_deref(),
            Some("shared-kek")
        );
        assert_eq!(
            decrypt(&encrypted.encrypted_data_xml, &KekDecryptor::new(kek))
                .expect("wrapped key must decrypt"),
            super::super::DecryptedContent::Xml("<secret>value</secret>".into())
        );
    }

    #[test]
    fn aes_key_wrap_rejects_mismatched_kek_before_provider_dispatch() {
        // Algorithm URIs define the KEK size. Provider implementations are
        // capabilities, not authorities allowed to reinterpret wire semantics.
        let builder = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .recipient_aes_kw([0x44; 32], KeyWrapAlgorithm::AesKw128);

        assert!(matches!(
            builder.validate_configuration(),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
    }

    #[test]
    fn rsa_oaep_round_trips_configurable_parameters() {
        let private = RsaPrivateKey::new(&mut UnwrapErr(SysRng), 2048)
            .expect("test RSA key generation must succeed");
        let public = RsaPublicKey::from(&private);
        let parameters =
            RsaOaepParameters::xmlenc11(OaepDigestAlgorithm::Sha256, OaepDigestAlgorithm::Sha512)
                .label(b"recipient-label".to_vec());
        let encrypted = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes256Gcm)
            .add_recipient(
                EncryptionRecipient::rsa_oaep(public)
                    .oaep_parameters(parameters)
                    .recipient("rsa-recipient"),
            )
            .encrypt_xml("<secret/>")
            .expect("RSA-OAEP encryption must succeed");
        assert_eq!(
            decrypt(
                &encrypted.encrypted_data_xml,
                &PrivateKeyDecryptor::new(private)
            )
            .expect("RSA recipient must recover content key"),
            super::super::DecryptedContent::Xml("<secret/>".into())
        );
    }

    #[test]
    fn legacy_oaep_rejects_non_sha1_mgf_during_configuration_validation() {
        // The legacy URI has no MGF child on the wire, so accepting another
        // digest here would let a permissive provider emit ambiguous ciphertext.
        let public = RsaPublicKey::from_public_key_pem(include_str!(
            "../../tests/fixtures/keys/rsa/rsa-2048-pubkey.pem"
        ))
        .expect("tracked RSA public key must parse");
        let parameters = RsaOaepParameters {
            algorithm: super::super::KeyTransportAlgorithm::RsaOaepMgf1p,
            digest: OaepDigestAlgorithm::Sha256,
            mgf_digest: OaepDigestAlgorithm::Sha256,
            label: Vec::new(),
        };
        let builder = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .add_recipient(EncryptionRecipient::rsa_oaep(public).oaep_parameters(parameters));

        assert!(matches!(
            builder.validate_configuration(),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
    }

    #[test]
    fn encrypt_document_replaces_element_and_self_closing_content() {
        let key = [0x55; 16];
        let document =
            "<root><target ID=\"element\"><child/></target><empty ID=\"content\"/></root>";
        let encrypted_element = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key(key)
            .encrypt_document(
                document,
                DocumentEncryptionOptions {
                    element_id: Some("element"),
                },
            )
            .expect("element replacement must succeed");
        let decrypted_element =
            decrypt_document(&encrypted_element, None, &SymmetricKeyDecryptor::new(key))
                .expect("element replacement must round-trip");
        assert_eq!(decrypted_element, document);

        let encrypted_content = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .encryption_type(EncryptedDataType::Content)
            .direct_key(key)
            .encrypt_document(
                document,
                DocumentEncryptionOptions {
                    element_id: Some("content"),
                },
            )
            .expect("self-closing content replacement must expand the element");
        assert!(encrypted_content.contains("<empty ID=\"content\"><xenc:EncryptedData"));
        let decrypted_content =
            decrypt_document(&encrypted_content, None, &SymmetricKeyDecryptor::new(key))
                .expect("empty content must decrypt");
        assert_eq!(
            decrypted_content,
            "<root><target ID=\"element\"><child/></target><empty ID=\"content\"></empty></root>"
        );
    }

    #[test]
    fn invalid_configuration_and_bounds_fail_before_encryption() {
        let no_key = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .encrypt_binary(b"data")
            .expect_err("missing key source must fail");
        assert!(matches!(no_key, XmlEncError::InvalidEncryptionConfig(_)));

        assert!(
            validate_plaintext_len(MAX_ENCRYPTION_PLAINTEXT_LEN, MAX_ENCRYPTION_PLAINTEXT_LEN,)
                .is_ok()
        );
        assert!(matches!(
            validate_plaintext_len(
                MAX_ENCRYPTION_PLAINTEXT_LEN + 1,
                MAX_ENCRYPTION_PLAINTEXT_LEN,
            ),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_PLAINTEXT_BYTES,
                    ..
                }
            ))
        ));

        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 15])
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidKeySize { .. })
        ));

        let too_many_recipients = (0..=MAX_ENCRYPTION_RECIPIENTS).fold(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm),
            |builder, _| builder.recipient_aes_kw([0_u8; 16], KeyWrapAlgorithm::AesKw128),
        );
        assert!(matches!(
            too_many_recipients.encrypt_binary(b"data"),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_RECIPIENTS,
                    ..
                }
            ))
        ));

        let oversized_metadata = "x".repeat(MAX_ENCRYPTION_METADATA_LEN + 1);
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .id(oversized_metadata)
                .encrypt_binary(b"data"),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_METADATA_BYTES,
                    ..
                }
            ))
        ));
    }

    #[test]
    fn oversized_xml_is_rejected_before_parsing() {
        // The input bound protects the parser and the Content wrapper
        // allocation, so size must take precedence over malformed XML.
        let oversized_malformed = format!(
            "<child>{}</unclosed>",
            "x".repeat(MAX_ENCRYPTION_PLAINTEXT_LEN)
        );

        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .encryption_type(EncryptedDataType::Content)
                .direct_key([0_u8; 16])
                .encrypt_xml(&oversized_malformed),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_PLAINTEXT_BYTES,
                    ..
                }
            ))
        ));
    }

    #[test]
    fn oversized_document_is_rejected_before_parsing() {
        // The document API has a separate parser-input bound because the
        // selected plaintext may be much smaller than its enclosing document.
        let oversized_malformed = format!(
            "<root>{}</unclosed>",
            "x".repeat(MAX_ENCRYPTION_DOCUMENT_LEN)
        );

        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .encrypt_document(&oversized_malformed, DocumentEncryptionOptions::default()),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_DOCUMENT,
                    ..
                }
            ))
        ));
    }

    #[test]
    fn encrypted_replacement_must_fit_document_policy() {
        // Cipher framing, base64, and EncryptedData markup expand the selected
        // range; the returned document must remain valid input to decryption.
        for encrypted_type in [EncryptedDataType::Element, EncryptedDataType::Content] {
            let document = "<root><target ID=\"selected\">x</target></root>";
            let policy = crate::policy::EncryptionPolicy {
                resources: crate::policy::ResourcePolicy {
                    max_xml_document_bytes: document.len(),
                    ..crate::policy::ResourcePolicy::default()
                },
                ..crate::policy::EncryptionPolicy::default()
            };

            assert!(matches!(
                EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                    .encryption_type(encrypted_type)
                    .direct_key([0_u8; 16])
                    .policy(policy)
                    .encrypt_document(
                        document,
                        DocumentEncryptionOptions {
                            element_id: Some("selected"),
                        },
                    ),
                Err(XmlEncError::Policy(
                    crate::policy::PolicyViolation::ResourceLimit {
                        resource: crate::policy::resource_name::XML_DOCUMENT,
                        ..
                    }
                ))
            ));
        }
    }

    #[test]
    fn binary_encryption_preserves_an_opaque_type_hint() {
        // A non-XML Type URI describes opaque application bytes. It must survive
        // binary encryption so decryption can continue returning byte content.
        let result = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .encryption_type(EncryptedDataType::Other("urn:example:binary".into()))
            .direct_key([0x42_u8; 16])
            .encrypt_binary(b"opaque payload")
            .expect("opaque binary Type must be accepted");

        assert!(
            result
                .encrypted_data_xml
                .contains("Type=\"urn:example:binary\"")
        );
    }

    #[test]
    fn binary_encryption_bounds_an_opaque_type_hint() {
        // Generated metadata must obey the same policy as reciprocal parsing so
        // the builder cannot emit an EncryptedData document it would reject.
        let maximum = 64;
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_encryption_metadata_bytes: maximum,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let encrypt = |uri: String| {
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .encryption_type(EncryptedDataType::Other(uri))
                .direct_key([0x42_u8; 16])
                .policy(policy.clone())
                .encrypt_binary(b"opaque payload")
        };

        encrypt(format!("urn:{}", "x".repeat(maximum - 4)))
            .expect("metadata at the configured boundary must remain accepted");
        assert!(matches!(
            encrypt(format!("urn:{}", "x".repeat(maximum - 3))),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_METADATA_BYTES,
                    maximum: 64,
                    actual: 65,
                }
            ))
        ));
    }

    #[test]
    fn encryption_policy_bounds_xml_nodes_at_both_parse_entry_points() {
        // XML plaintext and whole-document encryption are separate parser paths;
        // both must consume the same immutable operation-policy node ceiling.
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_nodes: 4,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let builder = || {
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy.clone())
        };
        let xml = "<root><a/><b/><c/><d/></root>";

        assert!(matches!(
            builder().encrypt_xml(xml),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_NODES,
                    maximum: 4,
                    actual: 5,
                }
            ))
        ));
        assert!(matches!(
            builder().encrypt_document(xml, DocumentEncryptionOptions::default()),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_NODES,
                    maximum: 4,
                    actual: 5,
                }
            ))
        ));
    }

    #[test]
    fn encryption_entry_points_enforce_policy_depth() {
        // Whole-document encryption must apply the same depth policy to string
        // and retained inputs before target selection or encryption work.
        let xml = "<root><child><leaf/></child></root>";
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_depth: 2,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let builder = || {
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy.clone())
        };
        let mut document = XmlDocument::parse(xml).expect("wide retained fixture must parse");

        assert!(matches!(
            builder().encrypt_document(xml, DocumentEncryptionOptions::default()),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_DEPTH,
                    maximum: 2,
                    actual: 3,
                }
            ))
        ));
        assert!(matches!(
            builder().encrypt_owned_document(&mut document, DocumentEncryptionOptions::default()),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_DEPTH,
                    maximum: 2,
                    actual: 3,
                }
            ))
        ));
    }

    #[test]
    fn encryption_plaintext_and_owned_mutations_use_the_active_depth() {
        // A document parsed under broad defaults must not retain those defaults
        // when a stricter encryption operation parses or commits replacement XML.
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_depth: 1,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let builder = || {
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy.clone())
        };

        assert!(matches!(
            builder().encrypt_xml("<root><child/></root>"),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_DEPTH,
                    maximum: 1,
                    actual: 2,
                }
            ))
        ));

        let generated = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .encryption_type(EncryptedDataType::Content)
            .encrypt_xml("")
            .expect("generated content replacement must parse");
        let generated_document = Document::parse(&generated.encrypted_data_xml)
            .expect("generated replacement must be XML");
        let generated_depth = generated_document
            .descendants()
            .filter(|node| node.is_element())
            .map(|node| {
                node.ancestors()
                    .filter(|ancestor| ancestor.is_element())
                    .count()
            })
            .max()
            .expect("generated replacement has elements");
        let mutation_policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_depth: generated_depth,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let mut document = XmlDocument::parse("<root/>").expect("shallow fixture must parse");
        let original = document.as_xml().to_owned();
        let generation = document.generation();
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .encryption_type(EncryptedDataType::Content)
                .policy(mutation_policy)
                .encrypt_owned_document(&mut document, DocumentEncryptionOptions::default()),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_DEPTH,
                    maximum,
                    actual,
                }
            )) if maximum == generated_depth && actual == generated_depth + 1
        ));
        assert_eq!(document.as_xml(), original);
        assert_eq!(document.generation(), generation);
    }

    #[test]
    fn owned_encryption_checks_active_node_limit_before_target_selection() {
        // A missing selector must not bypass the active policy or make target
        // discovery traverse a retained document parsed under a wider ceiling.
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_nodes: 1,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let mut document = XmlDocument::parse("<root><first/><second/></root>")
            .expect("retained fixture must parse");
        let before = document.as_xml().to_owned();

        let error = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy)
            .encrypt_owned_document(
                &mut document,
                DocumentEncryptionOptions {
                    element_id: Some("missing"),
                },
            )
            .expect_err("active node ceiling must precede target selection");

        assert!(matches!(
            error,
            XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::XML_NODES,
                maximum: 1,
                actual,
            }) if actual > 1
        ));
        assert_eq!(document.as_xml(), before);
        assert_eq!(document.generation(), 0);
    }

    #[test]
    fn document_encryption_initial_parse_uses_the_policy_work_budget() {
        // Parsing the caller's XML and parsing the encrypted replacement must
        // consume one operation-wide allowance rather than independent caps.
        let xml = "<root/>";
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_parse_work_bytes: 0,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };

        let error = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy)
            .encrypt_document(xml, DocumentEncryptionOptions::default())
            .expect_err("a zero parse-work budget must reject the input parse");

        assert!(matches!(
            error,
            XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::XML_PARSE_WORK_BYTES,
                maximum: 0,
                actual,
            }) if actual == xml.len()
        ));
    }

    #[test]
    fn content_plaintext_node_limit_excludes_the_internal_wrapper() {
        let policy = |max_xml_nodes| crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_nodes,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };

        let policy_three = policy(3);
        let budget_three = XmlParseWorkBudget::from_resources(&policy_three.resources);
        validate_xml_plaintext(
            "<first/><second/>",
            &EncryptedDataType::Content,
            &policy_three,
            &budget_three,
        )
        .expect("the caller root and two elements must fit a three-node policy");
        let policy_two = policy(2);
        let budget_two = XmlParseWorkBudget::from_resources(&policy_two.resources);
        assert!(matches!(
            validate_xml_plaintext(
                "<first/><second/>",
                &EncryptedDataType::Content,
                &policy_two,
                &budget_two,
            ),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_NODES,
                    maximum: 2,
                    actual: 3,
                }
            ))
        ));
    }

    #[test]
    fn content_plaintext_byte_limit_excludes_only_the_internal_wrapper() {
        // The parser-only wrapper must not replace the caller's byte ceiling.
        // Encryption plaintext may be larger than the XML input policy, but an
        // XML Content fragment still has to satisfy both limits before parsing.
        let xml = "<first/><second/>";
        let maximum = xml.len() - 1;
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_document_bytes: maximum,
                max_encryption_plaintext_bytes: xml.len(),
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let budget = XmlParseWorkBudget::from_resources(&policy.resources);

        assert!(matches!(
            validate_xml_plaintext(xml, &EncryptedDataType::Content, &policy, &budget),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_DOCUMENT,
                    maximum: observed_maximum,
                    actual,
                }
            )) if observed_maximum == maximum && actual == xml.len()
        ));
        assert_eq!(
            budget.consumed(),
            0,
            "oversized XML must fail before parsing"
        );
    }

    #[test]
    fn generated_encrypted_data_parse_uses_the_active_node_limit() {
        // Generated XML is still operation work: reject it in the parser under
        // the active policy rather than allocating up to the absolute ceiling.
        let xml = "<EncryptedData><CipherData><CipherValue>AA==</CipherValue></CipherData></EncryptedData>";
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_nodes: 1,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let budget = XmlParseWorkBudget::from_resources(&policy.resources);

        assert!(matches!(
            count_generated_encrypted_data_nodes(xml, &policy, &budget),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::XML_NODES,
                    maximum: 1,
                    actual: 2,
                }
            ))
        ));
    }

    #[test]
    fn document_encryption_bounds_projected_replacement_nodes() {
        fn policy(max_xml_nodes: usize) -> crate::policy::EncryptionPolicy {
            crate::policy::EncryptionPolicy {
                resources: crate::policy::ResourcePolicy {
                    max_xml_nodes,
                    ..crate::policy::ResourcePolicy::default()
                },
                ..crate::policy::EncryptionPolicy::default()
            }
        }

        let generated_nodes = {
            let encrypted = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .encrypt_binary(b"payload")
                .expect("default policy must permit generated EncryptedData");
            Document::parse(&encrypted.encrypted_data_xml)
                .expect("generated EncryptedData must parse")
                .root_element()
                .descendants()
                .count()
        };

        // The source document fits the low limit, but the generated
        // EncryptedData replacement does not. The ceiling admits the standalone
        // fragment so this specifically exercises whole-document projection.
        let element_actual = match EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy(generated_nodes))
            .encrypt_document("<root/>", DocumentEncryptionOptions::default())
        {
            Err(XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: "XML nodes",
                maximum,
                actual,
            })) if maximum == generated_nodes && actual > maximum => actual,
            result => panic!("expected projected element node bound, got {result:?}"),
        };
        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy(element_actual))
            .encrypt_document("<root/>", DocumentEncryptionOptions::default())
            .expect("the exact projected element node limit must be accepted");

        // Content replacement retains the selected element. In particular, a
        // self-closing element expands around EncryptedData without adding an
        // extra source node to the projection.
        let content_actual = match EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .encryption_type(EncryptedDataType::Content)
            .direct_key([0_u8; 16])
            .policy(policy(generated_nodes))
            .encrypt_document("<root/>", DocumentEncryptionOptions::default())
        {
            Err(XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: "XML nodes",
                maximum,
                actual,
            })) if maximum == generated_nodes && actual > maximum => actual,
            result => panic!("expected projected content node bound, got {result:?}"),
        };
        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .encryption_type(EncryptedDataType::Content)
            .direct_key([0_u8; 16])
            .policy(policy(content_actual))
            .encrypt_document("<root/>", DocumentEncryptionOptions::default())
            .expect("the exact projected content node limit must be accepted");
    }

    #[test]
    fn standalone_encryption_bounds_generated_xml_nodes() {
        fn policy(max_xml_nodes: usize) -> crate::policy::EncryptionPolicy {
            crate::policy::EncryptionPolicy {
                resources: crate::policy::ResourcePolicy {
                    max_xml_nodes,
                    ..crate::policy::ResourcePolicy::default()
                },
                ..crate::policy::EncryptionPolicy::default()
            }
        }

        // Binary encryption has no input XML tree, but its generated EncryptedData
        // must still be consumable under the same operation-policy node ceiling.
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy(1))
                .encrypt_binary(b"payload"),
            Err(XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: "XML nodes",
                maximum: 1,
                actual,
            })) if actual > 1
        ));

        let generated = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .encrypt_binary(b"payload")
            .expect("default policy must permit generated EncryptedData");
        let document = Document::parse(&generated.encrypted_data_xml)
            .expect("generated EncryptedData must parse");
        let actual = document.root().descendants().count();
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy(actual - 1))
                .encrypt_binary(b"payload"),
            Err(XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: "XML nodes",
                maximum,
                actual: reported,
            })) if maximum == actual - 1 && reported == actual
        ));
        let exact = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy(actual))
            .encrypt_binary(b"payload")
            .expect("the exact generated node limit must be accepted");
        let exact_document =
            Document::parse(&exact.encrypted_data_xml).expect("exact-boundary output must parse");
        let decryption_policy = crate::policy::DecryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_nodes: actual,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::DecryptionPolicy::default()
        };
        super::super::parse::parse_encrypted_data_node_with_policy(
            exact_document.root_element(),
            &decryption_policy,
        )
        .expect("output accepted at the exact limit must be consumable at the same limit");
    }

    #[test]
    fn document_dtd_is_controlled_only_by_operation_policy() {
        // Parser behavior comes from the immutable operation snapshot; target
        // selection options cannot independently weaken or tighten it.
        let document = "<!DOCTYPE root [<!ELEMENT root ANY>]><root/>";
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .encrypt_document(document, DocumentEncryptionOptions { element_id: None },),
            Err(XmlEncError::XmlParse(_))
        ));
        let mut policy = crate::policy::EncryptionPolicy::default();
        policy.xml.allow_internal_dtd = true;
        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy.clone())
            .encrypt_document(document, DocumentEncryptionOptions { element_id: None })
            .expect("the explicit operation policy should permit parsing");
    }

    #[test]
    fn invalid_resource_policy_is_rejected_at_every_entry_point() {
        // Entry points must reject an invalid snapshot before parsing or using
        // any caller-selected limit derived from it.
        let mut policy = crate::policy::EncryptionPolicy::default();
        policy.resources.max_encryption_plaintext_bytes =
            crate::hard_limits::ENCRYPTION_PLAINTEXT_BYTE_CEILING + 1;
        let builder = || {
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy.clone())
        };

        assert!(matches!(
            builder().encrypt_xml("<broken>"),
            Err(XmlEncError::Policy(_))
        ));
        assert!(matches!(
            builder().encrypt_binary(b"x"),
            Err(XmlEncError::Policy(_))
        ));
        assert!(matches!(
            builder().encrypt_document("<broken>", DocumentEncryptionOptions::default()),
            Err(XmlEncError::Policy(_))
        ));
    }

    #[test]
    fn standalone_encrypted_output_obeys_document_byte_ceiling() {
        // The returned fragment must remain admissible to the reciprocal parser;
        // plaintext bounds alone do not account for framing, base64, or markup.
        let policy = |maximum| crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_xml_document_bytes: maximum,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };

        let binary_len = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .encrypt_binary(b"bounded binary")
            .expect("baseline binary encryption must succeed")
            .encrypted_data_xml
            .len();
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy(binary_len - 1))
                .encrypt_binary(b"bounded binary"),
            Err(XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::XML_DOCUMENT,
                maximum,
                actual,
            }))
                if maximum == binary_len - 1 && actual == binary_len
        ));
        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy(binary_len))
            .encrypt_binary(b"bounded binary")
            .expect("the exact standalone binary output bound must be accepted");

        let xml_len = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .encrypt_xml("<secret>bounded XML</secret>")
            .expect("baseline XML encryption must succeed")
            .encrypted_data_xml
            .len();
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy(xml_len - 1))
                .encrypt_xml("<secret>bounded XML</secret>"),
            Err(XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::XML_DOCUMENT,
                maximum,
                actual,
            }))
                if maximum == xml_len - 1 && actual == xml_len
        ));
        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy(xml_len))
            .encrypt_xml("<secret>bounded XML</secret>")
            .expect("the exact standalone XML output bound must be accepted");
    }

    #[test]
    fn zero_resource_ceilings_allow_operations_that_consume_none() {
        // Zero is deny-all, not an invalid policy. Direct-key encryption has no
        // recipients, and an empty binary payload consumes no plaintext bytes.
        let policy = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_encryption_plaintext_bytes: 0,
                max_encryption_recipients: 0,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };

        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .policy(policy.clone())
            .encrypt_binary(&[])
            .expect("zero ceilings must allow resources the operation does not consume");

        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .policy(policy.clone())
                .encrypt_binary(b"x"),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_PLAINTEXT_BYTES,
                    maximum: 0,
                    actual: 1
                }
            ))
        ));
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .recipient_aes_kw([0_u8; 16], KeyWrapAlgorithm::AesKw128)
                .policy(policy)
                .encrypt_binary(&[]),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::ENCRYPTION_RECIPIENTS,
                    maximum: 0,
                    actual: 1,
                }
            ))
        ));
    }

    #[test]
    fn encryption_enforces_key_candidate_budget_before_inspection() {
        // Candidate accounting must reject configured keys before validating or
        // dispatching them, while accepting the exact operation-wide boundary.
        let deny_keys = crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_key_candidates: 0,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };

        for error in [
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 15])
                .policy(deny_keys.clone())
                .encrypt_binary(b"data")
                .expect_err("a direct key must consume one candidate"),
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .recipient_aes_kw([0_u8; 15], KeyWrapAlgorithm::AesKw128)
                .policy(deny_keys)
                .encrypt_binary(b"data")
                .expect_err("a recipient key must consume one candidate"),
        ] {
            assert!(matches!(
                error,
                XmlEncError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::KEY_CANDIDATES,
                    maximum: 0,
                    actual: 1,
                })
            ));
        }

        let recipient =
            || EncryptionRecipient::aes_key_wrap([0_u8; 16], KeyWrapAlgorithm::AesKw128);
        let policy_with_candidate_limit = |maximum| crate::policy::EncryptionPolicy {
            resources: crate::policy::ResourcePolicy {
                max_key_candidates: maximum,
                ..crate::policy::ResourcePolicy::default()
            },
            ..crate::policy::EncryptionPolicy::default()
        };
        let builder = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .add_recipient(recipient())
            .add_recipient(recipient());

        assert!(matches!(
            builder
                .clone()
                .policy(policy_with_candidate_limit(1))
                .encrypt_binary(b"data"),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::KEY_CANDIDATES,
                    maximum: 1,
                    actual: 2,
                }
            ))
        ));
        builder
            .policy(policy_with_candidate_limit(2))
            .encrypt_binary(b"data")
            .expect("the exact key-candidate boundary must be accepted");
    }

    #[test]
    fn element_plaintext_enforces_replacement_node_contract() {
        // Element ciphertext must be safe for the reciprocal document replacement:
        // boundary whitespace/comments are harmless, but processing instructions are not.
        let builder =
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm).direct_key([0_u8; 16]);
        builder
            .encrypt_xml("\n<!--before--><secret/><!--after-->\n")
            .expect("one element with boundary trivia must be accepted");

        assert!(matches!(
            builder.encrypt_xml("<?target value?><secret/>"),
            Err(XmlEncError::InvalidStructure(_))
        ));
    }

    #[test]
    fn empty_key_names_are_rejected_before_serialization() {
        // The reciprocal parser rejects empty KeyName elements, so encryption
        // must not emit output that its own decrypt pipeline cannot consume.
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .direct_key_name("")
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .add_recipient(
                    EncryptionRecipient::aes_key_wrap([0_u8; 16], KeyWrapAlgorithm::AesKw128)
                        .key_name("")
                )
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
    }

    #[test]
    fn xml_forbidden_metadata_characters_are_rejected() {
        // XML escaping cannot legalize forbidden XML 1.0 code points, so every
        // caller-controlled attribute/text path must fail before serialization.
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .id("invalid\0id")
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .direct_key([0_u8; 16])
                .direct_key_name("invalid\0name")
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .add_recipient(
                    EncryptionRecipient::aes_key_wrap([0_u8; 16], KeyWrapAlgorithm::AesKw128)
                        .recipient("invalid\0recipient")
                )
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
        assert!(matches!(
            EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .add_recipient(
                    EncryptionRecipient::aes_key_wrap([0_u8; 16], KeyWrapAlgorithm::AesKw128)
                        .key_name("invalid\0name")
                )
                .encrypt_binary(b"data"),
            Err(XmlEncError::InvalidEncryptionConfig(_))
        ));
    }

    #[test]
    fn encrypted_data_id_must_be_an_xml_ncname() {
        // xsd:ID derives from NCName; escaping arbitrary attribute text cannot
        // make whitespace, a leading digit, or a colon schema-valid.
        for invalid in ["bad id", "1leading", "qualified:name", ""] {
            assert!(matches!(
                EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                    .direct_key([0_u8; 16])
                    .id(invalid)
                    .encrypt_binary(b"data"),
                Err(XmlEncError::InvalidEncryptionConfig(_))
            ));
        }

        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key([0_u8; 16])
            .id("Δοκιμή")
            .encrypt_binary(b"data")
            .expect("Unicode XML NCNames must remain valid identifiers");
    }

    #[test]
    fn rejects_malformed_custom_provider_ciphertext_before_serialization() {
        // Providers supply primitives, but the facade owns the standard wire
        // contract and must not serialize output its own decryptor rejects.
        for (algorithm, ciphertext) in [
            (DataEncryptionAlgorithm::Aes128Gcm, vec![0_u8; 27]),
            (DataEncryptionAlgorithm::Aes128Cbc, vec![0_u8; 31]),
            (DataEncryptionAlgorithm::Aes256Cbc, vec![0_u8; 33]),
        ] {
            let error = EncryptedDataBuilder::new(algorithm)
                .provider(Arc::new(OverridingOutputProvider {
                    ciphertext: Some(ciphertext),
                    wrapped_key: None,
                    transported_key: None,
                    transport_calls: AtomicUsize::new(0),
                }))
                .direct_key(vec![0_u8; algorithm.key_len()])
                .encrypt_binary(b"data")
                .expect_err("malformed provider output must fail before XML serialization");
            assert!(matches!(
                error,
                XmlEncError::DataTooShort { .. } | XmlEncError::InvalidCbcCiphertextLength(_)
            ));
        }
    }

    #[test]
    fn rejects_overlong_custom_provider_ciphertext_before_serialization() {
        // Provider success cannot change the algorithm-defined relationship
        // between plaintext and ciphertext length.
        for (algorithm, expected, actual) in [
            (DataEncryptionAlgorithm::Aes128Gcm, 32, 33),
            (DataEncryptionAlgorithm::Aes128Cbc, 32, 48),
        ] {
            let error = EncryptedDataBuilder::new(algorithm)
                .provider(Arc::new(OverridingOutputProvider {
                    ciphertext: Some(vec![0_u8; actual]),
                    wrapped_key: None,
                    transported_key: None,
                    transport_calls: AtomicUsize::new(0),
                }))
                .direct_key(vec![0_u8; algorithm.key_len()])
                .encrypt_binary(b"data")
                .expect_err("overlong provider output must fail before XML serialization");
            assert!(matches!(
                error,
                XmlEncError::Provider(crate::provider::ProviderError::InvalidOutputSize {
                    operation: crate::provider::ProviderOperation::Encrypt,
                    expected: observed_expected,
                    actual: observed_actual,
                }) if observed_expected == expected && observed_actual == actual
            ));
        }
    }

    #[test]
    fn rejects_malformed_custom_provider_wrapped_keys_before_serialization() {
        // RFC 3394 adds exactly one 64-bit integrity block. Accepting any other
        // provider output would emit EncryptedKey data no recipient can unwrap.
        for wrapped_key in [vec![], vec![0_u8; 23], vec![0_u8; 25]] {
            let result = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .provider(Arc::new(OverridingOutputProvider {
                    ciphertext: None,
                    wrapped_key: Some(wrapped_key),
                    transported_key: None,
                    transport_calls: AtomicUsize::new(0),
                }))
                .recipient_aes_kw([0_u8; 16], KeyWrapAlgorithm::AesKw128)
                .encrypt_binary(b"data");
            assert!(matches!(
                result,
                Err(XmlEncError::InvalidWrappedKeyLength { expected: 24, actual })
                    if actual != 24
            ));
        }

        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .provider(Arc::new(OverridingOutputProvider {
                ciphertext: None,
                wrapped_key: Some(vec![0_u8; 24]),
                transported_key: None,
                transport_calls: AtomicUsize::new(0),
            }))
            .recipient_aes_kw([0_u8; 16], KeyWrapAlgorithm::AesKw128)
            .encrypt_binary(b"data")
            .expect("exact RFC 3394 wrapped-key length must remain accepted");
    }

    #[test]
    fn rejects_malformed_custom_provider_rsa_transport_before_serialization() {
        // RSA ciphertext is exactly one modulus wide. Enforcing that invariant
        // here prevents custom providers from emitting undecryptable XML.
        let private_key = RsaPrivateKey::new(&mut UnwrapErr(SysRng), 2048)
            .expect("RSA key generation should succeed");
        let public_key = RsaPublicKey::from(&private_key);
        for transported_key in [vec![], vec![0_u8; 255], vec![0_u8; 257]] {
            let result = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
                .provider(Arc::new(OverridingOutputProvider {
                    ciphertext: None,
                    wrapped_key: None,
                    transported_key: Some(transported_key),
                    transport_calls: AtomicUsize::new(0),
                }))
                .recipient_rsa_oaep(public_key.clone())
                .encrypt_binary(b"data");
            assert!(matches!(
                result,
                Err(XmlEncError::InvalidWrappedKeyLength {
                    expected: 256,
                    actual,
                }) if actual != 256
            ));
        }

        EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .provider(Arc::new(OverridingOutputProvider {
                ciphertext: None,
                wrapped_key: None,
                transported_key: Some(vec![0_u8; 256]),
                transport_calls: AtomicUsize::new(0),
            }))
            .recipient_rsa_oaep(public_key)
            .encrypt_binary(b"data")
            .expect("modulus-sized RSA transport output must remain accepted");
    }

    #[test]
    fn custom_provider_encrypts_with_an_opaque_transport_key() {
        // The key exposes only public policy metadata. Successful encryption
        // proves orchestration never needs a concrete RustCrypto RSA object.
        let provider = Arc::new(OverridingOutputProvider {
            ciphertext: None,
            wrapped_key: None,
            transported_key: Some(vec![0x5a; 256]),
            transport_calls: AtomicUsize::new(0),
        });
        let key = Arc::new(OpaqueTransportKey {
            modulus: vec![0x80; 256],
            exponent: vec![0x01, 0x00, 0x01],
        });

        let encrypted = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .provider(provider.clone())
            .recipient_key_transport(key)
            .encrypt_binary(b"opaque provider key")
            .expect("custom provider must accept its opaque transport key");

        assert_eq!(provider.transport_calls.load(Ordering::Relaxed), 1);
        assert!(encrypted.encrypted_data_xml.contains("rsa-oaep"));
    }

    #[test]
    fn opaque_transport_preflight_rejects_weak_rsa_metadata() {
        // Provider-owned keys cannot bypass the same outbound RSA policy used
        // by the RustCrypto convenience constructor.
        let key = OpaqueTransportKey {
            modulus: vec![0x80; 128],
            exponent: vec![0x01, 0x00, 0x01],
        };
        assert!(matches!(
            validate_key_transport_recipient(&key, &crate::policy::EncryptionPolicy::default()),
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::KeySize { .. }
            ))
        ));
    }

    #[test]
    fn encryption_policy_rejects_weak_rsa_recipient_before_provider_dispatch() {
        // Provider capability cannot weaken the outbound recipient-key policy.
        let private_key = RsaPrivateKey::new(&mut UnwrapErr(SysRng), 1024)
            .expect("test RSA key generation should succeed");
        let provider = Arc::new(OverridingOutputProvider {
            ciphertext: None,
            wrapped_key: None,
            transported_key: Some(vec![0_u8; 128]),
            transport_calls: AtomicUsize::new(0),
        });

        let result = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .provider(provider.clone())
            .recipient_rsa_oaep(RsaPublicKey::from(&private_key))
            .encrypt_binary(b"data");

        assert!(matches!(
            result,
            Err(XmlEncError::Policy(
                crate::policy::PolicyViolation::KeySize {
                    operation: "encryption",
                    minimum_bits: 2048,
                    maximum_bits: 8192,
                    actual_bits: 1024,
                    ..
                }
            ))
        ));
        assert_eq!(provider.transport_calls.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn debug_output_redacts_symmetric_key_material() {
        let direct_key = b"direct-key-secret".to_vec();
        let kek = b"key-wrap-secret!".to_vec();
        let builder = EncryptedDataBuilder::new(DataEncryptionAlgorithm::Aes128Gcm)
            .direct_key(direct_key.clone());
        let recipient = EncryptionRecipient::aes_key_wrap(kek.clone(), KeyWrapAlgorithm::AesKw128);

        let builder_debug = format!("{builder:?}");
        let recipient_debug = format!("{recipient:?}");
        assert!(builder_debug.contains("[REDACTED]"));
        assert!(recipient_debug.contains("[REDACTED]"));
        assert!(!builder_debug.contains(&format!("{direct_key:?}")));
        assert!(!recipient_debug.contains(&format!("{kek:?}")));
    }
}