xml-sec 0.1.16

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
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
//! Configuration and key material for XMLDSig key resolution.

use std::{collections::HashMap, fmt, time::SystemTime};

use crypto_bigint::BoxedUint;
use dsa::pkcs8::{DecodePublicKey as DsaDecodePublicKey, EncodePublicKey as DsaEncodePublicKey};
use hmac::{KeyInit, Mac};
use x509_parser::{
    prelude::{FromDer, X509Certificate},
    public_key::PublicKey,
    x509::SubjectPublicKeyInfo,
};
use zeroize::Zeroizing;

use super::signature::{
    signature_value_matches_spki, signature_value_matches_spki_with_encoding,
    validate_dsa_signature_spki_with_minimum, validate_rsa_signature_spki_with_minimum,
    verify_dsa_signature_spki_primitive, verify_dsa_signature_spki_with_minimum,
    verify_rsa_signature_spki_primitive, verify_rsa_signature_spki_with_minimum,
};
use super::{
    DsigError, KeyInfo, KeyInfoSource, KeyResolver, KeyValueInfo, SignatureAlgorithm, VerifyingKey,
    X509ChainOptions, X509DataInfo,
    parse::{
        EC_P256_OID, EC_P384_OID, EC_P521_OID, ParseError, X509ChainBuildError,
        build_x509_certificate_paths_to_selector_targets,
        build_x509_certificate_paths_to_trusted_prefix, distinguished_names_equal,
        parse_x509_certificate, x509_certificate_matches_any_selector,
        x509_data_has_lookup_identifiers, x509_selector_categories_match_chain,
    },
    verify_ecdsa_signature_spki, verify_ecdsa_signature_spki_with_encoding,
    x509::verify_x509_certificate_chain_with_provider,
};

/// Caller-owned HMAC verification key.
///
/// Policy-free [`VerifyingKey`] calls enforce [`crate::policy::HmacPolicy::default`].
/// [`super::VerifyContext`] supplies its immutable operation policy through the
/// policy-aware hooks, so legacy truncation always requires an explicit opt-in.
/// Owned secret bytes are zeroized when the key is dropped.
#[derive(Clone)]
pub struct HmacVerificationKey {
    secret: Zeroizing<Vec<u8>>,
}

impl fmt::Debug for HmacVerificationKey {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HmacVerificationKey")
            .finish_non_exhaustive()
    }
}

impl HmacVerificationKey {
    /// Construct a key from non-empty secret bytes.
    pub fn new(secret: impl Into<Vec<u8>>) -> Result<Self, KeyResolutionError> {
        let secret = secret.into();
        if secret.is_empty() {
            return Err(KeyResolutionError::InvalidPublicKey);
        }
        Ok(Self {
            secret: Zeroizing::new(secret),
        })
    }

    fn validate_output(
        &self,
        policy: crate::policy::HmacPolicy,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<(), DsigError> {
        if algorithm.hmac_output_bits().is_none() {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        policy.validate_key_bytes(self.secret.len())?;
        policy.validate_output(algorithm, signature_value.len().saturating_mul(8))?;
        Ok(())
    }

    fn verify_with_hmac_policy(
        &self,
        policy: crate::policy::HmacPolicy,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.validate_output(policy, algorithm, signature_value)?;
        macro_rules! verify_hmac {
            ($digest:ty) => {{
                let mut mac = hmac::Hmac::<$digest>::new_from_slice(&self.secret)
                    .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
                mac.update(signed_data);
                let expected = mac.finalize().into_bytes();
                subtle::ConstantTimeEq::ct_eq(&expected[..signature_value.len()], signature_value)
                    .into()
            }};
        }
        Ok(match algorithm {
            SignatureAlgorithm::HmacSha1 => verify_hmac!(sha1::Sha1),
            SignatureAlgorithm::HmacSha224 => verify_hmac!(sha2::Sha224),
            SignatureAlgorithm::HmacSha256 => verify_hmac!(sha2::Sha256),
            SignatureAlgorithm::HmacSha384 => verify_hmac!(sha2::Sha384),
            SignatureAlgorithm::HmacSha512 => verify_hmac!(sha2::Sha512),
            _ => return Err(KeyResolutionError::AlgorithmMismatch.into()),
        })
    }
}

impl VerifyingKey for HmacVerificationKey {
    fn validate_policy(&self, policy: &crate::policy::VerificationPolicy) -> Result<(), DsigError> {
        policy
            .hmac
            .validate_key_bytes(self.secret.len())
            .map_err(Into::into)
    }

    fn validate_signature_value(
        &self,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.validate_output(
            crate::policy::HmacPolicy::default(),
            algorithm,
            signature_value,
        )?;
        Ok(true)
    }

    fn validate_signature_value_with_policy(
        &self,
        policy: &crate::policy::VerificationPolicy,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.validate_output(policy.hmac, algorithm, signature_value)?;
        Ok(true)
    }

    fn verify(
        &self,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.verify_with_hmac_policy(
            crate::policy::HmacPolicy::default(),
            algorithm,
            signed_data,
            signature_value,
        )
    }

    fn verify_with_policy(
        &self,
        policy: &crate::policy::VerificationPolicy,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.verify_with_hmac_policy(policy.hmac, algorithm, signed_data, signature_value)
    }
}

/// Compatibility name for the verification key originally limited to HMAC-SHA1.
pub type HmacSha1VerificationKey = HmacVerificationKey;

/// A public verification key available to key resolvers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerificationKey {
    /// Signature algorithm this key is configured to verify.
    pub algorithm: SignatureAlgorithm,
    /// DER-encoded SubjectPublicKeyInfo bytes.
    pub public_key_bytes: Vec<u8>,
    /// DER certificate from which the key was extracted, when applicable.
    pub certificate_der: Option<Vec<u8>>,
    /// Name used to register this key for `<KeyName>` resolution.
    pub name: Option<String>,
}

impl VerifyingKey for VerificationKey {
    fn validate_policy(&self, policy: &crate::policy::VerificationPolicy) -> Result<(), DsigError> {
        let result = match self.algorithm {
            SignatureAlgorithm::DsaSha1 | SignatureAlgorithm::DsaSha256 => {
                validate_dsa_signature_spki_with_minimum(
                    &self.public_key_bytes,
                    policy.key_trust.dsa_keys.minimum_modulus_bits,
                )
            }
            SignatureAlgorithm::RsaSha1
            | SignatureAlgorithm::RsaSha224
            | SignatureAlgorithm::RsaSha256
            | SignatureAlgorithm::RsaSha384
            | SignatureAlgorithm::RsaSha512 => validate_rsa_signature_spki_with_minimum(
                self.algorithm,
                &self.public_key_bytes,
                policy.key_trust.rsa_keys.minimum_modulus_bits,
            ),
            SignatureAlgorithm::HmacSha1
            | SignatureAlgorithm::HmacSha224
            | SignatureAlgorithm::HmacSha256
            | SignatureAlgorithm::HmacSha384
            | SignatureAlgorithm::HmacSha512
            | SignatureAlgorithm::EcdsaSha1
            | SignatureAlgorithm::EcdsaSha224
            | SignatureAlgorithm::EcdsaSha256
            | SignatureAlgorithm::EcdsaSha384
            | SignatureAlgorithm::EcdsaSha512 => Ok(()),
        };
        result.map_err(DsigError::Crypto)
    }

    fn validate_signature_value(
        &self,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if algorithm != self.algorithm {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        signature_value_matches_spki(algorithm, &self.public_key_bytes, signature_value)
            .map_err(DsigError::Crypto)
    }

    fn validate_signature_value_with_policy(
        &self,
        policy: &crate::policy::VerificationPolicy,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if algorithm != self.algorithm {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        signature_value_matches_spki_with_encoding(
            algorithm,
            &self.public_key_bytes,
            signature_value,
            policy.ecdsa_signature_value_encoding,
        )
        .map_err(DsigError::Crypto)
    }

    fn verify(
        &self,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if algorithm != self.algorithm {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        let result = match algorithm {
            SignatureAlgorithm::DsaSha1 | SignatureAlgorithm::DsaSha256 => {
                verify_dsa_signature_spki_primitive(
                    algorithm,
                    &self.public_key_bytes,
                    signed_data,
                    signature_value,
                )
            }
            SignatureAlgorithm::HmacSha1
            | SignatureAlgorithm::HmacSha224
            | SignatureAlgorithm::HmacSha256
            | SignatureAlgorithm::HmacSha384
            | SignatureAlgorithm::HmacSha512 => {
                return Err(KeyResolutionError::AlgorithmMismatch.into());
            }
            SignatureAlgorithm::RsaSha1
            | SignatureAlgorithm::RsaSha224
            | SignatureAlgorithm::RsaSha256
            | SignatureAlgorithm::RsaSha384
            | SignatureAlgorithm::RsaSha512 => verify_rsa_signature_spki_primitive(
                algorithm,
                &self.public_key_bytes,
                signed_data,
                signature_value,
            ),
            SignatureAlgorithm::EcdsaSha1
            | SignatureAlgorithm::EcdsaSha224
            | SignatureAlgorithm::EcdsaSha256
            | SignatureAlgorithm::EcdsaSha384
            | SignatureAlgorithm::EcdsaSha512 => verify_ecdsa_signature_spki(
                algorithm,
                &self.public_key_bytes,
                signed_data,
                signature_value,
            ),
        };
        result.map_err(DsigError::Crypto)
    }

    fn verify_with_policy(
        &self,
        policy: &crate::policy::VerificationPolicy,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if algorithm != self.algorithm {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        if matches!(
            algorithm,
            SignatureAlgorithm::EcdsaSha1
                | SignatureAlgorithm::EcdsaSha224
                | SignatureAlgorithm::EcdsaSha256
                | SignatureAlgorithm::EcdsaSha384
                | SignatureAlgorithm::EcdsaSha512
        ) {
            return verify_ecdsa_signature_spki_with_encoding(
                algorithm,
                &self.public_key_bytes,
                signed_data,
                signature_value,
                policy.ecdsa_signature_value_encoding,
            )
            .map_err(DsigError::Crypto);
        }
        self.verify(algorithm, signed_data, signature_value)
    }
}

struct PolicyBoundVerificationKey {
    key: VerificationKey,
    rsa_minimum_bits: usize,
    dsa_minimum_bits: usize,
}

impl VerifyingKey for PolicyBoundVerificationKey {
    fn validate_signature_value(
        &self,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.key
            .validate_signature_value(algorithm, signature_value)
    }

    fn validate_signature_value_with_policy(
        &self,
        policy: &crate::policy::VerificationPolicy,
        algorithm: SignatureAlgorithm,
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        self.key
            .validate_signature_value_with_policy(policy, algorithm, signature_value)
    }

    fn verify(
        &self,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if algorithm != self.key.algorithm {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        let result = match algorithm {
            SignatureAlgorithm::DsaSha1 | SignatureAlgorithm::DsaSha256 => {
                verify_dsa_signature_spki_with_minimum(
                    algorithm,
                    &self.key.public_key_bytes,
                    signed_data,
                    signature_value,
                    self.dsa_minimum_bits,
                )
            }
            SignatureAlgorithm::RsaSha1
            | SignatureAlgorithm::RsaSha224
            | SignatureAlgorithm::RsaSha256
            | SignatureAlgorithm::RsaSha384
            | SignatureAlgorithm::RsaSha512 => verify_rsa_signature_spki_with_minimum(
                algorithm,
                &self.key.public_key_bytes,
                signed_data,
                signature_value,
                self.rsa_minimum_bits,
            ),
            _ => return self.key.verify(algorithm, signed_data, signature_value),
        };
        result.map_err(DsigError::Crypto)
    }

    fn verify_with_policy(
        &self,
        policy: &crate::policy::VerificationPolicy,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if matches!(
            algorithm,
            SignatureAlgorithm::EcdsaSha1
                | SignatureAlgorithm::EcdsaSha224
                | SignatureAlgorithm::EcdsaSha256
                | SignatureAlgorithm::EcdsaSha384
                | SignatureAlgorithm::EcdsaSha512
        ) {
            return self
                .key
                .verify_with_policy(policy, algorithm, signed_data, signature_value);
        }
        self.verify(algorithm, signed_data, signature_value)
    }
}

/// Failures while applying [`KeyResolverConfig`] to parsed key material.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KeyResolutionError {
    /// A configured or embedded key does not match the signature method.
    #[error("verification key does not match the signature algorithm")]
    AlgorithmMismatch,
    /// An embedded certificate could not be parsed completely.
    #[error("invalid embedded certificate DER")]
    InvalidCertificate,
    /// Configured or embedded public key DER could not be parsed completely.
    #[error("invalid public key DER")]
    InvalidPublicKey,
    /// More than one configured certificate satisfies all X.509 selectors.
    #[error("X.509 lookup selectors match multiple configured certificates")]
    AmbiguousCertificate,
    /// An X.509 selector uses a digest algorithm unsupported by this crate.
    #[error("unsupported X.509 digest algorithm: {0}")]
    UnsupportedDigestAlgorithm(String),
    /// Embedded certificate path validation failed.
    #[error("certificate chain validation failed: {0}")]
    Chain(#[from] super::X509ChainError),
    /// System time was unavailable for certificate validation.
    #[error("system time is unavailable")]
    SystemTime,
}

/// Configuration for the default XMLDSig key resolver.
///
/// The configuration owns all key material and has no global registry. Chain
/// verification is opt-in so callers that pin an embedded certificate can use
/// the documented TOFU model without constructing a certificate path.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct KeyResolverConfig {
    /// DER-encoded certificates available to X.509 selectors and as untrusted
    /// path intermediates. They establish trust only by chaining to an entry in
    /// [`Self::trusted_certs`].
    pub lookup_certs: Vec<Vec<u8>>,
    /// DER-encoded certificates accepted as trust anchors.
    pub trusted_certs: Vec<Vec<u8>>,
    /// Verification keys addressable by `<KeyName>` content.
    pub named_keys: HashMap<String, VerificationKey>,
}

/// Configuration-driven resolver for embedded certificates, DER keys, and key names.
#[derive(Debug, Clone, Default)]
pub struct DefaultKeyResolver {
    config: KeyResolverConfig,
}

/// Counts candidates actually inspected by one resolver invocation.
///
/// Parser cardinality preflights prevent expensive materialization, but do not
/// replace this runtime accounting: embedded and indirect candidates both
/// consume resolver work when inspected.
struct InspectedKeyCandidateBudget {
    maximum: usize,
    attempted: usize,
}

impl InspectedKeyCandidateBudget {
    fn new(maximum: usize) -> Self {
        Self {
            maximum,
            attempted: 0,
        }
    }

    fn charge(&mut self) -> Result<(), DsigError> {
        self.charge_many(1)
    }

    fn charge_many(&mut self, count: usize) -> Result<(), DsigError> {
        self.attempted = self.attempted.saturating_add(count);
        if self.attempted > self.maximum {
            return Err(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::KEY_CANDIDATES,
                maximum: self.maximum,
                actual: self.attempted,
            }
            .into());
        }
        Ok(())
    }
}

fn validate_key_info_source_permissions(
    key_info: &KeyInfo,
    allowed: crate::policy::KeySourcePolicy,
) -> Result<(), crate::policy::PolicyViolation> {
    for source in &key_info.sources {
        let disabled_reason = match source {
            KeyInfoSource::X509Data(_) if !allowed.x509_data => {
                Some("X509Data key sources are disabled")
            }
            KeyInfoSource::DerEncodedKeyValue(_) if !allowed.der_encoded_key_value => {
                Some("DEREncodedKeyValue key sources are disabled")
            }
            KeyInfoSource::KeyName(_) if !allowed.key_name => {
                Some("KeyName key sources are disabled")
            }
            KeyInfoSource::KeyValue(_) if !allowed.key_value => {
                Some("KeyValue key sources are disabled")
            }
            KeyInfoSource::KeyInfoReference { .. } if !allowed.key_info_reference => {
                Some("KeyInfoReference key sources are disabled")
            }
            KeyInfoSource::X509Data(_)
            | KeyInfoSource::DerEncodedKeyValue(_)
            | KeyInfoSource::KeyName(_)
            | KeyInfoSource::KeyValue(_)
            | KeyInfoSource::RetrievalMethod { .. }
            | KeyInfoSource::KeyInfoReference { .. } => None,
        };
        if let Some(reason) = disabled_reason {
            return Err(crate::policy::PolicyViolation::KeyTrust { reason });
        }
    }
    Ok(())
}

impl DefaultKeyResolver {
    /// Construct a resolver from explicit caller-owned key and certificate stores.
    #[must_use]
    pub fn new(config: KeyResolverConfig) -> Self {
        Self { config }
    }

    /// Borrow the active resolver configuration.
    #[must_use]
    pub fn config(&self) -> &KeyResolverConfig {
        &self.config
    }

    fn resolve_x509(
        &self,
        info: &X509DataInfo,
        algorithm: SignatureAlgorithm,
        trust: &crate::policy::KeyTrustPolicy,
        provider: &dyn crate::provider::CryptoProvider,
        budget: &mut InspectedKeyCandidateBudget,
    ) -> Result<Option<VerificationKey>, DsigError> {
        let certificate_der = if let Some(&signing_index) = info.certificate_chain.first() {
            if trust.verify_x509_chains {
                self.prepare_embedded_x509(info, signing_index, trust, provider, budget)?;
            } else {
                budget.charge_many(info.certificates.len())?;
            }
            info.certificates
                .get(signing_index)
                .ok_or(KeyResolutionError::InvalidCertificate)?
                .clone()
        } else {
            let Some(selected) = self.resolve_configured_x509(info, trust, provider, budget)?
            else {
                return Ok(None);
            };
            selected
                .certificate_chain
                .first()
                .and_then(|index| selected.certificates.get(*index))
                .ok_or(KeyResolutionError::InvalidCertificate)?
                .clone()
        };

        let (rest, certificate) = X509Certificate::from_der(&certificate_der)
            .map_err(|_| KeyResolutionError::InvalidCertificate)?;
        if !rest.is_empty() {
            return Err(KeyResolutionError::InvalidCertificate.into());
        }
        let public_key_bytes = certificate.public_key().raw.to_vec();
        validate_spki_algorithm(&public_key_bytes, algorithm)?;
        Ok(Some(VerificationKey {
            algorithm,
            public_key_bytes,
            certificate_der: Some(certificate_der),
            name: None,
        }))
    }

    fn verify_x509_policy(
        &self,
        info: &X509DataInfo,
        trust: &crate::policy::KeyTrustPolicy,
        provider: &dyn crate::provider::CryptoProvider,
    ) -> Result<(), KeyResolutionError> {
        let options = X509ChainOptions {
            trusted_certs: &self.config.trusted_certs,
            verification_time: trust.verification_time.unwrap_or_else(SystemTime::now),
            max_chain_depth: trust.max_x509_chain_depth,
            check_crls: trust.check_crls,
            allowed_extended_key_usages: Some(&trust.allowed_extended_key_usages),
            rsa_keys: trust.rsa_keys,
            dsa_keys: trust.dsa_keys,
        };
        verify_x509_certificate_chain_with_provider(info, &options, provider)?;
        Ok(())
    }

    fn prepare_embedded_x509(
        &self,
        info: &X509DataInfo,
        signing_index: usize,
        trust: &crate::policy::KeyTrustPolicy,
        provider: &dyn crate::provider::CryptoProvider,
        budget: &mut InspectedKeyCandidateBudget,
    ) -> Result<X509DataInfo, DsigError> {
        let signing_der = info
            .certificates
            .get(signing_index)
            .ok_or(KeyResolutionError::InvalidCertificate)?;
        let mut available = X509DataInfo {
            crls: info.crls.clone(),
            ..X509DataInfo::default()
        };
        let mut trusted_prefix_len = 0;
        for certificate in &self.config.trusted_certs {
            budget.charge()?;
            if available
                .certificates
                .iter()
                .any(|known| known == certificate)
            {
                continue;
            }
            available.parsed_certificates.push(
                parse_x509_certificate(certificate)
                    .map_err(|_| KeyResolutionError::InvalidCertificate)?,
            );
            available.certificates.push(certificate.clone());
            trusted_prefix_len += 1;
        }
        for certificate in self.config.lookup_certs.iter().chain(&info.certificates) {
            budget.charge()?;
            if available
                .certificates
                .iter()
                .any(|known| known == certificate)
            {
                continue;
            }
            available.parsed_certificates.push(
                parse_x509_certificate(certificate)
                    .map_err(|_| KeyResolutionError::InvalidCertificate)?,
            );
            available.certificates.push(certificate.clone());
        }
        let signing_index = available
            .certificates
            .iter()
            .position(|certificate| certificate == signing_der)
            .ok_or(KeyResolutionError::InvalidCertificate)?;
        self.select_valid_x509_path(
            &mut available,
            signing_index,
            trusted_prefix_len,
            trust,
            provider,
            None,
        )?;
        Ok(available)
    }

    fn select_valid_x509_path(
        &self,
        available: &mut X509DataInfo,
        signing_index: usize,
        trusted_prefix_len: usize,
        trust: &crate::policy::KeyTrustPolicy,
        provider: &dyn crate::provider::CryptoProvider,
        selectors: Option<&X509DataInfo>,
    ) -> Result<bool, KeyResolutionError> {
        let candidates = build_x509_certificate_paths_to_trusted_prefix(
            available,
            signing_index,
            trusted_prefix_len,
            trust.max_x509_chain_depth,
            trust.max_x509_candidate_paths,
            provider,
        )
        .map_err(|error| match error {
            X509ChainBuildError::AmbiguousIssuer => KeyResolutionError::AmbiguousCertificate,
            X509ChainBuildError::Provider(error) => {
                KeyResolutionError::Chain(super::X509ChainError::Provider(error))
            }
            X509ChainBuildError::UnsupportedSignatureAlgorithm { oid } => {
                KeyResolutionError::Chain(super::X509ChainError::UnsupportedSignatureAlgorithm {
                    oid,
                })
            }
            _ => KeyResolutionError::InvalidCertificate,
        })?;
        let mut first_error = None;
        let mut valid_path_without_selector_match = false;
        for candidate in candidates {
            available.certificate_chain = candidate;
            match self.verify_x509_policy(available, trust, provider) {
                Ok(()) => {
                    if match selectors {
                        Some(selectors) => {
                            selected_x509_path_matches_selectors(available, selectors, provider)?
                        }
                        None => true,
                    } {
                        return Ok(true);
                    }
                    valid_path_without_selector_match = true;
                }
                Err(error) => {
                    first_error.get_or_insert(error);
                }
            }
        }
        if valid_path_without_selector_match {
            return Ok(false);
        }
        Err(first_error.unwrap_or(KeyResolutionError::Chain(
            super::X509ChainError::UntrustedRoot,
        )))
    }

    fn select_x509_selector_path(
        &self,
        available: &mut X509DataInfo,
        signing_index: usize,
        matching_indices: &[usize],
        trust: &crate::policy::KeyTrustPolicy,
        provider: &dyn crate::provider::CryptoProvider,
        selectors: &X509DataInfo,
    ) -> Result<bool, KeyResolutionError> {
        let targets = matching_indices
            .iter()
            .copied()
            .filter(|index| *index != signing_index)
            .collect::<Vec<_>>();
        if targets.is_empty() {
            return Ok(false);
        }
        let candidates = build_x509_certificate_paths_to_selector_targets(
            available,
            signing_index,
            &targets,
            trust.max_x509_chain_depth,
            trust.max_x509_candidate_paths,
            provider,
        )
        .map_err(|error| match error {
            X509ChainBuildError::AmbiguousIssuer => KeyResolutionError::AmbiguousCertificate,
            X509ChainBuildError::Provider(error) => {
                KeyResolutionError::Chain(super::X509ChainError::Provider(error))
            }
            X509ChainBuildError::UnsupportedSignatureAlgorithm { oid } => {
                KeyResolutionError::Chain(super::X509ChainError::UnsupportedSignatureAlgorithm {
                    oid,
                })
            }
            _ => KeyResolutionError::InvalidCertificate,
        })?;
        for candidate in candidates {
            available.certificate_chain = candidate;
            if selected_x509_path_matches_selectors(available, selectors, provider)? {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn resolve_configured_x509(
        &self,
        info: &X509DataInfo,
        trust: &crate::policy::KeyTrustPolicy,
        provider: &dyn crate::provider::CryptoProvider,
        budget: &mut InspectedKeyCandidateBudget,
    ) -> Result<Option<X509DataInfo>, DsigError> {
        if !x509_data_has_lookup_identifiers(info) {
            return Ok(None);
        }

        let mut available = X509DataInfo {
            subject_names: info.subject_names.clone(),
            issuer_serials: info.issuer_serials.clone(),
            skis: info.skis.clone(),
            crls: info.crls.clone(),
            digests: info.digests.clone(),
            ..X509DataInfo::default()
        };
        let mut matches = Vec::new();
        let mut trusted_prefix_len = 0usize;
        for (trusted, certificate_der) in self
            .config
            .trusted_certs
            .iter()
            .map(|certificate| (true, certificate))
            .chain(
                self.config
                    .lookup_certs
                    .iter()
                    .map(|certificate| (false, certificate)),
            )
        {
            budget.charge()?;
            if available
                .certificates
                .iter()
                .any(|available_der| available_der == certificate_der)
            {
                continue;
            }
            let parsed = parse_x509_certificate(certificate_der)
                .map_err(|_| KeyResolutionError::InvalidCertificate)?;
            let is_match =
                x509_certificate_matches_any_selector(info, &parsed, certificate_der, provider)
                    .map_err(map_x509_selector_error)?;
            if is_match {
                matches.push((available.certificates.len(), parsed.clone()));
            }
            available.certificates.push(certificate_der.clone());
            available.parsed_certificates.push(parsed);
            if trusted {
                trusted_prefix_len += 1;
            }
        }

        let matched_chain = X509DataInfo {
            certificates: matches
                .iter()
                .map(|(index, _)| available.certificates[*index].clone())
                .collect(),
            parsed_certificates: matches.iter().map(|(_, parsed)| parsed.clone()).collect(),
            ..X509DataInfo::default()
        };
        if !x509_selector_categories_match_chain(
            &X509DataInfo {
                subject_names: info.subject_names.clone(),
                issuer_serials: info.issuer_serials.clone(),
                skis: info.skis.clone(),
                digests: info.digests.clone(),
                ..matched_chain
            },
            provider,
        )
        .map_err(map_x509_selector_error)?
        {
            return Ok(None);
        }

        let signing_index = match matches.as_slice() {
            [] => return Ok(None),
            [(index, _)] => *index,
            _ => {
                let leaves = matches
                    .iter()
                    .filter(|(_, candidate)| {
                        !distinguished_names_equal(&candidate.subject_dn, &candidate.issuer_dn)
                            && !matches.iter().any(|(_, other)| {
                                distinguished_names_equal(&other.issuer_dn, &candidate.subject_dn)
                            })
                    })
                    .collect::<Vec<_>>();
                match leaves.as_slice() {
                    [(index, _)] => *index,
                    _ => return Err(KeyResolutionError::AmbiguousCertificate.into()),
                }
            }
        };
        let matching_indices = matches.iter().map(|(index, _)| *index).collect::<Vec<_>>();
        // `available` preserves trusted certificates as a prefix. Selecting
        // one of those exact certificates is already a terminal trust
        // decision, even when the certificate is not self-signed.
        available.certificate_chain =
            if signing_index < trusted_prefix_len || !trust.verify_x509_chains {
                vec![signing_index]
            } else {
                if !self.select_valid_x509_path(
                    &mut available,
                    signing_index,
                    trusted_prefix_len,
                    trust,
                    provider,
                    Some(info),
                )? {
                    return Ok(None);
                }
                available.certificate_chain.clone()
            };
        if trust.verify_x509_chains && signing_index < trusted_prefix_len {
            self.verify_x509_policy(&available, trust, provider)?;
        }
        if !trust.verify_x509_chains || signing_index < trusted_prefix_len {
            let direct_match = selected_x509_path_matches_selectors(&available, info, provider)?;
            if !direct_match
                && (signing_index < trusted_prefix_len
                    || !self.select_x509_selector_path(
                        &mut available,
                        signing_index,
                        &matching_indices,
                        trust,
                        provider,
                        info,
                    )?)
            {
                return Ok(None);
            }
        }
        Ok(Some(available))
    }

    fn resolve_key_value(
        key_value: &KeyValueInfo,
        algorithm: SignatureAlgorithm,
    ) -> Result<Option<VerificationKey>, KeyResolutionError> {
        let public_key_bytes = match key_value {
            KeyValueInfo::Dsa { p, q, g, y } => {
                if !matches!(
                    algorithm,
                    SignatureAlgorithm::DsaSha1 | SignatureAlgorithm::DsaSha256
                ) {
                    return Err(KeyResolutionError::AlgorithmMismatch);
                }
                let (Some(p), Some(q), Some(g)) = (p.as_deref(), q.as_deref(), g.as_deref()) else {
                    return Err(KeyResolutionError::InvalidPublicKey);
                };
                dsa_key_value_to_spki_der(p, q, g, y)?
            }
            KeyValueInfo::Rsa { modulus, exponent } => {
                if !matches!(
                    algorithm,
                    SignatureAlgorithm::RsaSha1
                        | SignatureAlgorithm::RsaSha224
                        | SignatureAlgorithm::RsaSha256
                        | SignatureAlgorithm::RsaSha384
                        | SignatureAlgorithm::RsaSha512
                ) {
                    return Err(KeyResolutionError::AlgorithmMismatch);
                }
                rsa_key_value_to_spki_der(modulus, exponent)?
            }
            KeyValueInfo::Ec {
                curve_oid,
                public_key,
            } => {
                if !matches!(
                    algorithm,
                    SignatureAlgorithm::EcdsaSha1
                        | SignatureAlgorithm::EcdsaSha224
                        | SignatureAlgorithm::EcdsaSha256
                        | SignatureAlgorithm::EcdsaSha384
                        | SignatureAlgorithm::EcdsaSha512
                ) {
                    return Ok(None);
                }
                ec_key_value_to_spki_der(curve_oid, public_key)?
            }
            KeyValueInfo::InvalidEcKeyValue => return Err(KeyResolutionError::InvalidPublicKey),
            KeyValueInfo::Unsupported { .. } => return Ok(None),
        };
        validate_spki_algorithm(&public_key_bytes, algorithm)?;

        Ok(Some(VerificationKey {
            algorithm,
            public_key_bytes,
            certificate_der: None,
            name: None,
        }))
    }

    fn resolve_with_trust<'a>(
        &'a self,
        key_info: Option<&KeyInfo>,
        algorithm: SignatureAlgorithm,
        sources: crate::policy::KeySourcePolicy,
        trust: &crate::policy::KeyTrustPolicy,
        resources: &crate::policy::ResourcePolicy,
        provider: &dyn crate::provider::CryptoProvider,
    ) -> Result<Option<Box<dyn VerifyingKey + 'a>>, DsigError> {
        trust.validate()?;
        resources.validate()?;
        let Some(key_info) = key_info else {
            return Ok(None);
        };
        validate_key_info_source_permissions(key_info, sources)?;
        let mut candidate_budget = InspectedKeyCandidateBudget::new(resources.max_key_candidates);
        let mut deferred_key_value_error = None;
        for source in &key_info.sources {
            let resolved = match source {
                KeyInfoSource::X509Data(info) => {
                    self.resolve_x509(info, algorithm, trust, provider, &mut candidate_budget)?
                }
                KeyInfoSource::DerEncodedKeyValue(public_key_bytes) => {
                    candidate_budget.charge()?;
                    validate_spki_algorithm(public_key_bytes, algorithm)?;
                    Some(VerificationKey {
                        algorithm,
                        public_key_bytes: public_key_bytes.clone(),
                        certificate_der: None,
                        name: None,
                    })
                }
                KeyInfoSource::KeyName(name) => {
                    candidate_budget.charge()?;
                    self.config
                        .named_keys
                        .get(name)
                        .map(|key| {
                            if key.algorithm != algorithm {
                                return Err(KeyResolutionError::AlgorithmMismatch);
                            }
                            validate_spki_algorithm(&key.public_key_bytes, algorithm)?;
                            Ok(key.clone())
                        })
                        .transpose()?
                }
                KeyInfoSource::KeyValue(key_value) => {
                    candidate_budget.charge()?;
                    match Self::resolve_key_value(key_value, algorithm) {
                        Ok(resolved) => resolved,
                        Err(error) if key_value_error_allows_fallback(key_value, &error) => {
                            deferred_key_value_error.get_or_insert(error);
                            None
                        }
                        Err(error) => return Err(error.into()),
                    }
                }
                KeyInfoSource::RetrievalMethod { .. } => {
                    candidate_budget.charge()?;
                    None
                }
                KeyInfoSource::KeyInfoReference { .. } => {
                    candidate_budget.charge()?;
                    None
                }
            };
            if let Some(key) = resolved {
                return Ok(Some(Box::new(PolicyBoundVerificationKey {
                    key,
                    rsa_minimum_bits: trust.rsa_keys.minimum_modulus_bits,
                    dsa_minimum_bits: trust.dsa_keys.minimum_modulus_bits,
                })));
            }
        }
        if let Some(error) = deferred_key_value_error {
            return Err(error.into());
        }
        Ok(None)
    }
}

impl KeyResolver for DefaultKeyResolver {
    fn resolve<'a>(
        &'a self,
        key_info: Option<&KeyInfo>,
        algorithm: SignatureAlgorithm,
    ) -> Result<Option<Box<dyn VerifyingKey + 'a>>, DsigError> {
        let policy = crate::policy::VerificationPolicy::default();
        self.resolve_with_trust(
            key_info,
            algorithm,
            policy.key_sources,
            &policy.key_trust,
            &policy.resources,
            crate::provider::default_provider(),
        )
    }

    fn resolve_with_policy<'a>(
        &'a self,
        key_info: Option<&KeyInfo>,
        algorithm: SignatureAlgorithm,
        policy: &crate::policy::VerificationPolicy,
    ) -> Result<Option<Box<dyn VerifyingKey + 'a>>, DsigError> {
        self.resolve_with_policy_and_provider(
            key_info,
            algorithm,
            policy,
            crate::provider::default_provider(),
        )
    }

    fn resolve_with_policy_and_provider<'a>(
        &'a self,
        key_info: Option<&KeyInfo>,
        algorithm: SignatureAlgorithm,
        policy: &crate::policy::VerificationPolicy,
        provider: &dyn crate::provider::CryptoProvider,
    ) -> Result<Option<Box<dyn VerifyingKey + 'a>>, DsigError> {
        self.resolve_with_trust(
            key_info,
            algorithm,
            policy.key_sources,
            &policy.key_trust,
            &policy.resources,
            provider,
        )
    }

    fn consumes_document_key_info(&self) -> bool {
        true
    }
}

fn map_x509_selector_error(error: ParseError) -> DsigError {
    match error {
        ParseError::Provider(error) => DsigError::Provider(error),
        ParseError::UnsupportedAlgorithm { uri } => {
            KeyResolutionError::UnsupportedDigestAlgorithm(uri).into()
        }
        _ => KeyResolutionError::InvalidCertificate.into(),
    }
}

fn selected_x509_path_matches_selectors(
    available: &X509DataInfo,
    selectors: &X509DataInfo,
    provider: &dyn crate::provider::CryptoProvider,
) -> Result<bool, KeyResolutionError> {
    let selected = X509DataInfo {
        subject_names: selectors.subject_names.clone(),
        issuer_serials: selectors.issuer_serials.clone(),
        skis: selectors.skis.clone(),
        digests: selectors.digests.clone(),
        certificates: available
            .certificate_chain
            .iter()
            .map(|index| available.certificates[*index].clone())
            .collect(),
        parsed_certificates: available
            .certificate_chain
            .iter()
            .map(|index| available.parsed_certificates[*index].clone())
            .collect(),
        ..X509DataInfo::default()
    };
    x509_selector_categories_match_chain(&selected, provider).map_err(|error| match error {
        ParseError::Provider(error) => {
            KeyResolutionError::Chain(super::X509ChainError::Provider(error))
        }
        ParseError::UnsupportedAlgorithm { uri } => {
            KeyResolutionError::UnsupportedDigestAlgorithm(uri)
        }
        _ => KeyResolutionError::InvalidCertificate,
    })
}

fn rsa_key_value_to_spki_der(
    modulus: &[u8],
    exponent: &[u8],
) -> Result<Vec<u8>, KeyResolutionError> {
    let key = rsa::RsaPublicKey::new(
        BoxedUint::from_be_slice_vartime(modulus),
        BoxedUint::from_be_slice_vartime(exponent),
    )
    .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    key.to_public_key_der()
        .map_err(|_| KeyResolutionError::InvalidPublicKey)
        .map(|der| der.as_bytes().to_vec())
}

fn dsa_key_value_to_spki_der(
    p: &[u8],
    q: &[u8],
    g: &[u8],
    y: &[u8],
) -> Result<Vec<u8>, KeyResolutionError> {
    let components = dsa::Components::from_components(
        BoxedUint::from_be_slice_vartime(p),
        BoxedUint::from_be_slice_vartime(q),
        BoxedUint::from_be_slice_vartime(g),
    )
    .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    dsa::VerifyingKey::from_components(components, BoxedUint::from_be_slice_vartime(y))
        .map_err(|_| KeyResolutionError::InvalidPublicKey)?
        .to_public_key_der()
        .map_err(|_| KeyResolutionError::InvalidPublicKey)
        .map(|der| der.as_bytes().to_vec())
}

fn ec_key_value_to_spki_der(
    curve_oid: &str,
    public_key: &[u8],
) -> Result<Vec<u8>, KeyResolutionError> {
    match curve_oid {
        EC_P256_OID => p256::PublicKey::from_sec1_bytes(public_key)
            .map_err(|_| KeyResolutionError::InvalidPublicKey)?
            .to_public_key_der()
            .map_err(|_| KeyResolutionError::InvalidPublicKey)
            .map(|der| der.as_bytes().to_vec()),
        EC_P384_OID => p384::PublicKey::from_sec1_bytes(public_key)
            .map_err(|_| KeyResolutionError::InvalidPublicKey)?
            .to_public_key_der()
            .map_err(|_| KeyResolutionError::InvalidPublicKey)
            .map(|der| der.as_bytes().to_vec()),
        EC_P521_OID => p521::PublicKey::from_sec1_bytes(public_key)
            .map_err(|_| KeyResolutionError::InvalidPublicKey)?
            .to_public_key_der()
            .map_err(|_| KeyResolutionError::InvalidPublicKey)
            .map(|der| der.as_bytes().to_vec()),
        _ => Err(KeyResolutionError::InvalidPublicKey),
    }
}

fn key_value_error_allows_fallback(key_value: &KeyValueInfo, error: &KeyResolutionError) -> bool {
    matches!(
        key_value,
        KeyValueInfo::Dsa { .. } | KeyValueInfo::Ec { .. } | KeyValueInfo::InvalidEcKeyValue
    ) && matches!(
        error,
        KeyResolutionError::InvalidPublicKey | KeyResolutionError::AlgorithmMismatch
    )
}

fn validate_spki_algorithm(
    public_key_bytes: &[u8],
    algorithm: SignatureAlgorithm,
) -> Result<(), KeyResolutionError> {
    let (rest, spki) = SubjectPublicKeyInfo::from_der(public_key_bytes)
        .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    if !rest.is_empty() {
        return Err(KeyResolutionError::InvalidPublicKey);
    }
    let parsed = spki
        .parsed()
        .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    let curve_oid = spki
        .algorithm
        .parameters
        .as_ref()
        .and_then(|value| value.as_oid().ok())
        .map(|oid| oid.to_id_string());
    match (algorithm, parsed) {
        (SignatureAlgorithm::DsaSha1 | SignatureAlgorithm::DsaSha256, PublicKey::DSA(_)) => {
            let _ = dsa::VerifyingKey::from_public_key_der(public_key_bytes)
                .map_err(|_| KeyResolutionError::AlgorithmMismatch)?;
            Ok(())
        }
        (
            SignatureAlgorithm::RsaSha1
            | SignatureAlgorithm::RsaSha224
            | SignatureAlgorithm::RsaSha256
            | SignatureAlgorithm::RsaSha384
            | SignatureAlgorithm::RsaSha512,
            PublicKey::RSA(_),
        ) => Ok(()),
        (
            SignatureAlgorithm::EcdsaSha1
            | SignatureAlgorithm::EcdsaSha224
            | SignatureAlgorithm::EcdsaSha256
            | SignatureAlgorithm::EcdsaSha384
            | SignatureAlgorithm::EcdsaSha512,
            PublicKey::EC(_),
        ) if matches!(
            curve_oid.as_deref(),
            Some(EC_P256_OID | EC_P384_OID | EC_P521_OID)
        ) =>
        {
            Ok(())
        }
        _ => Err(KeyResolutionError::AlgorithmMismatch),
    }
}

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

    use base64::{Engine, engine::general_purpose::STANDARD};
    use rsa::{pkcs8::DecodePublicKey, traits::PublicKeyParts};

    use super::*;

    struct RejectSecondSha512Provider {
        sha512_calls: AtomicUsize,
        verification_calls: AtomicUsize,
        reject_verification_call: Option<usize>,
        rejected_verification_data: Option<Vec<u8>>,
    }

    impl crate::provider::CryptoProvider for RejectSecondSha512Provider {
        fn name(&self) -> &'static str {
            "reject-second-sha512"
        }

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

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

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

        fn digest(
            &self,
            algorithm: super::super::DigestAlgorithm,
            data: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            if algorithm == super::super::DigestAlgorithm::Sha512
                && self.sha512_calls.fetch_add(1, Ordering::Relaxed) > 0
            {
                return Err(crate::provider::ProviderError::Unsupported {
                    operation: crate::provider::ProviderOperation::Digest,
                    algorithm: Some(algorithm.uri().to_owned()),
                });
            }
            crate::provider::default_provider().digest(algorithm, data)
        }

        fn sign(
            &self,
            key: &dyn super::super::SigningKey,
            algorithm: SignatureAlgorithm,
            data: &[u8],
        ) -> Result<Vec<u8>, super::super::SigningKeyError> {
            crate::provider::default_provider().sign(key, algorithm, data)
        }

        fn verify(
            &self,
            key: &dyn VerifyingKey,
            algorithm: SignatureAlgorithm,
            data: &[u8],
            signature: &[u8],
        ) -> Result<bool, DsigError> {
            let call = self.verification_calls.fetch_add(1, Ordering::Relaxed);
            if self.reject_verification_call == Some(call)
                || self
                    .rejected_verification_data
                    .as_deref()
                    .is_some_and(|rejected| rejected == data)
            {
                return Err(crate::provider::ProviderError::Unsupported {
                    operation: crate::provider::ProviderOperation::Verify,
                    algorithm: Some(algorithm.uri().to_owned()),
                }
                .into());
            }
            crate::provider::default_provider().verify(key, algorithm, data, signature)
        }

        fn verify_x509_signature(
            &self,
            algorithm: crate::provider::X509SignatureAlgorithm,
            data: &[u8],
            signature: &[u8],
            issuer_spki_der: &[u8],
        ) -> Result<bool, crate::provider::ProviderError> {
            let call = self.verification_calls.fetch_add(1, Ordering::Relaxed);
            if self.reject_verification_call == Some(call)
                || self
                    .rejected_verification_data
                    .as_deref()
                    .is_some_and(|rejected| rejected == data)
            {
                return Err(crate::provider::ProviderError::Unsupported {
                    operation: crate::provider::ProviderOperation::VerifyCertificate,
                    algorithm: Some(algorithm.oid().to_owned()),
                });
            }
            crate::provider::default_provider().verify_x509_signature(
                algorithm,
                data,
                signature,
                issuer_spki_der,
            )
        }

        #[cfg(feature = "xmlenc")]
        fn encrypt_data(
            &self,
            algorithm: crate::xmlenc::DataEncryptionAlgorithm,
            key: &[u8],
            plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().encrypt_data(algorithm, key, plaintext)
        }

        #[cfg(feature = "xmlenc")]
        fn decrypt_data(
            &self,
            algorithm: crate::xmlenc::DataEncryptionAlgorithm,
            key: &[u8],
            ciphertext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().decrypt_data(algorithm, key, ciphertext)
        }

        #[cfg(feature = "xmlenc")]
        fn wrap_key(
            &self,
            algorithm: crate::xmlenc::KeyWrapAlgorithm,
            kek: &[u8],
            key: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().wrap_key(algorithm, kek, key)
        }

        #[cfg(feature = "xmlenc")]
        fn unwrap_key(
            &self,
            algorithm: crate::xmlenc::KeyWrapAlgorithm,
            kek: &[u8],
            wrapped: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().unwrap_key(algorithm, kek, wrapped)
        }

        #[cfg(feature = "xmlenc")]
        fn transport_key(
            &self,
            key: &dyn crate::provider::KeyTransportKey,
            parameters: &crate::xmlenc::RsaOaepParameters,
            plaintext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().transport_key(key, parameters, plaintext)
        }

        #[cfg(feature = "xmlenc")]
        fn recover_key(
            &self,
            key: &dyn crate::provider::KeyRecoveryKey,
            parameters: &crate::xmlenc::RsaOaepParameters,
            ciphertext: &[u8],
        ) -> Result<Vec<u8>, crate::provider::ProviderError> {
            crate::provider::default_provider().recover_key(key, parameters, ciphertext)
        }
    }

    fn chain_policy() -> crate::policy::KeyTrustPolicy {
        crate::policy::KeyTrustPolicy {
            verify_x509_chains: true,
            ..crate::policy::KeyTrustPolicy::default()
        }
    }

    fn chain_policy_at(verification_time: SystemTime) -> crate::policy::KeyTrustPolicy {
        crate::policy::KeyTrustPolicy {
            verification_time: Some(verification_time),
            ..chain_policy()
        }
    }

    fn verification_policy_with_trust(
        key_trust: crate::policy::KeyTrustPolicy,
    ) -> crate::policy::VerificationPolicy {
        crate::policy::VerificationPolicy {
            key_trust,
            ..crate::policy::VerificationPolicy::default()
        }
    }

    const SIGNED_SAML: &str =
        include_str!("../../tests/fixtures/saml/response_signed_by_idp_ecdsa.xml");
    const SAML_PUBLIC_KEY: &str =
        include_str!("../../tests/fixtures/keys/ec/saml-idp-ecdsa-pubkey.pem");
    const RSA_PUBLIC_KEY: &str = include_str!("../../tests/fixtures/keys/rsa/rsa-2048-pubkey.pem");
    const RSA_4096_CERTIFICATE: &str =
        include_str!("../../tests/fixtures/keys/rsa/rsa-4096-cert.pem");
    const X509_DIGEST_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/aleksey-xmldsig-01/enveloped-x509-digest-sha512.xml"
    );
    const X509_DIGEST_SHA256_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/aleksey-xmldsig-01/enveloped-x509-digest-sha256.xml"
    );
    const RSA_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/aleksey-xmldsig-01/enveloping-sha256-rsa-sha256.xml"
    );
    const LEGACY_RSA_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/signature-enveloping-rsa.xml"
    );
    const EC_P256_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/xmldsig11-interop-2012/signature-enveloping-p256_sha256.xml"
    );
    const EC_P384_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/xmldsig11-interop-2012/signature-enveloping-p384_sha384.xml"
    );

    fn replace_key_info(xml: &str, replacement: &str) -> String {
        let start = xml.find("<ds:KeyInfo>").expect("fixture has KeyInfo");
        let end = xml
            .find("</ds:KeyInfo>")
            .expect("fixture has closing KeyInfo")
            + "</ds:KeyInfo>".len();
        format!("{}{}{}", &xml[..start], replacement, &xml[end..])
    }

    fn replace_unprefixed_key_info(xml: &str, replacement: &str) -> String {
        let start = xml.find("<KeyInfo>").expect("fixture has KeyInfo");
        let end = xml.find("</KeyInfo>").expect("fixture has closing KeyInfo") + "</KeyInfo>".len();
        format!("{}{}{}", &xml[..start], replacement, &xml[end..])
    }

    fn rsa_key_value_parts(public_key: &rsa::RsaPublicKey) -> (String, String) {
        (
            STANDARD.encode(public_key.n().to_be_bytes_trimmed_vartime()),
            STANDARD.encode(public_key.e().to_be_bytes_trimmed_vartime()),
        )
    }

    fn x509_signature_with_leaf_subject() -> String {
        replace_unprefixed_key_info(
            X509_DIGEST_SIGNATURE,
            "<KeyInfo><X509Data><X509SubjectName>CN=Test Key rsa-4096,O=XML Security Library (http://www.aleksey.com/xmlsec),ST=California,C=US</X509SubjectName></X509Data></KeyInfo>",
        )
    }

    fn fixture_certificate_time() -> SystemTime {
        // 2027-01-15 UTC, inside the donor certificates' 2026-2126 validity window.
        SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000)
    }

    fn public_key_der(pem_text: &str) -> Vec<u8> {
        let (rest, pem) = x509_parser::pem::parse_x509_pem(pem_text.as_bytes())
            .expect("fixture public key is PEM");
        assert!(rest.iter().all(|byte| byte.is_ascii_whitespace()));
        assert_eq!(pem.label, "PUBLIC KEY");
        pem.contents
    }

    fn certificate_der(pem_text: &str) -> Vec<u8> {
        let (rest, pem) = x509_parser::pem::parse_x509_pem(pem_text.as_bytes())
            .expect("fixture certificate is PEM");
        assert!(rest.iter().all(|byte| byte.is_ascii_whitespace()));
        assert_eq!(pem.label, "CERTIFICATE");
        pem.contents
    }

    fn crl_der(pem_text: &str) -> Vec<u8> {
        let (rest, pem) =
            x509_parser::pem::parse_x509_pem(pem_text.as_bytes()).expect("fixture CRL is PEM");
        assert!(rest.iter().all(|byte| byte.is_ascii_whitespace()));
        assert_eq!(pem.label, "X509 CRL");
        pem.contents
    }

    fn generated_certificate_params(common_name: &str, is_ca: bool) -> rcgen::CertificateParams {
        let mut params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty SAN list should produce valid certificate parameters");
        params
            .distinguished_name
            .push(rcgen::DnType::CommonName, common_name);
        if is_ca {
            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
            params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        }
        params
    }

    fn x509_info(certificates: Vec<Vec<u8>>, signing_index: usize) -> X509DataInfo {
        let parsed_certificates = certificates
            .iter()
            .map(|certificate| {
                parse_x509_certificate(certificate)
                    .expect("generated certificate should have supported metadata")
            })
            .collect();
        X509DataInfo {
            certificates,
            parsed_certificates,
            certificate_chain: vec![signing_index],
            ..X509DataInfo::default()
        }
    }

    #[test]
    fn defaults_match_key_resolution_policy() {
        // Defaults must remain compatible with xmlsec1's depth and opt-in trust policy.
        let config = KeyResolverConfig::default();

        assert!(config.trusted_certs.is_empty());
        assert!(config.lookup_certs.is_empty());
        assert!(config.named_keys.is_empty());
        let trust = crate::policy::VerificationPolicy::default().key_trust;
        assert!(!trust.verify_x509_chains);
        assert!(!trust.check_crls);
        assert_eq!(trust.verification_time, None);
        assert_eq!(trust.max_x509_chain_depth, 9);
    }

    #[test]
    fn verification_policy_controls_leaf_extended_key_usage() {
        // The immutable operation snapshot must reach certificate-path
        // validation; resolver-local trust defaults cannot bypass EKU policy.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("EKU policy root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("TLS-only XML signer", false);
        leaf_params.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature];
        leaf_params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth];
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign leaf certificate");
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(x509_info(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                0,
            ))],
        };
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![root.der().to_vec()],
            ..KeyResolverConfig::default()
        });
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.key_trust.verify_x509_chains = true;

        let error = match resolver.resolve_with_policy(
            Some(&key_info),
            SignatureAlgorithm::EcdsaSha256,
            &policy,
        ) {
            Ok(_) => panic!("unapproved restricted EKU must be rejected"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::InvalidKeyUsage {
                    position: 0,
                    required: "an approved extended key usage",
                }
            ))
        ));

        policy.key_trust.allowed_extended_key_usages =
            std::collections::HashSet::from([crate::policy::ExtendedKeyPurpose::ServerAuth]);
        assert!(
            resolver
                .resolve_with_policy(Some(&key_info), SignatureAlgorithm::EcdsaSha256, &policy,)
                .expect("approved restricted EKU must pass path validation")
                .is_some()
        );
    }

    #[test]
    fn operation_policy_rejects_zero_x509_resource_limits() {
        // X.509 work limits belong to the immutable operation snapshot and are
        // rejected before resolver-owned certificate material is inspected.
        for trust in [
            crate::policy::KeyTrustPolicy {
                verify_x509_chains: true,
                max_x509_chain_depth: 0,
                ..crate::policy::KeyTrustPolicy::default()
            },
            crate::policy::KeyTrustPolicy {
                verify_x509_chains: true,
                max_x509_candidate_paths: 0,
                ..crate::policy::KeyTrustPolicy::default()
            },
        ] {
            let certificate = certificate_der(RSA_4096_CERTIFICATE);
            let resolver = DefaultKeyResolver::new(KeyResolverConfig {
                trusted_certs: vec![certificate],
                ..KeyResolverConfig::default()
            });
            let policy = crate::policy::VerificationPolicy {
                key_trust: trust,
                ..crate::policy::VerificationPolicy::default()
            };
            let error = super::super::VerifyContext::new()
                .policy(policy)
                .key_resolver(&resolver)
                .verify(&x509_signature_with_leaf_subject())
                .expect_err("zero composed X.509 limits must fail as policy errors");

            assert!(matches!(
                error,
                DsigError::Policy(crate::policy::PolicyViolation::InvalidResourceLimit {
                    requirement: "limit must be nonzero",
                    actual: 0,
                    ..
                })
            ));
        }
    }

    #[test]
    fn operation_policy_rejects_crl_checking_without_chain_validation() {
        // CRL authentication is part of path validation. A resolver must not
        // accept a configuration that would silently skip the requested check.
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate_der(RSA_4096_CERTIFICATE)],
            ..KeyResolverConfig::default()
        });
        let policy = crate::policy::VerificationPolicy {
            key_trust: crate::policy::KeyTrustPolicy {
                check_crls: true,
                ..crate::policy::KeyTrustPolicy::default()
            },
            ..crate::policy::VerificationPolicy::default()
        };
        let error = super::super::VerifyContext::new()
            .policy(policy)
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("CRL-only trust policy must fail before certificate use");

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::KeyTrust {
                reason: "CRL checking requires X.509 chain validation"
            })
        ));
    }

    #[test]
    fn hmac_key_rejects_empty_secret_and_wrong_algorithm() {
        // HMAC secrets are caller-owned and cannot be reused as asymmetric keys.
        assert!(matches!(
            HmacSha1VerificationKey::new(Vec::new()),
            Err(KeyResolutionError::InvalidPublicKey)
        ));
        let key = HmacSha1VerificationKey::new(b"secret".to_vec())
            .expect("non-empty HMAC secret must be accepted");
        assert!(matches!(
            key.verify(SignatureAlgorithm::RsaSha256, b"data", b"signature"),
            Err(DsigError::KeyResolution(
                KeyResolutionError::AlgorithmMismatch
            ))
        ));
    }

    #[test]
    fn hmac_key_uses_the_operation_policy_for_truncation() {
        // Output length belongs to SignatureMethod and operation policy, not
        // reusable secret key material. Legacy truncation therefore requires
        // an explicit compatibility policy even on the policy-aware key hook.
        let key = HmacVerificationKey::new(b"secret".to_vec())
            .expect("the fixture HMAC secret is non-empty");
        let mut mac = hmac::Hmac::<sha1::Sha1>::new_from_slice(b"secret")
            .expect("HMAC accepts an arbitrary non-empty secret");
        mac.update(b"data");
        let expected = mac.finalize().into_bytes();

        let policy = crate::policy::VerificationPolicy {
            hmac: crate::policy::HmacPolicy {
                minimum_key_bits: 40,
                minimum_output_bits: 80,
            },
            ..crate::policy::VerificationPolicy::default()
        };
        assert!(
            key.verify_with_policy(
                &policy,
                SignatureAlgorithm::HmacSha1,
                b"data",
                &expected[..10],
            )
            .expect("the compatibility policy and algorithm match")
        );
        assert!(
            !key.verify_with_policy(&policy, SignatureAlgorithm::HmacSha1, b"data", &[0_u8; 10],)
                .expect("a mismatched truncated MAC must be rejected")
        );
    }

    #[test]
    fn hmac_key_direct_api_rejects_attacker_selected_short_output() {
        // The policy-free trait method applies secure defaults; signature bytes
        // cannot act as their own one-byte truncation declaration.
        let key = HmacVerificationKey::new([0x42; 16]).expect("fixed HMAC key must parse");
        let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(&[0x42; 16])
            .expect("HMAC accepts the fixed secret");
        mac.update(b"data");
        let expected = mac.finalize().into_bytes();

        assert!(matches!(
            key.verify(SignatureAlgorithm::HmacSha256, b"data", &expected[..1]),
            Err(DsigError::Policy(
                crate::policy::PolicyViolation::HmacOutputLength {
                    minimum: 128,
                    maximum: 256,
                    actual: 8,
                }
            ))
        ));
    }

    #[test]
    fn hmac_key_debug_redacts_secret_material() {
        // Debug output may expose public verification parameters, never caller secrets.
        let secret = b"unique-debug-secret-marker";
        let key = HmacVerificationKey::new(secret.to_vec())
            .expect("the fixture HMAC secret is non-empty");

        let debug = format!("{key:?}");
        assert!(
            !debug
                .contains(std::str::from_utf8(secret).expect("the debug marker is literal ASCII"))
        );
        assert!(!debug.contains(&format!("{secret:?}")));
        assert!(!debug.contains("output_length_bits"));
    }

    #[test]
    fn stores_named_verification_key_metadata() {
        // Named resolution must retain every field needed by the later resolver wiring.
        let key = VerificationKey {
            algorithm: SignatureAlgorithm::RsaSha256,
            public_key_bytes: vec![1, 2, 3],
            certificate_der: Some(vec![4, 5, 6]),
            name: Some("idp-signing".into()),
        };
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert("idp-signing".into(), key.clone());

        assert_eq!(config.named_keys.get("idp-signing"), Some(&key));
    }

    #[test]
    fn resolves_embedded_certificate_end_to_end() {
        // The default resolver must make parsed X509Data usable by VerifyContext.
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(SIGNED_SAML)
            .expect("embedded certificate should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_x509_digest_from_configured_certificates() {
        // Selector-only X509Data must locate the signing certificate without
        // embedding key material or supplying a preset verification key.
        let leaf_certificate_der = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![leaf_certificate_der],
            trusted_certs: vec![
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                certificate_der(include_str!("../../tests/fixtures/keys/cacert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        for signature in [X509_DIGEST_SHA256_SIGNATURE, X509_DIGEST_SIGNATURE] {
            let result = super::super::VerifyContext::new()
                .key_resolver(&resolver)
                .verify(signature)
                .expect("X509Digest should resolve a configured certificate");

            assert_eq!(result.status, super::super::DsigStatus::Valid);
        }
    }

    #[test]
    fn selector_resolved_certificate_obeys_chain_policy() {
        // Enabling chain verification must apply validity policy even when
        // X509Data contains only selectors and the matching cert is configured.
        let leaf_certificate_der = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![leaf_certificate_der],
            trusted_certs: vec![
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                certificate_der(include_str!("../../tests/fixtures/keys/cacert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .policy(verification_policy_with_trust(chain_policy_at(
                SystemTime::UNIX_EPOCH,
            )))
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("selector-resolved certificate must satisfy chain policy");

        assert!(
            matches!(
                &error,
                DsigError::KeyResolution(KeyResolutionError::Chain(
                    super::super::X509ChainError::CertificateNotValid(_)
                ))
            ),
            "unexpected selector policy error: {error:?}"
        );
    }

    #[test]
    fn selector_resolved_configured_root_remains_a_trust_anchor() {
        // A certificate explicitly configured in trusted_certs remains an
        // anchor when X509Data selects it by subject instead of embedding it.
        let mut params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty SAN list should produce valid certificate parameters");
        params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "configured root");
        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        let key_pair = rcgen::KeyPair::generate().expect("test key generation should succeed");
        let certificate = params
            .self_signed(&key_pair)
            .expect("test root should be self-signable");
        let certificate_der = certificate.der().to_vec();
        let key_info_xml = concat!(
            "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">",
            "<X509Data><X509SubjectName>CN=configured root</X509SubjectName></X509Data>",
            "</KeyInfo>"
        );
        let document = roxmltree::Document::parse(key_info_xml)
            .expect("static selector KeyInfo should parse as XML");
        let key_info = super::super::parse_key_info(document.root_element())
            .expect("static selector KeyInfo should satisfy XMLDSig structure");
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate_der],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("configured self-signed certificate should validate as its own anchor");

        assert!(resolved.is_some());
    }

    #[test]
    fn selector_resolved_non_self_signed_trust_anchor_terminates_the_path() {
        // Trust is assigned to the exact configured certificate, not inferred
        // from self-signing. A lookup-only issuer must not extend that anchor
        // into a new path that requires another trust decision.
        let mut issuer_params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty issuer SAN list should be valid");
        issuer_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "lookup-only issuer");
        issuer_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        issuer_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        let issuer = rcgen::CertifiedIssuer::self_signed(
            issuer_params,
            rcgen::KeyPair::generate().expect("issuer key generation should succeed"),
        )
        .expect("issuer certificate should be self-signable");

        let mut anchor_params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty anchor SAN list should be valid");
        anchor_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "direct trust anchor");
        let anchor = anchor_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("anchor key generation should succeed"),
                &issuer,
            )
            .expect("issuer should sign the directly trusted certificate");
        let key_info_xml = concat!(
            "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">",
            "<X509Data><X509SubjectName>CN=direct trust anchor</X509SubjectName></X509Data>",
            "</KeyInfo>"
        );
        let document = roxmltree::Document::parse(key_info_xml)
            .expect("static selector KeyInfo should parse as XML");
        let key_info = super::super::parse_key_info(document.root_element())
            .expect("static selector KeyInfo should satisfy XMLDSig structure");
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![anchor.der().to_vec()],
            lookup_certs: vec![issuer.der().to_vec()],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("an explicitly trusted selected certificate must terminate its path");

        assert!(resolved.is_some());
    }

    #[test]
    fn selector_resolved_leaf_stops_at_non_self_signed_trust_anchor() {
        // A configured anchor terminates trust even when a lookup certificate
        // could continue the issuer-name chain beyond it.
        let external_issuer = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("external issuer", true),
            rcgen::KeyPair::generate().expect("external issuer key generation should succeed"),
        )
        .expect("external issuer should be self-signable");
        let anchor = rcgen::CertifiedIssuer::signed_by(
            generated_certificate_params("non-self-signed anchor", true),
            rcgen::KeyPair::generate().expect("anchor key generation should succeed"),
            &external_issuer,
        )
        .expect("external issuer should sign the anchor");
        let leaf = generated_certificate_params("anchor leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &anchor,
            )
            .expect("anchor should sign the leaf");
        let leaf_metadata = parse_x509_certificate(leaf.der())
            .expect("generated leaf should have supported metadata");
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                subject_names: vec![leaf_metadata.subject_dn],
                ..X509DataInfo::default()
            })],
        };
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![anchor.der().to_vec()],
            lookup_certs: vec![leaf.der().to_vec(), external_issuer.der().to_vec()],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("path construction must stop at the configured anchor");

        assert!(resolved.is_some());
    }

    #[test]
    fn selector_resolved_leaf_does_not_anchor_itself() {
        // A certificate available for selector lookup is not automatically a
        // trust anchor; chain verification still requires a separate issuer.
        let certificate_der = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate_der],
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .policy(verification_policy_with_trust(chain_policy_at(
                fixture_certificate_time(),
            )))
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("selector-resolved leaf must not trust itself");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::UntrustedRoot
            ))
        ));
    }

    #[test]
    fn selector_resolved_leaf_uses_separate_anchor() {
        // Selector lookup may use the leaf from the configured set, but chain
        // verification must terminate at a different configured certificate.
        let leaf = certificate_der(RSA_4096_CERTIFICATE);
        let issuer = certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem"));
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![leaf],
            trusted_certs: vec![issuer],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .policy(verification_policy_with_trust(chain_policy_at(
                fixture_certificate_time(),
            )))
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect("selector-resolved leaf should chain to its configured issuer");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn selector_resolved_leaf_uses_lookup_intermediate() {
        // Lookup certificates may complete an untrusted path, but only the
        // separately configured root is allowed to establish trust.
        let mut root_params =
            rcgen::CertificateParams::new(Vec::new()).expect("empty root SAN list should be valid");
        root_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "lookup root");
        root_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        root_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root certificate should be self-signable");

        let mut intermediate_params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty intermediate SAN list should be valid");
        intermediate_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "lookup intermediate");
        intermediate_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        intermediate_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        let intermediate = rcgen::CertifiedIssuer::signed_by(
            intermediate_params,
            rcgen::KeyPair::generate().expect("intermediate key generation should succeed"),
            &root,
        )
        .expect("root should sign the intermediate certificate");

        let mut leaf_params =
            rcgen::CertificateParams::new(Vec::new()).expect("empty leaf SAN list should be valid");
        leaf_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "lookup leaf");
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &intermediate,
            )
            .expect("intermediate should sign the leaf certificate");
        let key_info_xml = concat!(
            "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">",
            "<X509Data><X509SubjectName>CN=lookup leaf</X509SubjectName></X509Data>",
            "</KeyInfo>"
        );
        let document = roxmltree::Document::parse(key_info_xml)
            .expect("static selector KeyInfo should parse as XML");
        let key_info = super::super::parse_key_info(document.root_element())
            .expect("static selector KeyInfo should satisfy XMLDSig structure");
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![leaf.der().to_vec(), intermediate.der().to_vec()],
            trusted_certs: vec![root.der().to_vec()],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("selector-resolved leaf should chain through the lookup intermediate");

        assert!(resolved.is_some());
    }

    #[test]
    fn x509_path_signatures_use_the_operation_provider() {
        // Embedded and selector-resolved certificates converge on the same
        // path validator. Neither source may fall back to a crate-global
        // verifier when the operation provider rejects certificate signatures.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("provider root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let leaf = generated_certificate_params("provider leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign the leaf");
        let leaf_der = leaf.der().to_vec();
        let leaf_metadata =
            parse_x509_certificate(&leaf_der).expect("generated leaf metadata should parse");
        let policy = crate::policy::VerificationPolicy {
            key_trust: chain_policy(),
            ..crate::policy::VerificationPolicy::default()
        };

        let cases = [
            (
                KeyInfo {
                    sources: vec![KeyInfoSource::X509Data(x509_info(
                        vec![leaf_der.clone()],
                        0,
                    ))],
                },
                Vec::new(),
            ),
            (
                KeyInfo {
                    sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                        subject_names: vec![leaf_metadata.subject_dn],
                        ..X509DataInfo::default()
                    })],
                },
                vec![leaf_der],
            ),
        ];

        for (key_info, lookup_certs) in cases {
            let provider = RejectSecondSha512Provider {
                sha512_calls: AtomicUsize::new(0),
                verification_calls: AtomicUsize::new(0),
                reject_verification_call: Some(0),
                rejected_verification_data: None,
            };
            let resolver = DefaultKeyResolver::new(KeyResolverConfig {
                trusted_certs: vec![root.der().to_vec()],
                lookup_certs,
                ..KeyResolverConfig::default()
            });
            let error = match resolver.resolve_with_policy_and_provider(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &policy,
                &provider,
            ) {
                Ok(_) => panic!("the operation provider must gate every X.509 path signature"),
                Err(error) => error,
            };

            assert!(matches!(
                error,
                DsigError::KeyResolution(KeyResolutionError::Chain(
                    super::super::X509ChainError::UnsupportedSignatureAlgorithm { ref oid }
                )) if oid == "1.2.840.10045.4.3.2"
            ));
            assert_eq!(provider.verification_calls.load(Ordering::Relaxed), 1);
        }

        // A provider rejection after path construction proves complete-path
        // validation does not switch back to the crate-global provider.
        let provider = RejectSecondSha512Provider {
            sha512_calls: AtomicUsize::new(0),
            verification_calls: AtomicUsize::new(0),
            reject_verification_call: Some(1),
            rejected_verification_data: None,
        };
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![root.der().to_vec()],
            ..KeyResolverConfig::default()
        });
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(x509_info(
                vec![leaf.der().to_vec()],
                0,
            ))],
        };
        let error = match resolver.resolve_with_policy_and_provider(
            Some(&key_info),
            SignatureAlgorithm::EcdsaSha256,
            &policy,
            &provider,
        ) {
            Ok(_) => panic!("complete-path validation must retain the operation provider"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::Provider(_)
            ))
        ));
        assert_eq!(provider.verification_calls.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn embedded_leaf_uses_lookup_intermediate_with_duplicate_anchor() {
        // Deduplicating repeated trust anchors must not shift an untrusted
        // lookup intermediate into the trusted prefix used by path building.
        let trusted_root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("unrelated trusted root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let issuer_root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("untrusted issuer root", true),
            rcgen::KeyPair::generate().expect("issuer root key generation should succeed"),
        )
        .expect("issuer root should be self-signable");
        let intermediate = rcgen::CertifiedIssuer::signed_by(
            generated_certificate_params("embedded intermediate", true),
            rcgen::KeyPair::generate().expect("intermediate key generation should succeed"),
            &issuer_root,
        )
        .expect("issuer root should sign the intermediate");
        let leaf = generated_certificate_params("embedded leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &intermediate,
            )
            .expect("intermediate should sign the leaf");
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(x509_info(
                vec![leaf.der().to_vec()],
                0,
            ))],
        };
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![intermediate.der().to_vec()],
            trusted_certs: vec![trusted_root.der().to_vec(), trusted_root.der().to_vec()],
            ..KeyResolverConfig::default()
        });

        let policy = verification_policy_with_trust(chain_policy());
        let error = match resolver.resolve_with_policy(
            Some(&key_info),
            SignatureAlgorithm::EcdsaSha256,
            &policy,
        ) {
            Ok(_) => panic!("an untrusted lookup intermediate must not become a trust anchor"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::UntrustedRoot
            ))
        ));
    }

    #[test]
    fn selector_resolved_leaf_chooses_unique_valid_same_key_path() {
        // Cross-signing can produce issuer certificates with the same subject
        // and public key. Trust policy, not the immediate signature edge, must
        // select the sole path that reaches a configured anchor.
        let trusted_root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("trusted cross-sign root", true),
            rcgen::KeyPair::generate().expect("trusted root key generation should succeed"),
        )
        .expect("trusted root should be self-signable");
        let untrusted_root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("untrusted cross-sign root", true),
            rcgen::KeyPair::generate().expect("untrusted root key generation should succeed"),
        )
        .expect("untrusted root should be self-signable");
        let shared_params = generated_certificate_params("shared cross-sign issuer", true);
        let shared_key =
            rcgen::KeyPair::generate().expect("shared issuer key generation should succeed");
        let trusted_intermediate = shared_params
            .signed_by(&shared_key, &trusted_root)
            .expect("trusted root should cross-sign the shared issuer key");
        let untrusted_intermediate = shared_params
            .signed_by(&shared_key, &untrusted_root)
            .expect("untrusted root should cross-sign the shared issuer key");
        let shared_issuer = rcgen::Issuer::from_params(&shared_params, &shared_key);
        let leaf = generated_certificate_params("cross-signed leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &shared_issuer,
            )
            .expect("shared issuer key should sign the leaf");
        let leaf_metadata = parse_x509_certificate(leaf.der())
            .expect("generated leaf should have supported metadata");
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                subject_names: vec![leaf_metadata.subject_dn],
                ..X509DataInfo::default()
            })],
        };
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![trusted_root.der().to_vec()],
            lookup_certs: vec![
                leaf.der().to_vec(),
                untrusted_intermediate.der().to_vec(),
                trusted_intermediate.der().to_vec(),
                untrusted_root.der().to_vec(),
            ],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("the sole path to a configured anchor should be selected");

        assert!(resolved.is_some());
    }

    #[test]
    fn self_issued_rollover_continues_to_same_name_trusted_signer() {
        // Subject/issuer name equality does not prove self-signing: rollover
        // certificates may be issued by a distinct same-name trust anchor.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("rollover authority", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let rollover_params = generated_certificate_params("rollover authority", true);
        let rollover_key =
            rcgen::KeyPair::generate().expect("rollover key generation should succeed");
        let rollover_certificate = rollover_params
            .signed_by(&rollover_key, &root)
            .expect("root should sign the same-name rollover certificate");
        let rollover_issuer = rcgen::Issuer::from_params(&rollover_params, &rollover_key);
        let leaf = generated_certificate_params("rollover leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &rollover_issuer,
            )
            .expect("rollover key should sign the leaf");
        let leaf_metadata =
            parse_x509_certificate(leaf.der()).expect("generated leaf metadata should parse");
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                subject_names: vec![leaf_metadata.subject_dn],
                ..X509DataInfo::default()
            })],
        };
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![root.der().to_vec()],
            lookup_certs: vec![leaf.der().to_vec(), rollover_certificate.der().to_vec()],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("same-name rollover path must reach its configured signer");

        assert!(resolved.is_some());
    }

    #[test]
    fn x509_candidate_limit_counts_generated_partial_paths() {
        // A narrow DFS frontier can still generate unbounded partial paths over
        // time, so the resource limit must account for every generated state.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("candidate root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let intermediate = rcgen::CertifiedIssuer::signed_by(
            generated_certificate_params("candidate intermediate", true),
            rcgen::KeyPair::generate().expect("intermediate key generation should succeed"),
            &root,
        )
        .expect("root should sign the intermediate");
        let leaf = generated_certificate_params("candidate leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &intermediate,
            )
            .expect("intermediate should sign the leaf");
        let info = x509_info(
            vec![
                root.der().to_vec(),
                intermediate.der().to_vec(),
                leaf.der().to_vec(),
            ],
            2,
        );

        assert!(matches!(
            build_x509_certificate_paths_to_trusted_prefix(
                &info,
                2,
                1,
                9,
                2,
                crate::provider::default_provider(),
            ),
            Err(X509ChainBuildError::AmbiguousIssuer)
        ));
    }

    #[test]
    fn selector_resolved_leaf_disambiguates_same_subject_issuers_by_signature() {
        // Certificate renewal may leave multiple configured intermediates with
        // the same subject DN. The leaf signature, not pool order, identifies
        // the one issuer that belongs to the verification path.
        let mut root_params =
            rcgen::CertificateParams::new(Vec::new()).expect("empty root SAN list should be valid");
        root_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "shared-issuer root");
        root_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        root_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root certificate should be self-signable");

        let intermediate = |key: rcgen::KeyPair| {
            let mut params = rcgen::CertificateParams::new(Vec::new())
                .expect("empty intermediate SAN list should be valid");
            params
                .distinguished_name
                .push(rcgen::DnType::CommonName, "renewed intermediate");
            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
            params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
            rcgen::CertifiedIssuer::signed_by(params, key, &root)
                .expect("root should sign the intermediate certificate")
        };
        let unrelated_intermediate = intermediate(
            rcgen::KeyPair::generate().expect("unrelated intermediate key generation should work"),
        );
        let signing_intermediate = intermediate(
            rcgen::KeyPair::generate().expect("signing intermediate key generation should work"),
        );

        let mut leaf_params =
            rcgen::CertificateParams::new(Vec::new()).expect("empty leaf SAN list should be valid");
        leaf_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "same-subject leaf");
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &signing_intermediate,
            )
            .expect("the selected intermediate should sign the leaf certificate");
        let key_info_xml = concat!(
            "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">",
            "<X509Data><X509SubjectName>CN=same-subject leaf</X509SubjectName></X509Data>",
            "</KeyInfo>"
        );
        let document = roxmltree::Document::parse(key_info_xml)
            .expect("static selector KeyInfo should parse as XML");
        let key_info = super::super::parse_key_info(document.root_element())
            .expect("static selector KeyInfo should satisfy XMLDSig structure");
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![
                leaf.der().to_vec(),
                unrelated_intermediate.der().to_vec(),
                signing_intermediate.der().to_vec(),
            ],
            trusted_certs: vec![root.der().to_vec()],
            ..KeyResolverConfig::default()
        });

        let resolved = resolver
            .resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &verification_policy_with_trust(chain_policy()),
            )
            .expect("the leaf signature should select its unique same-subject issuer");

        assert!(resolved.is_some());
    }

    #[test]
    fn x509_path_builder_skips_branch_local_unsupported_algorithms() {
        // An untrusted intermediate can share both the subject and public key
        // of the valid path while using an unsupported signature algorithm on
        // its own parent edge. That branch must not suppress the valid path.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("unsupported-edge root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root certificate should be self-signable");
        let signing_intermediate = rcgen::CertifiedIssuer::signed_by(
            generated_certificate_params("shared unsupported-edge issuer", true),
            rcgen::KeyPair::generate().expect("signing issuer key generation should succeed"),
            &root,
        )
        .expect("root should sign the intermediate certificate");
        let key_unsupported_intermediate = rcgen::CertifiedIssuer::signed_by(
            generated_certificate_params("shared unsupported-edge issuer", true),
            rcgen::KeyPair::generate().expect("unsupported issuer key generation should succeed"),
            &root,
        )
        .expect("root should sign the alternate intermediate certificate");
        let leaf = generated_certificate_params("unsupported-edge leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &signing_intermediate,
            )
            .expect("signing intermediate should sign the leaf");

        let ordered = x509_info(
            vec![
                leaf.der().to_vec(),
                key_unsupported_intermediate.der().to_vec(),
                signing_intermediate.der().to_vec(),
                root.der().to_vec(),
            ],
            0,
        );
        let key_selective_provider = RejectSecondSha512Provider {
            sha512_calls: AtomicUsize::new(0),
            verification_calls: AtomicUsize::new(0),
            reject_verification_call: Some(0),
            rejected_verification_data: None,
        };
        assert_eq!(
            super::super::parse::build_x509_certificate_chain_from(
                &ordered,
                0,
                &key_selective_provider,
            )
            .expect("one unsupported issuer key must not suppress a usable candidate"),
            vec![0, 2, 3]
        );

        let anchored_same_edge = x509_info(
            vec![
                root.der().to_vec(),
                leaf.der().to_vec(),
                key_unsupported_intermediate.der().to_vec(),
                signing_intermediate.der().to_vec(),
            ],
            1,
        );
        let first_candidate_unsupported = RejectSecondSha512Provider {
            sha512_calls: AtomicUsize::new(0),
            verification_calls: AtomicUsize::new(0),
            reject_verification_call: Some(0),
            rejected_verification_data: None,
        };
        assert_eq!(
            build_x509_certificate_paths_to_trusted_prefix(
                &anchored_same_edge,
                1,
                1,
                4,
                8,
                &first_candidate_unsupported,
            )
            .expect("a later same-DN issuer must survive an earlier provider capability miss"),
            vec![vec![1, 3, 0]]
        );

        let mut unsupported_intermediate = signing_intermediate.der().to_vec();
        let ecdsa_sha256_oid = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
        let offsets = unsupported_intermediate
            .windows(ecdsa_sha256_oid.len())
            .enumerate()
            .filter_map(|(offset, window)| (window == ecdsa_sha256_oid).then_some(offset))
            .collect::<Vec<_>>();
        assert_eq!(
            offsets.len(),
            2,
            "certificate must repeat its signature OID"
        );
        for offset in offsets {
            unsupported_intermediate[offset + ecdsa_sha256_oid.len() - 1] = 0x05;
        }

        let anchored = x509_info(
            vec![
                root.der().to_vec(),
                leaf.der().to_vec(),
                signing_intermediate.der().to_vec(),
                unsupported_intermediate,
            ],
            1,
        );
        assert_eq!(
            build_x509_certificate_paths_to_trusted_prefix(
                &anchored,
                1,
                1,
                4,
                8,
                crate::provider::default_provider(),
            )
            .expect("a branch-local provider gap must not abort path enumeration"),
            vec![vec![1, 2, 0]]
        );

        let unsupported_only = x509_info(
            vec![
                root.der().to_vec(),
                leaf.der().to_vec(),
                anchored.certificates[3].clone(),
            ],
            1,
        );
        assert!(matches!(
            build_x509_certificate_paths_to_trusted_prefix(
                &unsupported_only,
                1,
                1,
                4,
                8,
                crate::provider::default_provider(),
            ),
            Err(X509ChainBuildError::UnsupportedSignatureAlgorithm { ref oid })
                if oid == "1.2.840.10045.4.3.5"
        ));
    }

    #[test]
    fn selector_resolved_certificate_preserves_supplied_crls() {
        let selector = "<KeyInfo><X509Data><X509SubjectName>CN=Test Key rsa-2048,O=XML Security Library (http://www.aleksey.com/xmlsec),ST=California,C=US</X509SubjectName><X509CRL>CRL_PLACEHOLDER</X509CRL></X509Data></KeyInfo>";
        let crl = crl_der(include_str!(
            "../../tests/fixtures/keys/rsa/rsa-2048-cert-revoked-crl.pem"
        ));
        let (_, parsed_crl) =
            x509_parser::revocation_list::CertificateRevocationList::from_der(&crl)
                .expect("tracked CRL must parse");
        let crl_signed_data = parsed_crl.tbs_cert_list.as_ref().to_vec();
        let xml = replace_unprefixed_key_info(
            RSA_KEY_VALUE_SIGNATURE,
            &selector.replace("CRL_PLACEHOLDER", &STANDARD.encode(&crl)),
        );
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate_der(include_str!(
                "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
            ))],
            trusted_certs: vec![
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                certificate_der(include_str!("../../tests/fixtures/keys/cacert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        let policy = verification_policy_with_trust(crate::policy::KeyTrustPolicy {
            check_crls: true,
            max_x509_chain_depth: 3,
            ..chain_policy_at(
                SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_773_964_800),
            )
        });

        let error = super::super::VerifyContext::new()
            .policy(policy.clone())
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("selector lookup must retain and enforce the supplied CRL");
        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::Revoked(0)
            ))
        ));

        // Match the exact TBSCertList bytes so earlier certificate-edge
        // verification succeeds and the provider rejection occurs at CRL
        // authentication itself.
        let provider = RejectSecondSha512Provider {
            sha512_calls: AtomicUsize::new(0),
            verification_calls: AtomicUsize::new(0),
            reject_verification_call: None,
            rejected_verification_data: Some(crl_signed_data),
        };
        let error = super::super::VerifyContext::new()
            .policy(policy)
            .key_resolver(&resolver)
            .provider(&provider)
            .verify(&xml)
            .expect_err("CRL authentication must retain the operation provider");
        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::Provider(_)
            ))
        ));
    }

    #[test]
    fn resolves_each_x509_selector_from_configured_certificates() {
        // Every selector form documented by KeyInfo must independently locate
        // the same configured RSA certificate without embedded key material.
        let selectors = [
            "<X509SubjectName>CN=Test Key rsa-2048,O=XML Security Library (http://www.aleksey.com/xmlsec),ST=California,C=US</X509SubjectName>",
            "<X509SubjectName>CN=  test   key rsa-2048  ,O=xml security library (HTTP://WWW.ALEKSEY.COM/XMLSEC),ST=california,C=us</X509SubjectName>",
            "<X509IssuerSerial><X509IssuerName>Email=xmlsec@aleksey.com,CN=Aleksey Sanin,OU=Second level CA,O=XML Security Library (http://www.aleksey.com/xmlsec),ST=California,C=US</X509IssuerName><X509SerialNumber>680572598617295163017172295025714171905498632019</X509SerialNumber></X509IssuerSerial>",
            "<X509SKI>bcOXN/nsVl8GatRbcKrPbzIbw0Y=</X509SKI>",
        ];
        let configured_certificate = certificate_der(include_str!(
            "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
        ));

        for selector in selectors {
            let key_info = format!("<KeyInfo><X509Data>{selector}</X509Data></KeyInfo>");
            let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, &key_info);
            let resolver = DefaultKeyResolver::new(KeyResolverConfig {
                lookup_certs: vec![configured_certificate.clone()],
                ..KeyResolverConfig::default()
            });
            let result = super::super::VerifyContext::new()
                .key_resolver(&resolver)
                .verify(&xml)
                .expect("X509 selector should resolve configured certificate");

            assert_eq!(result.status, super::super::DsigStatus::Valid);
        }
    }

    #[test]
    fn resolves_configured_chain_selectors_across_certificates() {
        // Selector categories may identify different members of one configured
        // chain; the unique leaf remains the signing certificate.
        let key_info = r#"<KeyInfo><X509Data><X509SubjectName>CN=Test Key rsa-2048,O=XML Security Library (http://www.aleksey.com/xmlsec),ST=California,C=US</X509SubjectName><X509SKI>0X0XrEVCio75sBcl1TxymJ2IOiU=</X509SKI></X509Data></KeyInfo>"#;
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![
                certificate_der(include_str!(
                    "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
                )),
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("selectors across one configured chain should resolve its leaf");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn selectors_must_all_match_the_selected_certificate_path() {
        // Selector categories may identify different certificates only when
        // those certificates belong to the one path chosen for the signer.
        let signing_certificate = certificate_der(include_str!(
            "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
        ));
        let issuer_certificate =
            certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem"));
        let unrelated = generated_certificate_params("unrelated selector certificate", false)
            .self_signed(
                &rcgen::KeyPair::generate().expect("unrelated key generation should succeed"),
            )
            .expect("unrelated certificate should be self-signable")
            .der()
            .to_vec();
        let digest = crate::provider::default_provider()
            .digest(super::super::DigestAlgorithm::Sha256, &unrelated)
            .expect("SHA-256 selector digest must be available");
        let key_info_xml = format!(
            "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:dsig11=\"http://www.w3.org/2009/xmldsig11#\"><X509Data><X509SubjectName>CN=Test Key rsa-2048,O=XML Security Library (http://www.aleksey.com/xmlsec),ST=California,C=US</X509SubjectName><dsig11:X509Digest Algorithm=\"http://www.w3.org/2001/04/xmlenc#sha256\">{}</dsig11:X509Digest></X509Data></KeyInfo>",
            STANDARD.encode(digest)
        );
        let document = roxmltree::Document::parse(&key_info_xml)
            .expect("generated selector KeyInfo must be XML");
        let key_info = super::super::parse_key_info(document.root_element())
            .expect("generated selector KeyInfo must be structurally valid");
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![signing_certificate, issuer_certificate, unrelated],
            ..KeyResolverConfig::default()
        });

        assert!(
            resolver
                .resolve(Some(&key_info), SignatureAlgorithm::RsaSha256)
                .expect("disjoint selector matches are a key miss")
                .is_none()
        );
    }

    #[test]
    fn unmatched_x509_selector_does_not_resolve() {
        // A selector mismatch must not fall back to arbitrary configured key material.
        let key_info = "<KeyInfo><X509Data><X509SubjectName>CN=not-the-signer</X509SubjectName></X509Data></KeyInfo>";
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate_der(include_str!(
                "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
            ))],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("an unmatched selector is a key miss, not a parser failure");

        assert!(matches!(
            result.status,
            super::super::DsigStatus::Invalid(super::super::FailureReason::KeyNotFound)
        ));
    }

    #[test]
    fn overlapping_trusted_and_lookup_certificate_preserves_trust() {
        // One physical certificate appearing in both pools is one candidate;
        // deduplication must retain the stronger trusted classification.
        let certificate = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate.clone()],
            lookup_certs: vec![certificate],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .policy(verification_policy_with_trust(chain_policy_at(
                fixture_certificate_time(),
            )))
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect("trusted/lookup overlap must resolve as one trusted candidate");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn distinct_x509_selector_matches_remain_ambiguous() {
        // Deduplication is identity-based, not selector-based: two distinct
        // certificates with the same subject remain separate candidates.
        let certificate = || {
            generated_certificate_params("ambiguous selector", false)
                .self_signed(
                    &rcgen::KeyPair::generate().expect("test key generation should succeed"),
                )
                .expect("test certificate should be self-signable")
                .der()
                .to_vec()
        };
        let xml = replace_unprefixed_key_info(
            X509_DIGEST_SIGNATURE,
            "<KeyInfo><X509Data><X509SubjectName>CN=ambiguous selector</X509SubjectName></X509Data></KeyInfo>",
        );
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate(), certificate()],
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("distinct selector matches must fail closed");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AmbiguousCertificate)
        ));
    }

    #[test]
    fn unsupported_x509_digest_selector_fails_closed() {
        // Unknown digest URIs must not be treated as a normal key miss because
        // that would silently weaken the caller's explicit selector policy.
        let key_info = "<KeyInfo xmlns:dsig11=\"http://www.w3.org/2009/xmldsig11#\"><X509Data><dsig11:X509Digest Algorithm=\"urn:unsupported\">AQ==</dsig11:X509Digest></X509Data></KeyInfo>";
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate_der(include_str!(
                "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
            ))],
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("unsupported X509Digest algorithm must fail closed");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::UnsupportedDigestAlgorithm(uri))
                if uri == "urn:unsupported"
        ));
    }

    #[test]
    fn x509_digest_selector_uses_operation_provider() {
        // The SHA-512 selector is distinct from the SHA-256 reference digest,
        // so only provider-aware key selection can surface this rejection.
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate_der(RSA_4096_CERTIFICATE)],
            trusted_certs: vec![
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                certificate_der(include_str!("../../tests/fixtures/keys/cacert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        let provider = RejectSecondSha512Provider {
            sha512_calls: AtomicUsize::new(0),
            verification_calls: AtomicUsize::new(0),
            reject_verification_call: None,
            rejected_verification_data: None,
        };
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .provider(&provider)
            .verify(X509_DIGEST_SIGNATURE)
            .expect_err("X509Digest selection must use the operation provider");

        assert!(
            matches!(
                error,
                DsigError::Provider(crate::provider::ProviderError::Unsupported {
                    operation: crate::provider::ProviderOperation::Digest,
                    algorithm: Some(ref uri),
                }) if uri == super::super::DigestAlgorithm::Sha512.uri()
            ),
            "unexpected error: {error:?}"
        );
    }

    #[test]
    fn resolves_named_key_end_to_end() {
        // KeyName lookup must preserve the same cryptographic result as embedded X509Data.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("named key should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_der_encoded_key_end_to_end() {
        // DSig 1.1 DEREncodedKeyValue must feed the same SPKI verifier path.
        let encoded = STANDARD.encode(public_key_der(SAML_PUBLIC_KEY));
        let xml = replace_key_info(
            SIGNED_SAML,
            &format!(
                "<ds:KeyInfo><dsig11:DEREncodedKeyValue xmlns:dsig11=\"http://www.w3.org/2009/xmldsig11#\">{encoded}</dsig11:DEREncodedKeyValue></ds:KeyInfo>"
            ),
        );
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("DER key should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_rsa_key_value_end_to_end() {
        // Embedded CryptoBinary parameters must verify the original RSA-2048 donor signature.
        let public_key = rsa::RsaPublicKey::from_public_key_pem(RSA_PUBLIC_KEY)
            .expect("fixture must contain an RSA public key");
        let (modulus, exponent) = rsa_key_value_parts(&public_key);
        let key_info = format!(
            "<KeyInfo><KeyValue><RSAKeyValue><Modulus>{}</Modulus><Exponent>{}</Exponent></RSAKeyValue></KeyValue></KeyInfo>",
            modulus, exponent,
        );
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, &key_info);
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("RSAKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn rsa_key_value_rejects_legacy_weak_modulus() {
        // The secure policy rejects legacy RSA-SHA1 independently of whether
        // the capable key came from RSAKeyValue, DER, X.509, or KeyName.
        let resolver = DefaultKeyResolver::default();
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(LEGACY_RSA_KEY_VALUE_SIGNATURE)
            .expect_err("context policy must override permissive resolver defaults");

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::Algorithm {
                operation: "verification",
                ..
            })
        ));
    }

    #[test]
    fn operation_policy_rejects_disabled_embedded_key_source() {
        // Resolver-owned key material cannot override the operation snapshot's
        // decision about which attacker-controlled KeyInfo forms are trusted.
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::KeyValue(KeyValueInfo::Rsa {
                modulus: vec![0x80; 256],
                exponent: vec![1, 0, 1],
            })],
        };
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.key_sources.key_value = false;

        let error = match DefaultKeyResolver::default().resolve_with_policy(
            Some(&key_info),
            SignatureAlgorithm::RsaSha256,
            &policy,
        ) {
            Ok(_) => panic!("disabled KeyValue must fail before key construction"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::KeyTrust {
                reason: "KeyValue key sources are disabled"
            })
        ));
    }

    #[test]
    fn operation_policy_preflights_every_key_info_source_before_resolution() {
        // A permitted source resolving first must not hide a later source that
        // the immutable operation policy rejects.
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.key_sources.x509_data = false;

        for sources in [
            vec![
                KeyInfoSource::KeyName("idp-signing".into()),
                KeyInfoSource::X509Data(X509DataInfo::default()),
            ],
            vec![
                KeyInfoSource::X509Data(X509DataInfo::default()),
                KeyInfoSource::KeyName("idp-signing".into()),
            ],
        ] {
            let error = match resolver.resolve_with_policy(
                Some(&KeyInfo { sources }),
                SignatureAlgorithm::EcdsaSha256,
                &policy,
            ) {
                Ok(_) => panic!("source order must not hide disabled X509Data"),
                Err(error) => error,
            };

            assert!(matches!(
                error,
                DsigError::Policy(crate::policy::PolicyViolation::KeyTrust {
                    reason: "X509Data key sources are disabled"
                })
            ));
        }
    }

    #[test]
    fn operation_policy_bounds_ordered_key_info_candidates() {
        // The candidate ceiling belongs to the complete verification snapshot:
        // neither a first source nor fallback to a later source may bypass it.
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let key_info = KeyInfo {
            sources: vec![
                KeyInfoSource::KeyValue(KeyValueInfo::Ec {
                    curve_oid: "1.3.132.0.35".into(),
                    public_key: vec![4],
                }),
                KeyInfoSource::KeyName("idp-signing".into()),
            ],
        };

        for maximum in [0, 1] {
            let mut policy = crate::policy::VerificationPolicy::default();
            policy.resources.max_key_candidates = maximum;
            let error = match resolver.resolve_with_policy(
                Some(&key_info),
                SignatureAlgorithm::EcdsaSha256,
                &policy,
            ) {
                Ok(_) => panic!("candidate ceiling {maximum} must stop resolution"),
                Err(error) => error,
            };
            assert!(matches!(
                error,
                DsigError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                    resource: crate::policy::resource_name::KEY_CANDIDATES,
                    maximum: observed,
                    actual,
                }) if observed == maximum && actual == maximum + 1
            ));
        }

        let mut policy = crate::policy::VerificationPolicy::default();
        policy.resources.max_key_candidates = 2;
        assert!(
            resolver
                .resolve_with_policy(Some(&key_info), SignatureAlgorithm::EcdsaSha256, &policy,)
                .expect("two allowed attempts must reach the named key")
                .is_some()
        );
    }

    #[test]
    fn operation_policy_bounds_configured_x509_selector_candidates() {
        // One X509Data selector can fan out across the resolver-owned store.
        // Every distinct certificate inspected is candidate work, rather than
        // the complete store counting as one KeyInfo source.
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                certificate_der(RSA_4096_CERTIFICATE),
            ],
            ..KeyResolverConfig::default()
        });
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.resources.max_key_candidates = 1;

        let error = super::super::VerifyContext::new()
            .policy(policy)
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("the second configured certificate must exceed the candidate budget");

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::KEY_CANDIDATES,
                maximum: 1,
                actual: 2,
            })
        ));
    }

    #[test]
    fn operation_policy_bounds_embedded_x509_certificate_candidates() {
        // Embedded X509Data is also composite key material. Its certificate
        // entries must not collapse into one candidate merely because they
        // share a single KeyInfo source node.
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                certificates: vec![
                    certificate_der(RSA_4096_CERTIFICATE),
                    certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                ],
                certificate_chain: vec![0],
                ..X509DataInfo::default()
            })],
        };
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.resources.max_key_candidates = 1;

        let error = match DefaultKeyResolver::default().resolve_with_policy(
            Some(&key_info),
            SignatureAlgorithm::RsaSha256,
            &policy,
        ) {
            Ok(_) => panic!("the second embedded certificate must exceed the candidate budget"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::KEY_CANDIDATES,
                maximum: 1,
                actual: 2,
            })
        ));
    }

    #[test]
    fn operation_policy_charges_duplicate_configured_x509_candidates() {
        // Deduplication may avoid repeated parsing, but inspecting a duplicate
        // resolver entry still consumes work and must not bypass the budget.
        let certificate = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            lookup_certs: vec![certificate.clone(), certificate],
            ..KeyResolverConfig::default()
        });
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.resources.max_key_candidates = 1;

        let error = super::super::VerifyContext::new()
            .policy(policy)
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("the duplicate configured entry must consume candidate work");

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::KEY_CANDIDATES,
                maximum: 1,
                actual: 2,
            })
        ));
    }

    #[test]
    fn operation_policy_charges_duplicate_embedded_x509_candidates() {
        // Public callers can construct KeyInfo without passing through parser
        // entry limits, so duplicate embedded entries must consume the budget.
        let certificate = certificate_der(RSA_4096_CERTIFICATE);
        let key_info = KeyInfo {
            sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                certificates: vec![certificate.clone(), certificate],
                certificate_chain: vec![0],
                ..X509DataInfo::default()
            })],
        };
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.resources.max_key_candidates = 1;

        let error = match DefaultKeyResolver::default().resolve_with_policy(
            Some(&key_info),
            SignatureAlgorithm::RsaSha256,
            &policy,
        ) {
            Ok(_) => panic!("the duplicate embedded entry must consume candidate work"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::KEY_CANDIDATES,
                maximum: 1,
                actual: 2,
            })
        ));
    }

    #[test]
    fn policy_aware_resolver_rejects_resources_above_hard_ceiling() {
        // The resolver is a public policy enforcement boundary in its own
        // right; callers must not need VerifyContext to validate the snapshot.
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.resources.max_key_candidates = usize::MAX;

        let error = match DefaultKeyResolver::default().resolve_with_policy(
            None,
            SignatureAlgorithm::RsaSha256,
            &policy,
        ) {
            Ok(_) => panic!("invalid resource policy must fail before key resolution"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            DsigError::Policy(crate::policy::PolicyViolation::ResourceLimit {
                resource: crate::policy::resource_name::KEY_CANDIDATES,
                actual: usize::MAX,
                ..
            })
        ));
    }

    #[test]
    fn embedded_x509_digest_selection_uses_operation_provider() {
        // Embedded certificate selection happens while KeyInfo is parsed, so
        // that parser path must retain the verification operation's provider.
        let certificate = certificate_der(RSA_4096_CERTIFICATE);
        let digest =
            super::super::compute_digest(super::super::DigestAlgorithm::Sha512, &certificate);
        let xml = format!(
            "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Data><X509Certificate>{}</X509Certificate><X509Digest xmlns=\"http://www.w3.org/2009/xmldsig11#\" Algorithm=\"{}\">{}</X509Digest></X509Data></KeyInfo>",
            STANDARD.encode(&certificate),
            super::super::DigestAlgorithm::Sha512.uri(),
            STANDARD.encode(digest),
        );
        let document = roxmltree::Document::parse(&xml).expect("generated KeyInfo must be XML");
        let provider = RejectSecondSha512Provider {
            sha512_calls: AtomicUsize::new(1),
            verification_calls: AtomicUsize::new(0),
            reject_verification_call: None,
            rejected_verification_data: None,
        };

        let error =
            super::super::parse::parse_key_info_with_provider(document.root_element(), &provider)
                .expect_err("embedded X509Digest selection must use the operation provider");

        assert!(
            matches!(
                error,
                ParseError::Provider(crate::provider::ProviderError::Unsupported {
                    operation: crate::provider::ProviderOperation::Digest,
                    algorithm: Some(ref uri),
                }) if uri == super::super::DigestAlgorithm::Sha512.uri()
            ),
            "unexpected error: {error:?}"
        );
    }

    #[test]
    fn generic_key_resolution_keeps_legacy_capability_source_independent() {
        let certificate =
            include_bytes!("../../tests/fixtures/xmldsig/phaos-xmldsig-three/certs/rsa-cert.der")
                .to_vec();
        let (_, parsed_certificate) = X509Certificate::from_der(&certificate)
            .expect("the Phaos fixture is a DER certificate");
        let public_key = parsed_certificate.public_key().raw.to_vec();
        let rsa_public_key = rsa::RsaPublicKey::from_public_key_der(&public_key)
            .expect("the Phaos certificate contains an RSA public key");
        let certificate_metadata = parse_x509_certificate(&certificate)
            .expect("the Phaos fixture has supported X.509 metadata");
        let named_key = VerificationKey {
            algorithm: SignatureAlgorithm::RsaSha1,
            public_key_bytes: public_key.clone(),
            certificate_der: None,
            name: Some("legacy".into()),
        };
        let key_infos = [
            KeyInfo {
                sources: vec![KeyInfoSource::KeyName("legacy".into())],
            },
            KeyInfo {
                sources: vec![KeyInfoSource::DerEncodedKeyValue(public_key.clone())],
            },
            KeyInfo {
                sources: vec![KeyInfoSource::KeyValue(KeyValueInfo::Rsa {
                    modulus: rsa_public_key.n().to_be_bytes_trimmed_vartime().to_vec(),
                    exponent: rsa_public_key.e().to_be_bytes_trimmed_vartime().to_vec(),
                })],
            },
            KeyInfo {
                sources: vec![KeyInfoSource::X509Data(X509DataInfo {
                    certificates: vec![certificate],
                    parsed_certificates: vec![certificate_metadata],
                    certificate_chain: vec![0],
                    ..X509DataInfo::default()
                })],
            },
        ];
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            named_keys: HashMap::from([("legacy".into(), named_key.clone())]),
            ..KeyResolverConfig::default()
        });
        let mut policy = crate::policy::VerificationPolicy::default();
        policy.key_trust.rsa_keys.minimum_modulus_bits = 1024;
        policy
            .key_trust
            .allowed_legacy_signature_algorithms
            .insert(SignatureAlgorithm::RsaSha1);

        for key_info in &key_infos {
            let key = resolver
                .resolve_with_policy(Some(key_info), SignatureAlgorithm::RsaSha1, &policy)
                .expect("the key source is valid")
                .expect("key resolution remains independent from operation policy");
            assert!(
                !key.verify(SignatureAlgorithm::RsaSha1, b"data", &[0; 128])
                    .expect("the legacy RSA key is structurally valid")
            );
        }
    }

    #[test]
    fn rsa_key_value_rejects_ecdsa_signature_method() {
        // Embedded RSA parameters must not be relabeled for an ECDSA SignatureMethod.
        let public_key = rsa::RsaPublicKey::from_public_key_pem(RSA_PUBLIC_KEY)
            .expect("fixture must contain an RSA public key");
        let (modulus, exponent) = rsa_key_value_parts(&public_key);
        let key_info = format!(
            "<ds:KeyInfo><ds:KeyValue><ds:RSAKeyValue><ds:Modulus>{}</ds:Modulus><ds:Exponent>{}</ds:Exponent></ds:RSAKeyValue></ds:KeyValue></ds:KeyInfo>",
            modulus, exponent,
        );
        let xml = replace_key_info(SIGNED_SAML, &key_info);
        let resolver = DefaultKeyResolver::default();
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("RSAKeyValue must not resolve for ECDSA");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn resolves_ec_p256_key_value_end_to_end() {
        // XMLDSig 1.1 ECKeyValue must verify without a preset key or certificate.
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(EC_P256_KEY_VALUE_SIGNATURE)
            .expect("P-256 ECKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_ec_p384_key_value_end_to_end() {
        // The donor P-384 vector uses NamedCurve + uncompressed PublicKey.
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(EC_P384_KEY_VALUE_SIGNATURE)
            .expect("P-384 ECKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn ec_key_value_ignored_for_rsa_signature_method() {
        // Embedded EC key material must not be relabeled for an RSA SignatureMethod.
        let key_info = r#"<KeyInfo xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BJ/yaXNlq4FRObyJCBhb5jAz8GVzinK3bBGLjSDfjbJwNfydtgjnlS4EsDmxSRhWyJWq6GIqy5wvnaiARK04uB4=</dsig11:PublicKey></dsig11:ECKeyValue></KeyValue></KeyInfo>"#;
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("single incompatible ECKeyValue should be ignored");

        assert_eq!(
            result.status,
            super::super::DsigStatus::Invalid(super::super::FailureReason::KeyNotFound)
        );
    }

    #[test]
    fn incompatible_ec_key_value_falls_back_to_later_rsa_key_value() {
        // Mixed KeyInfo should keep scanning after an incompatible ECKeyValue source.
        let public_key = rsa::RsaPublicKey::from_public_key_pem(RSA_PUBLIC_KEY)
            .expect("fixture must contain an RSA public key");
        let (modulus, exponent) = rsa_key_value_parts(&public_key);
        let key_info = format!(
            r#"<KeyInfo xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BJ/yaXNlq4FRObyJCBhb5jAz8GVzinK3bBGLjSDfjbJwNfydtgjnlS4EsDmxSRhWyJWq6GIqy5wvnaiARK04uB4=</dsig11:PublicKey></dsig11:ECKeyValue></KeyValue><KeyValue><RSAKeyValue><Modulus>{}</Modulus><Exponent>{}</Exponent></RSAKeyValue></KeyValue></KeyInfo>"#,
            modulus, exponent,
        );
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, &key_info);
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later RSAKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn unsupported_ec_key_value_falls_back_to_later_key_name() {
        // Unsupported curves are non-fatal so a later compatible source can verify.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.3.132.0.35"/><dsig11:PublicKey>BA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn invalid_ec_key_value_falls_back_to_later_key_name() {
        // Off-curve EC points are typed errors only if no later source can verify.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after invalid ECKeyValue");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn malformed_ec_key_value_falls_back_to_later_key_name() {
        // Parse-level EC point errors remain non-fatal while later sources exist.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after malformed ECKeyValue");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn invalid_base64_ec_key_value_falls_back_to_later_key_name() {
        // A bad ECKeyValue payload is an unusable source, not a reason to skip
        // later ordered KeyInfo sources that can verify the signature.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>not base64!</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after bad ECKeyValue base64");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn missing_curve_uri_ec_key_value_falls_back_to_later_key_name() {
        // Missing EC curve parameters make only this KeyValue source unusable.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve/><dsig11:PublicKey>BA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after missing EC curve URI");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn malformed_ec_key_value_children_fall_back_to_later_key_name() {
        // An unusable EC source must not prevent later ordered KeyInfo sources
        // from resolving, regardless of which required child-shape check fails.
        let malformed_ec_key_values = [
            r#"<dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/>"#,
            r#"<dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/>"#,
            r#"<dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BA==</dsig11:PublicKey><dsig11:PublicKey>BA==</dsig11:PublicKey>"#,
        ];

        for malformed_children in malformed_ec_key_values {
            let key_info = format!(
                r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue>{malformed_children}</dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#
            );
            let xml = replace_key_info(SIGNED_SAML, &key_info);
            let mut config = KeyResolverConfig::default();
            config.named_keys.insert(
                "idp-signing".into(),
                VerificationKey {
                    algorithm: SignatureAlgorithm::EcdsaSha256,
                    public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                    certificate_der: None,
                    name: Some("idp-signing".into()),
                },
            );
            let resolver = DefaultKeyResolver::new(config);
            let result = super::super::VerifyContext::new()
                .key_resolver(&resolver)
                .verify(&xml)
                .expect("later KeyName should resolve after malformed EC child shape");

            assert_eq!(result.status, super::super::DsigStatus::Valid);
        }
    }

    #[test]
    fn supported_ec_curve_does_not_fall_back_to_later_key_name() {
        // ECDSA-SHA256 accepts P-384, so this first source is a usable key and
        // must not be skipped merely because a later P-256 KeyName happens to
        // verify the signature. Verification fails against the selected key.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.3.132.0.34"/><dsig11:PublicKey>BO/yd/OZzDfjX4qivDY/vsUIuh6KWAxoxW5P4ukvwd+T6pVljWsX2UBJNNy5MdhTwB8e2YwB8kUbJwdsAS/XGi/fz8unFrs+lVlAgIs6s/xBYFbfUoRiAacD2SpVDe6XBA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("a usable first key source must not fall through after verification");

        assert!(matches!(
            error,
            DsigError::Crypto(super::super::SignatureVerificationError::InvalidSignatureFormat)
        ));
    }

    #[test]
    fn lone_malformed_ec_key_value_reports_invalid_public_key() {
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let error = super::super::VerifyContext::new()
            .key_resolver(&DefaultKeyResolver::default())
            .verify(&xml)
            .expect_err("lone malformed ECKeyValue should surface typed key error");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::InvalidPublicKey)
        ));
    }

    #[test]
    fn lone_supported_ec_curve_reaches_signature_verification() {
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.3.132.0.34"/><dsig11:PublicKey>BO/yd/OZzDfjX4qivDY/vsUIuh6KWAxoxW5P4ukvwd+T6pVljWsX2UBJNNy5MdhTwB8e2YwB8kUbJwdsAS/XGi/fz8unFrs+lVlAgIs6s/xBYFbfUoRiAacD2SpVDe6XBA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let error = super::super::VerifyContext::new()
            .key_resolver(&DefaultKeyResolver::default())
            .verify(&xml)
            .expect_err("a supported EC curve must reach signature verification");

        assert!(matches!(
            error,
            DsigError::Crypto(super::super::SignatureVerificationError::InvalidSignatureFormat)
        ));
    }

    #[test]
    fn chain_verification_rejects_untrusted_embedded_certificate() {
        // Enabling chain policy must fail closed when no trust anchor is configured.
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .policy(verification_policy_with_trust(chain_policy()))
            .key_resolver(&resolver)
            .verify(SIGNED_SAML)
            .expect_err("untrusted certificate must fail chain validation");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::UntrustedRoot
            ))
        ));
    }

    #[test]
    fn named_key_algorithm_mismatch_fails_closed() {
        // A key registered for RSA must never be attempted for an ECDSA signature.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>wrong-algorithm</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "wrong-algorithm".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::RsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("wrong-algorithm".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("algorithm mismatch must fail closed");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn named_key_spki_type_mismatch_fails_during_resolution() {
        // The configured algorithm label cannot override the actual SPKI key type.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>mislabeled</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "mislabeled".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: public_key_der(RSA_PUBLIC_KEY),
                certificate_der: None,
                name: Some("mislabeled".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("mislabeled named key must fail during resolution");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn malformed_named_key_reports_public_key_error() {
        // Non-certificate SPKI failures must not be mislabeled as certificate errors.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>malformed</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "malformed".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaSha256,
                public_key_bytes: vec![1, 2, 3],
                certificate_der: None,
                name: Some("malformed".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("malformed named key must fail during resolution");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::InvalidPublicKey)
        ));
    }
}