xml-sec 0.1.23

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

use std::{collections::HashSet, time::SystemTime};

use x509_parser::x509::AlgorithmIdentifier;
#[cfg(test)]
use x509_parser::{
    certificate::X509Certificate, prelude::FromDer, revocation_list::CertificateRevocationList,
    time::ASN1Time,
};

use super::X509DataInfo;
use super::pkix::X509DataSource;
use crate::{
    policy::{DsaKeyPolicy, ExtendedKeyPurpose, RsaKeyPolicy},
    provider::X509SignatureAlgorithm,
};

/// Inputs controlling X.509 certificate-chain validation.
#[derive(Debug, Clone)]
pub struct X509ChainOptions<'a> {
    /// Caller-owned UTC history for evaluating supplied certificate evidence.
    /// This is a request fact; the core does not discover or update the table.
    pub utc_facts: Option<structured_pkix::temporal::LeapTable<'a>>,
    /// DER-encoded certificates accepted as trust anchors.
    pub trusted_certs: &'a [Vec<u8>],
    /// Time used for certificate, CRL, and revocation checks.
    pub verification_time: SystemTime,
    /// Maximum number of certificates in the validated path, including the anchor.
    pub max_chain_depth: usize,
    /// Whether parsed `<X509CRL>` entries are enforced.
    pub check_crls: bool,
    /// Purposes accepted when any path certificate carries ExtendedKeyUsage.
    pub allowed_extended_key_usages: Option<&'a HashSet<ExtendedKeyPurpose>>,
    /// RSA strength requirements for every issuer key used by the path.
    pub rsa_keys: RsaKeyPolicy,
    /// DSA strength requirements for every issuer key used by the path.
    pub dsa_keys: DsaKeyPolicy,
    /// Borrowed certificate/CRL permissions from the operation's trust policy.
    /// `None` rejects PQ signatures; explicit permissions can select an exact
    /// allowlist or all provider-supported algorithms for compatibility.
    pub certificate_signature_algorithms: Option<&'a crate::policy::CertificateSignatureAlgorithms>,
}

/// Certificate-chain validation failure.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum X509ChainError {
    /// A located error from the common certificate mechanism.
    #[error("X.509 processing failed: {0}")]
    Processing(#[source] structured_pkix::Error),
    /// The operation does not permit this certificate or CRL signature method.
    #[error("X.509 signature policy rejected authentication: {0}")]
    Policy(#[from] crate::policy::PolicyViolation),
    /// The selected cryptographic provider rejected path authentication.
    #[error("cryptographic provider rejected X.509 authentication: {0}")]
    Provider(#[from] crate::provider::ProviderError),
    /// The provider cannot answer for this path's algorithm/key/parameters.
    #[error("certificate signature at chain position {0} is unsupported")]
    UnsupportedSignature(usize),
    /// The configured path limit cannot contain a certificate.
    #[error("maximum certificate chain depth must be greater than zero")]
    InvalidDepth,
    /// A certificate or CRL is malformed DER.
    #[error("invalid {kind} DER: {message}")]
    InvalidDer {
        /// Object type being parsed.
        kind: &'static str,
        /// Parser diagnostic.
        message: String,
    },
    /// A certificate repeats an extension OID, which RFC 5280 forbids.
    #[error("certificate at chain position {position} repeats extension {oid}")]
    DuplicateExtension {
        /// Position of the malformed certificate in the candidate path.
        position: usize,
        /// Repeated extension object identifier.
        oid: String,
    },
    /// The ordered embedded path cannot be completed to a configured anchor.
    #[error("certificate chain does not terminate at a trusted certificate")]
    UntrustedRoot,
    /// The path contains more certificates than allowed.
    #[error("certificate chain exceeds maximum depth of {0}")]
    DepthExceeded(usize),
    /// Static checking stopped without producing an accepted path.
    #[error("certificate path checking stopped at {0:?}")]
    PathIncomplete(structured_pkix::path::Truncation),
    /// The path's certificate policies do not permit the requested operation.
    #[error("certificate path policy constraints are not satisfied")]
    CertificatePolicies,
    /// A certificate is outside its validity period.
    #[error("certificate at chain position {0} is expired or not yet valid")]
    CertificateNotValid(usize),
    /// An issuer certificate is not authorized to issue certificates.
    #[error("certificate at chain position {0} is not a CA")]
    IssuerNotCa(usize),
    /// A CA path-length constraint is violated.
    #[error("certificate at chain position {position} exceeds path length constraint {limit}")]
    PathLengthExceeded {
        /// Position of the constraining CA certificate.
        position: usize,
        /// Maximum permitted subordinate CA count.
        limit: u32,
    },
    /// A subordinate certificate is outside a CA's permitted name space.
    #[error(
        "certificate at chain position {position} violates name constraints from position {constraining_position}"
    )]
    NameConstraintViolation {
        /// Position of the subordinate certificate.
        position: usize,
        /// Position of the CA carrying NameConstraints.
        constraining_position: usize,
    },
    /// A critical certificate extension is not implemented by path validation.
    #[error("certificate at chain position {position} has unsupported critical extension {oid}")]
    UnsupportedCriticalExtension {
        /// Position of the certificate in the validated path.
        position: usize,
        /// Extension object identifier.
        oid: String,
    },
    /// NameConstraints is not a critical CA extension as required by RFC 5280.
    #[error("certificate at chain position {position} has invalid NameConstraints placement")]
    InvalidNameConstraints {
        /// Position of the certificate carrying the invalid extension.
        position: usize,
    },
    /// A certificate key usage extension forbids the required operation.
    #[error("certificate at chain position {position} does not permit {required}")]
    InvalidKeyUsage {
        /// Position of the certificate in the validated path.
        position: usize,
        /// RFC 5280 key usage required for the operation.
        required: &'static str,
    },
    /// A certificate signature does not verify under its issuer key.
    #[error("certificate signature at chain position {0} is invalid or unsupported")]
    InvalidSignature(usize),
    /// An issuer key violates the active key-strength policy.
    #[error("certificate issuer key at chain position {position} is rejected by policy: {source}")]
    KeyPolicy {
        /// Position of the issuer certificate in the candidate path.
        position: usize,
        /// Typed key-policy rejection.
        source: crate::policy::PolicyViolation,
    },
    /// The certificate or CRL declares an algorithm this build cannot verify.
    #[error("unsupported X.509 signature algorithm: {oid}")]
    UnsupportedSignatureAlgorithm {
        /// AlgorithmIdentifier object identifier.
        oid: String,
    },
    /// A CRL is not valid for the selected verification time or issuer.
    #[error("CRL {0} is invalid or cannot be authenticated")]
    InvalidCrl(usize),
    /// Applicable authenticated lists do not cover every revocation reason.
    #[error("CRL evidence has incomplete reason coverage at chain position {0}")]
    IncompleteCrlCoverage(usize),
    /// Revocation-time qualification requires caller-supplied UTC evidence.
    #[error("CRL validation requires caller-supplied UTC facts")]
    MissingUtcFacts,
    /// The caller's UTC evidence cannot establish a CRL temporal fact.
    #[error("UTC evidence cannot establish CRL {index} time: {reason:?}")]
    CrlTimeUncertain {
        /// Original embedded/inventory source index.
        index: usize,
        /// Lossless reason supplied by the common temporal mechanism.
        reason: structured_pkix::temporal::Uncertainty,
    },
    /// A path certificate was revoked by an applicable CRL.
    #[error("certificate at chain position {0} is revoked")]
    Revoked(usize),
}

impl X509ChainError {
    pub(crate) fn is_execution_failure(&self) -> bool {
        match self {
            Self::Processing(error) => error.is_resource(),
            Self::Policy(
                crate::policy::PolicyViolation::ResourceLimit { .. }
                | crate::policy::PolicyViolation::ResourceLimitExceeded { .. },
            ) => true,
            Self::Provider(crate::provider::ProviderError::Unsupported { .. }) => false,
            Self::Provider(_) => true,
            Self::PathIncomplete(reason) => !matches!(
                reason,
                structured_pkix::path::Truncation::Depth
                    | structured_pkix::path::Truncation::Paths
                    | structured_pkix::path::Truncation::Policies
            ),
            _ => false,
        }
    }
}

/// Verify a path with the default standalone resource allowance.
/// Use [`verify_x509_certificate_chain_with_resources`] with the operation's resource snapshot.
pub fn verify_x509_certificate_chain(
    info: &X509DataInfo,
    options: &X509ChainOptions<'_>,
) -> Result<(), X509ChainError> {
    verify_x509_certificate_chain_with_resources(
        info,
        options,
        &crate::policy::ResourcePolicy::default(),
        crate::provider::default_provider(),
    )
}

/// Validate supplied evidence under explicit borrowed resource limits.
/// XML operations pass their immutable policy's `resources` snapshot; other
/// path constraints, trust anchors, time and UTC history come from `options`.
pub fn verify_x509_certificate_chain_with_resources(
    info: &X509DataInfo,
    options: &X509ChainOptions<'_>,
    resources: &crate::policy::ResourcePolicy,
    provider: &dyn crate::provider::CryptoProvider,
) -> Result<(), X509ChainError> {
    resources.validate()?;
    let session = super::pkix::CertificateSession::new(resources);
    // Borrowed DER still consumes the supplied source-byte allowance. Admit
    // all evidence, including unused CRLs/anchors, before path storage/parsing.
    let count = info
        .certificates
        .len()
        .checked_add(info.crls.len())
        .and_then(|count| count.checked_add(options.trusted_certs.len()))
        .ok_or(crate::policy::PolicyViolation::ResourceLimitExceeded {
            resource: crate::policy::resource_name::X509_WORK,
            maximum: resources.max_x509_work,
        })?;
    session
        .memory()
        .charge_work(count as u64)
        .map_err(|reason| {
            session.error(structured_pkix::Error::resource(
                reason,
                "certificate.evidence",
                0,
            ))
        })?;
    let mut remaining = resources.max_external_resource_total_bytes;
    for bytes in info
        .certificates
        .iter()
        .chain(&info.crls)
        .chain(options.trusted_certs)
    {
        if bytes.len() > resources.max_external_resource_bytes {
            return Err(crate::policy::PolicyViolation::ResourceLimitExceeded {
                resource: crate::policy::resource_name::EXTERNAL_RESOURCE_BYTES,
                maximum: resources.max_external_resource_bytes,
            }
            .into());
        }
        if bytes.len() > remaining {
            return Err(crate::policy::PolicyViolation::ResourceLimitExceeded {
                resource: crate::policy::resource_name::AGGREGATE_EXTERNAL_RESOURCE_BYTES,
                maximum: resources.max_external_resource_total_bytes,
            }
            .into());
        }
        remaining -= bytes.len();
    }
    verify_x509_certificate_chain_in_session(info, options, provider, &[], &session).map(|_| ())
}

pub(crate) fn verify_x509_certificate_chain_in_session(
    info: &impl X509DataSource,
    options: &X509ChainOptions<'_>,
    provider: &dyn crate::provider::CryptoProvider,
    additional_crls: &[Vec<u8>],
    session: &super::pkix::CertificateSession,
) -> Result<super::pkix::ValidatedX509Key, X509ChainError> {
    if options.max_chain_depth == 0 {
        return Err(X509ChainError::InvalidDepth);
    }
    if info.chain().is_empty() {
        return Err(X509ChainError::UntrustedRoot);
    }

    let storage_error = |reason| {
        session.error(structured_pkix::Error::resource(
            reason,
            "certificate.path",
            0,
        ))
    };
    let mut path_der = session.memory().vector();
    path_der
        .try_reserve_exact(info.chain().len())
        .map_err(storage_error)?;
    for &index in info.chain() {
        let bytes = info
            .certificate(index)
            .ok_or(X509ChainError::UntrustedRoot)?;
        path_der.try_push(bytes).map_err(storage_error)?;
    }

    let last = session.read(
        path_der
            .last()
            .copied()
            .ok_or(X509ChainError::UntrustedRoot)?,
    )?;
    let trusted_anchors =
        session
            .read_pool(options.trusted_certs)
            .map_err(|error| match error {
                X509ChainError::Processing(error) if !error.is_resource() => {
                    X509ChainError::InvalidDer {
                        kind: "certificate",
                        message: error.to_string(),
                    }
                }
                error => error,
            })?;
    let embedded_anchor = trusted_anchors
        .iter()
        .any(|cert| cert.as_bytes() == last.as_bytes());
    if embedded_anchor {
        return validate_path(
            &path_der,
            info,
            options,
            (provider, session),
            additional_crls,
        );
    }

    // Root replacement requires a proved self-signature and child signature;
    // a merely prospective edge cannot authorize discarding a certificate.
    let replace_untrusted_root = if path_der.len() > 1
        && session.source_names_equal(last.tbs().subject(), last.tbs().issuer())?
        && shared_certificate_signature_outcome(
            &last,
            &last,
            provider,
            options.certificate_signature_algorithms,
            session,
        )? == structured_pkix::path::Verified::Yes
    {
        let child = session.read(path_der[path_der.len() - 2])?;
        session.source_names_equal(child.tbs().issuer(), last.tbs().subject())?
            && shared_certificate_signature_outcome(
                &child,
                &last,
                provider,
                options.certificate_signature_algorithms,
                session,
            )? == structured_pkix::path::Verified::Yes
    } else {
        false
    };
    let candidate_base = if replace_untrusted_root {
        &path_der[..path_der.len() - 1]
    } else {
        &path_der[..]
    };
    let candidate_child = session.read(
        candidate_base
            .last()
            .copied()
            .ok_or(X509ChainError::UntrustedRoot)?,
    )?;

    let mut first_validation_error = None;
    for cert in &trusted_anchors {
        if !session.source_names_equal(cert.tbs().subject(), candidate_child.tbs().issuer())? {
            continue;
        }
        match shared_certificate_signature_outcome(
            &candidate_child,
            cert,
            provider,
            options.certificate_signature_algorithms,
            session,
        )? {
            structured_pkix::path::Verified::Yes | structured_pkix::path::Verified::Unsupported => {
            }
            _ => continue,
        }
        let mut candidate_path = session.memory().vector();
        candidate_path
            .try_extend_from_slice(candidate_base)
            .map_err(storage_error)?;
        candidate_path
            .try_push(cert.as_bytes())
            .map_err(storage_error)?;
        match validate_path(
            &candidate_path,
            info,
            options,
            (provider, session),
            additional_crls,
        ) {
            Ok(key) => return Ok(key),
            Err(error) if error.is_execution_failure() => return Err(error),
            Err(error) => first_validation_error.get_or_insert(error),
        };
    }

    Err(first_validation_error.unwrap_or(X509ChainError::UntrustedRoot))
}

fn validate_path(
    path_der: &[&[u8]],
    info: &impl X509DataSource,
    options: &X509ChainOptions<'_>,
    execution: (
        &dyn crate::provider::CryptoProvider,
        &super::pkix::CertificateSession,
    ),
    additional_crls: &[Vec<u8>],
) -> Result<super::pkix::ValidatedX509Key, X509ChainError> {
    let (provider, session) = execution;
    if path_der.len() > options.max_chain_depth {
        return Err(X509ChainError::DepthExceeded(options.max_chain_depth));
    }

    let mut decoded = session.memory().vector();
    for der in path_der {
        let certificate = session.read(der)?;
        if decoded.is_empty() {
            // Fail the target's time gate before examining issuer permissions,
            // as shared path discovery also does before entering its pool.
            let at = super::pkix::verification_instant(options.verification_time)?;
            let validity = certificate.tbs().validity();
            if at < validity.not_before().instant() || at > validity.not_after().instant() {
                return Err(X509ChainError::CertificateNotValid(0));
            }
        }
        decoded.try_push(certificate).map_err(|reason| {
            X509ChainError::Processing(structured_pkix::Error::resource(
                reason,
                "certificate.path",
                0,
            ))
        })?;
    }

    let mut effective_extended_key_usages = session.memory().vector();
    if let Some(purposes) = options.allowed_extended_key_usages {
        for purpose in purposes {
            effective_extended_key_usages
                .try_push(purpose)
                .map_err(|reason| {
                    session.error(structured_pkix::Error::resource(
                        reason,
                        "certificate.extended_key_usage",
                        0,
                    ))
                })?;
        }
    }
    let mut anchor_limit = None;
    let at = super::pkix::verification_instant(options.verification_time)?;
    for (position, cert) in decoded.iter().enumerate() {
        validate_positive_serial_bytes(
            cert.tbs().serial().as_bytes(),
            "certificate serial number",
        )?;
        if position == decoded.len() - 1
            && (at < cert.tbs().validity().not_before().instant()
                || at > cert.tbs().validity().not_after().instant())
        {
            return Err(X509ChainError::CertificateNotValid(position));
        }
        let extensions = cert.tbs().extensions();
        if position == 0 {
            if let Some(usage) = shared_key_usage(cert, position, session)?
                && !usage.digital_signature()
                && !usage.content_commitment()
            {
                return Err(X509ChainError::InvalidKeyUsage {
                    position,
                    required: "digitalSignature or nonRepudiation",
                });
            }
        } else if position == decoded.len() - 1 {
            // RFC 5280 4.2.1.9 requires critical cA BasicConstraints of issuers;
            // 6.1.4(k) requires the assertion, not an extra criticality gate.
            // This certificate-anchor profile likewise does not invent one.
            // https://www.rfc-editor.org/rfc/rfc5280.html#section-4.2.1.9
            // https://www.rfc-editor.org/rfc/rfc5280.html#section-6.1.4
            let basic = extensions
                .basic_constraints(session.memory())
                .map_err(|error| session.error(error))?
                .filter(|basic| basic.is_authority())
                .ok_or(X509ChainError::IssuerNotCa(position))?;
            anchor_limit = basic.path_length().and_then(|limit| limit.certificates());
            if let Some(usage) = shared_key_usage(cert, position, session)?
                && !usage.key_cert_sign()
            {
                return Err(X509ChainError::InvalidKeyUsage {
                    position,
                    required: "keyCertSign",
                });
            }
        }
        validate_shared_extended_key_usage(
            cert,
            position,
            &mut effective_extended_key_usages,
            session,
        )?;
        validate_shared_subject_identity(cert, session)?;
        if position == decoded.len() - 1 {
            validate_shared_anchor_extensions(cert, position, session)?;
        }
        // This strict issuance-profile rule is XML security policy, not an
        // additional RFC 5280 6.1 processor mandate. The common processor
        // handles the actual name constraints and their provenance.
        if let Some(extension) = extensions
            .get(structured_pkix::oid::NAME_CONSTRAINTS, session.memory())
            .map_err(|error| session.error(error))?
            && (position == 0 || !extension.is_critical())
        {
            return Err(X509ChainError::InvalidNameConstraints { position });
        }
    }
    let mut effective_key = super::pkix::ValidatedX509Key {
        effective_spki: None,
    };
    if path_der.len() > 1 {
        let anchor = decoded.last().expect("nonempty path");
        let mut chain = session.memory().vector();
        for certificate in &decoded[..decoded.len() - 1] {
            chain.try_push(certificate).map_err(|reason| {
                X509ChainError::Processing(structured_pkix::Error::resource(
                    reason,
                    "certificate.path",
                    0,
                ))
            })?;
        }
        let facts =
            super::pkix::validate_supplied_path(&chain, anchor, options, provider, session)?;
        // The anchor is a caller input, excluded by RFC 5280 6.1. Our existing
        // certificate-anchor profile additionally honors its pathLenConstraint.
        // https://www.rfc-editor.org/rfc/rfc5280.html#section-6.1
        if let Some(limit) = anchor_limit
            && facts.non_self_issued_intermediates > limit
        {
            return Err(X509ChainError::PathLengthExceeded {
                position: decoded.len() - 1,
                limit,
            });
        }
        // RFC 5280 6.1.4(e): keep the target's authenticated working key for
        // subsequent data verification; never rewrite the certificate's TBS.
        // https://www.rfc-editor.org/rfc/rfc5280.html#section-6.1.4
        effective_key = super::pkix::effective_target_spki(facts.key, session.memory())?;
    }

    if options.check_crls {
        super::pkix::verify_crls(
            &decoded,
            info.crls(),
            additional_crls,
            options,
            provider,
            session,
        )?;
    }
    Ok(effective_key)
}

fn shared_key_usage<'a>(
    certificate: &structured_pkix::Certificate<'a>,
    position: usize,
    session: &super::pkix::CertificateSession,
) -> Result<Option<structured_pkix::usage::KeyUsage<'a>>, X509ChainError> {
    let Some(extension) = certificate
        .tbs()
        .extensions()
        .get(structured_pkix::oid::KEY_USAGE, session.memory())
        .map_err(|error| session.error(error))?
    else {
        return Ok(None);
    };
    structured_pkix::usage::KeyUsage::read(extension, session.memory())
        .map(Some)
        .map_err(|error| {
            if error.is_resource() {
                session.error(error)
            } else if extension.is_critical() {
                X509ChainError::UnsupportedCriticalExtension {
                    position,
                    oid: "2.5.29.15".into(),
                }
            } else {
                session.error(error)
            }
        })
}

fn validate_shared_extended_key_usage(
    certificate: &structured_pkix::Certificate<'_>,
    position: usize,
    effective: &mut structured_asn1::memory::OwnedVec<&ExtendedKeyPurpose>,
    session: &super::pkix::CertificateSession,
) -> Result<(), X509ChainError> {
    let Some(usage) = certificate
        .tbs()
        .extensions()
        .extended_key_usage(session.memory())
        .map_err(|error| session.error(error))?
    else {
        return Ok(());
    };
    if usage
        .has(
            structured_pkix::oid::ANY_EXTENDED_KEY_USAGE,
            session.memory(),
        )
        .map_err(|error| session.error(error))?
    {
        return Ok(());
    }
    let mut kept = 0;
    for index in 0..effective.len() {
        if shared_usage_contains(&usage, effective[index], session)? {
            effective[kept] = effective[index];
            kept += 1;
        }
    }
    while effective.len() > kept {
        effective.pop();
    }
    if kept == 0 {
        return Err(X509ChainError::InvalidKeyUsage {
            position,
            required: "an approved extended key usage",
        });
    }
    Ok(())
}

fn shared_usage_contains(
    usage: &structured_pkix::usage::ExtendedKeyUsage<'_>,
    purpose: &ExtendedKeyPurpose,
    session: &super::pkix::CertificateSession,
) -> Result<bool, X509ChainError> {
    use structured_pkix::oid;
    let kind = match purpose {
        ExtendedKeyPurpose::ServerAuth => oid::SERVER_AUTH,
        ExtendedKeyPurpose::ClientAuth => oid::CLIENT_AUTH,
        ExtendedKeyPurpose::CodeSigning => oid::CODE_SIGNING,
        ExtendedKeyPurpose::EmailProtection => oid::EMAIL_PROTECTION,
        ExtendedKeyPurpose::TimeStamping => oid::TIME_STAMPING,
        ExtendedKeyPurpose::OcspSigning => oid::OCSP_SIGNING,
        ExtendedKeyPurpose::Other(expected) => {
            for kind in usage.purposes() {
                session
                    .memory()
                    .charge_work(kind.as_bytes().len() as u64 + expected.len() as u64 + 1)
                    .map_err(|reason| {
                        session.error(structured_pkix::Error::resource(
                            reason,
                            "certificate.extended_key_usage",
                            0,
                        ))
                    })?;
                let mut arcs = kind.arcs();
                let mut matches = true;
                for &expected in expected {
                    if arcs.next().and_then(|arc| arc.as_u64()) != Some(expected) {
                        matches = false;
                        break;
                    }
                }
                if matches && arcs.next().is_none() {
                    return Ok(true);
                }
            }
            return Ok(false);
        }
    };
    usage
        .has(kind, session.memory())
        .map_err(|error| session.error(error))
}

fn validate_shared_subject_identity(
    certificate: &structured_pkix::Certificate<'_>,
    session: &super::pkix::CertificateSession,
) -> Result<(), X509ChainError> {
    let subject = certificate.tbs().subject();
    for attribute in subject.attributes_of(structured_pkix::oid::EMAIL_ADDRESS, session.memory()) {
        let attribute = attribute.map_err(|error| session.error(error))?;
        let text = attribute
            .text(session.memory())
            .map_err(|error| session.error(error))?
            .ok_or_else(|| invalid_subject_identity("subject emailAddress is not text"))?;
        let text = text.as_str(session.memory()).map_err(|reason| {
            session.error(structured_pkix::Error::resource(
                reason,
                "certificate.subject",
                0,
            ))
        })?;
        session
            .memory()
            .charge_work(text.len() as u64)
            .map_err(|reason| {
                session.error(structured_pkix::Error::resource(
                    reason,
                    "certificate.subject",
                    0,
                ))
            })?;
        if !mailbox_has_valid_syntax(text) {
            return Err(invalid_subject_identity(
                "invalid subject emailAddress syntax",
            ));
        }
    }
    let extensions = certificate.tbs().extensions();
    let extension = extensions
        .get(structured_pkix::oid::SUBJECT_ALT_NAME, session.memory())
        .map_err(|error| session.error(error))?;
    let Some(extension) = extension else {
        return if subject.is_empty() {
            Err(invalid_subject_identity(
                "an empty subject requires a critical SubjectAlternativeName",
            ))
        } else {
            Ok(())
        };
    };
    // RFC 5280 4.1.2.6 / 4.2.1.6: empty subjects need a critical SAN;
    // the common decoder owns its schema, syntax and non-empty-list checks.
    // https://www.rfc-editor.org/rfc/rfc5280.html#section-4.2.1.6
    if let Err(error) = structured_pkix::general_name::read_alternative(extension, session.memory())
    {
        return Err(shared_san_error(extension, error, session)?);
    }
    if subject.is_empty() && !extension.is_critical() {
        return Err(invalid_subject_identity(
            "an empty subject requires a critical SubjectAlternativeName",
        ));
    }
    Ok(())
}

fn shared_san_error(
    extension: &structured_pkix::extension::Extension<'_>,
    error: structured_pkix::Error,
    session: &super::pkix::CertificateSession,
) -> Result<X509ChainError, X509ChainError> {
    if error.is_resource() {
        return Ok(session.error(error));
    }
    let decode_error = |error: structured_asn1::Error| {
        let error = structured_pkix::Error::new(
            structured_pkix::ErrorCode::Encoding(error.code()),
            "certificate.subjectAltName",
            error.offset(),
        );
        if error.is_resource() {
            session.error(error)
        } else {
            invalid_subject_identity("invalid SubjectAlternativeName")
        }
    };
    // Decode only on a semantic failure to preserve the existing distinction
    // between malformed IA5 encoding and a well-encoded invalid DNS name.
    // This is the producing parser/account, not a fresh diagnostic allowance.
    let mut reader = extension.reader(session.memory()).map_err(decode_error)?;
    let sequence = reader
        .expect(structured_asn1::Tag::constructed(
            structured_asn1::universal::SEQUENCE,
        ))
        .map_err(decode_error)?;
    let mut inside = reader.enter(&sequence).map_err(decode_error)?;
    while let Some(element) = inside.next_element().map_err(decode_error)? {
        if element.span().start != error.offset() {
            continue;
        }
        if element.tag() == structured_asn1::Tag::context(false, 2) {
            inside
                .charge(element.contents().len() as u64)
                .map_err(|error| {
                    session.error(structured_pkix::Error::new(
                        structured_pkix::ErrorCode::Encoding(error.code()),
                        "certificate.subjectAltName",
                        error.offset(),
                    ))
                })?;
            if element.contents().is_ascii() {
                return Ok(X509ChainError::InvalidDer {
                    kind: "certificate DNS name",
                    message: "invalid SubjectAlternativeName dNSName".into(),
                });
            }
        }
        break;
    }
    Ok(invalid_subject_identity("invalid SubjectAlternativeName"))
}

fn validate_shared_anchor_extensions(
    certificate: &structured_pkix::Certificate<'_>,
    position: usize,
    session: &super::pkix::CertificateSession,
) -> Result<(), X509ChainError> {
    use structured_pkix::{error::CallbackError, oid};
    let extensions = certificate.tbs().extensions();
    for extension in extensions.criticals(session.memory()) {
        let extension = extension.map_err(|error| session.error(error))?;
        let kind = extension.kind();
        let accepted = matches!(
            kind,
            oid::KEY_USAGE
                | oid::SUBJECT_ALT_NAME
                | oid::BASIC_CONSTRAINTS
                | oid::NAME_CONSTRAINTS
                | oid::EXT_KEY_USAGE
        );
        let understood = if accepted {
            match extensions.understands(extension, &(), session.memory()) {
                Ok(value) => value,
                Err(CallbackError::Processing(error)) => return Err(session.error(error)),
                Err(CallbackError::Callback(error)) => match error {},
            }
        } else {
            false
        };
        if !understood {
            if kind == oid::NAME_CONSTRAINTS {
                return Err(X509ChainError::InvalidNameConstraints { position });
            }
            let oid = kind.text(session.memory()).map_err(|reason| {
                session.error(structured_pkix::Error::resource(
                    reason,
                    "certificate.anchor",
                    extension.span().start,
                ))
            })?;
            let oid = oid.as_str(session.memory()).map_err(|reason| {
                session.error(structured_pkix::Error::resource(
                    reason,
                    "certificate.anchor",
                    extension.span().start,
                ))
            })?;
            return Err(X509ChainError::UnsupportedCriticalExtension {
                position,
                oid: oid.into(),
            });
        }
    }
    Ok(())
}

pub(crate) fn validate_issuer_spki_policy(
    encoded: &[u8],
    position: usize,
    rsa_keys: RsaKeyPolicy,
    dsa_keys: DsaKeyPolicy,
) -> Result<(), X509ChainError> {
    use der::Decode as _;
    let key = pkcs8::SubjectPublicKeyInfoRef::from_der(encoded).map_err(|error| {
        X509ChainError::InvalidDer {
            kind: "issuer SubjectPublicKeyInfo",
            message: error.to_string(),
        }
    })?;
    // RFC 5280 4.1.2.7 makes key encoding algorithm-specific. An opaque
    // algorithm's BIT STRING must not acquire RSA's octet-alignment rule.
    // https://www.rfc-editor.org/rfc/rfc5280.html#section-4.1.2.7
    match key.algorithm.oid {
        // RFC 4055 1.2/3.1: rsaEncryption and id-RSASSA-PSS identify RSA
        // public-key material. PSS restrictions never bypass the RSA minimum.
        // https://www.rfc-editor.org/rfc/rfc4055.html#section-1.2
        oid if oid == pkcs1::ALGORITHM_OID
            || oid.as_bytes() == structured_pkix::oid::RSASSA_PSS.as_bytes() =>
        {
            let octets =
                key.subject_public_key
                    .as_bytes()
                    .ok_or_else(|| X509ChainError::InvalidDer {
                        kind: "issuer SubjectPublicKeyInfo",
                        message: "RSA public key is not octet-aligned".into(),
                    })?;
            let key = pkcs1::RsaPublicKeyRef::from_der(octets).map_err(|error| {
                X509ChainError::InvalidDer {
                    kind: "RSA issuer SubjectPublicKeyInfo",
                    message: error.to_string(),
                }
            })?;
            rsa_keys
                .validate_components(
                    "X.509 issuer verification",
                    key.modulus.as_bytes(),
                    key.public_exponent.as_bytes(),
                )
                .map(|_| ())
                .map_err(|source| X509ChainError::KeyPolicy { position, source })
        }
        dsa::OID => {
            match super::signature::validate_dsa_signature_spki_with_minimum(
                encoded,
                dsa_keys.minimum_modulus_bits,
            ) {
                Ok(()) => Ok(()),
                Err(super::SignatureVerificationError::KeyPolicy(source)) => {
                    Err(X509ChainError::KeyPolicy { position, source })
                }
                Err(_) => Err(X509ChainError::InvalidDer {
                    kind: "DSA issuer SubjectPublicKeyInfo",
                    message: "invalid DSA key parameters".into(),
                }),
            }
        }
        _ => Ok(()),
    }
}

pub(crate) fn validate_positive_serial_bytes(
    serial: &[u8],
    kind: &'static str,
) -> Result<(), X509ChainError> {
    let magnitude = serial.strip_prefix(&[0]).unwrap_or(serial);
    if serial.is_empty()
        || serial[0] & 0x80 != 0
        || magnitude.is_empty()
        || magnitude.len() > 20
        || magnitude.iter().all(|byte| *byte == 0)
    {
        return Err(X509ChainError::InvalidDer {
            kind,
            message: "RFC 5280 requires a positive, non-zero value of at most 20 octets".into(),
        });
    }
    Ok(())
}

fn mailbox_has_valid_syntax(value: &str) -> bool {
    value.rsplit_once('@').is_some_and(|(local, domain)| {
        mailbox_local_part_has_valid_syntax(local) && mailbox_domain_has_valid_syntax(domain)
    })
}

fn mailbox_domain_has_valid_syntax(domain: &str) -> bool {
    let Some(literal) = domain
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
    else {
        return dns_name_has_valid_syntax(domain, false);
    };
    if literal
        .get(..5)
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("IPv6:"))
    {
        literal[5..].parse::<std::net::Ipv6Addr>().is_ok()
    } else {
        literal.parse::<std::net::Ipv4Addr>().is_ok()
    }
}

fn mailbox_local_part_has_valid_syntax(local: &str) -> bool {
    if let Some(quoted) = local
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
    {
        if quoted.is_empty() {
            return false;
        }
        let mut escaped = false;
        for byte in quoted.bytes() {
            if escaped {
                if !(0x20..=0x7e).contains(&byte) {
                    return false;
                }
                escaped = false;
            } else if byte == b'\\' {
                escaped = true;
            } else if byte == b'"' || !(0x20..=0x7e).contains(&byte) {
                return false;
            }
        }
        return !escaped;
    }

    local.split('.').all(|atom| {
        !atom.is_empty()
            && atom.bytes().all(|byte| {
                byte.is_ascii_alphanumeric()
                    || matches!(
                        byte,
                        b'!' | b'#'
                            | b'$'
                            | b'%'
                            | b'&'
                            | b'\''
                            | b'*'
                            | b'+'
                            | b'-'
                            | b'/'
                            | b'='
                            | b'?'
                            | b'^'
                            | b'_'
                            | b'`'
                            | b'{'
                            | b'|'
                            | b'}'
                            | b'~'
                    )
            })
    })
}

fn invalid_subject_identity(message: &str) -> X509ChainError {
    X509ChainError::InvalidDer {
        kind: "certificate subject identity",
        message: message.into(),
    }
}

#[cfg(test)]
fn verify_certificate_signature(
    certificate: &X509Certificate<'_>,
    issuer: &X509Certificate<'_>,
) -> bool {
    verify_certificate_signature_with_provider(
        certificate,
        issuer,
        crate::provider::default_provider(),
        None,
    )
    .unwrap_or(false)
}

#[cfg(test)]
fn verify_certificate_signature_with_provider(
    certificate: &X509Certificate<'_>,
    issuer: &X509Certificate<'_>,
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
) -> Result<bool, X509ChainError> {
    // RFC 5280 sections 4.1.1.2 and 4.1.2.3 require the outer and signed
    // AlgorithmIdentifier values to be identical. Enforce this independently
    // of the backend so the legacy DSA path cannot bypass the invariant.
    verify_x509_signed_object_with_provider(
        &certificate.signature_algorithm,
        &certificate.tbs_certificate.signature,
        &certificate.signature_value.data,
        certificate.tbs_certificate.as_ref(),
        issuer.public_key().raw,
        provider,
        allowed,
    )
}

/// Test a candidate certificate-path edge without assigning trust to either
/// certificate. Path construction uses this only to distinguish certificates
/// that share an issuer subject name; full policy validation still happens
/// after the complete path has been assembled.
#[cfg(test)]
pub(crate) fn certificate_signature_matches(certificate_der: &[u8], issuer_der: &[u8]) -> bool {
    certificate_signature_matches_with_provider(
        certificate_der,
        issuer_der,
        crate::provider::default_provider(),
        None,
        &super::pkix::CertificateSession::new(&crate::policy::ResourcePolicy::default()),
    )
    .unwrap_or(false)
}

pub(crate) fn certificate_signature_matches_with_provider(
    certificate_der: &[u8],
    issuer_der: &[u8],
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
    session: &super::pkix::CertificateSession,
) -> Result<bool, X509ChainError> {
    match certificate_signature_outcome_with_provider(
        certificate_der,
        issuer_der,
        provider,
        allowed,
        session,
    )? {
        structured_pkix::path::Verified::Yes => Ok(true),
        structured_pkix::path::Verified::No => Ok(false),
        _ => Err(X509ChainError::Provider(
            crate::provider::ProviderError::Unsupported {
                operation: crate::provider::ProviderOperation::VerifyCertificate,
                algorithm: None,
            },
        )),
    }
}

pub(crate) fn certificate_signature_outcome_with_provider(
    certificate_der: &[u8],
    issuer_der: &[u8],
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
    session: &super::pkix::CertificateSession,
) -> Result<structured_pkix::path::Verified, X509ChainError> {
    let certificate = session.read(certificate_der)?;
    let issuer = session.read(issuer_der)?;
    shared_certificate_signature_outcome(&certificate, &issuer, provider, allowed, session)
}

pub(crate) fn shared_certificate_signature_outcome(
    certificate: &structured_pkix::Certificate<'_>,
    issuer: &structured_pkix::Certificate<'_>,
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
    session: &super::pkix::CertificateSession,
) -> Result<structured_pkix::path::Verified, X509ChainError> {
    use structured_pkix::path::{Verify as _, WorkingKey};
    let verifier = super::pkix::ProviderVerifier { provider, allowed };
    verifier
        .verify(
            &certificate.tbs().signature(),
            WorkingKey::standing(issuer.tbs().public_key()),
            certificate.signed_bytes(),
            certificate.signature(),
            session.memory(),
        )
        .map_err(|error| match error {
            X509ChainError::Processing(error) => session.error(error),
            error => error,
        })
}

#[cfg(test)]
fn verify_crl_signature(crl: &CertificateRevocationList<'_>, issuer: &X509Certificate<'_>) -> bool {
    verify_crl_signature_with_provider(crl, issuer, crate::provider::default_provider(), None)
        .unwrap_or(false)
}

#[cfg(test)]
fn verify_crl_signature_with_provider(
    crl: &CertificateRevocationList<'_>,
    issuer: &X509Certificate<'_>,
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
) -> Result<bool, X509ChainError> {
    // RFC 5280 sections 5.1.1.2 and 5.1.2.2 impose the same equality rule on
    // CRLs as certificates.
    verify_x509_signed_object_with_provider(
        &crl.signature_algorithm,
        &crl.tbs_cert_list.signature,
        &crl.signature_value.data,
        crl.tbs_cert_list.as_ref(),
        issuer.public_key().raw,
        provider,
        allowed,
    )
}

#[cfg(test)]
fn verify_x509_signed_object_with_provider(
    outer_algorithm: &AlgorithmIdentifier<'_>,
    signed_algorithm: &AlgorithmIdentifier<'_>,
    signature_der: &[u8],
    signed_data: &[u8],
    issuer_spki_der: &[u8],
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
) -> Result<bool, X509ChainError> {
    if outer_algorithm != signed_algorithm {
        return Ok(false);
    }
    verify_x509_signature_with_provider(
        outer_algorithm,
        signature_der,
        signed_data,
        issuer_spki_der,
        provider,
        allowed,
    )
}

#[cfg(test)]
pub(crate) fn verify_x509_signature_with_provider(
    algorithm_identifier: &AlgorithmIdentifier<'_>,
    signature_der: &[u8],
    signed_data: &[u8],
    issuer_spki_der: &[u8],
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
) -> Result<bool, X509ChainError> {
    let algorithm = authorize_x509_signature_algorithm(algorithm_identifier, provider, allowed)?;
    provider
        .verify_x509_signature(algorithm, signed_data, signature_der, issuer_spki_der)
        .map_err(Into::into)
}

pub(crate) fn authorize_x509_signature_algorithm(
    algorithm_identifier: &AlgorithmIdentifier<'_>,
    provider: &dyn crate::provider::CryptoProvider,
    allowed: Option<&crate::policy::CertificateSignatureAlgorithms>,
) -> Result<X509SignatureAlgorithm, X509ChainError> {
    let algorithm = x509_signature_algorithm(algorithm_identifier)?;
    crate::policy::KeyTrustPolicy::check_certificate_signature_algorithm(algorithm, allowed)?;
    provider
        .require_capability(crate::provider::ProviderCapability::VerifyCertificate(
            algorithm,
        ))
        .map_err(X509ChainError::from)?;
    Ok(algorithm)
}

fn x509_signature_algorithm(
    identifier: &AlgorithmIdentifier<'_>,
) -> Result<X509SignatureAlgorithm, X509ChainError> {
    let oid = identifier.algorithm.to_id_string();
    let algorithm = match oid.as_str() {
        "1.2.840.10040.4.3" => X509SignatureAlgorithm::Dsa(super::DigestAlgorithm::Sha1),
        "2.16.840.1.101.3.4.3.1" => X509SignatureAlgorithm::Dsa(super::DigestAlgorithm::Sha224),
        "2.16.840.1.101.3.4.3.2" => X509SignatureAlgorithm::Dsa(super::DigestAlgorithm::Sha256),
        "2.16.840.1.101.3.4.3.3" => X509SignatureAlgorithm::Dsa(super::DigestAlgorithm::Sha384),
        "2.16.840.1.101.3.4.3.4" => X509SignatureAlgorithm::Dsa(super::DigestAlgorithm::Sha512),
        "1.2.840.113549.1.1.5" | "1.3.14.3.2.29" => {
            X509SignatureAlgorithm::RsaPkcs1v15(super::DigestAlgorithm::Sha1)
        }
        "1.2.840.113549.1.1.14" => {
            X509SignatureAlgorithm::RsaPkcs1v15(super::DigestAlgorithm::Sha224)
        }
        "1.2.840.113549.1.1.11" => {
            X509SignatureAlgorithm::RsaPkcs1v15(super::DigestAlgorithm::Sha256)
        }
        "1.2.840.113549.1.1.12" => {
            X509SignatureAlgorithm::RsaPkcs1v15(super::DigestAlgorithm::Sha384)
        }
        "1.2.840.113549.1.1.13" => {
            X509SignatureAlgorithm::RsaPkcs1v15(super::DigestAlgorithm::Sha512)
        }
        "1.2.840.113549.1.1.10" => parse_rsa_pss_algorithm(identifier)?,
        "1.2.840.10045.4.1" => X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha1),
        "1.2.840.10045.4.3.1" => X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha224),
        "1.2.840.10045.4.3.2" => X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha256),
        "1.2.840.10045.4.3.3" => X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha384),
        "1.2.840.10045.4.3.4" => X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha512),
        // NIST CSOR, "ECDSA with SHA-3 family", assigns these identifiers.
        // https://csrc.nist.gov/projects/computer-security-objects-register/algorithm-registration
        // The shared ECDSA parameter check below also applies to SHA-3.
        "2.16.840.1.101.3.4.3.9" => X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha3_224),
        "2.16.840.1.101.3.4.3.10" => {
            X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha3_256)
        }
        "2.16.840.1.101.3.4.3.11" => {
            X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha3_384)
        }
        "2.16.840.1.101.3.4.3.12" => {
            X509SignatureAlgorithm::Ecdsa(super::DigestAlgorithm::Sha3_512)
        }
        "1.3.101.112" => X509SignatureAlgorithm::Ed25519,
        // RFC 8410 sections 3 and 6 require absent Ed448 parameters:
        // https://www.rfc-editor.org/rfc/rfc8410.html#section-3
        "1.3.101.113" => X509SignatureAlgorithm::Ed448,
        _ => {
            let Some(algorithm) = super::PqAlgorithm::ALL
                .into_iter()
                .find(|algorithm| algorithm.oid() == oid)
            else {
                return Err(X509ChainError::UnsupportedSignatureAlgorithm { oid });
            };
            X509SignatureAlgorithm::PostQuantum(algorithm)
        }
    };
    match &algorithm {
        X509SignatureAlgorithm::Dsa(_)
        | X509SignatureAlgorithm::Ecdsa(_)
        | X509SignatureAlgorithm::Ed25519
        | X509SignatureAlgorithm::Ed448 => require_absent_signature_parameters(identifier)?,
        X509SignatureAlgorithm::PostQuantum(_) => {
            // RFC 9881 §2 / RFC 9909 §3 forbid even NULL parameters.
            // https://www.rfc-editor.org/rfc/rfc9881.html#section-2
            // https://www.rfc-editor.org/rfc/rfc9909.html#section-3
            require_absent_signature_parameters(identifier)?;
        }
        X509SignatureAlgorithm::RsaPkcs1v15(_) => {
            require_null_or_absent_signature_parameters(identifier)?;
        }
        X509SignatureAlgorithm::RsaPss { .. } => {}
    }
    Ok(algorithm)
}

fn require_absent_signature_parameters(
    identifier: &AlgorithmIdentifier<'_>,
) -> Result<(), X509ChainError> {
    if identifier.parameters.is_some() {
        return Err(invalid_signature_parameters(
            identifier,
            "parameters must be absent",
        ));
    }
    Ok(())
}

fn require_null_or_absent_signature_parameters(
    identifier: &AlgorithmIdentifier<'_>,
) -> Result<(), X509ChainError> {
    if identifier
        .parameters
        .as_ref()
        .is_some_and(|parameters| parameters.tag() != x509_parser::asn1_rs::Tag::Null)
    {
        return Err(invalid_signature_parameters(
            identifier,
            "parameters must be NULL or absent",
        ));
    }
    Ok(())
}

fn invalid_signature_parameters(
    identifier: &AlgorithmIdentifier<'_>,
    requirement: &str,
) -> X509ChainError {
    X509ChainError::InvalidDer {
        kind: "X.509 signature AlgorithmIdentifier parameters",
        message: format!("{}: {requirement}", identifier.algorithm),
    }
}

fn parse_rsa_pss_algorithm(
    identifier: &AlgorithmIdentifier<'_>,
) -> Result<X509SignatureAlgorithm, X509ChainError> {
    let parameters = identifier
        .parameters
        .as_ref()
        .ok_or_else(|| X509ChainError::InvalidDer {
            kind: "RSASSA-PSS parameters",
            message: "missing parameters".into(),
        })?;
    let parameters = x509_parser::signature_algorithm::RsaSsaPssParams::try_from(parameters)
        .map_err(|error| X509ChainError::InvalidDer {
            kind: "RSASSA-PSS parameters",
            message: error.to_string(),
        })?;
    if parameters.trailer_field() != 1 {
        return Err(X509ChainError::InvalidDer {
            kind: "RSASSA-PSS parameters",
            message: "trailerField must be 1".into(),
        });
    }
    let digest = x509_digest_algorithm(&parameters.hash_algorithm_oid().to_id_string())?;
    let mask = parameters
        .mask_gen_algorithm()
        .map_err(|error| X509ChainError::InvalidDer {
            kind: "RSASSA-PSS parameters",
            message: error.to_string(),
        })?;
    if mask.mgf.to_id_string() != "1.2.840.113549.1.1.8" {
        return Err(X509ChainError::UnsupportedSignatureAlgorithm {
            oid: mask.mgf.to_id_string(),
        });
    }
    let mgf_digest = x509_digest_algorithm(&mask.hash.to_id_string())?;
    let salt_len =
        usize::try_from(parameters.salt_length()).map_err(|_| X509ChainError::InvalidDer {
            kind: "RSASSA-PSS parameters",
            message: "saltLength does not fit this platform".into(),
        })?;
    Ok(X509SignatureAlgorithm::RsaPss {
        digest,
        mgf_digest,
        salt_len,
    })
}

fn x509_digest_algorithm(oid: &str) -> Result<super::DigestAlgorithm, X509ChainError> {
    match oid {
        "1.3.14.3.2.26" => Ok(super::DigestAlgorithm::Sha1),
        "2.16.840.1.101.3.4.2.4" => Ok(super::DigestAlgorithm::Sha224),
        "2.16.840.1.101.3.4.2.1" => Ok(super::DigestAlgorithm::Sha256),
        "2.16.840.1.101.3.4.2.2" => Ok(super::DigestAlgorithm::Sha384),
        "2.16.840.1.101.3.4.2.3" => Ok(super::DigestAlgorithm::Sha512),
        _ => Err(X509ChainError::UnsupportedSignatureAlgorithm {
            oid: oid.to_owned(),
        }),
    }
}

#[cfg(test)]
fn parse_certificate(der: &[u8]) -> Result<X509Certificate<'_>, X509ChainError> {
    let (rest, cert) =
        X509Certificate::from_der(der).map_err(|error| X509ChainError::InvalidDer {
            kind: "certificate",
            message: error.to_string(),
        })?;
    if !rest.is_empty() {
        return Err(X509ChainError::InvalidDer {
            kind: "certificate",
            message: "trailing data".into(),
        });
    }
    Ok(cert)
}

#[cfg(test)]
fn system_time_to_asn1(time: SystemTime) -> Result<ASN1Time, X509ChainError> {
    let instant = super::pkix::verification_instant(time)?;
    // RFC 5280 6.1.3(a)(2) compares the actual validation time, not its
    // whole-second truncation. Keep the same instant for CRL freshness.
    // https://www.rfc-editor.org/rfc/rfc5280.html#section-6.1.3
    let whole = ASN1Time::from_timestamp(instant.seconds()).map_err(|error| {
        X509ChainError::InvalidDer {
            kind: "verification time",
            message: error.to_string(),
        }
    })?;
    whole
        .to_datetime()
        .replace_nanosecond(instant.nanos())
        .map(ASN1Time::new)
        .map_err(|error| X509ChainError::InvalidDer {
            kind: "verification time",
            message: error.to_string(),
        })
}

fn dns_name_has_valid_syntax(value: &str, allow_leading_dot: bool) -> bool {
    let domain = if allow_leading_dot {
        value.strip_prefix('.').unwrap_or(value)
    } else {
        value
    };
    if domain.is_empty()
        || domain.len() > 253
        || domain.split('.').any(|label| {
            label.is_empty()
                || label.len() > 63
                || !label
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
                || !label
                    .as_bytes()
                    .first()
                    .is_some_and(u8::is_ascii_alphanumeric)
                || !label
                    .as_bytes()
                    .last()
                    .is_some_and(u8::is_ascii_alphanumeric)
        })
    {
        return false;
    }
    true
}

#[cfg(test)]
mod tests {
    use std::str::FromStr as _;

    use super::*;
    use crate::xml::dom::Document;
    use crate::xmldsig::{KeyInfoSource, parse::XMLDSIG_NS, parse_key_info};
    use p256::pkcs8::EncodePublicKey;
    use sha2::{Digest, Sha256, Sha384};
    use signature::hazmat::PrehashSigner;
    use std::time::{Duration, UNIX_EPOCH};
    use x509_parser::oid_registry::{OID_SIG_ECDSA_WITH_SHA256, OID_SIG_ECDSA_WITH_SHA384, Oid};

    #[test]
    fn issuer_spki_preflight_checks_borrowed_components_and_exact_der()
    -> Result<(), Box<dyn std::error::Error>> {
        // Strength and exact framing are enforced before bigint decoding or
        // signature work; the reported position stays attached to the issuer.
        use der::Encode as _;
        let modulus = [0xff; 32];
        let exponent = [1, 0, 1];
        let public = pkcs1::RsaPublicKeyRef {
            modulus: der::asn1::UintRef::new(&modulus)?,
            public_exponent: der::asn1::UintRef::new(&exponent)?,
        }
        .to_der()?;
        let encoded = pkcs8::SubjectPublicKeyInfoRef {
            algorithm: pkcs1::ALGORITHM_ID,
            subject_public_key: der::asn1::BitStringRef::from_bytes(&public)?,
        }
        .to_der()?;
        assert!(matches!(
            validate_issuer_spki_policy(
                &encoded,
                7,
                RsaKeyPolicy::default(),
                DsaKeyPolicy::default()
            ),
            Err(X509ChainError::KeyPolicy { position: 7, .. }),
        ));
        // RFC 4055 3.1 permits absent parameters for PSS SPKI, but its key
        // material is still RSA and must obey the same strength policy.
        // https://www.rfc-editor.org/rfc/rfc4055.html#section-3.1
        let pss = pkcs8::SubjectPublicKeyInfoRef {
            algorithm: pkcs8::AlgorithmIdentifierRef {
                oid: der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10"),
                parameters: None,
            },
            subject_public_key: der::asn1::BitStringRef::from_bytes(&public)?,
        }
        .to_der()?;
        assert!(matches!(
            validate_issuer_spki_policy(&pss, 7, RsaKeyPolicy::default(), DsaKeyPolicy::default()),
            Err(X509ChainError::KeyPolicy { position: 7, .. }),
        ));
        let mut trailing = encoded.clone();
        trailing.push(0);
        assert!(matches!(
            validate_issuer_spki_policy(
                &trailing,
                7,
                RsaKeyPolicy::default(),
                DsaKeyPolicy::default()
            ),
            Err(X509ChainError::InvalidDer {
                kind: "issuer SubjectPublicKeyInfo",
                ..
            }),
        ));
        let unaligned = pkcs8::SubjectPublicKeyInfoRef {
            algorithm: pkcs1::ALGORITHM_ID,
            subject_public_key: der::asn1::BitStringRef::new(1, &[0])?,
        }
        .to_der()?;
        assert!(matches!(
            validate_issuer_spki_policy(
                &unaligned,
                7,
                RsaKeyPolicy::default(),
                DsaKeyPolicy::default()
            ),
            Err(X509ChainError::InvalidDer {
                kind: "issuer SubjectPublicKeyInfo",
                ..
            }),
        ));
        // A generic SPKI BIT STRING does not require octet alignment. Unknown
        // algorithms have no RSA/DSA strength contract to guess here.
        let opaque = pkcs8::SubjectPublicKeyInfoRef {
            algorithm: pkcs8::AlgorithmIdentifierRef {
                oid: der::asn1::ObjectIdentifier::new_unwrap("1.2.3.4"),
                parameters: None,
            },
            subject_public_key: der::asn1::BitStringRef::new(1, &[0])?,
        }
        .to_der()?;
        validate_issuer_spki_policy(&opaque, 7, RsaKeyPolicy::default(), DsaKeyPolicy::default())?;
        Ok(())
    }

    #[test]
    fn verification_time_retains_subseconds_on_both_sides_of_epoch() {
        // A fractional instant must not extend notAfter or shift a pre-epoch
        // validation request forward to the next second.
        for (input, seconds, nanos) in [
            (UNIX_EPOCH + Duration::new(1, 123), 1, 123),
            (UNIX_EPOCH - Duration::new(1, 123), -2, 999_999_877),
        ] {
            let actual = system_time_to_asn1(input).expect("representable validation time");
            assert_eq!(actual.timestamp(), seconds);
            assert_eq!(actual.to_datetime().nanosecond(), nanos);
        }
    }

    #[test]
    fn exact_certificate_pin_does_not_bypass_execution_budget() {
        // Caller trust skips path construction, not certificate decoding/accounting.
        let certificate = generated_certificate_params("pinned signer", false)
            .self_signed(&rcgen::KeyPair::generate().expect("test key"))
            .expect("test certificate");
        let anchors = vec![certificate.der().to_vec()];
        let info = X509DataInfo {
            certificates: anchors.clone(),
            certificate_chain: vec![0],
            ..X509DataInfo::default()
        };
        let options = X509ChainOptions {
            trusted_certs: &anchors,
            verification_time: SystemTime::now(),
            max_chain_depth: 1,
            utc_facts: None,
            check_crls: false,
            allowed_extended_key_usages: None,
            rsa_keys: RsaKeyPolicy::default(),
            dsa_keys: DsaKeyPolicy::default(),
            certificate_signature_algorithms: None,
        };
        let session = super::super::pkix::CertificateSession::new(&crate::policy::ResourcePolicy {
            max_x509_work: 0,
            ..crate::policy::ResourcePolicy::default()
        });
        assert!(matches!(
            verify_x509_certificate_chain_in_session(
                &info,
                &options,
                crate::provider::default_provider(),
                &[],
                &session,
            ),
            Err(X509ChainError::Policy(
                crate::policy::PolicyViolation::ResourceLimitExceeded {
                    resource: crate::policy::resource_name::X509_WORK,
                    maximum: 0,
                }
            ))
        ));
    }

    #[test]
    fn crl_key_usage_absence_depends_on_certificate_version() {
        // RFC 10007's v1/v2 exemption is checked on original DER by the shared
        // authentication API, not a mutated phase-local parser projection.
        use der::{Decode as _, Encode as _};
        let mut params = rcgen::CertificateParams::new(Vec::new()).expect("empty SANs are valid");
        params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "CRL issuer");
        let certificate = params
            .self_signed(&rcgen::KeyPair::generate().expect("test key generation"))
            .expect("test certificate signing");
        let encoded =
            x509_cert::Certificate::from_der(certificate.der()).expect("generated issuer DER");
        let mut crl: x509_cert::crl::CertificateList =
            x509_cert::crl::CertificateList::from_der(&merlin_crl_der()).expect("Merlin CRL DER");
        crl.tbs_cert_list.issuer = encoded.tbs_certificate().subject().clone();
        let crl_bytes = crl.to_der().expect("modified CRL encoding");
        for version in [
            x509_cert::Version::V1,
            x509_cert::Version::V2,
            x509_cert::Version::V3,
        ] {
            use der::Tagged as _;
            let mut fields = Vec::<der::asn1::Any>::from_der(
                &encoded
                    .tbs_certificate()
                    .to_der()
                    .expect("issuer TBS encoding"),
            )
            .expect("issuer TBS fields");
            fields.remove(0); // Replace the explicitly encoded v3 version.
            fields.retain(|field| {
                field.tag()
                    != der::Tag::ContextSpecific {
                        constructed: true,
                        number: der::TagNumber(3),
                    }
            });
            if version != x509_cert::Version::V1 {
                fields.insert(
                    0,
                    der::asn1::Any::from_der(&[0xa0, 3, 2, 1, version as u8])
                        .expect("version encoding"),
                );
            }
            let sequence = vec![
                der::asn1::Any::from_der(&fields.to_der().expect("modified TBS encoding"))
                    .expect("modified TBS sequence"),
                der::asn1::Any::from_der(
                    &encoded
                        .signature_algorithm()
                        .to_der()
                        .expect("signature algorithm encoding"),
                )
                .expect("signature algorithm sequence"),
                der::asn1::Any::from_der(
                    &encoded.signature().to_der().expect("signature encoding"),
                )
                .expect("signature BIT STRING"),
            ];
            let bytes = sequence.to_der().expect("modified issuer encoding");
            let session = super::super::pkix::CertificateSession::new(
                &crate::policy::ResourcePolicy::default(),
            );
            let issuer = session.read(&bytes).expect("modified issuer parses");
            let crl = session.read_crl(&crl_bytes).expect("modified CRL parses");
            let outcome = crl
                .authenticate(
                    &issuer,
                    structured_pkix::path::WorkingKey::standing(issuer.tbs().public_key()),
                    &FormatOnly,
                    session.memory(),
                )
                .expect("format-only authentication returns an outcome");
            if version == x509_cert::Version::V3 {
                assert!(matches!(
                    outcome,
                    structured_pkix::crl::Authentication::Rejected(
                        structured_pkix::crl::AuthenticationFailure::KeyUsage
                    )
                ));
            } else {
                assert!(matches!(
                    outcome,
                    structured_pkix::crl::Authentication::Authenticated(_)
                ));
            }
        }
    }

    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 verify_generated_path(
        certificates: Vec<Vec<u8>>,
        trusted_anchor: Vec<u8>,
    ) -> Result<(), X509ChainError> {
        verify_generated_path_with_eku(certificates, trusted_anchor, None)
    }

    fn verify_generated_path_with_eku(
        certificates: Vec<Vec<u8>>,
        trusted_anchor: Vec<u8>,
        allowed_extended_key_usages: Option<&HashSet<ExtendedKeyPurpose>>,
    ) -> Result<(), X509ChainError> {
        let info = X509DataInfo {
            certificate_chain: (0..certificates.len()).collect(),
            certificates,
            ..X509DataInfo::default()
        };
        let anchors = vec![trusted_anchor];
        verify_x509_certificate_chain(
            &info,
            &X509ChainOptions {
                trusted_certs: &anchors,
                utc_facts: None,
                verification_time: SystemTime::now(),
                max_chain_depth: info.certificate_chain.len(),
                check_crls: false,
                allowed_extended_key_usages,
                rsa_keys: RsaKeyPolicy::default(),
                dsa_keys: DsaKeyPolicy::default(),
                certificate_signature_algorithms: None,
            },
        )
    }

    fn verify_generated_constraints(
        constraints: x509_cert::ext::pkix::NameConstraints,
        name: x509_cert::ext::pkix::name::GeneralName,
    ) -> Result<(), X509ChainError> {
        use der::Encode as _;
        let mut root_params = generated_certificate_params("constraint authority", true);
        let mut constraint_extension = rcgen::CustomExtension::from_oid_content(
            &[2, 5, 29, 30],
            constraints.to_der().expect("constraint fixture DER"),
        );
        constraint_extension.set_criticality(true);
        root_params.custom_extensions.push(constraint_extension);
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("constraint root key"),
        )
        .expect("constraint root");
        let mut leaf_params = generated_certificate_params("constraint signer", false);
        let mut san = rcgen::CustomExtension::from_oid_content(
            &[2, 5, 29, 17],
            vec![name].to_der().expect("SAN fixture DER"),
        );
        san.set_criticality(true);
        leaf_params.custom_extensions.push(san);
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("constraint leaf key"),
                &root,
            )
            .expect("constraint leaf");
        let session =
            super::super::pkix::CertificateSession::new(&crate::policy::ResourcePolicy::default());
        let leaf = session.read(leaf.der())?;
        let root = session.read(root.der())?;
        let options = X509ChainOptions {
            trusted_certs: &[],
            utc_facts: None,
            verification_time: SystemTime::now(),
            max_chain_depth: 2,
            check_crls: false,
            allowed_extended_key_usages: None,
            rsa_keys: RsaKeyPolicy::default(),
            dsa_keys: DsaKeyPolicy::default(),
            certificate_signature_algorithms: None,
        };
        super::super::pkix::validate_supplied_path(
            &[&leaf],
            &root,
            &options,
            crate::provider::default_provider(),
            &session,
        )
        .map(|_| ())
    }

    #[test]
    fn noncritical_ca_basic_constraints_remain_path_compatible() {
        // Criticality is an issuer conformance requirement, not an additional
        // relying-party path gate; historical xmlsec1 chains depend on this.
        let mut params = generated_certificate_params("non-critical authority", false);
        params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        params
            .custom_extensions
            .push(rcgen::CustomExtension::from_oid_content(
                &[2, 5, 29, 19],
                vec![0x30, 0x03, 0x01, 0x01, 0xff],
            ));
        let key = rcgen::KeyPair::generate().expect("CA key generation should succeed");
        let issuer = rcgen::Issuer::from_params(&params, &key);
        let certificate = params
            .clone()
            .self_signed(&key)
            .expect("test CA should be self-signable");
        let leaf = generated_certificate_params("noncritical CA target", false)
            .signed_by(&rcgen::KeyPair::generate().expect("target key"), &issuer)
            .expect("target certificate");
        verify_generated_path(
            vec![leaf.der().to_vec(), certificate.der().to_vec()],
            certificate.der().to_vec(),
        )
        .expect("the actual common path accepts noncritical cA");
    }

    #[test]
    fn restricted_leaf_eku_requires_an_approved_purpose() {
        // A server-authentication certificate is not implicitly authorized for
        // XML signatures merely because its key permits digital signatures.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("EKU authority", 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 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 leaf_der = leaf.der().to_vec();
        let root_der = root.der().to_vec();

        assert!(matches!(
            verify_generated_path(vec![leaf_der.clone(), root_der.clone()], root_der.clone(),),
            Err(X509ChainError::InvalidKeyUsage {
                position: 0,
                required: "an approved extended key usage",
            })
        ));

        let allowed = HashSet::from([ExtendedKeyPurpose::ServerAuth]);
        verify_generated_path_with_eku(vec![leaf_der, root_der.clone()], root_der, Some(&allowed))
            .expect("an explicitly approved leaf purpose must be accepted");
    }

    #[test]
    fn critical_leaf_eku_uses_the_same_purpose_policy() {
        // Criticality changes whether an unknown extension may be ignored, not
        // the authorization semantics of an EKU that this validator implements.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("critical EKU authority", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("critical TLS signer", false);
        leaf_params.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature];
        let mut extension = rcgen::CustomExtension::from_oid_content(
            &[2, 5, 29, 37],
            vec![
                0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01,
            ],
        );
        extension.set_criticality(true);
        leaf_params.custom_extensions.push(extension);
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign leaf certificate");
        let allowed = HashSet::from([ExtendedKeyPurpose::ServerAuth]);

        verify_generated_path_with_eku(
            vec![leaf.der().to_vec(), root.der().to_vec()],
            root.der().to_vec(),
            Some(&allowed),
        )
        .expect("approved critical EKU must be processed rather than rejected as unknown");
    }

    #[test]
    fn issuer_eku_restricts_the_entire_certificate_path() {
        // RFC 5280 applies an issuer EKU as a path-wide purpose constraint. A
        // leaf approval cannot override an incompatible critical CA authorization.
        for (issuer_purpose_der, accepted) in [
            (
                vec![
                    0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02,
                ],
                false,
            ),
            (
                vec![
                    0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01,
                ],
                true,
            ),
        ] {
            let mut root_params =
                generated_certificate_params("purpose-constrained authority", true);
            let mut extension =
                rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 37], issuer_purpose_der);
            extension.set_criticality(true);
            root_params.custom_extensions.push(extension);
            let root = rcgen::CertifiedIssuer::self_signed(
                root_params,
                rcgen::KeyPair::generate().expect("root key generation should succeed"),
            )
            .expect("root should be self-signable");
            let mut leaf_params = generated_certificate_params("TLS server 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 allowed = HashSet::from([
                ExtendedKeyPurpose::ServerAuth,
                ExtendedKeyPurpose::ClientAuth,
            ]);
            let result = verify_generated_path_with_eku(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
                Some(&allowed),
            );

            if accepted {
                result.expect("a shared allowed purpose must satisfy the complete path");
            } else {
                assert!(matches!(
                    result,
                    Err(X509ChainError::InvalidKeyUsage {
                        position: 1,
                        required: "an approved extended key usage",
                    })
                ));
            }
        }
    }

    #[test]
    fn any_extended_key_usage_does_not_restrict_xml_signing() {
        // RFC 5280 anyExtendedKeyUsage explicitly leaves the key unrestricted,
        // so it does not require a deployment-specific purpose allowlist entry.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("any EKU authority", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("unrestricted signer", false);
        leaf_params.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature];
        leaf_params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::Any];
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign leaf certificate");

        verify_generated_path(
            vec![leaf.der().to_vec(), root.der().to_vec()],
            root.der().to_vec(),
        )
        .expect("anyExtendedKeyUsage must remain unrestricted");
    }

    #[test]
    #[cfg(feature = "experimental-pq")]
    fn pq_certificate_verification_requires_explicit_trust_permission() {
        use super::super::{
            PostQuantumSigningKey, PqAlgorithm, SignatureAlgorithm, SignatureContext, SigningKey,
        };
        // The provider must support a valid pure PKIX signature, but that
        // compiled capability cannot authorize certificate/CRL trust by itself.
        let parameter = PqAlgorithm::MlDsa44;
        let key = PostQuantumSigningKey::from_pkcs8_der(
            parameter,
            include_bytes!("../../tests/fixtures/xmldsig/keys/ml-dsa/ml-dsa-44-key.der"),
        )
        .expect("donor ML-DSA private key must import");
        let data = b"PKIX signed data";
        let provider = crate::provider::default_provider();
        let signature = provider
            .sign_with_context(
                &key,
                SignatureAlgorithm::PostQuantum(parameter),
                &SignatureContext::default(),
                data,
            )
            .expect("ML-DSA key must sign PKIX data");
        let public = key.public_key_info().expect("public key must export");
        let spki = public.spki_der().expect("PQ public key must contain SPKI");
        let algorithm = X509SignatureAlgorithm::PostQuantum(parameter);
        assert!(
            provider
                .verify_x509_signature(algorithm, data, &signature, spki)
                .expect("provider must verify valid PQ signature")
        );
        let identifier = AlgorithmIdentifier::new(
            parameter
                .oid()
                .parse()
                .expect("registered PQ OID must parse"),
            None,
        );
        assert!(
            verify_x509_signature_with_provider(
                &identifier,
                &signature,
                data,
                spki,
                provider,
                None
            )
            .is_err(),
            "default certificate policy must reject PQ before provider verification"
        );
        let permitted =
            crate::policy::CertificateSignatureAlgorithms::Allowlist(HashSet::from([algorithm]));
        assert!(
            verify_x509_signed_object_with_provider(
                &identifier,
                &identifier,
                &signature,
                data,
                spki,
                provider,
                Some(&permitted)
            )
            .expect("explicit permission must enable valid PQ authentication")
        );
        assert!(matches!(
            verify_x509_signed_object_with_provider(
                &identifier,
                &identifier,
                &signature,
                data,
                spki,
                provider,
                Some(&crate::policy::CertificateSignatureAlgorithms::Allowlist(
                    HashSet::new()
                ))
            ),
            Err(X509ChainError::Policy(_))
        ));
    }

    #[test]
    fn x509_ecdsa_hash_oid_does_not_select_the_issuer_curve() {
        // RFC 5758 signature OIDs select the digest while SubjectPublicKeyInfo
        // selects the curve. Both non-default pairings must therefore reach
        // the provider with the issuer's actual curve rather than a curve
        // inferred from the hash OID.
        let data = b"certificate tbs bytes";

        let p384_key = p384::ecdsa::SigningKey::from_slice(&[0x42; 48])
            .expect("fixed P-384 test key must be valid");
        let p384_signature: p384::ecdsa::Signature = p384_key
            .sign_prehash(&Sha256::digest(data))
            .expect("P-384 must sign a SHA-256 prehash");
        let p384_spki = p384_key
            .verifying_key()
            .to_public_key_der()
            .expect("P-384 SPKI must encode");
        assert!(
            verify_x509_signature_with_provider(
                &AlgorithmIdentifier::new(OID_SIG_ECDSA_WITH_SHA256, None),
                p384_signature.to_der().as_bytes(),
                data,
                p384_spki.as_bytes(),
                crate::provider::default_provider(),
                None,
            )
            .expect("P-384 with SHA-256 must be a supported X.509 pairing")
        );

        let p256_key = p256::ecdsa::SigningKey::from_slice(&[0x24; 32])
            .expect("fixed P-256 test key must be valid");
        let p256_signature: p256::ecdsa::Signature = p256_key
            .sign_prehash(&Sha384::digest(data))
            .expect("P-256 must sign a SHA-384 prehash");
        let p256_spki = p256_key
            .verifying_key()
            .to_public_key_der()
            .expect("P-256 SPKI must encode");
        assert!(
            verify_x509_signature_with_provider(
                &AlgorithmIdentifier::new(OID_SIG_ECDSA_WITH_SHA384, None),
                p256_signature.to_der().as_bytes(),
                data,
                p256_spki.as_bytes(),
                crate::provider::default_provider(),
                None,
            )
            .expect("P-256 with SHA-384 must be a supported X.509 pairing")
        );
    }

    #[test]
    fn path_edge_signature_check_does_not_repeat_name_matching() {
        // Path construction performs RFC 5280 name matching before asking this
        // helper to disambiguate same-name candidates. Only proof of possession
        // of the issuer key belongs in this second gate.
        let issuer_key = rcgen::KeyPair::generate().expect("issuer key generation should succeed");
        let issuer_key_pem = issuer_key.serialize_pem();
        let mut signing_params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty issuer SAN list should be valid");
        signing_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "signing name");
        signing_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        signing_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        let signing_issuer = rcgen::CertifiedIssuer::self_signed(signing_params, issuer_key)
            .expect("issuer certificate should be self-signable");

        let mut alternate_params = rcgen::CertificateParams::new(Vec::new())
            .expect("empty alternate SAN list should be valid");
        alternate_params
            .distinguished_name
            .push(rcgen::DnType::CommonName, "name already matched by caller");
        alternate_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
        alternate_params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign];
        let alternate_issuer = rcgen::CertifiedIssuer::self_signed(
            alternate_params,
            rcgen::KeyPair::from_pem(&issuer_key_pem)
                .expect("serialized issuer key should parse again"),
        )
        .expect("alternate issuer certificate should be self-signable");

        let leaf = rcgen::CertificateParams::new(Vec::new())
            .expect("empty leaf SAN list should be valid")
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &signing_issuer,
            )
            .expect("issuer should sign leaf certificate");

        assert!(certificate_signature_matches(
            leaf.der(),
            alternate_issuer.der()
        ));
    }

    #[test]
    fn certificate_path_edge_preserves_ed25519_verification() {
        // Provider routing must preserve the certificate algorithms accepted by
        // the previous x509-parser verifier rather than narrowing them to the
        // XMLDSig SignatureMethod enum.
        let issuer_key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519)
            .expect("Ed25519 issuer key generation should succeed");
        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, "Ed25519 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, issuer_key)
            .expect("Ed25519 issuer certificate should be self-signable");
        let leaf_key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519)
            .expect("Ed25519 leaf key generation should succeed");
        let leaf = rcgen::CertificateParams::new(Vec::new())
            .expect("empty leaf SAN list should be valid")
            .signed_by(&leaf_key, &issuer)
            .expect("Ed25519 issuer should sign leaf certificate");

        assert!(certificate_signature_matches(leaf.der(), issuer.der()));
    }

    #[test]
    fn ed448_certificate_signature_identifier_requires_absent_parameters() {
        use x509_parser::asn1_rs::{Any, Tag};

        // RFC 8410 sections 3 and 6 assign Ed448's OID and require absent
        // parameters, not ASN.1 NULL, for its signature identifier.
        let oid = Oid::from_str("1.3.101.113").expect("RFC 8410 Ed448 OID must parse");
        assert!(x509_signature_algorithm(&AlgorithmIdentifier::new(oid.clone(), None)).is_ok());
        assert!(matches!(
            x509_signature_algorithm(&AlgorithmIdentifier::new(
                oid,
                Some(Any::from_tag_and_data(Tag::Null, &[]))
            )),
            Err(X509ChainError::InvalidDer {
                kind: "X.509 signature AlgorithmIdentifier parameters",
                ..
            })
        ));
    }

    #[test]
    fn every_modeled_non_parameterized_x509_algorithm_reaches_the_provider() {
        // Parsing and provider capability are separate contracts. Once an OID
        // has a typed representation, custom providers must get the chance to
        // implement it even when RustCrypto does not.
        for (oid, expected) in [
            (
                "2.16.840.1.101.3.4.3.1",
                X509SignatureAlgorithm::Dsa(super::super::DigestAlgorithm::Sha224),
            ),
            (
                "2.16.840.1.101.3.4.3.2",
                X509SignatureAlgorithm::Dsa(super::super::DigestAlgorithm::Sha256),
            ),
            (
                "2.16.840.1.101.3.4.3.3",
                X509SignatureAlgorithm::Dsa(super::super::DigestAlgorithm::Sha384),
            ),
            (
                "2.16.840.1.101.3.4.3.4",
                X509SignatureAlgorithm::Dsa(super::super::DigestAlgorithm::Sha512),
            ),
            (
                "1.2.840.10045.4.1",
                X509SignatureAlgorithm::Ecdsa(super::super::DigestAlgorithm::Sha1),
            ),
            (
                "1.2.840.113549.1.1.14",
                X509SignatureAlgorithm::RsaPkcs1v15(super::super::DigestAlgorithm::Sha224),
            ),
            (
                "1.2.840.10045.4.3.1",
                X509SignatureAlgorithm::Ecdsa(super::super::DigestAlgorithm::Sha224),
            ),
            (
                "1.2.840.10045.4.3.4",
                X509SignatureAlgorithm::Ecdsa(super::super::DigestAlgorithm::Sha512),
            ),
        ] {
            let identifier = AlgorithmIdentifier::new(
                Oid::from_str(oid).expect("static signature OID must parse"),
                None,
            );
            assert_eq!(x509_signature_algorithm(&identifier), Ok(expected), "{oid}");
        }
    }

    #[test]
    fn pq_certificate_identifiers_require_absent_parameters() {
        use x509_parser::asn1_rs::{Any, Tag};

        // RFC 9881 §2 and RFC 9909 §3 require parameters to be absent,
        // including when the primitive is not compiled into this provider.
        for algorithm in super::super::PqAlgorithm::ALL {
            let oid = Oid::from_str(algorithm.oid()).expect("registered PQ signature OID");
            assert!(x509_signature_algorithm(&AlgorithmIdentifier::new(oid.clone(), None)).is_ok());
            assert!(matches!(
                x509_signature_algorithm(&AlgorithmIdentifier::new(
                    oid,
                    Some(Any::from_tag_and_data(Tag::Null, &[]))
                )),
                Err(X509ChainError::InvalidDer {
                    kind: "X.509 signature AlgorithmIdentifier parameters",
                    ..
                })
            ));
        }
    }

    #[test]
    fn sha3_ecdsa_certificate_identifiers_require_absent_parameters() {
        use x509_parser::asn1_rs::{Any, Tag};
        // Every advertised SHA3-ECDSA capability must survive identifier
        // parsing; malformed parameters must fail before provider dispatch.
        for digest in [
            super::super::DigestAlgorithm::Sha3_224,
            super::super::DigestAlgorithm::Sha3_256,
            super::super::DigestAlgorithm::Sha3_384,
            super::super::DigestAlgorithm::Sha3_512,
        ] {
            let expected = X509SignatureAlgorithm::Ecdsa(digest);
            let oid = Oid::from_str(expected.oid().expect("registered signature OID"))
                .expect("registered SHA3 ECDSA OID must parse");
            assert_eq!(
                x509_signature_algorithm(&AlgorithmIdentifier::new(oid.clone(), None)),
                Ok(expected)
            );
            assert!(matches!(
                x509_signature_algorithm(&AlgorithmIdentifier::new(
                    oid,
                    Some(Any::from_tag_and_data(Tag::Null, &[]))
                )),
                Err(X509ChainError::InvalidDer { .. })
            ));
        }
    }

    #[test]
    fn x509_signature_parameters_follow_each_algorithm_profile() {
        use x509_parser::asn1_rs::{Any, Tag};

        // DSA, ECDSA, and Ed25519 signature identifiers require absent
        // parameters. A NULL is not equivalent for these algorithm profiles.
        for oid in [
            "1.2.840.10040.4.3",
            "2.16.840.1.101.3.4.3.1",
            "2.16.840.1.101.3.4.3.2",
            "1.2.840.10045.4.1",
            "1.2.840.10045.4.3.1",
            "1.2.840.10045.4.3.2",
            "1.3.101.112",
        ] {
            let identifier = AlgorithmIdentifier::new(
                Oid::from_str(oid).expect("static signature OID must parse"),
                Some(Any::from_tag_and_data(Tag::Null, &[])),
            );
            assert!(matches!(
                x509_signature_algorithm(&identifier),
                Err(X509ChainError::InvalidDer {
                    kind: "X.509 signature AlgorithmIdentifier parameters",
                    ..
                })
            ));
        }

        // RSA PKCS#1 signature identifiers accept absent and NULL parameters
        // for interoperability, but no other ASN.1 value.
        for (oid, digest) in [
            (
                "1.2.840.113549.1.1.14",
                super::super::DigestAlgorithm::Sha224,
            ),
            (
                "1.2.840.113549.1.1.11",
                super::super::DigestAlgorithm::Sha256,
            ),
        ] {
            let rsa_oid = Oid::from_str(oid).expect("static RSA signature OID must parse");
            for parameters in [None, Some(Any::from_tag_and_data(Tag::Null, &[]))] {
                assert_eq!(
                    x509_signature_algorithm(&AlgorithmIdentifier::new(
                        rsa_oid.clone(),
                        parameters,
                    )),
                    Ok(X509SignatureAlgorithm::RsaPkcs1v15(digest)),
                );
            }
            assert!(matches!(
                x509_signature_algorithm(&AlgorithmIdentifier::new(
                    rsa_oid,
                    Some(Any::from_tag_and_data(Tag::OctetString, &[])),
                )),
                Err(X509ChainError::InvalidDer {
                    kind: "X.509 signature AlgorithmIdentifier parameters",
                    ..
                })
            ));
        }
    }

    #[test]
    fn unknown_x509_signature_algorithm_remains_diagnosable() {
        let oid = "1.2.3.4.5";
        let identifier = AlgorithmIdentifier::new(
            Oid::from_str(oid).expect("static unknown OID must parse"),
            None,
        );

        assert_eq!(
            x509_signature_algorithm(&identifier),
            Err(X509ChainError::UnsupportedSignatureAlgorithm { oid: oid.into() })
        );
    }

    #[test]
    fn parses_rsa_pss_certificate_parameters_without_xml_dsig_loss() {
        // RFC 4055 carries the digest, MGF digest, and salt length inside the
        // AlgorithmIdentifier. Preserve all three values at the provider edge.
        let der = [
            0x30, 0x41, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30,
            0x34, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
            0x02, 0x01, 0x05, 0x00, 0xa1, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
            0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
            0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x20,
        ];
        let (rest, identifier) = AlgorithmIdentifier::from_der(&der)
            .expect("standard SHA-256 RSA-PSS AlgorithmIdentifier must parse");
        assert!(rest.is_empty());

        assert_eq!(
            x509_signature_algorithm(&identifier),
            Ok(X509SignatureAlgorithm::RsaPss {
                digest: super::super::DigestAlgorithm::Sha256,
                mgf_digest: super::super::DigestAlgorithm::Sha256,
                salt_len: 32,
            })
        );
    }

    #[test]
    fn parses_sha224_rsa_pss_certificate_parameters() {
        // RFC 4055 permits SHA-224 independently for the message digest and
        // MGF1. The provider-neutral parser must preserve that capability.
        let der = [
            0x30, 0x41, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30,
            0x34, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
            0x02, 0x04, 0x05, 0x00, 0xa1, 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
            0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
            0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x1c,
        ];
        let (rest, identifier) = AlgorithmIdentifier::from_der(&der)
            .expect("standard SHA-224 RSA-PSS AlgorithmIdentifier must parse");
        assert!(rest.is_empty());

        assert_eq!(
            x509_signature_algorithm(&identifier),
            Ok(X509SignatureAlgorithm::RsaPss {
                digest: super::super::DigestAlgorithm::Sha224,
                mgf_digest: super::super::DigestAlgorithm::Sha224,
                salt_len: 28,
            })
        );
    }

    #[test]
    fn dsa_rollover_replaces_embedded_root_before_depth_validation() {
        let leaf = include_bytes!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/balor.der"
        )
        .to_vec();
        let embedded_root =
            include_bytes!("../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/ca.der")
                .to_vec();

        // Trust-anchor self-signatures are not part of path validation. Changing
        // only that signature gives this test a distinct rollover certificate
        // with the same subject and DSA public key as the embedded stale root.
        let mut rollover_anchor = embedded_root.clone();
        *rollover_anchor
            .last_mut()
            .expect("certificate is non-empty") ^= 1;
        parse_certificate(&rollover_anchor).expect("modified trust anchor remains valid DER");
        let anchors = vec![rollover_anchor];
        let info = X509DataInfo {
            certificates: vec![leaf, embedded_root],
            certificate_chain: vec![0, 1],
            ..X509DataInfo::default()
        };
        let options = X509ChainOptions {
            trusted_certs: &anchors,
            verification_time: UNIX_EPOCH + Duration::from_secs(1_104_580_800),
            max_chain_depth: 2,
            check_crls: false,
            allowed_extended_key_usages: None,
            rsa_keys: RsaKeyPolicy::default(),
            dsa_keys: DsaKeyPolicy {
                minimum_modulus_bits: 1024,
            },
            utc_facts: None,
            certificate_signature_algorithms: None,
        };

        verify_x509_certificate_chain(&info, &options)
            .expect("the stale DSA root must be replaced by the configured anchor");
    }

    #[test]
    fn dsa_issuer_key_uses_the_configured_strength_policy() {
        let leaf = include_bytes!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/balor.der"
        )
        .to_vec();
        let anchor =
            include_bytes!("../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/ca.der")
                .to_vec();
        let anchors = vec![anchor.clone()];
        let info = X509DataInfo {
            certificates: vec![leaf, anchor],
            certificate_chain: vec![0, 1],
            ..X509DataInfo::default()
        };
        let options = X509ChainOptions {
            trusted_certs: &anchors,
            verification_time: UNIX_EPOCH + Duration::from_secs(1_104_580_800),
            max_chain_depth: 2,
            check_crls: false,
            allowed_extended_key_usages: None,
            rsa_keys: RsaKeyPolicy::default(),
            dsa_keys: DsaKeyPolicy::default(),
            utc_facts: None,
            certificate_signature_algorithms: None,
        };

        assert!(matches!(
            verify_x509_certificate_chain(&info, &options),
            Err(X509ChainError::KeyPolicy {
                position: 1,
                source: crate::policy::PolicyViolation::KeySize {
                    key_type: "DSA",
                    minimum_bits: 2048,
                    actual_bits: 1024,
                    ..
                }
            })
        ));
    }

    #[test]
    fn path_length_excludes_self_issued_rollover_certificates() {
        // RFC 5280 excludes self-issued rollover CAs from pathLenConstraint;
        // only non-self-issued intermediate CA certificates consume the limit.
        let mut root_params = generated_certificate_params("rollover path authority", true);
        root_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Constrained(0));
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let rollover_params = generated_certificate_params("rollover path 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 same-name rollover certificate");
        let rollover_issuer = rcgen::Issuer::from_params(&rollover_params, &rollover_key);
        let leaf = generated_certificate_params("rollover path leaf", false)
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &rollover_issuer,
            )
            .expect("rollover key should sign leaf certificate");

        verify_generated_path(
            vec![
                leaf.der().to_vec(),
                rollover_certificate.der().to_vec(),
                root.der().to_vec(),
            ],
            root.der().to_vec(),
        )
        .expect("self-issued rollover must not consume a zero path-length allowance");
    }

    #[test]
    fn ca_name_constraints_reject_disallowed_dns_names() {
        let mut root_params = generated_certificate_params("constrained authority", true);
        root_params.name_constraints = Some(rcgen::NameConstraints {
            permitted_subtrees: vec![rcgen::GeneralSubtree::DnsName("example.com".into())],
            excluded_subtrees: vec![rcgen::GeneralSubtree::DnsName("blocked.example.com".into())],
        });
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("constrained root should be self-signable");

        for (dns_name, accepted) in [
            ("www.example.com", true),
            ("blocked.example.com", false),
            ("www.example.net", false),
        ] {
            let leaf = rcgen::CertificateParams::new(vec![dns_name.into()])
                .expect("DNS SAN should be valid")
                .signed_by(
                    &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                    &root,
                )
                .expect("root should sign leaf certificate");
            assert_eq!(
                verify_generated_path(
                    vec![leaf.der().to_vec(), root.der().to_vec()],
                    root.der().to_vec(),
                )
                .is_ok(),
                accepted,
                "unexpected name-constraint result for {dns_name}"
            );
        }
    }

    #[test]
    fn rfc5280_dns_names_require_preferred_name_syntax() {
        let mut root_params = generated_certificate_params("DNS syntax authority", true);
        root_params.name_constraints = Some(rcgen::NameConstraints {
            permitted_subtrees: vec![rcgen::GeneralSubtree::DnsName("example.com".into())],
            excluded_subtrees: Vec::new(),
        });
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("constrained root should be self-signable");

        let mut leaf_params = generated_certificate_params("malformed DNS leaf", false);
        let dns_name = b"bad..example.com";
        let mut san_der = vec![
            0x30,
            u8::try_from(dns_name.len() + 2).expect("test SAN must fit short-form DER"),
            0x82,
        ];
        san_der.push(u8::try_from(dns_name.len()).expect("test DNS name must fit short-form DER"));
        san_der.extend_from_slice(dns_name);
        leaf_params
            .custom_extensions
            .push(rcgen::CustomExtension::from_oid_content(
                &[2, 5, 29, 17],
                san_der,
            ));
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign malformed-DNS leaf");

        let outcome = verify_generated_path(
            vec![leaf.der().to_vec(), root.der().to_vec()],
            root.der().to_vec(),
        );
        assert!(
            matches!(
                outcome,
                Err(X509ChainError::InvalidDer {
                    kind: "certificate DNS name",
                    ..
                })
            ),
            "{outcome:?}"
        );

        for dns_name in ["*.example.com", "_signing.example.com"] {
            let mut params = generated_certificate_params("invalid DNS target", false);
            let mut san = vec![
                0x30,
                u8::try_from(dns_name.len() + 2).expect("SAN length"),
                0x82,
                u8::try_from(dns_name.len()).expect("DNS length"),
            ];
            san.extend_from_slice(dns_name.as_bytes());
            params
                .custom_extensions
                .push(rcgen::CustomExtension::from_oid_content(
                    &[2, 5, 29, 17],
                    san,
                ));
            let leaf = params
                .signed_by(&rcgen::KeyPair::generate().expect("target key"), &root)
                .expect("target certificate");
            assert!(
                matches!(
                    verify_generated_path(
                        vec![leaf.der().to_vec(), root.der().to_vec()],
                        root.der().to_vec()
                    ),
                    Err(X509ChainError::InvalidDer {
                        kind: "certificate DNS name",
                        ..
                    })
                ),
                "{dns_name}"
            );
        }
    }

    #[test]
    fn name_constraint_matchers_cover_email_uri_and_ip_forms() {
        use der::asn1::{Ia5String, OctetString};
        use x509_cert::ext::pkix::{
            NameConstraints as Constraints, constraints::name::GeneralSubtree,
            name::GeneralName as Name,
        };
        // Exercise the actual shared processor, not the retired local matchers.
        // RFC 5280 4.2.1.10 gives each form distinct subtree semantics.
        let email = |value: &str| Name::Rfc822Name(Ia5String::new(value).expect("email fixture"));
        let uri = |value: &str| {
            Name::UniformResourceIdentifier(Ia5String::new(value).expect("URI fixture"))
        };
        let ip = |value: &[u8]| Name::IpAddress(OctetString::new(value).expect("IP fixture"));
        for (name, base, accepted) in [
            (email("ops@example.com"), email("example.com"), true),
            (email("ops@example.com"), email("ops@example.com"), true),
            (email("other@example.com"), email("ops@example.com"), false),
            (
                uri("https://user@api.example.com:8443/path"),
                uri(".example.com"),
                true,
            ),
            (
                uri("https://api.example.com/path"),
                uri(".example.com"),
                true,
            ),
            (
                ip(&[192, 0, 2, 42]),
                ip(&[192, 0, 2, 0, 255, 255, 255, 0]),
                true,
            ),
            (
                ip(&[192, 0, 3, 42]),
                ip(&[192, 0, 2, 0, 255, 255, 255, 0]),
                false,
            ),
        ] {
            let result = verify_generated_constraints(
                Constraints {
                    permitted_subtrees: Some(vec![GeneralSubtree {
                        base,
                        minimum: 0,
                        maximum: None,
                    }]),
                    excluded_subtrees: None,
                },
                name,
            );
            if accepted {
                result.expect("matching name must be accepted");
            } else {
                assert_eq!(
                    result,
                    Err(X509ChainError::NameConstraintViolation {
                        position: 0,
                        constraining_position: 1,
                    })
                );
            }
        }
        let result = verify_generated_constraints(
            Constraints {
                permitted_subtrees: Some(vec![GeneralSubtree {
                    base: uri(".example.com"),
                    minimum: 0,
                    maximum: None,
                }]),
                excluded_subtrees: None,
            },
            uri("https://user@other@example.com/path"),
        );
        assert_eq!(
            result,
            Err(X509ChainError::UnsupportedCriticalExtension {
                position: 0,
                oid: "2.5.29.17".into(),
            }),
            "a second userinfo delimiter must not expose a constraint-matchable host"
        );
        let result = verify_generated_constraints(
            Constraints {
                permitted_subtrees: Some(vec![GeneralSubtree {
                    base: ip(&[192, 0, 2, 0, 255, 0, 255, 0]),
                    minimum: 0,
                    maximum: None,
                }]),
                excluded_subtrees: None,
            },
            ip(&[192, 0, 2, 42]),
        );
        assert_eq!(
            result,
            Err(X509ChainError::InvalidNameConstraints { position: 1 })
        );
    }

    #[test]
    fn malformed_ip_name_constraints_fail_before_matching() {
        use der::asn1::OctetString;
        use x509_cert::ext::pkix::{
            NameConstraints as Constraints, constraints::name::GeneralSubtree,
            name::GeneralName as Name,
        };
        // Both permitted/excluded constraints must reject malformed masks
        // through the production common processor before any name can match.
        for malformed in [
            &[192, 0, 2, 0, 255, 255, 255][..],
            &[192, 0, 2, 0, 255, 0, 255, 0][..],
        ] {
            for permitted in [true, false] {
                let subtree = GeneralSubtree {
                    base: Name::IpAddress(
                        OctetString::new(malformed).expect("IP constraint fixture"),
                    ),
                    minimum: 0,
                    maximum: None,
                };
                let constraints = Constraints {
                    permitted_subtrees: permitted.then(|| vec![subtree.clone()]),
                    excluded_subtrees: (!permitted).then(|| vec![subtree]),
                };
                assert_eq!(
                    verify_generated_constraints(
                        constraints,
                        Name::IpAddress(OctetString::new([192, 0, 2, 42]).expect("IP SAN fixture")),
                    ),
                    Err(X509ChainError::InvalidNameConstraints { position: 1 })
                );
            }
        }
    }

    #[test]
    fn malformed_string_name_constraints_fail_before_matching() {
        use der::asn1::Ia5String;
        use x509_cert::ext::pkix::{
            NameConstraints as Constraints, constraints::name::GeneralSubtree,
            name::GeneralName as Name,
        };
        let dns =
            |value: &str| Name::DnsName(Ia5String::new(value).expect("DNS constraint fixture"));
        let email = |value: &str| {
            Name::Rfc822Name(Ia5String::new(value).expect("email constraint fixture"))
        };
        let uri = |value: &str| {
            Name::UniformResourceIdentifier(Ia5String::new(value).expect("URI constraint fixture"))
        };

        // Matchers assume admitted string constraints have RFC 5280 syntax.
        // Invalid values must not degrade into ordinary non-matches.
        for malformed in [
            dns(""),
            dns("example..com"),
            email("@example.com"),
            email("bad..local@example.com"),
            uri("https://example.com"),
        ] {
            let constraints = Constraints {
                permitted_subtrees: None,
                excluded_subtrees: Some(vec![GeneralSubtree {
                    base: malformed,
                    minimum: 0,
                    maximum: None,
                }]),
            };
            assert_eq!(
                verify_generated_constraints(constraints, dns("www.example.com")),
                Err(X509ChainError::InvalidNameConstraints { position: 1 })
            );
        }

        for valid in [
            dns("example.com"),
            dns(".example.com"),
            email("ops@example.com"),
            email("example.com"),
            uri(".example.com"),
        ] {
            let constraints = Constraints {
                permitted_subtrees: Some(vec![GeneralSubtree {
                    base: valid,
                    minimum: 0,
                    maximum: None,
                }]),
                excluded_subtrees: None,
            };
            verify_generated_constraints(constraints, dns("www.example.com"))
                .expect("valid string constraints must remain supported");
        }
    }

    #[test]
    fn empty_name_constraint_collections_are_rejected() {
        use der::asn1::Ia5String;
        use x509_cert::ext::pkix::NameConstraints as EncodedNameConstraints;

        // RFC 5280 requires at least one subtree overall and at least one entry
        // in every explicitly present GeneralSubtrees collection.
        for constraints in [
            EncodedNameConstraints {
                permitted_subtrees: None,
                excluded_subtrees: None,
            },
            EncodedNameConstraints {
                permitted_subtrees: Some(Vec::new()),
                excluded_subtrees: None,
            },
            EncodedNameConstraints {
                permitted_subtrees: None,
                excluded_subtrees: Some(Vec::new()),
            },
        ] {
            assert_eq!(
                verify_generated_constraints(
                    constraints,
                    x509_cert::ext::pkix::name::GeneralName::DnsName(
                        Ia5String::new("www.example.com").expect("DNS SAN fixture")
                    ),
                ),
                Err(X509ChainError::InvalidNameConstraints { position: 1 })
            );
        }
    }

    #[test]
    fn unsupported_name_constraint_distances_fail_path_validation() {
        use der::{Encode as _, asn1::Ia5String};
        use x509_cert::ext::pkix::{
            NameConstraints as EncodedNameConstraints,
            constraints::name::GeneralSubtree as EncodedGeneralSubtree,
            name::GeneralName as EncodedGeneralName,
        };

        // x509-parser exposes only GeneralSubtree::base. Exercise the complete
        // extension DER so unsupported distance fields cannot disappear before
        // RFC 5280 path validation sees them.
        for (permitted, minimum, maximum) in [
            (true, 1, None),
            (false, 1, None),
            (true, 0, Some(1)),
            (false, 0, Some(1)),
        ] {
            let dns_name = if permitted {
                "example.com"
            } else {
                "blocked.example.com"
            };
            let subtree = EncodedGeneralSubtree {
                base: EncodedGeneralName::DnsName(
                    Ia5String::new(dns_name.as_bytes()).expect("valid DNS IA5String"),
                ),
                minimum,
                maximum,
            };
            let constraints = EncodedNameConstraints {
                permitted_subtrees: permitted.then(|| vec![subtree.clone()]),
                excluded_subtrees: (!permitted).then(|| vec![subtree]),
            };
            let mut extension = rcgen::CustomExtension::from_oid_content(
                &[2, 5, 29, 30],
                constraints
                    .to_der()
                    .expect("NameConstraints must encode as DER"),
            );
            extension.set_criticality(true);

            let mut root_params = generated_certificate_params("distance authority", true);
            root_params.custom_extensions.push(extension);
            let root = rcgen::CertifiedIssuer::self_signed(
                root_params,
                rcgen::KeyPair::generate().expect("root key generation should succeed"),
            )
            .expect("constrained root should be self-signable");
            let leaf = rcgen::CertificateParams::new(vec!["www.example.com".into()])
                .expect("leaf DNS SAN should be valid")
                .signed_by(
                    &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                    &root,
                )
                .expect("root should sign leaf certificate");

            let outcome = verify_generated_path(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
            );
            assert!(
                matches!(
                    outcome,
                    Err(X509ChainError::InvalidNameConstraints { position: 1 })
                ),
                "{outcome:?}"
            );
        }
    }

    #[test]
    fn name_constraints_cover_subject_email_and_directory_name() {
        // RFC 5280 requires subject emailAddress attributes to be checked even
        // without a SAN, and directoryName constraints compare RDN subtrees.
        let mut permitted_directory = rcgen::DistinguishedName::new();
        permitted_directory.push(rcgen::DnType::OrganizationName, "Example Corp");
        let mut root_params = generated_certificate_params("name authority", true);
        root_params.name_constraints = Some(rcgen::NameConstraints {
            permitted_subtrees: vec![
                rcgen::GeneralSubtree::Rfc822Name("example.com".into()),
                rcgen::GeneralSubtree::DirectoryName(permitted_directory),
            ],
            excluded_subtrees: Vec::new(),
        });
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("constrained root should be self-signable");

        for (organization, email, accepted) in [
            ("Example Corp", "ops@example.com", true),
            ("Other Corp", "ops@example.com", false),
            ("Example Corp", "ops@example.net", false),
            ("Example Corp", "bad..local@example.com", false),
        ] {
            let mut leaf_params = generated_certificate_params("name-constrained leaf", false);
            leaf_params.distinguished_name = rcgen::DistinguishedName::new();
            leaf_params
                .distinguished_name
                .push(rcgen::DnType::OrganizationName, organization);
            leaf_params
                .distinguished_name
                .push(rcgen::DnType::CommonName, "name-constrained leaf");
            leaf_params.distinguished_name.push(
                rcgen::DnType::CustomDnType(vec![1, 2, 840, 113549, 1, 9, 1]),
                rcgen::DnValue::Ia5String(
                    email
                        .try_into()
                        .expect("test email must be a valid IA5String"),
                ),
            );
            let leaf = leaf_params
                .signed_by(
                    &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                    &root,
                )
                .expect("root should sign leaf certificate");
            let result = verify_generated_path(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
            );
            assert_eq!(
                result.is_ok(),
                accepted,
                "unexpected subject constraint result for {organization} / {email}: {result:?}",
            );
        }
    }

    #[test]
    fn empty_subject_requires_a_critical_nonempty_san() {
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("subject identity authority", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");

        let mut missing_san = rcgen::CertificateParams::new(Vec::new())
            .expect("empty SAN list should produce certificate parameters");
        missing_san.distinguished_name = rcgen::DistinguishedName::new();
        let missing_san = missing_san
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("test issuer should sign an empty-subject certificate");

        let mut noncritical_san = rcgen::CertificateParams::new(Vec::new())
            .expect("empty SAN list should produce certificate parameters");
        noncritical_san.distinguished_name = rcgen::DistinguishedName::new();
        // GeneralNames ::= SEQUENCE { dNSName [2] "a" }. Using a custom
        // extension is intentional because rcgen correctly marks its normal
        // SAN extension critical whenever the subject is empty.
        noncritical_san
            .custom_extensions
            .push(rcgen::CustomExtension::from_oid_content(
                &[2, 5, 29, 17],
                vec![0x30, 0x03, 0x82, 0x01, b'a'],
            ));
        let noncritical_san = noncritical_san
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("test issuer should sign a non-critical-SAN certificate");

        for leaf in [missing_san, noncritical_san] {
            // The shared reader now reports the original subject range rather
            // than the legacy projection's unlocated subject-identity message.
            let error = verify_generated_path(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
            )
            .expect_err("an empty subject without critical SAN must fail");
            let X509ChainError::Processing(error) = error else {
                panic!("expected located subject rejection: {error:?}");
            };
            assert_eq!(error.code(), structured_pkix::ErrorCode::MissingField);
            assert_eq!(error.field(), "certificate.tbsCertificate.subject");
            assert!(error.offset() > 0 && error.offset() < leaf.der().len() as u64);
        }
    }

    #[test]
    fn empty_subject_with_critical_san_skips_directory_name_constraints() {
        // RFC 5280 permits an empty subject when a critical SAN carries the
        // identity. An absent DirectoryName need not match a permitted subtree.
        let mut permitted_directory = rcgen::DistinguishedName::new();
        permitted_directory.push(rcgen::DnType::OrganizationName, "Example Corp");
        let mut root_params = generated_certificate_params("empty-subject authority", true);
        root_params.name_constraints = Some(rcgen::NameConstraints {
            permitted_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(permitted_directory)],
            excluded_subtrees: Vec::new(),
        });
        let root = rcgen::CertifiedIssuer::self_signed(
            root_params,
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("constrained root should be self-signable");
        let mut leaf_params = rcgen::CertificateParams::new(vec!["allowed.example".into()])
            .expect("DNS SAN should be valid");
        leaf_params.distinguished_name = rcgen::DistinguishedName::new();
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign empty-subject leaf");

        verify_generated_path(
            vec![leaf.der().to_vec(), root.der().to_vec()],
            root.der().to_vec(),
        )
        .expect("only present name forms should be constrained");
    }

    #[test]
    fn malformed_general_names_in_san_fail_path_validation() {
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("malformed-SAN root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        for empty_subject in [true, false] {
            let mut leaf_params = generated_certificate_params("malformed-SAN leaf", false);
            if empty_subject {
                leaf_params.distinguished_name = rcgen::DistinguishedName::new();
            }
            // GeneralNames ::= SEQUENCE { dNSName [2] <invalid IA5 octet> }.
            let mut malformed_san = rcgen::CustomExtension::from_oid_content(
                &[2, 5, 29, 17],
                vec![0x30, 0x03, 0x82, 0x01, 0xff],
            );
            malformed_san.set_criticality(true);
            leaf_params.custom_extensions.push(malformed_san);
            let leaf = leaf_params
                .signed_by(
                    &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                    &root,
                )
                .expect("root should sign malformed-SAN leaf");

            assert!(matches!(
                verify_generated_path(
                    vec![leaf.der().to_vec(), root.der().to_vec()],
                    root.der().to_vec(),
                ),
                Err(X509ChainError::InvalidDer {
                    kind: "certificate subject identity",
                    ..
                })
            ));
        }
    }

    #[test]
    fn typed_subject_alternative_names_require_rfc5280_syntax() {
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("typed-SAN root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");

        for (tag, value) in [
            (0x81, b"operator@".as_slice()),
            (0x81, b"first..last@example.com".as_slice()),
            (0x86, b"relative/path".as_slice()),
            (0x86, b"https://example.com/%zz".as_slice()),
            (0x86, b"https://user@other@example.com/path".as_slice()),
            (0x86, b"file:///path".as_slice()),
            (0x87, &[192, 0, 2][..]),
        ] {
            for empty_subject in [false, true] {
                let mut leaf_params = generated_certificate_params("typed-SAN leaf", false);
                if empty_subject {
                    leaf_params.distinguished_name = rcgen::DistinguishedName::new();
                }
                let mut san_der = vec![
                    0x30,
                    u8::try_from(value.len() + 2).expect("test SAN must fit short-form DER"),
                    tag,
                    u8::try_from(value.len()).expect("test GeneralName must fit short-form DER"),
                ];
                san_der.extend_from_slice(value);
                let mut san = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], san_der);
                san.set_criticality(true);
                leaf_params.custom_extensions.push(san);
                let leaf = leaf_params
                    .signed_by(
                        &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                        &root,
                    )
                    .expect("root should sign typed-SAN leaf");

                assert!(matches!(
                    verify_generated_path(
                        vec![leaf.der().to_vec(), root.der().to_vec()],
                        root.der().to_vec(),
                    ),
                    Err(X509ChainError::InvalidDer {
                        kind: "certificate subject identity",
                        ..
                    })
                ));
            }
        }

        for (tag, value) in [
            (0x81, b"operator@example.com".as_slice()),
            (0x81, b"operator@[192.0.2.1]".as_slice()),
            (0x81, b"operator@[IPv6:2001:db8::1]".as_slice()),
            (0x81, br#""operator desk"@example.com"#.as_slice()),
            (0x86, b"urn:example:operator".as_slice()),
            (
                0x86,
                b"https://operator@example.com:8443/path?q=1#id".as_slice(),
            ),
            (0x87, &[192, 0, 2, 1][..]),
            (
                0x87,
                &[0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1][..],
            ),
        ] {
            let mut leaf_params = rcgen::CertificateParams::new(Vec::new())
                .expect("empty SAN list should produce certificate parameters");
            leaf_params.distinguished_name = rcgen::DistinguishedName::new();
            let mut san_der = vec![
                0x30,
                u8::try_from(value.len() + 2).expect("test SAN must fit short-form DER"),
                tag,
                u8::try_from(value.len()).expect("test GeneralName must fit short-form DER"),
            ];
            san_der.extend_from_slice(value);
            let mut san = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], san_der);
            san.set_criticality(true);
            leaf_params.custom_extensions.push(san);
            let leaf = leaf_params
                .signed_by(
                    &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                    &root,
                )
                .expect("root should sign typed-SAN leaf");

            verify_generated_path(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
            )
            .unwrap_or_else(|error| {
                panic!(
                    "valid typed SAN {tag:#x} {value:?} must satisfy an empty subject: {error:?}"
                )
            });
        }
    }

    fn parsed_merlin_crl(der: &[u8]) -> CertificateRevocationList<'_> {
        CertificateRevocationList::from_der(der)
            .expect("modified Merlin CRL must remain parseable")
            .1
    }

    fn merlin_crl_fixture() -> X509DataInfo {
        let xml = include_str!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/signature-x509-crt-crl.xml"
        );
        let document = Document::parse(xml).expect("tracked Merlin document must parse");
        let key_info_node = document
            .descendants()
            .find(|node| node.has_tag_name((XMLDSIG_NS, "KeyInfo")))
            .expect("tracked Merlin document contains KeyInfo");
        let key_info = parse_key_info(key_info_node).expect("tracked Merlin KeyInfo must parse");
        let KeyInfoSource::X509Data(info) = &key_info.sources[0] else {
            panic!("expected X509Data")
        };
        info.clone()
    }

    fn merlin_crl_der() -> Vec<u8> {
        merlin_crl_fixture().crls[0].clone()
    }

    struct FormatOnly;
    impl structured_pkix::path::Verify for FormatOnly {
        type Error = std::convert::Infallible;
        fn verify(
            &self,
            _: &structured_pkix::algorithm::AlgorithmIdentifier<'_>,
            _: structured_pkix::path::WorkingKey<'_>,
            _: &[u8],
            _: structured_asn1::BitString<'_>,
            _: &structured_asn1::memory::Memory,
        ) -> Result<structured_pkix::path::Verified, Self::Error> {
            Ok(structured_pkix::path::Verified::Yes)
        }
    }

    fn validate_crl_extensions(bytes: &[u8], index: usize) -> Result<(), X509ChainError> {
        // Isolate format/entry semantics for deliberately re-encoded test
        // inputs. Signature authentication is exercised by the public-path tests.
        let session =
            super::super::pkix::CertificateSession::new(&crate::policy::ResourcePolicy::default());
        let crl = session
            .read_crl(bytes)
            .map_err(|_| X509ChainError::InvalidCrl(index))?;
        let memory = session.memory();
        for entry in crl.tbs().revoked_certificates() {
            validate_positive_serial_bytes(
                entry.serial().as_bytes(),
                "CRL revoked certificate serial",
            )
            .map_err(|_| X509ChainError::InvalidCrl(index))?;
        }
        if crl
            .tbs()
            .extensions()
            .get(structured_pkix::oid::DELTA_CRL_INDICATOR, memory)
            .map_err(|_| X509ChainError::InvalidCrl(index))?
            .is_some()
        {
            return Err(X509ChainError::InvalidCrl(index));
        }
        let mut fixture = merlin_crl_fixture();
        fixture.certificates.push(
            pem::parse(include_bytes!(
                "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/ca.pem"
            ))
            .expect("public Merlin issuer PEM")
            .into_contents(),
        );
        for encoded in &fixture.certificates {
            // Strip extensions/version in this format-only fixture so a
            // deliberately unrelated KeyUsage cannot mask entry semantics.
            use der::{Decode as _, Encode as _, Tagged as _};
            let mut envelope =
                Vec::<der::asn1::Any>::from_der(encoded).expect("fixture certificate fields");
            let mut fields = Vec::<der::asn1::Any>::from_der(
                &envelope[0].to_der().expect("fixture TBS encoding"),
            )
            .expect("fixture TBS fields");
            fields.retain(|field| {
                !matches!(
                    field.tag(),
                    der::Tag::ContextSpecific {
                        number: der::TagNumber(0 | 3),
                        ..
                    }
                )
            });
            envelope[0] =
                der::asn1::Any::from_der(&fields.to_der().expect("versionless TBS encoding"))
                    .expect("versionless TBS sequence");
            let bytes = envelope.to_der().expect("versionless issuer encoding");
            let issuer = session.read(&bytes)?;
            if !crl
                .tbs()
                .issuer()
                .matches(issuer.tbs().subject(), memory)
                .map_err(|_| X509ChainError::InvalidCrl(index))?
            {
                continue;
            }
            let proof = crl
                .authenticate(
                    &issuer,
                    structured_pkix::path::WorkingKey::standing(issuer.tbs().public_key()),
                    &FormatOnly,
                    memory,
                )
                .map_err(|_| X509ChainError::InvalidCrl(index))?;
            let structured_pkix::crl::Authentication::Authenticated(proof) = proof else {
                return Err(X509ChainError::InvalidCrl(index));
            };
            return match proof
                .entry(&issuer, memory)
                .map_err(|_| X509ChainError::InvalidCrl(index))?
            {
                structured_pkix::crl::EntryLookup::Absent
                | structured_pkix::crl::EntryLookup::Found(_) => Ok(()),
                _ => Err(X509ChainError::InvalidCrl(index)),
            };
        }
        Err(X509ChainError::InvalidCrl(index))
    }

    #[test]
    fn duplicate_crl_and_entry_extension_oids_fail_closed() {
        use der::{Decode as _, Encode as _};
        use x509_cert::crl::CertificateList;

        let original = merlin_crl_der();
        let mut duplicate_crl: CertificateList =
            CertificateList::from_der(&original).expect("tracked Merlin CRL must decode");
        let extensions = duplicate_crl
            .tbs_cert_list
            .crl_extensions
            .as_mut()
            .expect("tracked Merlin CRL must contain extensions");
        extensions.push(extensions[0].clone());
        let duplicate_crl = duplicate_crl
            .to_der()
            .expect("duplicate CRL extension test vector must encode");
        assert_eq!(
            validate_crl_extensions(&duplicate_crl, 0),
            Err(X509ChainError::InvalidCrl(0))
        );

        let mut duplicate_entry: CertificateList =
            CertificateList::from_der(&original).expect("tracked Merlin CRL must decode");
        let duplicate = duplicate_entry
            .tbs_cert_list
            .crl_extensions
            .as_ref()
            .and_then(|extensions| extensions.first())
            .expect("tracked Merlin CRL must contain an extension")
            .clone();
        let revoked = duplicate_entry
            .tbs_cert_list
            .revoked_certificates
            .as_mut()
            .and_then(|entries| entries.first_mut())
            .expect("tracked Merlin CRL must contain a revoked entry");
        revoked.crl_entry_extensions = Some(vec![duplicate.clone(), duplicate]);
        let duplicate_entry = duplicate_entry
            .to_der()
            .expect("duplicate entry extension test vector must encode");
        assert_eq!(
            validate_crl_extensions(&duplicate_entry, 0),
            Err(X509ChainError::InvalidCrl(0))
        );
    }

    #[test]
    fn malformed_revoked_certificate_serials_fail_closed() {
        // Mutate the signed Merlin CRL fixture without changing DER lengths so
        // zero and negative serials exercise the actual CRL parser path.
        let original = merlin_crl_der();
        let serial = parsed_merlin_crl(&original)
            .iter_revoked_certificates()
            .next()
            .expect("tracked Merlin CRL must contain a revoked entry")
            .raw_serial()
            .to_vec();
        let offsets = original
            .windows(serial.len())
            .enumerate()
            .filter_map(|(offset, bytes)| (bytes == serial).then_some(offset))
            .collect::<Vec<_>>();
        assert_eq!(
            offsets.len(),
            1,
            "revoked serial fixture must be unambiguous"
        );

        for replacement in [vec![0; serial.len()], {
            let mut negative = serial.clone();
            negative[0] = 0x80;
            negative
        }] {
            let mut malformed = original.clone();
            malformed[offsets[0]..offsets[0] + serial.len()].copy_from_slice(&replacement);
            assert_eq!(
                validate_crl_extensions(&malformed, 0),
                Err(X509ChainError::InvalidCrl(0))
            );
        }
    }

    #[test]
    fn delta_crl_indicator_is_rejected_regardless_of_criticality() {
        use der::{Decode as _, Encode as _, asn1::OctetString};
        use x509_cert::{crl::CertificateList, ext::Extension};

        let original = merlin_crl_der();
        for critical in [false, true] {
            let mut encoded: CertificateList =
                CertificateList::from_der(&original).expect("tracked Merlin CRL must decode");
            encoded
                .tbs_cert_list
                .crl_extensions
                .get_or_insert_default()
                .push(Extension {
                    extn_id: der::asn1::ObjectIdentifier::new_unwrap("2.5.29.27"),
                    critical,
                    extn_value: OctetString::new([0x02, 0x01, 0x01])
                        .expect("DER INTEGER extension payload must be valid"),
                });
            let encoded = encoded
                .to_der()
                .expect("delta CRL indicator test vector must encode");
            assert_eq!(
                validate_crl_extensions(&encoded, 0),
                Err(X509ChainError::InvalidCrl(0)),
                "delta CRL indicator criticality must not change unsupported semantics"
            );
        }
    }

    #[test]
    fn remove_from_crl_is_rejected_in_a_complete_crl() {
        use der::{Decode as _, Encode as _, asn1::OctetString};
        use x509_cert::{crl::CertificateList, ext::Extension};

        let original = merlin_crl_der();
        for (reason, accepted) in [(1_u8, true), (8_u8, false)] {
            let mut encoded: CertificateList =
                CertificateList::from_der(&original).expect("tracked Merlin CRL must decode");
            // This vector isolates entry reason semantics, not the historical
            // fixture's issuer-hint profile. Absence of CRL extensions is legal.
            encoded.tbs_cert_list.crl_extensions = None;
            let revoked = encoded
                .tbs_cert_list
                .revoked_certificates
                .as_mut()
                .and_then(|entries| entries.first_mut())
                .expect("tracked Merlin CRL must contain a revoked entry");
            revoked
                .crl_entry_extensions
                .get_or_insert_default()
                .push(Extension {
                    extn_id: der::asn1::ObjectIdentifier::new_unwrap("2.5.29.21"),
                    critical: false,
                    extn_value: OctetString::new([0x0a, 0x01, reason])
                        .expect("DER ENUMERATED extension payload must be valid"),
                });
            let encoded = encoded
                .to_der()
                .expect("reason-code CRL test vector must encode");
            let result = validate_crl_extensions(&encoded, 0);
            if accepted {
                assert_eq!(result, Ok(()), "ordinary revocation reasons remain valid");
            } else {
                assert_eq!(result, Err(X509ChainError::InvalidCrl(0)));
            }
        }
    }

    #[test]
    fn unevaluable_uri_names_fail_closed_for_both_constraint_forms() {
        use der::asn1::Ia5String;
        use x509_cert::ext::pkix::{
            NameConstraints as Constraints, constraints::name::GeneralSubtree,
            name::GeneralName as Name,
        };

        // A URI without a DNS host is not a non-match: treating it that way
        // would bypass excluded URI subtrees while rejecting permitted ones.
        let uri = || {
            Name::UniformResourceIdentifier(
                Ia5String::new("urn:example:opaque").expect("URI SAN fixture"),
            )
        };
        let base = || {
            Name::UniformResourceIdentifier(
                Ia5String::new(".example.com").expect("URI constraint fixture"),
            )
        };
        for constraints in [
            Constraints {
                permitted_subtrees: Some(vec![GeneralSubtree {
                    base: base(),
                    minimum: 0,
                    maximum: None,
                }]),
                excluded_subtrees: None,
            },
            Constraints {
                permitted_subtrees: None,
                excluded_subtrees: Some(vec![GeneralSubtree {
                    base: base(),
                    minimum: 0,
                    maximum: None,
                }]),
            },
        ] {
            assert_eq!(
                verify_generated_constraints(constraints, uri()),
                Err(X509ChainError::NameConstraintViolation {
                    position: 0,
                    constraining_position: 1,
                })
            );
        }
    }

    #[test]
    fn unknown_critical_certificate_extension_fails_closed() {
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("critical-extension root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("critical-extension leaf", false);
        let mut extension =
            rcgen::CustomExtension::from_oid_content(&[1, 2, 3, 4], vec![0x05, 0x00]);
        extension.set_criticality(true);
        leaf_params.custom_extensions.push(extension);
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign leaf certificate");

        assert_eq!(
            verify_generated_path(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
            ),
            Err(X509ChainError::UnsupportedCriticalExtension {
                position: 0,
                oid: "1.2.3.4".into(),
            })
        );
    }

    #[test]
    fn duplicate_certificate_extension_oids_fail_closed() {
        // RFC 5280 forbids repeated extension OIDs. Enforce that certificate-wide
        // invariant before individual extension consumers select a first match.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("duplicate-extension root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("duplicate-extension leaf", false);
        for _ in 0..2 {
            leaf_params
                .custom_extensions
                .push(rcgen::CustomExtension::from_oid_content(
                    &[1, 2, 3, 4],
                    vec![0x05, 0x00],
                ));
        }
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign leaf certificate");

        // Duplicate-extension identity now comes from the common decoder's
        // located structural failure, without reparsing solely for a display OID.
        let error = verify_generated_path(
            vec![leaf.der().to_vec(), root.der().to_vec()],
            root.der().to_vec(),
        )
        .expect_err("duplicate extension must fail");
        let X509ChainError::Processing(error) = error else {
            panic!("expected located duplicate-extension rejection: {error:?}");
        };
        assert_eq!(error.code(), structured_pkix::ErrorCode::DuplicateExtension);
        assert_eq!(error.field(), "certificate.tbsCertificate.extensions");
        assert!(error.offset() > 0 && error.offset() < leaf.der().len() as u64);
    }

    #[test]
    fn invalid_certificate_serial_numbers_fail_path_validation() {
        for serial in [vec![0], vec![1; 21]] {
            let root = rcgen::CertifiedIssuer::self_signed(
                generated_certificate_params("serial root", true),
                rcgen::KeyPair::generate().expect("root key generation should succeed"),
            )
            .expect("root should be self-signable");
            let mut leaf_params = generated_certificate_params("invalid serial leaf", false);
            leaf_params.serial_number = Some(rcgen::SerialNumber::from_slice(&serial));
            let leaf = leaf_params
                .signed_by(
                    &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                    &root,
                )
                .expect("root should sign leaf certificate");

            assert!(matches!(
                verify_generated_path(
                    vec![leaf.der().to_vec(), root.der().to_vec()],
                    root.der().to_vec(),
                ),
                Err(X509ChainError::InvalidDer {
                    kind: "certificate serial number",
                    ..
                })
            ));
        }

        assert!(validate_positive_serial_bytes(&[0x80], "certificate serial number").is_err());
        assert!(validate_positive_serial_bytes(&[1; 20], "certificate serial number").is_ok());

        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("serial-padding root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("serial-padding leaf", false);
        leaf_params.serial_number = Some(rcgen::SerialNumber::from_slice(&[0x80; 20]));
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign a maximum-magnitude serial");

        verify_generated_path(
            vec![leaf.der().to_vec(), root.der().to_vec()],
            root.der().to_vec(),
        )
        .expect("a 20-octet magnitude may require a DER sign-padding octet");
    }

    #[test]
    fn name_constraints_are_rejected_on_end_entity_certificates() {
        // RFC 5280 limits NameConstraints to critical CA extensions; merely
        // parsing the extension on an end entity must not count as processing it.
        let root = rcgen::CertifiedIssuer::self_signed(
            generated_certificate_params("name-placement root", true),
            rcgen::KeyPair::generate().expect("root key generation should succeed"),
        )
        .expect("root should be self-signable");
        let mut leaf_params = generated_certificate_params("name-placement leaf", false);
        leaf_params.name_constraints = Some(rcgen::NameConstraints {
            permitted_subtrees: vec![rcgen::GeneralSubtree::DnsName("example.com".into())],
            excluded_subtrees: Vec::new(),
        });
        let leaf = leaf_params
            .signed_by(
                &rcgen::KeyPair::generate().expect("leaf key generation should succeed"),
                &root,
            )
            .expect("root should sign leaf certificate");

        assert!(matches!(
            verify_generated_path(
                vec![leaf.der().to_vec(), root.der().to_vec()],
                root.der().to_vec(),
            ),
            Err(X509ChainError::InvalidNameConstraints { position: 0 })
        ));
    }

    #[test]
    fn dsa_certificate_rejects_mismatched_inner_signature_algorithm() {
        // The signed TBSCertificate algorithm is a separate RFC 5280 invariant;
        // a valid signature over the original bytes must not bypass a mismatch
        // in the parsed metadata through the legacy DSA fallback.
        let (_, mut certificate) = X509Certificate::from_der(include_bytes!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/balor.der"
        ))
        .expect("the tracked Merlin certificate is valid DER");
        let (_, issuer) = X509Certificate::from_der(include_bytes!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/ca.der"
        ))
        .expect("the tracked Merlin issuer is a DER certificate");
        assert!(verify_certificate_signature(&certificate, &issuer));

        certificate.tbs_certificate.signature = issuer.public_key().algorithm.clone();

        assert_ne!(
            certificate.tbs_certificate.signature,
            certificate.signature_algorithm
        );
        assert!(!verify_certificate_signature(&certificate, &issuer));
    }

    #[test]
    fn dsa_sha1_crl_signature_uses_the_same_fallback_as_certificates() {
        let xml = include_str!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/signature-x509-crt-crl.xml"
        );
        let document = Document::parse(xml).expect("the tracked Merlin document is valid XML");
        let key_info_node = document
            .descendants()
            .find(|node| node.has_tag_name((XMLDSIG_NS, "KeyInfo")))
            .expect("the Merlin document contains KeyInfo");
        let key_info = parse_key_info(key_info_node).expect("the Merlin KeyInfo is valid");
        let KeyInfoSource::X509Data(info) = &key_info.sources[0] else {
            panic!("expected X509Data")
        };
        let (_, issuer) = X509Certificate::from_der(include_bytes!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/ca.der"
        ))
        .expect("the tracked Merlin issuer is a DER certificate");
        let (_, crl) = CertificateRevocationList::from_der(&info.crls[0])
            .expect("the tracked Merlin CRL is valid DER");

        assert!(verify_crl_signature(&crl, &issuer));
    }

    #[test]
    fn dsa_crl_rejects_mismatched_inner_signature_algorithm() {
        let xml = include_str!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/signature-x509-crt-crl.xml"
        );
        let document = Document::parse(xml).expect("the tracked Merlin document is valid XML");
        let key_info_node = document
            .descendants()
            .find(|node| node.has_tag_name((XMLDSIG_NS, "KeyInfo")))
            .expect("the Merlin document contains KeyInfo");
        let key_info = parse_key_info(key_info_node).expect("the Merlin KeyInfo is valid");
        let KeyInfoSource::X509Data(info) = &key_info.sources[0] else {
            panic!("expected X509Data")
        };
        let (_, issuer) = X509Certificate::from_der(include_bytes!(
            "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/certs/ca.der"
        ))
        .expect("the tracked Merlin issuer is a DER certificate");
        let (_, mut crl) = CertificateRevocationList::from_der(&info.crls[0])
            .expect("the tracked Merlin CRL is valid DER");
        assert!(verify_crl_signature(&crl, &issuer));

        crl.tbs_cert_list.signature = issuer.public_key().algorithm.clone();

        assert_ne!(crl.tbs_cert_list.signature, crl.signature_algorithm);
        assert!(!verify_crl_signature(&crl, &issuer));
    }
}