pkix-path 0.6.0

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms)]
// Documentation links to `DefaultVerifier`, which needs at least one
// signature backend enabled. With none of them the item does not exist,
// so the link cannot resolve and `cargo doc` on a consumer's own
// feature selection reports an error.
//
// Allowing the lint only where it cannot tell a gated item from a
// mistake loses no signal: a mistyped link is broken with every feature
// enabled too, and the all-features doc build is what the quality gate
// runs under RUSTDOCFLAGS=-D warnings. Demoting the links to code spans
// instead would cost every docs.rs reader a working link, to spare a
// configuration nobody publishes documentation from.
// `RsaPssVerifier` and `RsaPkcs1v15Sha1Verifier` are gated on `rsa`,
// and `rsa` is itself one of the features that brings `DefaultVerifier`
// into existence — so every link in this crate's docs resolves exactly
// when `rsa` is on, and the five-feature condition this replaced was
// both wider than needed and, for a single-signature-feature build like
// `--features p256`, not wide enough.
#![cfg_attr(not(feature = "rsa"), allow(rustdoc::broken_intra_doc_links))]
//! RFC 5280 X.509 certificate path validation — pure Rust, `no_std`.
//!
//! Implements certificate path building and validation per
//! [RFC 5280 §6](https://www.rfc-editor.org/rfc/rfc5280#section-6).
//!
//! # Architecture
//!
//! Cryptographic signature verification is pluggable via [`SignatureVerifier`].
//! The default feature set wires in `RustCrypto` backends for RSA
//! (PKCS#1 v1.5 and RSASSA-PSS with SHA-256/384/512; `rsa` feature) and
//! ECDSA on P-256 (`p256` feature). The optional `p384`, `p521` and
//! `ed25519` features add ECDSA on P-384 and P-521 and Ed25519;
//! `rustcrypto` enables all of them. [`DefaultVerifier`] dispatches over
//! whatever is enabled, taking the ECDSA curve from the issuer's key.
//! For FIPS-validated crypto, implement [`SignatureVerifier`] against
//! `wolfcrypt-rustcrypto` and disable the `rustcrypto` feature.
//!
//! Revocation checking is handled by `pkix-revocation`. This crate never
//! touches the network — use `pkix_chain::verify_chain` for the combined API.
//!
//! [`validate_path`] takes anything implementing [`PathCertificate`], which
//! is how it gets the bytes an issuer signed. Hand it
//! [`CertificateWithDer`] and the signed message is a subslice of the
//! certificate's own DER; hand it a bare [`Certificate`] and the message is
//! rebuilt by re-encoding the parse, which is slower and correct only while
//! the encoder is byte-faithful for every field — an assumption that has
//! already failed once, for pre-2050 `GeneralizedTime` validity dates. Any
//! caller who still has the bytes should pass them; see [`tbs_der_slice`].
//!
//! # Scope: what §6.1 asks, and what it does not
//!
//! §6.1 is an algorithm over the certificates in a path: it maintains a
//! working issuer name, public key and policy state, and checks each
//! certificate against that state. It does not ask whether any
//! certificate *conforms* to §4.1 and §4.2, the sections that tell a CA
//! how to issue one.
//!
//! So a rule of the form "conforming CAs MUST …" is generally **not**
//! enforced here. A certificate missing the `subjectKeyIdentifier` that
//! §4.2.1.2 requires of every conforming CA certificate validates, as
//! does one whose `commonName` is not a character-for-character copy of a
//! `dNSName` in its `subjectAltName`, which CA/B Forum BR 7.1.4.3
//! requires. Those rules are real; they belong to `pkix-lint` (the RFC
//! 5280 profile) and `pkix-lint-cabf` (the CA/B Forum Baseline
//! Requirements), which exist to check exactly this and can report every
//! finding on a certificate rather than stopping at the first.
//!
//! Rejecting a chain because its issuer broke an issuance rule is doing
//! lint work inside path validation, and it costs something real: the
//! caller learns "this chain is invalid" when the truth is "this
//! certificate is non-conforming in a way that does not affect whether
//! the chain is valid". Those want different responses.
//!
//! ## "Belongs to the lint layer" is now also where it is
//!
//! Stated plainly, because the sentence above is easy to read as a
//! promise that something else here catches these: **it does, for all
//! 33.** Each has an owning lint in `pkix-lint` or `pkix-lint-cabf` that
//! fires on it, out of an implemented catalogue of 27 lints.
//!
//! The thirty-third was added last, and the order is worth recording.
//! `webpki::explicit-curve` is an EC key conveyed as an X9.62
//! `SpecifiedECDomain` instead of a `namedCurve` OID -- which CA/B Forum
//! BR 7.1.3.1.2 forbids and RFC 5480 §2.1.1 permits, so this crate reads
//! it deliberately and the refusal belongs to the forum layer. For a
//! while nothing there implemented it: the entry was classified as the
//! lint layer's while `pkix-lint-cabf` had no `namedCurve` check, making
//! "belongs to the lint layer" mean nothing checked it. `PKIX-mxj4`
//! wrote `cabf.br.tls.spki.ec_named_curve`, and Mark's call was to write
//! it before the release rather than ship the gap.
//!
//! The count read 32 of 32 before that entry existed at all, which looks
//! like a regression and is not one. The row had been a ground-truth
//! disagreement with no ledger entry ever since this crate gained
//! `specifiedCurve` support, because a committed baseline was not
//! regenerated when the behaviour changed. Classifying it moved the
//! denominator; writing the lint moved the numerator back.
//!
//! It was 4 of 32 when the claim was first measured, under `PKIX-x2gx`.
//! 27 entries named a rule no lint here implemented and 1 named a lint
//! that existed and missed its case; `PKIX-9kag` wrote the missing ones.
//! The gap is recorded rather than quietly closed, because the stance
//! above was asserted for some time before anyone checked it, and the
//! check is the only reason it is true.
//!
//! What it still does not mean. It is not a claim about CA/B Forum
//! conformance in general: 32 entries of one corpus is not the Baseline
//! Requirements, and a consumer who needs that should run zlint or
//! pkilint.
//!
//! The measurement is `pkix-difftest/lint-coverage.json`, re-derivable
//! with `pkix-difftest lint-limbo --features lint-oracles`, and the
//! per-entry table is in
//! `pkix-difftest/disagreement-classification.md`. Three of the twelve
//! lints are not the ones `PKIX-9kag` planned, because the plan named
//! the wrong owning document or called a check unreachable that is not;
//! the corrections are recorded next to the entries they apply to.
//!
//! This is measured, not asserted. Of the 37 chains where this crate
//! currently disagrees with x509-limbo's expected result, 33 are this —
//! CA/B Forum BR 7.1.4.3 (9), 6.1.5 key sizes (2), RFC 5280 §4.2.1.1 and
//! §4.2.1.2 `authorityKeyIdentifier` and `subjectKeyIdentifier` (4),
//! §4.2.1.6 `subjectAltName` shape (2), §4.2.1.10 `nameConstraints` in an
//! end-entity certificate and degenerate encodings (4), leaf `keyUsage`
//! and `basicConstraints` profile rules (3), and `authorityKeyIdentifier`
//! treated as a path-building hint rather than a filter (6). Each is
//! classified with its rule named in
//! `pkix-difftest/disagreement-classification.md`.
//!
//! ## Three places the line is drawn the other way
//!
//! "§6.1 does not ask for it" is a reason, not a licence, and these are
//! the cases that show where it stops being one. Each enforces something
//! §6.1 does not mention, and each was a real defect found by reading the
//! corpus disagreements rather than by reasoning from the specification.
//!
//! 1. **The trust anchor is validated.** §6.1 treats the anchor as a
//!    trusted input and never examines its extensions or its validity
//!    dates. This crate checks both, reporting [`AnchorDefect`] — because
//!    "the operator chose this anchor" is a decent argument for ignoring
//!    its contents and a poor one for ignoring its expiry, and a trust
//!    store is precisely where an expired or malformed root sits
//!    unnoticed for years.
//!
//! 2. **A CA's `extendedKeyUsage` constrains what it may issue.** §6.1
//!    has no EKU step at all. Without this, a CA restricted to
//!    `emailProtection` could issue a TLS server certificate and the
//!    chain would validate, which is the cross-purpose confusion EKU on a
//!    CA exists to prevent. See [`ValidationPolicy::enforce_ca_eku`].
//!
//! 3. **A CA certificate must have a non-empty subject.** This one *is*
//!    an issuance MUST — §4.1.2.6 — and it is enforced anyway, because it
//!    changes what §6.1 itself computes: §6.1.3(a)(4) chains a
//!    certificate to its issuer by comparing distinguished names, and an
//!    empty name compares equal to an empty name. An unnamed CA therefore
//!    issues certificates that chain to *any* unnamed CA, and name
//!    chaining stops distinguishing issuers.
//!
//! ## The test, stated so it can be applied again
//!
//! Does the non-conformance change what §6.1 computes, or create a
//! confusion §6.1's state machine cannot see? If so it is this crate's
//! problem, wherever the requirement happens to be written down. If it is
//! non-conformance with no effect on the algorithm's output, it is the
//! linter's.
//!
//! Stated that way because the shorter version — "path validation does
//! not enforce issuance-profile MUSTs" — is the formulation that would
//! have licensed all three cases above. Two of them were live defects
//! when that stance was first proposed.
//!
//! # Limitations
//!
//! The following are **not** currently implemented:
//! - **`UTCTime` before 1970.** The supported range is **1970-2049**,
//!   where RFC 5280 §4.1.2.5.1 allows 1950-2049. A certificate whose
//!   `notBefore` or `notAfter` falls in the missing twenty years is
//!   refused, and refused at the DER layer — the error reads "malformed
//!   ASN.1 DER value for UTCTime" and comes back before validation runs.
//!
//!   This is a deliberate scope decision, not an accident. The floor is
//!   the Unix epoch because `der` 0.8 puts it there ("due to common
//!   operations working on `UNIX_EPOCH`, `UtcTime`s are only supported
//!   for the years 1970-2049"), and lifting it would mean forking the DER
//!   layer every consumer of this crate depends on. No conforming CA
//!   issues certificates dated before 1970, so the trade is a fork of a
//!   foundational dependency against twenty years of dates nobody uses.
//!
//!   It is fail-closed: such a certificate is refused, never misread.
//!   OpenSSL does read them, so expect a genuine disagreement rather than
//!   a difference of strictness — NIST PKITS §4.2.3 "Valid pre2000 UTC
//!   notBefore Date Test3" is exactly this shape, and is the one PKITS
//!   vector this crate does not evaluate.
//! - **Legacy SHA-1** — shipped, but behind `rsa-sha1` and `ecdsa-sha1`,
//!   which are deliberately outside `default` and outside the
//!   `rustcrypto` umbrella: that umbrella means "algorithms we
//!   recommend" and these are not. Verification only; nothing here
//!   signs with SHA-1. RSA moduli outside 1024–8192 bits are refused by
//!   the bundled RSA backend.
//! - **DSA** — not implemented. The recorded stance is verify-only and
//!   opt-in, following FIPS 186-5, which retains DSA "only for the
//!   purposes of verifying existing signatures"; a chain issued under
//!   DSA before it was retired either verifies or it does not, and
//!   saying which is more useful than refusing to look. When it lands
//!   it will sit outside `default` and outside `rustcrypto`, as the
//!   SHA-1 features do. Until then such a certificate is refused as an
//!   unsupported algorithm, never misread. NIST PKITS `4.1.4` and
//!   `4.1.5` are the two vectors this affects, and RFC 3279 §2.3.2
//!   domain-parameter inheritance is the awkward half of `4.1.5`.
//! - **RFC 4518 full Unicode NFKC DN normalization** — ASCII case-folding
//!   plus insignificant-whitespace collapsing is applied. `BMPString` AVA
//!   values are transcoded UCS-2-BE → UTF-8 and then compared via the same
//!   ASCII-only normalization pipeline, so two AVAs that share Unicode
//!   code points but differ only in DER string-type (e.g. `BMPString`
//!   "Foo Co" vs `UTF8String` "Foo Co") compare equal. Full RFC 4518 prep
//!   (NFKC, non-ASCII Unicode case fold, prohibit/bidi steps) is future
//!   work tracked under `PKIX-l63j`; until it lands, two `BMPString` values
//!   that contain the same Unicode code points but differ in canonical
//!   decomposition (e.g. precomposed U+00E9 'é' vs decomposed U+0065 U+0301
//!   'e'+ combining acute) compare unequal. `UniversalString` AVA values
//!   are rejected by the `der` crate at parse time (tag 0x1C is not in
//!   `der::Tag`, in 0.8 as in 0.7) and never reach the path validator.
//!   `NumericString` AVAs go through the same ASCII pipeline: X.680 limits
//!   the type to digits and space, and LDAP's `numericStringMatch`
//!   (RFC 4517 §4.2.22) prescribes the same preparation. `TeletexString`
//!   AVAs go through it only when every octet lies in the ISO 646
//!   invariant set, where T.61 and ASCII cannot disagree; outside that —
//!   a non-spacing diacritic at 0xC0–0xCF, or one of the twelve
//!   nationally-variable positions — they fall back to raw DER byte
//!   comparison, because `pkix-path` deliberately does not transcode T.61
//!   to Unicode. See `teletex_is_iso646_invariant` for where the line sits
//!   and why.
//! - **`privateKeyUsagePeriod` (2.5.29.16)** — not processed. RFC 3280
//!   deprecated it and RFC 5280 dropped it from the profile, so a CA
//!   asserting a key-usage window narrower than the certificate's own
//!   validity is saying something this crate does not enforce. It is
//!   common in the wild rather than vestigial: 495 of the 609 ePassport
//!   CSCA certificates vendored under `third_party/trust-stores/` carry
//!   it, as do two Russian national roots that declare an eight-year key
//!   window inside an eighteen-year certificate.
//!
//!   It is non-critical in every one of those, which is why none is
//!   refused — a critical instance would hit the §6.1.4 rule and come
//!   back as [`AnchorDefect::UnhandledCriticalExtension`], correctly but
//!   to the surprise of anyone whose root suddenly stopped loading. The
//!   corpus measuring the extension's presence is the early warning for
//!   that. A fractional-seconds `GeneralizedTime` inside one is also
//!   unreachable for the same reason; `tests/fractional_generalizedtime.rs`
//!   pins both halves.
//! - **Path building** — converting an unordered bag of certificates into a
//!   validated chain is handled by `pkix-path-builder`. This crate validates
//!   a caller-ordered `&[Certificate]` only.
//! - **AIA fetching** — chains with missing intermediates are not
//!   reassembled from `AuthorityInfoAccess` URIs here. Callers supply a
//!   complete chain, or go through `pkix-chain`, which follows
//!   `caIssuers` URIs via `pkix-aia` / `pkix-aia-http` (`PKIX-zkjb`).

// For no_std builds, pull in the alloc crate explicitly so `alloc::` paths
// and the `vec!` macro resolve. `#[macro_use]` re-exports alloc macros
// (vec!, format!, etc.) into the crate root, making them available everywhere
// without qualifying them as `alloc::vec!(...)`.
#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc;

// Unified Vec import: alloc::vec::Vec in no_std, std::vec::Vec under std.
// Both map to the same concrete type; this alias lets the rest of the file
// write `Vec<_>` without cfg-gating every use site.
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::vec::Vec;

// Unified Cow import: same cfg-gate pattern as Vec. `Cow` is owned by
// `alloc` but `std` re-exports it; we can't write `alloc::borrow::Cow`
// unconditionally because `extern crate alloc` is gated to no_std mode.
// Only the serde wire helper uses it (DN comparison is allocation-free).
#[cfg(all(feature = "serde", not(feature = "std")))]
use alloc::borrow::Cow;
#[cfg(all(feature = "serde", feature = "std"))]
use std::borrow::Cow;

use der::Tagged;
// Re-exported, not merely imported: both types appear in
// `SignatureVerifier::verify_signature`'s signature, so an out-of-crate
// implementor has to name them. Reachable only as `spki::...` they meant
// reading this crate's source to discover the origin and taking a direct
// dependency on a matching `spki` version to say it.
pub use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
pub use x509_cert::Certificate;

/// Helper module for format-adaptive serde serialization of DER-encodable
/// types. Public so downstream crates (`pkix-chain`, `pkix-revocation`,
/// `pkix-truststore`) can reuse the same wire form on their own result
/// types without redefining the helpers.
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub mod serde_der;

mod policy_graph;

/// Recognizing an X9.62 `SpecifiedECDomain` as a named curve.
///
/// Public because every [`SignatureVerifier`] implementation needs it,
/// not just the one in this crate: a backend built on wolfCrypt, or on
/// a hardware token, reads an EC key's curve the same way and hits the
/// same `specifiedCurve` form in the same certificates.
pub mod specified_curve;

/// brainpoolP512r1, implemented here for want of an upstream crate.
///
/// See the module docs: it is a stopgap, it is every German CSCA
/// certificate, and it costs no new dependencies.
#[cfg(feature = "bp512")]
#[cfg_attr(docsrs, doc(cfg(feature = "bp512")))]
pub mod brainpool_p512r1;

/// brainpoolP224r1, implemented here for want of an upstream crate.
///
/// Two of Germany's CSCA document signers use it. Same recipe as
/// [`brainpool_p512r1`], and the same stopgap status.
#[cfg(feature = "bp224")]
#[cfg_attr(docsrs, doc(cfg(feature = "bp224")))]
pub mod brainpool_p224r1;

/// GOST R 34.10 signature verification, implemented here for want of an
/// upstream crate.
///
/// Its own signature equation, not ECDSA on another curve. See the
/// module docs on why there was an argument against doing it and what
/// replaced the missing oracle.
#[cfg(feature = "gost")]
#[cfg_attr(docsrs, doc(cfg(feature = "gost")))]
pub mod gost_r3410;

/// Ed521 (EdDSA over E-521), for one ICP-Brasil certificate.
///
/// **Read the module docs before enabling `ed521`.** It has no test
/// vectors, no second implementation to check against, and one real
/// signature exercising it. Not for general use.
#[cfg(feature = "ed521")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed521")))]
pub mod ed521;

mod verification_error;
pub use verification_error::{VerificationError, VerificationErrorKind};

mod verifiers;
#[cfg(any(
    feature = "p256",
    feature = "p384",
    feature = "p521",
    feature = "rsa",
    feature = "ed25519"
))]
pub use verifiers::DefaultVerifier;
#[cfg(feature = "p256")]
pub use verifiers::EcdsaP256Verifier;
#[cfg(feature = "p384")]
pub use verifiers::EcdsaP384Verifier;
#[cfg(feature = "p521")]
pub use verifiers::EcdsaP521Verifier;
#[cfg(feature = "ecdsa-sha1")]
#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
pub use verifiers::EcdsaSha1Verifier;
#[cfg(feature = "ed448")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed448")))]
pub use verifiers::Ed448Verifier;
#[cfg(feature = "ed521")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed521")))]
pub use verifiers::Ed521Verifier;
#[cfg(feature = "ed25519")]
pub use verifiers::Ed25519Verifier;
#[cfg(feature = "gost")]
#[cfg_attr(docsrs, doc(cfg(feature = "gost")))]
pub use verifiers::GostR3410Verifier;
#[cfg(feature = "ml-dsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "ml-dsa")))]
pub use verifiers::MlDsa87Verifier;
#[cfg(feature = "rsa-ripemd160")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa-ripemd160")))]
pub use verifiers::RsaPkcs1v15Ripemd160Verifier;
#[cfg(feature = "rsa-sha1")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
pub use verifiers::RsaPkcs1v15Sha1Verifier;
#[cfg(feature = "sm2")]
#[cfg_attr(docsrs, doc(cfg(feature = "sm2")))]
pub use verifiers::Sm2WithSm3Verifier;
/// Reading an RSA public key whose DER INTEGERs are not minimal, and
/// saying what had to be forgiven. See [`rsa_public_key_lenient`].
///
/// The link carries no explicit target: this `pub use` re-exports
/// `rsa_public_key_lenient`, so the label resolves on its own and an
/// explicit one is redundant. rustdoc says so under `-D warnings` and
/// cannot say where, because a doc comment on a multi-item `pub use` is
/// attached to each item -- one link, two warnings, no single span.
#[cfg(feature = "rsa")]
pub use verifiers::{RsaKeyDeviation, rsa_public_key_lenient};
#[cfg(feature = "rsa")]
pub use verifiers::{
    RsaPkcs1v15Sha256Verifier, RsaPkcs1v15Sha384Verifier, RsaPkcs1v15Sha512Verifier, RsaPssVerifier,
};

/// Re-exported for use with [`TrustAnchor::name_constraints`].
pub use x509_cert::ext::pkix::constraints::name::NameConstraints;

// --- Upstream types this crate's public API names ---------------------------
//
// Re-exported so a caller never declares `x509-cert` or `der` themselves, and
// so an upstream major bump is "update the pkix crates" rather than lockstep
// coordination across every direct dependency. These are re-exported rather
// than wrapped because a caller reads their fields: there is nothing to wrap
// them in that is not a reimplementation of x509-cert. Contrast `DerError`,
// which a caller only reads a message from and which is therefore opaque.
// AGENTS.md non-negotiable #9 has the rule.
pub use der::Decode;
pub use der::asn1::ObjectIdentifier;

/// Private shorthand for the `GeneralSubtrees` type used throughout NC processing.
type GeneralSubtrees = x509_cert::ext::pkix::constraints::name::GeneralSubtrees;

/// Opaque wrapper around an underlying ASN.1 / DER error.
///
/// Carries a [`Display`] message identical to the wrapped `der::Error` so
/// diagnostic output is preserved, but does not expose the underlying type
/// in the public API. This insulates callers from semver-breaking changes
/// in the `der` crate's error variants.
///
/// Construct via [`DerError::new`] (or implicitly via
/// [`From<der::Error> for Error`]). Sibling workspace crates that wrap
/// DER decoding failures in their own `Error` enums (`pkix-revocation`,
/// `pkix-truststore`) call [`DerError::new`] directly.
///
/// # Serde wire form
///
/// When the `serde` feature is enabled, `DerError` (de)serializes via its
/// `Display` message as a single `String` field. Because `der::Error` does
/// not itself carry a textual message — its `Display` is derived from
/// `der::ErrorKind` — round-trip is **lossy**: a deserialized `DerError`
/// preserves the original `Display` output verbatim but its
/// [`core::error::Error::source`] is `None` because the original
/// `der::Error` value cannot be reconstructed from a free-form string.
/// This trade is acceptable for diagnostic error types; the success type
/// (`ValidatedPath`) round-trips losslessly because all its fields are
/// canonically DER-encodable.
///
/// [`Display`]: core::fmt::Display
#[derive(Clone, Debug)]
pub struct DerError {
    /// Original `der::Error` value, when available.
    ///
    /// Populated by [`DerError::new`] from a real `der::Error`. `None`
    /// only when the `DerError` was reconstructed from serialized form;
    /// in that case [`core::error::Error::source`] returns `None` and the
    /// Display message is taken from the preserved [`Self::message`].
    ///
    /// Under `no_std` builds the `core::error::Error::source` impl is
    /// not available, so this field is only read for its `Debug`
    /// representation; `#[allow(dead_code)]` silences the lint in
    /// that configuration.
    #[cfg_attr(not(feature = "std"), allow(dead_code))]
    inner: Option<der::Error>,
    /// Cached Display rendering of `inner`, preserved across serde
    /// round-trips so that the diagnostic message survives even when
    /// `inner` cannot be reconstructed.
    message: BoxStr,
}

// Hand-written `PartialEq` / `Eq` compare only the cached Display
// message. Pre-refactor (tuple struct over `der::Error`) PartialEq was
// structural over `der::Error`'s `{kind, position}` fields; two
// `der::Error`s with identical `{kind, position}` always produce
// identical Display output, so comparing on `message` preserves the
// pre-refactor equality verdicts in practice. This also makes serde
// round-trip preserve `Eq` even though deserialize drops the `inner`
// field (it cannot be reconstructed from the rendered message).
impl PartialEq for DerError {
    fn eq(&self, other: &Self) -> bool {
        self.message == other.message
    }
}
impl Eq for DerError {}

/// Hashes `message`, the one field [`PartialEq`] compares.
///
/// That correspondence is the whole argument for correctness: `Hash`
/// requires that equal values hash equally, and since equality here is
/// defined solely by `message`, hashing solely `message` cannot violate
/// it. Hashing `inner` as well would break the contract, because
/// `inner` is dropped on a serde round-trip while equality is preserved
/// — two equal values would then hash differently.
///
/// Written out rather than derived for that reason: a derive would
/// include `inner`.
///
/// This exists so [`Error`] can derive `Hash`. `Der(DerError)` was the
/// only variant standing in the way, which in turn is why
/// `pkix_path_builder::Error::NoValidPath` stores its inner error as a
/// rendered `String` — the builder's own enum derives `Hash` and could
/// not hold a non-`Hash` field. That storage choice is now a semver
/// question rather than a technical obstacle.
impl core::hash::Hash for DerError {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.message.hash(state);
    }
}

// Internal: use a Box<str> so the struct is `Clone` cheaply and we keep
// the heap allocation small. A type alias keeps the `#[cfg(not(feature
// = "std"))]` use-statements in the rest of the file unchanged. Defined
// here to localise the no_std-vs-std import.
#[cfg(not(feature = "std"))]
type BoxStr = alloc::boxed::Box<str>;
#[cfg(feature = "std")]
type BoxStr = std::boxed::Box<str>;

impl DerError {
    /// Construct a `DerError` from a real `der::Error`.
    ///
    /// The original `der::Error` is preserved internally so
    /// [`core::error::Error::source`] returns it; the rendered
    /// `Display` message is cached so the diagnostic survives serde
    /// round-trips. See the type-level rustdoc for the round-trip
    /// fidelity contract.
    ///
    /// Exposed to permit sibling workspace crates (`pkix-revocation`,
    /// `pkix-truststore`) to construct their own `Error::Der`-equivalent
    /// variants from `der::Error` results without going through the
    /// `pkix_path::Error::from(der::Error)` conversion (which would
    /// produce a `pkix_path::Error`, not the sibling crate's `Error`).
    #[must_use]
    pub fn new(e: der::Error) -> Self {
        // Pre-render the Display message so it survives serde round-trips
        // even when `inner` cannot be reconstructed on the deserialize side.
        #[cfg(feature = "std")]
        let message = e.to_string().into_boxed_str();
        #[cfg(not(feature = "std"))]
        let message = {
            use core::fmt::Write as _;
            let mut s = alloc::string::String::new();
            // Display on der::Error is infallible (uses core::fmt::Result
            // = (), no I/O); write! against a String returns Ok unless
            // allocation fails.
            let _ = write!(&mut s, "{}", e);
            s.into_boxed_str()
        };
        Self {
            inner: Some(e),
            message,
        }
    }
}

impl core::fmt::Display for DerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.message)
    }
}

impl core::error::Error for DerError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        self.inner.as_ref().map(|e| e as &dyn core::error::Error)
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
const _: () = {
    use serde::{Deserializer, Serializer};

    // Local helper struct that carries only the message; both branches
    // of the serde impl re-use the same field-name shape so wire form
    // is stable between encoder and decoder.
    #[derive(serde::Serialize, serde::Deserialize)]
    struct Wire<'a> {
        // Use Cow to avoid allocating on the serialize side. The
        // deserialize side always owns the recovered String.
        #[serde(borrow)]
        message: Cow<'a, str>,
    }

    impl serde::Serialize for DerError {
        fn serialize<S: Serializer>(&self, s: S) -> core::result::Result<S::Ok, S::Error> {
            Wire {
                message: Cow::Borrowed(&self.message),
            }
            .serialize(s)
        }
    }

    impl<'de> serde::Deserialize<'de> for DerError {
        fn deserialize<D: Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
            let Wire { message } = Wire::deserialize(d)?;
            Ok(Self {
                inner: None,
                message: message.into_owned().into_boxed_str(),
            })
        }
    }
};

/// What RFC 5280 §6.3.3(f) can be determined about a trust anchor that
/// also signs CRLs.
///
/// Step (f) of the CRL validation algorithm asks whether the CRL
/// issuer's certificate is certified for CRL signing. When the CRL
/// issuer is a certificate in the path, the answer is read from that
/// certificate. When it is the trust anchor, there may be no certificate
/// to read: RFC 5280 §6.1.1 permits an anchor to be supplied as a name,
/// a key and an algorithm, and [`TrustAnchor::new`] does exactly that.
///
/// So the question has five answers rather than two, and collapsing them
/// into `Option<bool>` loses the one that matters —
/// [`KeyUsageMissing`](Self::KeyUsageMissing) is a *violation* under RFC
/// 10007 while [`Unknown`](Self::Unknown) is silence. Mapping them onto
/// one `None` is how an anchor with no certificate and an anchor whose
/// certificate omits a required extension come to look alike.
///
/// Retained on [`TrustAnchor`] for the same reason as
/// [`name_constraints`][TrustAnchor::name_constraints],
/// [`validity_unix`][TrustAnchor::validity_unix] and
/// [`extended_key_usage`][TrustAnchor::extended_key_usage]: RFC 5280
/// §6.1 never examines the anchor, so if the anchor does not carry what
/// its certificate said, nothing downstream can ask.
///
/// `pkix-revocation` is the consumer. See `PKIX-1y95`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum AnchorCrlSign {
    /// The anchor was built from a name and a key, with no certificate,
    /// so step (f) has nothing to read.
    ///
    /// Treated as permission rather than refusal: a caller who supplied
    /// no certificate has stated no restriction, exactly as
    /// [`TrustAnchor::new`] states no validity window and no name
    /// constraints. Refusing every such anchor's CRLs would break the
    /// §6.1.1 anchor form the RFC explicitly allows.
    Unknown,
    /// The anchor's certificate is X.509 v1 or v2.
    ///
    /// RFC 10007 §4 exempts these outright, because those versions "do
    /// not have an extensions field where the key usage extension can be
    /// included". The exemption is the document's, not this crate's.
    Exempt,
    /// The anchor's certificate is v3 and carries no `KeyUsage`
    /// extension at all.
    ///
    /// A violation of RFC 5280 §4.2.1.3 for a CA that issues CRLs, and
    /// since RFC 10007 §4 a violation step (f) is required to catch.
    KeyUsageMissing,
    /// `KeyUsage` is present and asserts `cRLSign`.
    Asserted,
    /// `KeyUsage` is present and withholds `cRLSign`.
    Withheld,
}

/// Why a trust anchor certificate was refused.
///
/// See [`Error::TrustAnchorRejected`] for why the anchor is examined at
/// all, given that RFC 5280 §6.1 does not.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum AnchorDefect {
    /// No `BasicConstraints` extension. RFC 5280 §4.2.1.9 requires one
    /// in every CA certificate whose key signs certificates.
    BasicConstraintsMissing,
    /// `BasicConstraints` present but not marked critical, which
    /// §4.2.1.9 requires for a CA certificate.
    BasicConstraintsNotCritical,
    /// `BasicConstraints` present with `cA=FALSE`: the certificate says
    /// it is not a CA, so it cannot be one.
    NotCa,
    /// The certificate is a CA and its subject names nothing. RFC 5280
    /// §4.1.2.6: "If the subject is a CA [...], then the subject field
    /// MUST be populated with a non-empty distinguished name".
    ///
    /// §4.1.2.6 also lets an *end entity* carry its name only in a
    /// critical `subjectAltName`, with an empty subject. That exception
    /// does not extend to a CA, and the reason is structural rather than
    /// stylistic: §6.1.3(a)(4) chains a certificate to its issuer by
    /// comparing the issuer field against the working issuer name, and an
    /// empty DN matches an empty DN. A CA named by nothing therefore
    /// issues certificates whose issuer field is also empty, and any such
    /// CA chains to any other -- name chaining stops distinguishing
    /// issuers at all. The SAN cannot stand in, because §6.1.3 never
    /// reads a SAN as the working issuer name.
    ///
    /// Reported for a CA whatever its `subjectAltName` says, including a
    /// critical one.
    EmptySubject,
    /// `KeyUsage` is present and does not assert `keyCertSign`, so the
    /// key is not permitted to sign certificates. Absent `KeyUsage` is
    /// not a defect -- §4.2.1.3 leaves every usage permitted then.
    KeyCertSignMissing,
    /// A critical extension this implementation does not process. §6.1.4
    /// would reject such a certificate inside the path; the same rule is
    /// applied to the anchor.
    UnhandledCriticalExtension,
    /// An extension's DER could not be parsed, so what it requires
    /// cannot be known.
    MalformedExtension,
    /// An extension holds a `BOOLEAN` that is valid BER and not valid
    /// DER, so a strict parser cannot read it even though what it says is
    /// not in doubt.
    ///
    /// X.690 §11.1 requires a DER `BOOLEAN` with the value TRUE to have
    /// every bit of its content octet set, that is `0xFF`. BER permits any
    /// non-zero octet, and RFC 5280 §4.1 requires certificates to be
    /// DER-encoded, so `0x01` is a non-conforming encoding of TRUE.
    ///
    /// Reported instead of [`MalformedExtension`] because the two call for
    /// different responses. A malformed extension is unreadable and might
    /// say anything; this one is readable by every lenient parser in the
    /// world and says `TRUE`. A caller seeing this knows the certificate
    /// is salvageable by its issuer re-encoding it, and knows that peers
    /// using OpenSSL or NSS accept it today -- neither of which
    /// [`MalformedExtension`] conveys.
    ///
    /// The certificate is still refused. Reading a non-DER encoding
    /// generously would mean deciding that `cA` is TRUE on the strength of
    /// an encoding the profile forbids. Three real certificates in
    /// `third_party/trust-stores/` encode `basicConstraints` `cA` this
    /// way, out of 1,923 that encode the boolean at all: two eIDAS roots
    /// and Ukraine's ePassport CSCA.
    ///
    /// Detected for `basicConstraints`, the only extension in this
    /// profile carrying a `BOOLEAN` in its own value.
    ///
    /// [`MalformedExtension`]: AnchorDefect::MalformedExtension
    NonDerBoolean,
    /// The same extension OID appears more than once. RFC 5280 §4.2:
    /// "A certificate MUST NOT include more than one instance of a
    /// particular extension."
    ///
    /// Reported in preference to every other defect here, because the
    /// extension list is what the rest of the profile check reads and a
    /// duplicate makes those reads arbitrary: this crate takes the first
    /// instance of an OID, another validator may take the last, and a
    /// certificate with two `basicConstraints` or two `KeyUsage` values
    /// then means different things to different implementations. A real
    /// Lenovo UEFI Platform Key carries two critical `KeyUsage`
    /// extensions whose values disagree, one permitting `keyCertSign`
    /// and one permitting only `digitalSignature`.
    ///
    /// `validate_path` has always rejected such a certificate inside a
    /// path, as [`Error::MalformedCertificate`]; this is the same rule
    /// applied to the anchor.
    DuplicateExtension,
    /// The anchor's `notAfter` is before the validation time.
    Expired,
    /// The anchor's `notBefore` is after the validation time.
    NotYetValid,
}

/// Errors returned by path validation.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Error {
    /// Certificate signature verification failed at the given chain index:
    /// the signature does not verify, or is not a well-formed signature
    /// value ([`VerificationErrorKind::InvalidSignature`]).
    SignatureInvalid {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// The certificate's signature could not be checked at the given chain
    /// index: the [`SignatureVerifier`] does not support its algorithm or
    /// the issuer's key, or the issuer's key is malformed. `reason` says
    /// which; it is never [`VerificationErrorKind::InvalidSignature`].
    SignatureNotVerified {
        /// Zero-based index into the `chain` slice of the certificate.
        index: usize,
        /// Why the verifier could not check the signature.
        reason: VerificationErrorKind,
    },
    /// A structural encoding error was found in a certificate.
    ///
    /// Returned when the outer `signatureAlgorithm` OID differs from the
    /// inner `TBSCertificate.signature` OID (RFC 5280 §4.1.1.2; parameters
    /// are not compared, see `check_oid_consistency` for rationale), when a
    /// certificate carries more than one instance of an extension (RFC 5280
    /// §4.2), and when a security-relevant extension fails to decode.
    MalformedCertificate {
        /// Zero-based index into the `chain` slice of the malformed certificate.
        ///
        /// The underlying `der::Error` is intentionally not stored here to keep
        /// this variant `no_std`-compatible and to preserve the stable API shape.
        /// Callers that need the root-cause parse error should validate the
        /// DER certificate independently before calling [`validate_path`].
        index: usize,
    },
    /// Certificate validity period check failed (expired or not yet valid).
    ValidityPeriod {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// Issuer/subject name linkage is broken at the given chain index.
    ChainBroken {
        /// Zero-based index into the `chain` slice where the break was found.
        index: usize,
    },
    /// The trust anchor certificate itself does not satisfy the profile a
    /// CA certificate must meet, or is outside its validity period.
    ///
    /// RFC 5280 §6.1 treats the anchor as an input and never examines it,
    /// so the literal algorithm accepts an expired root, a root with no
    /// `BasicConstraints`, and a root bearing an unrecognised critical
    /// extension. This workspace checks it anyway: a certificate's own
    /// constraints are the issuer's statement about what it may be used
    /// for, and honouring them belongs here rather than being left to
    /// whoever assembled the trust store.
    ///
    /// Structural defects are caught when the anchor is built
    /// ([`TrustAnchor::from_cert`]), so a root that cannot be a CA never
    /// enters a trust store. [`AnchorDefect::Expired`] and
    /// [`AnchorDefect::NotYetValid`] depend on the clock and are
    /// therefore reported by [`validate_path`].
    ///
    /// # Which anchor this describes
    ///
    /// The error names a defect, not an anchor, and several anchors may
    /// share a subject name. When more than one is outside its window --
    /// a rollover pair straddling the clock, with the old root past its
    /// `notAfter` and the new one short of its `notBefore` --
    /// [`AnchorDefect::Expired`] is reported, so the answer does not
    /// depend on the order the trust store supplied its anchors in.
    ///
    /// An anchor skipped for its window is reported only when no anchor
    /// produced a more specific failure. A trust store holding an expired
    /// root beside an unrelated root of the same name whose signature
    /// check fails reports the signature failure, and the expiry does not
    /// appear. The specific error is the more useful one, but the expiry
    /// is not additionally reported.
    TrustAnchorRejected {
        /// Which requirement the anchor fails.
        defect: AnchorDefect,
    },
    /// No path from the subject certificate to any trust anchor was found.
    NoTrustedPath,
    /// Path length exceeds [`ValidationPolicy::max_path_len`].
    PathTooLong,
    /// A CA in the path has an `ExtendedKeyUsage` that does not permit
    /// what is being asked of the chain below it. See
    /// [`ValidationPolicy::enforce_ca_eku`].
    EkuNotPermittedByIssuer {
        /// Position of the CA whose `ExtendedKeyUsage` excludes it. This
        /// is the certificate that narrowed the permitted set to the
        /// point of failure, not the leaf that asked.
        index: usize,
    },
    /// A certificate that issues another in the path is a CA whose
    /// subject names nothing, against RFC 5280 §4.1.2.6.
    ///
    /// Distinct from [`NotCA`] because the certificate does claim to be a
    /// CA; what it lacks is a name to be one under. See
    /// [`AnchorDefect::EmptySubject`] for why an empty DN on a CA is not
    /// merely non-conforming: §6.1.3(a)(4) name chaining compares DNs,
    /// and an empty DN matches an empty DN, so such a CA chains to any
    /// other certificate issued by any other unnamed CA.
    ///
    /// [`NotCA`]: Error::NotCA
    CaEmptySubject {
        /// Position of the offending certificate in the chain.
        index: usize,
    },
    /// An intermediate certificate is missing `BasicConstraints` `cA=TRUE`.
    NotCA {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// An intermediate certificate has a `KeyUsage` extension with `keyCertSign` not set.
    ///
    /// This error is only returned when a `KeyUsage` extension is **present** and the
    /// `keyCertSign` bit is explicitly absent or zero (RFC 5280 §6.1.4(n): "If a `KeyUsage`
    /// extension is present, verify that the keyCertSign bit is set.").
    ///
    /// Certificates with **no** `KeyUsage` extension are not rejected by this check;
    /// RFC 5280 does not require the extension to be present on CA certificates.
    KeyUsageMissing {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// An intermediate certificate has a `KeyUsage` extension with `cRLSign` not set.
    ///
    /// This error is only returned when
    /// [`ValidationPolicy::require_crl_sign_on_cas`] is `true` **and** the
    /// intermediate's `KeyUsage` extension is **present** with the `cRLSign` bit
    /// explicitly absent or zero. Certificates with **no** `KeyUsage` extension
    /// are not rejected by this check (RFC 5280 does not require the extension
    /// to be present on CA certificates).
    ///
    /// RFC 5280 §6.1 does not mandate this check; it is an opt-in policy that
    /// restores PKITS §4.7.4 / §4.7.5 conformance for callers who treat a CA
    /// cert without `cRLSign` as non-issuable. Default is off.
    ///
    /// **Disambiguation:** [`pkix_revocation::Error::CrlSignMissing`] (same
    /// variant name, different crate) fires during CRL verification when the
    /// CRL *signer* cert lacks `cRLSign` (RFC 5280 §6.3.3(f)). This variant
    /// fires during *path validation* when an intermediate CA cert in the
    /// chain lacks `cRLSign` and the caller opted into the policy check.
    ///
    /// [`pkix_revocation::Error::CrlSignMissing`]: https://docs.rs/pkix-revocation/latest/pkix_revocation/enum.Error.html#variant.CrlSignMissing
    CrlSignMissing {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// A critical extension is present that this implementation does not handle.
    UnhandledCriticalExtension {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// A certificate carries `noRevAvail` together with something RFC 9608
    /// §3 forbids alongside it.
    ///
    /// RFC 9608 §3 lists four prohibitions and ends: "If any of the above
    /// are violated in a certificate, then the relying party MUST
    /// consider the certificate invalid." That sentence is addressed to a
    /// relying party rather than to an issuer, which is why this is a
    /// path-validation error and not only a lint finding.
    ///
    /// # Why this is enforced even though `pkix-path` checks no revocation
    ///
    /// `noRevAvail` asserts that no revocation information will ever be
    /// published. RFC 9608 §4 accordingly skips RFC 5280 §6.1.3 step
    /// (a)(3) for such a certificate, and `pkix-chain` implements that
    /// skip. §3 is the only thing that makes the skip safe: without it,
    /// any certificate carrying `noRevAvail` would escape revocation
    /// checking permanently. Enforcing it here — before any revocation
    /// work is driven, and whether or not the caller does any — keeps
    /// the guard with the thing it guards.
    ///
    /// A certificate that contradicts itself this way is also one §6.1's
    /// state machine cannot otherwise see: it asserts that no revocation
    /// information exists while naming where to fetch it, and two
    /// relying parties reading different halves reach different
    /// verdicts.
    NoRevAvailProfileViolation {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
        /// Which of RFC 9608 §3's prohibitions the certificate violates.
        prohibition: NoRevAvailProhibition,
    },
    /// Certificate name constraints violated (RFC 5280 §4.2.1.10); `index` is the 0-based chain position.
    ///
    /// Also returned when a constraint is in effect for a name the validator
    /// cannot evaluate: a URI without an authority or with an IP-address
    /// host, a name of an unsupported form (`otherName`, `ediPartyName`,
    /// `registeredID`) under a constraint of that form, a non-IA5String
    /// subject `emailAddress`, or a `SmtpUTF8Mailbox` whose domain is not
    /// ASCII.
    NameConstraintViolation {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// Certificate policy validation failed (RFC 5280 §6.1.5(g)).
    ///
    /// Returned when `explicit_policy` reaches zero and the valid policy tree
    /// is empty, meaning no acceptable certificate policy exists for the chain.
    PolicyViolation {
        /// Zero-based index of the certificate where the violation was detected.
        index: usize,
    },
    /// ASN.1 / DER encoding or decoding error.
    ///
    /// Returned when a structural encoding error is found in a certificate or
    /// when re-encoding `TBSCertificate` for signature verification fails.
    /// Signature verification now uses heap-allocated encoding (no fixed size
    /// limit), so this error reflects a genuine DER encoding defect in the
    /// certificate, not an implementation size constraint.
    ///
    /// The inner [`DerError`] is an opaque newtype; the underlying `der::Error`
    /// is intentionally not exposed so a future major-version bump in the
    /// `der` crate cannot cascade into a semver break here.
    Der(DerError),
    /// A certificate's validity period (notAfter − notBefore) exceeds
    /// [`ValidationPolicy::max_validity_secs`].
    ///
    /// This check fires for every certificate in the chain, not just the leaf.
    ValidityPeriodExceedsMax {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// A certificate's signature algorithm OID is not in
    /// [`ValidationPolicy::allowed_signature_algs`].
    ///
    /// The check fires before signature verification so the error is diagnostic
    /// rather than a confusing `SignatureInvalid`.
    AlgorithmNotAllowed {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// An RSA public key's modulus is smaller than
    /// [`ValidationPolicy::min_rsa_key_bits`] bits.
    ///
    /// Non-RSA keys (EC, Ed25519, …) are not affected by this check.
    KeyTooSmall {
        /// Zero-based index into the `chain` slice of the failing certificate.
        index: usize,
    },
    /// The leaf certificate (chain index 0) has no `SubjectAltName` extension,
    /// or the extension is present but empty.
    ///
    /// Only checked when [`ValidationPolicy::require_subject_alt_name`] is `true`.
    /// Intermediate CA certificates are not subject to this check.
    MissingSan,
    /// The leaf certificate (chain index 0) has a `SubjectAltName` extension but
    /// none of its entries is an `rfc822Name` (email address).
    ///
    /// Only checked when [`ValidationPolicy::require_rfc822_san`] is `true`.
    /// Intermediate CA certificates are not subject to this check.
    MissingRfc822San,
    /// The leaf certificate (chain index 0) does not assert all OIDs required
    /// by [`ValidationPolicy::required_leaf_eku`].
    ///
    /// `anyExtendedKeyUsage` (2.5.29.37.0) does not satisfy a specific OID
    /// requirement — each required OID must be listed explicitly.
    MissingEku,
    /// The leaf certificate's `CertificatePolicies` extension does not assert
    /// a required policy OID from
    /// [`ValidationPolicy::required_leaf_policy_oids`].
    ///
    /// `anyPolicy` (2.5.29.32.0) does not satisfy a specific OID requirement;
    /// each required OID must be listed explicitly in the leaf's
    /// `CertificatePolicies` extension.
    ///
    /// Distinct from [`Error::PolicyViolation`], which signals failure of the
    /// RFC 5280 §6.1 policy tree (`initial_policy_set` /
    /// `initial_explicit_policy`). `MissingLeafPolicyOid` signals a leaf-only
    /// assertion check that is independent of the policy tree.
    MissingLeafPolicyOid {
        /// The required policy OID that the leaf does not assert.
        #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
        required: der::asn1::ObjectIdentifier,
    },
    /// The leaf certificate's Subject DN does not satisfy
    /// [`ValidationPolicy::required_leaf_subject_dn_attrs`].
    ///
    /// This variant carries no payload; richer "which branch of the rule
    /// failed" diagnostics are a non-breaking follow-up.
    SubjectDnAttrRuleUnmet,
    /// Two certificates in the chain share the same `(issuer DN, serial number)`.
    ///
    /// Per RFC 5280 §4.1.2.2, the combination of issuer DN and serial number
    /// uniquely identifies a certificate. A cert appearing twice at different
    /// chain positions is a construction error. Returned as a diagnostic rather
    /// than a confusing [`Error::SignatureInvalid`] or [`Error::ChainBroken`].
    ///
    /// Note: two certificates with the same public key but different
    /// issuer+serial are *distinct* certificates (e.g. cross-signed CAs) and
    /// are **not** rejected by this check.
    ///
    /// `first` and `second` are the zero-based chain indices of the two duplicates.
    DuplicateCertificate {
        /// First occurrence index.
        first: usize,
        /// Second occurrence index.
        second: usize,
    },
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::SignatureInvalid { index } => {
                write!(f, "signature invalid at chain index {index}")
            }
            Self::SignatureNotVerified { index, reason } => {
                write!(f, "signature not verified at chain index {index}: {reason}")
            }
            Self::TrustAnchorRejected { defect } => {
                let what = match defect {
                    AnchorDefect::BasicConstraintsMissing => "no BasicConstraints extension",
                    AnchorDefect::BasicConstraintsNotCritical => {
                        "BasicConstraints is not marked critical"
                    }
                    AnchorDefect::NotCa => "BasicConstraints says cA=FALSE",
                    AnchorDefect::EmptySubject => "a CA certificate's subject is empty",
                    AnchorDefect::KeyCertSignMissing => "KeyUsage does not permit keyCertSign",
                    AnchorDefect::UnhandledCriticalExtension => {
                        "an unhandled critical extension is present"
                    }
                    AnchorDefect::MalformedExtension => "an extension could not be parsed",
                    AnchorDefect::NonDerBoolean => {
                        "an extension holds a BER-encoded BOOLEAN, which DER forbids"
                    }
                    AnchorDefect::DuplicateExtension => "the same extension appears more than once",
                    AnchorDefect::Expired => "the anchor has expired",
                    AnchorDefect::NotYetValid => "the anchor is not yet valid",
                };
                write!(f, "trust anchor rejected: {what}")
            }
            Self::ValidityPeriod { index } => {
                write!(f, "validity period check failed at chain index {index}")
            }
            Self::MalformedCertificate { index } => {
                write!(f, "malformed certificate at chain index {index}")
            }
            Self::ChainBroken { index } => {
                write!(f, "issuer/subject linkage broken at chain index {index}")
            }
            Self::NoTrustedPath => write!(f, "no path to a trusted anchor"),
            Self::PathTooLong => write!(f, "path length exceeds maximum"),
            Self::EkuNotPermittedByIssuer { index } => {
                write!(
                    f,
                    "ExtendedKeyUsage of the CA at index {index} does not permit this use"
                )
            }
            Self::CaEmptySubject { index } => {
                write!(f, "CA certificate at index {index} has an empty subject")
            }
            Self::NotCA { index } => write!(f, "certificate at index {index} is not a CA"),
            Self::KeyUsageMissing { index } => {
                write!(f, "keyCertSign missing at chain index {index}")
            }
            Self::CrlSignMissing { index } => {
                write!(f, "cRLSign missing at chain index {index}")
            }
            Self::UnhandledCriticalExtension { index } => {
                write!(f, "unhandled critical extension at chain index {index}")
            }
            Self::NoRevAvailProfileViolation { index, prohibition } => {
                write!(
                    f,
                    "certificate at chain index {index} carries noRevAvail and {}, \
                     which RFC 9608 §3 forbids",
                    prohibition.as_str()
                )
            }
            Self::NameConstraintViolation { index } => {
                write!(f, "name constraints violated at certificate index {index}")
            }
            Self::PolicyViolation { index } => {
                write!(f, "certificate policy violation at chain index {index}")
            }
            Self::Der(e) => write!(f, "DER error: {e}"),
            Self::ValidityPeriodExceedsMax { index } => {
                write!(f, "validity period exceeds maximum at chain index {index}")
            }
            Self::AlgorithmNotAllowed { index } => {
                write!(f, "signature algorithm not allowed at chain index {index}")
            }
            Self::KeyTooSmall { index } => {
                write!(f, "RSA key too small at chain index {index}")
            }
            Self::MissingSan => write!(f, "leaf certificate is missing SubjectAltName"),
            Self::MissingRfc822San => write!(
                f,
                "leaf certificate SubjectAltName contains no rfc822Name entry"
            ),
            Self::MissingEku => {
                write!(
                    f,
                    "leaf certificate is missing required ExtendedKeyUsage OID(s)"
                )
            }
            Self::MissingLeafPolicyOid { required } => {
                write!(
                    f,
                    "leaf certificate is missing required CertificatePolicies OID {required}"
                )
            }
            Self::SubjectDnAttrRuleUnmet => {
                write!(
                    f,
                    "leaf certificate Subject DN does not satisfy the required attribute rule"
                )
            }
            Self::DuplicateCertificate { first, second } => {
                write!(
                    f,
                    "duplicate certificate (issuer+serial) at chain indices {first} and {second}"
                )
            }
        }
    }
}

impl core::error::Error for Error {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Der(e) => Some(e),
            Self::SignatureInvalid { .. }
            | Self::SignatureNotVerified { .. }
            | Self::MalformedCertificate { .. }
            | Self::ValidityPeriod { .. }
            | Self::TrustAnchorRejected { .. }
            | Self::ChainBroken { .. }
            | Self::NoTrustedPath
            | Self::PathTooLong
            | Self::NotCA { .. }
            | Self::CaEmptySubject { .. }
            | Self::EkuNotPermittedByIssuer { .. }
            | Self::KeyUsageMissing { .. }
            | Self::CrlSignMissing { .. }
            | Self::UnhandledCriticalExtension { .. }
            | Self::NoRevAvailProfileViolation { .. }
            | Self::NameConstraintViolation { .. }
            | Self::PolicyViolation { .. }
            | Self::ValidityPeriodExceedsMax { .. }
            | Self::AlgorithmNotAllowed { .. }
            | Self::KeyTooSmall { .. }
            | Self::MissingSan
            | Self::MissingRfc822San
            | Self::MissingEku
            | Self::MissingLeafPolicyOid { .. }
            | Self::SubjectDnAttrRuleUnmet
            | Self::DuplicateCertificate { .. } => None,
        }
    }
}

impl From<der::Error> for Error {
    fn from(e: der::Error) -> Self {
        Self::Der(DerError::new(e))
    }
}

/// Result alias for this crate.
pub type Result<T> = core::result::Result<T, Error>;

/// Pluggable signature verification backend.
///
/// Implement this trait to provide algorithm-specific signature verification.
/// The trait is OID-dispatched: the `algorithm` argument carries the OID and
/// any parameters from the certificate's `signatureAlgorithm` field.
///
/// This trait is object-safe and can be used as `dyn SignatureVerifier`.
/// All method arguments are either `&self` or borrows, so no `Sized` bound
/// is implied.
///
/// # Implementing a custom backend
///
/// ```rust,no_run
/// use der::asn1::ObjectIdentifier;
/// const MY_RSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
/// const MY_ECDSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
///
/// struct MyVerifier;
///
/// impl pkix_path::SignatureVerifier for MyVerifier {
///     fn verify_signature(
///         &self,
///         algorithm: spki::AlgorithmIdentifierRef<'_>,
///         _issuer_spki: spki::SubjectPublicKeyInfoRef<'_>,
///         _message: &[u8],
///         _signature: &[u8],
///     ) -> Result<(), pkix_path::VerificationError> {
///         match algorithm.oid {
///             MY_RSA_OID => { Ok(()) /* RSA verification */ }
///             MY_ECDSA_OID => { Ok(()) /* ECDSA verification */ }
///             _ => Err(pkix_path::VerificationError::unsupported_algorithm()),
///         }
///     }
/// }
/// ```
pub trait SignatureVerifier {
    /// Verify `signature` over `message`.
    ///
    /// - `algorithm`    — from the subject cert's `signatureAlgorithm` field
    /// - `issuer_spki`  — SPKI extracted from the issuer or trust anchor cert
    /// - `message`      — DER-encoded `TBSCertificate` (the bytes that were signed)
    /// - `signature`    — raw signature bytes (`BitString` content, not the wrapper)
    ///
    /// Returns `Ok(())` when the signature verifies. The caller
    /// ([`validate_path`]) adds the chain index: an error of kind
    /// [`VerificationErrorKind::InvalidSignature`] becomes
    /// [`Error::SignatureInvalid`], any other kind
    /// [`Error::SignatureNotVerified`] — the verifier does not need to know
    /// the index.
    ///
    /// # Errors
    ///
    /// Returns a [`VerificationError`] whose kind says why the signature
    /// was not accepted: the algorithm is not supported
    /// ([`UnsupportedAlgorithm`](VerificationErrorKind::UnsupportedAlgorithm)),
    /// the issuer key is unsupported or does not fit the algorithm
    /// ([`UnsupportedKey`](VerificationErrorKind::UnsupportedKey)) or does
    /// not decode ([`MalformedKey`](VerificationErrorKind::MalformedKey)),
    /// or the signature is malformed or does not verify
    /// ([`InvalidSignature`](VerificationErrorKind::InvalidSignature)).
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> core::result::Result<(), VerificationError>;
}

/// Forwarding impl so a shared reference to a verifier is itself a
/// verifier.
///
/// This is what makes a verifier that cannot be `Clone` usable.
/// [`crate::validate_path`] and the `CrlChecker` / `OcspChecker` types in
/// `pkix-revocation` take a verifier by value and require `Clone`, since
/// they hold it and may be cloned themselves. A verifier that owns a
/// hardware token handle, an open session, or anything else not
/// duplicable therefore could not be used at all.
///
/// With this impl it can: pass `&verifier` and the type parameter
/// becomes `&V`, which is `Copy`, so the `Clone` bound is satisfied for
/// free and nothing is duplicated. The borrow is the only cost, and it
/// is what a scoped validation wants anyway.
///
/// For a verifier shared by something outliving a borrow — a fetcher
/// held for the life of a process — use the `Arc` impl below instead.
impl<T: SignatureVerifier + ?Sized> SignatureVerifier for &T {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> core::result::Result<(), VerificationError> {
        (**self).verify_signature(algorithm, issuer_spki, message, signature)
    }
}

/// Forwarding impl so an `Arc`-shared verifier is itself a verifier.
///
/// The owned counterpart to the `&T` impl above, for a verifier that has
/// to outlive any particular borrow. `Arc<V>` is `Clone` whatever `V` is,
/// and cloning it is a refcount bump rather than a duplication of
/// whatever the verifier holds.
///
/// # Why this is gated on `std`
///
/// `Arc` lives in `alloc::sync`, which exists only on targets with
/// atomic compare-and-swap. Implementing it unconditionally would make
/// this crate stop compiling for a `no_std` target without atomics
/// (`thumbv6m-none-eabi`, for instance) in exchange for a convenience.
/// Under `std` those atomics are guaranteed, so the impl is free there.
/// A `no_std` consumer that does have atomics and wants this shape can
/// write the same four-line forwarding impl over its own newtype.
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<T: SignatureVerifier + ?Sized> SignatureVerifier for std::sync::Arc<T> {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> core::result::Result<(), VerificationError> {
        (**self).verify_signature(algorithm, issuer_spki, message, signature)
    }
}

/// A trust anchor used to terminate path validation.
///
/// A trust anchor is typically either a self-signed root CA certificate
/// or a raw (name, SPKI) pair extracted from a platform trust store.
/// The trust anchor itself is **not** signature-verified — it is trusted
/// by definition (RFC 5280 §6.1.1(c)).
///
/// **Validity period**: RFC 5280 §6.1.1(c) explicitly excludes the trust
/// anchor's notBefore/notAfter from path validation. An expired root CA
/// certificate used as a trust anchor will still anchor valid paths — this
/// is intentional behavior, not a bug. Callers are responsible for ensuring
/// their trust store contains the anchors they intend to trust.
///
/// **`PartialEq` is byte-level, not semantic**: The derived `PartialEq`
/// compares fields verbatim. Two anchors representing the same CA may compare
/// unequal if their DER encodings differ — for example, one `AlgorithmIdentifier`
/// with explicit `NULL` parameters and another with absent parameters are both
/// valid for RSA (RFC 3279 §2.3.1) but will not be equal under `==`. Do not use
/// `==` to deduplicate a trust store; use [`names_match`] and compare
/// `algorithm.oid` plus `subject_public_key` bytes directly. Path validation
/// already handles this internally, so it is not affected by this encoding difference.
///
/// # Stability
///
/// `TrustAnchor` is `#[non_exhaustive]`: new fields may be added in minor
/// versions. Construct via [`TrustAnchor::new`], [`TrustAnchor::from_cert`],
/// or [`TrustAnchor::from_cert_ref`]; `TryFrom` delegates to the same
/// checks. There is deliberately no infallible conversion -- see
/// [`Error::TrustAnchorRejected`]. Do not use struct literal syntax.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct TrustAnchor {
    /// The subject distinguished name of the trust anchor.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub subject: x509_cert::name::Name,
    /// The subject public key info of the trust anchor.
    ///
    /// Must be a valid SPKI for the chosen signature algorithm. An empty or
    /// malformed SPKI will cause signature verification to fail with
    /// `Error::NoTrustedPath` (no anchor matched), not a panic.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
    /// `NameConstraints` from the trust anchor certificate, if present.
    ///
    /// When set, `chain_walk` seeds the initial `permitted_subtrees` and
    /// `excluded_subtrees` state from this value before walking the chain.
    /// Populated automatically by `from_cert`; `None` for programmatically
    /// constructed anchors unless explicitly set.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option"))]
    pub name_constraints: Option<x509_cert::ext::pkix::constraints::name::NameConstraints>,
    /// The anchor certificate's validity window, as Unix seconds.
    ///
    /// Retained because RFC 5280 §6.1 never examines the anchor, so
    /// nothing else would: the algorithm checks the certificates in the
    /// path and the anchor is an input. A root's `notAfter` is its
    /// issuer's statement about how long it may be used, and a trust
    /// store is exactly where an expired root sits unnoticed for years.
    ///
    /// Retaining it is not merely permitted but named as an option.
    /// [RFC 6818][rfc6818] §4 replaced §6.2's third paragraph, and the
    /// replacement ends: "Implementations are free to make use of any
    /// additional information that is included in a trust anchor
    /// representation, or to ignore such information." The four fields
    /// this type keeps from an anchor certificate — this one,
    /// [`name_constraints`][Self::name_constraints],
    /// [`extended_key_usage`][Self::extended_key_usage] and
    /// [`crl_sign`][Self::crl_sign] — are that choice exercised, and
    /// `PKIX-2mof` made it before anyone here had read RFC 6818.
    ///
    /// [rfc6818]: https://www.rfc-editor.org/rfc/rfc6818#section-4
    ///
    /// [`validate_path`] compares [`ValidationPolicy::current_time_unix`] against
    /// this and reports [`AnchorDefect::Expired`] or
    /// [`AnchorDefect::NotYetValid`]. The structural requirements are
    /// checked when the anchor is built instead, since they do not
    /// depend on the clock.
    pub validity_unix: (u64, u64),

    /// `ExtendedKeyUsage` from the trust anchor certificate, if present.
    ///
    /// Retained for the same reason as [`name_constraints`]: RFC 5280
    /// §6.1 never examines the anchor, so a root restricted to one
    /// purpose would otherwise constrain nothing below it. 245 of the
    /// 2,872 CA certificates in `third_party/trust-stores` carry an EKU,
    /// and some of those are roots.
    ///
    /// When set, [`validate_path`] seeds the permitted-purpose set from it
    /// before walking the chain, so the anchor narrows exactly as an
    /// intermediate would. See [`ValidationPolicy::enforce_ca_eku`].
    ///
    /// Populated automatically by [`from_cert`]; `None` for
    /// programmatically constructed anchors, which have no certificate to
    /// read and so state no restriction.
    ///
    /// [`name_constraints`]: Self::name_constraints
    /// [`from_cert`]: Self::from_cert
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
    pub extended_key_usage: Option<Vec<der::asn1::ObjectIdentifier>>,

    /// What the anchor's certificate says about signing CRLs — RFC 5280
    /// §6.3.3(f) as amended by RFC 10007 §4.
    ///
    /// A root that anchors a path commonly also signs the CRL covering
    /// the certificates it issued, and then it *is* the CRL issuer that
    /// step (f) asks about. Nothing else can answer: §6.1 does not
    /// examine the anchor, and by the time a revocation checker holds a
    /// [`TrustAnchor`] the certificate is gone.
    ///
    /// [`AnchorCrlSign::Unknown`] for an anchor built by
    /// [`new`](Self::new), which has no certificate to read; computed
    /// from the certificate by [`from_cert`](Self::from_cert).
    pub crl_sign: AnchorCrlSign,

    /// `pathLenConstraint` from the anchor certificate's
    /// `BasicConstraints`, if present.
    ///
    /// Retained for the reason the four fields above are: RFC 5280 §6.1
    /// never examines the anchor, so a root that restricted the depth
    /// below it would otherwise restrict nothing. A root asserting
    /// `pathLen 0` is saying "I issue end entities only", and that is the
    /// same kind of statement as "I issue only for these names", which
    /// [`name_constraints`] already carries.
    ///
    /// 820 of the 2,409 self-signed CA certificates in
    /// `third_party/trust-stores` assert one and 692 assert zero, so this
    /// is a statement issuers make constantly. OpenSSL has enforced it
    /// for decades; leaving it unenforced made `pkix-path` accept chains
    /// `openssl verify` rejects. PKIX-zr0n has the measurement and Mark's
    /// ruling.
    ///
    /// Counted the way §6.1.4(l) and §4.2.1.9 count: only
    /// non-self-issued intermediates below the anchor, so a key-rollover
    /// certificate does not consume depth.
    ///
    /// `None` for an anchor built by [`new`](Self::new), which has no
    /// certificate to read and therefore states no limit; read from the
    /// certificate by [`from_cert`](Self::from_cert).
    ///
    /// [`name_constraints`]: Self::name_constraints
    pub path_len_constraint: Option<u8>,
}

impl TrustAnchor {
    /// Create a trust anchor from raw subject name and SPKI.
    #[must_use]
    pub const fn new(
        subject: x509_cert::name::Name,
        subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
    ) -> Self {
        Self {
            subject,
            subject_public_key_info,
            // A caller supplying a bare subject and key has stated no
            // validity window, so there is none to enforce. An anchor
            // built from a certificate carries that certificate's.
            validity_unix: (0, u64::MAX),
            name_constraints: None,
            extended_key_usage: None,
            // No certificate, so nothing to read. See AnchorCrlSign::Unknown
            // for why that is permission and not refusal.
            crl_sign: AnchorCrlSign::Unknown,
            // Likewise: a caller supplying a bare subject and key has
            // stated no depth limit.
            path_len_constraint: None,
        }
    }

    /// Build a trust anchor from a root CA certificate, checking that the
    /// certificate can be one.
    ///
    /// This is the typical constructor when your trust store contains full
    /// self-signed root CA certificates. Use
    /// [`from_cert_ref`](Self::from_cert_ref) when you need to keep `cert`
    /// alive after building the anchor.
    ///
    /// RFC 5280 §6.1 takes the trust anchor as given and specifies no
    /// checks on it, so an implementation that reads only the subject name
    /// and public key will accept any certificate at all as a root --
    /// including one that says `cA=FALSE`, one whose `KeyUsage` withholds
    /// `keyCertSign`, and one carrying a critical extension the
    /// implementation cannot process. The certificate's own statements
    /// about what it may be used for are checked here instead.
    ///
    /// # Errors
    ///
    /// [`Error::TrustAnchorRejected`], carrying the [`AnchorDefect`] that
    /// disqualified the certificate:
    ///
    /// * [`BasicConstraintsMissing`] or [`BasicConstraintsNotCritical`] --
    ///   §4.2.1.9 requires the extension, marked critical, in a CA
    ///   certificate.
    /// * [`NotCa`] -- `cA` is `FALSE`.
    /// * [`KeyCertSignMissing`] -- `KeyUsage` is present and withholds
    ///   `keyCertSign`. An absent `KeyUsage` is not a defect: §4.2.1.3
    ///   leaves every usage permitted then.
    /// * [`UnhandledCriticalExtension`] -- a critical extension this
    ///   implementation does not process. §6.1.4 would reject such a
    ///   certificate inside the path; the anchor is held to the same rule.
    /// * [`MalformedExtension`] -- an extension's DER could not be parsed,
    ///   so what it requires cannot be known.
    /// * [`NonDerBoolean`] -- `basicConstraints` holds a `cA` `BOOLEAN`
    ///   encoded as valid BER and invalid DER, `0x01` rather than the
    ///   `0xFF` X.690 §11.1 requires for TRUE. Reported apart from
    ///   `MalformedExtension` because the certificate is readable by
    ///   lenient parsers and says `TRUE`; it is refused anyway, since
    ///   honouring it would mean trusting an encoding the profile forbids.
    /// * [`DuplicateExtension`] -- the same extension OID appears more than
    ///   once, which §4.2 forbids. Reported in preference to the others,
    ///   because every check above finds an extension by OID and reads the
    ///   first match: on a certificate with two of something, those checks
    ///   would be answering about whichever copy came first. `validate_path`
    ///   has always refused such a certificate inside a path, as
    ///   [`Error::MalformedCertificate`]; this is that rule applied to the
    ///   anchor.
    ///
    /// [`Expired`] and [`NotYetValid`] are not produced here. They depend
    /// on the validation time, which this constructor is not given;
    /// [`validate_path`] checks [`validity_unix`] against its policy's
    /// clock. A trust store is typically loaded once and used for a long
    /// time, so an anchor's window is re-examined per validation rather
    /// than fixed at load.
    ///
    /// # Algorithm support is not checked here
    ///
    /// A certificate whose public key algorithm this build cannot verify
    /// with still becomes an anchor. That is deliberate, and this
    /// constructor could not do otherwise: it is given no
    /// [`SignatureVerifier`], and which algorithms are supported is a
    /// property of the verifier rather than of the certificate. The
    /// trait is public, so a caller may supply one that handles an
    /// algorithm this crate's own backends do not; screening anchors
    /// against the default set here would make that configuration
    /// impossible to express.
    ///
    /// Note the asymmetry with [`AnchorDefect::NonDerBoolean`], which
    /// refuses a certificate over a single mis-encoded octet. The two are
    /// different kinds of problem. A BER boolean means the certificate's
    /// own claim cannot be read, and the profile check needs `cA`, so
    /// refusing is the only way to avoid guessing a security-relevant
    /// value. An unsupported key algorithm means everything the
    /// certificate says is legible and satisfied, and what is missing is
    /// a capability of this build. Refuse when the certificate is
    /// unreadable; do not refuse when the limitation is ours.
    ///
    /// The cost is discoverability: a trust store can hold anchors that
    /// cannot verify anything, and `pkix-truststore`'s loaders will not
    /// list them as rejected, because nothing about them is wrong. Loading
    /// `third_party/trust-stores/ru-national/` gives eight anchors of
    /// which six are GOST, and a caller counting usable anchors from the
    /// length of the list over-counts by six.
    ///
    /// What bounds that cost is the error at the point of use.
    /// [`validate_path`] reports
    /// [`Error::SignatureNotVerified`] carrying
    /// [`VerificationErrorKind::UnsupportedAlgorithm`] and the chain
    /// index -- not [`Error::NoTrustedPath`], which would hide that an
    /// anchor matched, and not [`Error::SignatureInvalid`], which would
    /// turn a missing feature into an accusation that the issuer did not
    /// sign the certificate. `tests/unsupported_key_algorithm.rs` pins
    /// all of that against two real Russian national roots.
    ///
    /// # `NameConstraints` are read fail-closed
    ///
    /// A certificate whose `NameConstraints` extension cannot be parsed is
    /// refused with [`MalformedExtension`] rather than accepted with the
    /// constraint dropped. Dropping it would be a fail-open: the
    /// deployment asserted through that extension that this root may sign
    /// only for certain names, and an anchor without it may sign for any.
    /// RFC 5280 §4.2 requires rejection when a critical extension cannot
    /// be processed, and the strongest form of "cannot process" is
    /// "cannot parse".
    ///
    /// A subtree encoding a non-zero `minimum` or any `maximum` is refused
    /// for the same reason. §4.2.1.10 forbids both, so such a constraint
    /// has a scope that cannot be honoured as written: enforcing it as
    /// though `minimum` were zero applies it to more names than the issuer
    /// wrote, and discarding it applies it to none.
    ///
    /// [`BasicConstraintsMissing`]: AnchorDefect::BasicConstraintsMissing
    /// [`BasicConstraintsNotCritical`]: AnchorDefect::BasicConstraintsNotCritical
    /// [`NotCa`]: AnchorDefect::NotCa
    /// [`KeyCertSignMissing`]: AnchorDefect::KeyCertSignMissing
    /// [`UnhandledCriticalExtension`]: AnchorDefect::UnhandledCriticalExtension
    /// [`MalformedExtension`]: AnchorDefect::MalformedExtension
    /// [`NonDerBoolean`]: AnchorDefect::NonDerBoolean
    /// [`DuplicateExtension`]: AnchorDefect::DuplicateExtension
    /// [`Expired`]: AnchorDefect::Expired
    /// [`NotYetValid`]: AnchorDefect::NotYetValid
    /// [`validity_unix`]: Self::validity_unix
    pub fn from_cert(cert: Certificate) -> crate::Result<Self> {
        Self::from_cert_ref(&cert)
    }

    /// As [`from_cert`](Self::from_cert), borrowing the certificate.
    ///
    /// # Errors
    ///
    /// The same [`Error::TrustAnchorRejected`] defects as
    /// [`from_cert`](Self::from_cert); the two differ only in ownership.
    pub fn from_cert_ref(cert: &Certificate) -> crate::Result<Self> {
        Self::from_cert_ref_admitting(cert, AnchorAdmission::Strict).map(|(a, _)| a)
    }

    /// Build an anchor under a stated [`AnchorAdmission`], returning any
    /// profile deviation alongside it.
    ///
    /// [`from_cert_ref`](Self::from_cert_ref) and
    /// [`from_cert`](Self::from_cert) are this with
    /// [`AnchorAdmission::Strict`], discarding the deviation because
    /// under that mode a deviation is an error instead.
    ///
    /// Under [`AsPublished`](AnchorAdmission::AsPublished) the returned
    /// `Option<AnchorDefect>` is the thing a caller wants to log: the
    /// anchor is usable, and this says what is odd about the certificate
    /// that carried it. Ignoring it is a choice, not an accident -- see
    /// that variant on why the certificate's profile is not what decides
    /// whether an anchor exists.
    ///
    /// # Errors
    ///
    /// Under `Strict`, any [`AnchorDefect`]. Under `AsPublished`, only
    /// [`AnchorDefect::EmptySubject`], because §6.1.1(d)(1) requires a
    /// trusted issuer name and an empty subject supplies none; plus the
    /// name-constraint failures below, which are refused under both
    /// modes because a constraint that cannot be parsed cannot be
    /// honoured and dropping it would silently widen the anchor.
    pub fn from_cert_ref_admitting(
        cert: &Certificate,
        admission: AnchorAdmission,
    ) -> crate::Result<(Self, Option<AnchorDefect>)> {
        let deviation = anchor_profile_deviation(cert);
        match admission {
            AnchorAdmission::Strict => check_anchor_profile(cert)?,
            AnchorAdmission::AsPublished => anchor_is_structurally_usable(cert)?,
        }
        Self::from_cert_ref_unchecked(cert).map(|a| (a, deviation))
    }

    fn from_cert_ref_unchecked(cert: &Certificate) -> crate::Result<Self> {
        // Read fail-closed, with `try_find_cert_ext` rather than
        // `find_cert_ext`: the lenient lookup returns `None` on a parse
        // failure, which would drop the extension and accept the anchor.
        // The deployment said "this root may only sign for these names",
        // and silently discarding that removes the constraint at
        // validation time. RFC 5280 §4.2 requires rejection when a
        // critical extension cannot be processed, and the strongest
        // form of "cannot process" is "cannot parse".
        //
        // §4.2.1.10 also forbids a `minimum` other than 0 and forbids
        // `maximum` entirely, so a constraint carrying either has a
        // scope that cannot be honoured as written.
        let name_constraints: Option<NameConstraints> =
            try_find_cert_ext(cert, OID_NAME_CONSTRAINTS).map_err(|_| {
                Error::TrustAnchorRejected {
                    defect: AnchorDefect::MalformedExtension,
                }
            })?;
        if name_constraints
            .as_ref()
            .is_some_and(|nc| !subtrees_are_conformant(nc))
        {
            return Err(Error::TrustAnchorRejected {
                defect: AnchorDefect::MalformedExtension,
            });
        }
        let v = cert.tbs_certificate().validity();
        let extended_key_usage = try_find_cert_ext::<x509_cert::ext::pkix::ExtendedKeyUsage>(
            cert,
            OID_EXTENDED_KEY_USAGE,
        )
        .map_err(|_| Error::TrustAnchorRejected {
            defect: AnchorDefect::MalformedExtension,
        })?
        .map(|eku| eku.0);
        Ok(Self {
            subject: cert.tbs_certificate().subject().clone(),
            subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
            name_constraints,
            validity_unix: (
                time_to_unix_secs(&v.not_before),
                time_to_unix_secs(&v.not_after),
            ),
            extended_key_usage,
            crl_sign: anchor_crl_sign(cert),
            path_len_constraint: anchor_path_len(cert),
        })
    }
}

/// The requirements a certificate must meet to be usable as a trust
/// anchor, excluding the clock-dependent ones.
///
/// RFC 5280 §6.1 never examines the anchor, so none of this is required
/// by the path-validation algorithm. It is checked because a
/// certificate's own extensions are its issuer's statement about what
/// the key may be used for, and a root that says `cA=FALSE` or carries a
/// critical extension nobody can process should not become a trust
/// anchor on the strength of someone having put it in a file.
///
/// Measured against the 122 roots in a current system CA bundle, these
/// rules refuse one: a root whose `BasicConstraints` is not marked
/// critical. None lacks `BasicConstraints`, none asserts `cA=TRUE`
/// without `keyCertSign`, and the only critical extensions present are
/// `BasicConstraints` and `KeyUsage`, both of which are handled.
/// How much of the CA-certificate profile an anchor must satisfy.
///
/// # Why this is a choice at all
///
/// RFC 5280 §6.1.1(d) defines what a trust anchor *is*, and it is not a
/// certificate:
///
/// > trust anchor information, describing a CA that serves as a trust
/// > anchor for the certification path. The trust anchor information
/// > includes: (1) the trusted issuer name, (2) the trusted public key
/// > algorithm, (3) the trusted public key, and (4) optionally, the
/// > trusted public key parameters associated with the public key.
///
/// A certificate is one optional carrier for that tuple, and when one is
/// used the section names exactly which two fields are consumed:
///
/// > The trust anchor information may be provided to the path processing
/// > procedure in the form of a self-signed certificate. When the trust
/// > anchor information is provided in the form of a certificate, the
/// > name in the subject field is used as the trusted issuer name and
/// > the contents of the subjectPublicKeyInfo field is used as the
/// > source of the trusted public key algorithm and the trusted public
/// > key.
///
/// `basicConstraints`, its criticality, the `cA` boolean and its
/// encoding, `keyUsage`, the validity window -- none of them is an
/// input. So refusing an anchor over one of them is a policy choice
/// this crate may offer and must not impose.
///
/// # Why the default changed
///
/// It was imposed, and measurably so. Across the 28 bundles vendored in
/// `third_party/trust-stores/` -- DoD, Microsoft, UEFI, eIDAS, 24
/// national and sectoral PKIs -- strict admission refuses **735**
/// anchors, and **734** of those are over fields §6.1.1(d) does not
/// read. 650 are `basicConstraints` presence or criticality alone.
///
/// Each of those publishers is a body the operator already decided to
/// trust by installing its bundle. Refusing a third of it on a field
/// the specification ignores is not caution; it is substituting our
/// profile judgement for their curation, and then reporting the result
/// as if the certificate were unusable.
///
/// [`AnchorDefect`] exists so a caller learns what is odd about an
/// anchor. It should not have to choose between learning that and
/// having the anchor.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AnchorAdmission {
    /// Admit every certificate from which the §6.1.1(d) tuple can be
    /// taken, and report profile deviations rather than refusing them.
    ///
    /// The default, and what a bundle from a publisher you already
    /// trust wants: a root program, a national CSCA list, DoD's PKI.
    ///
    /// Still refused: a certificate that cannot be parsed, and one
    /// whose subject names nothing. The second is structural rather
    /// than stylistic -- §6.1.1(d)(1) requires a trusted issuer name,
    /// and an empty subject means there is none, so the tuple cannot be
    /// formed. See [`AnchorDefect::EmptySubject`].
    #[default]
    AsPublished,
    /// Additionally require the full CA-certificate profile, refusing
    /// any [`AnchorDefect`].
    ///
    /// For auditing a bundle rather than consuming one: answering "does
    /// this publisher emit conforming CA certificates?" instead of "can
    /// I validate paths against these?".
    ///
    /// Reachable per-certificate through
    /// [`TrustAnchor::from_cert`], [`from_cert_ref`][Self::Strict] and
    /// `TryFrom<Certificate>`, all of which are strict. The bundle
    /// loaders in `pkix-truststore` admit as published and report, which
    /// answers the audit question just as well from
    /// `LoadedAnchors::deviations` -- the same set, without costing the
    /// caller the anchors to learn it.
    Strict,
}

/// Every way `cert` deviates from the CA-certificate profile, ignoring
/// whether any of them disqualifies it as an anchor.
///
/// Returns at most one defect, because the checks are ordered and the
/// first is reported -- `DuplicateExtension` before anything that reads
/// an extension by OID, since on a certificate with two of something
/// every later check would be answering about whichever copy came
/// first.
///
/// `None` means the certificate satisfies the profile.
#[must_use]
pub fn anchor_profile_deviation(cert: &Certificate) -> Option<AnchorDefect> {
    match check_anchor_profile(cert) {
        Ok(()) => None,
        Err(Error::TrustAnchorRejected { defect, .. }) => Some(defect),
        // `check_anchor_profile` constructs no other error.
        Err(_) => None,
    }
}

/// Whether the §6.1.1(d) tuple can be formed from `cert` at all.
///
/// The only structural requirement, and the one defect
/// [`AnchorAdmission::AsPublished`] still refuses: §6.1.1(d)(1) needs a
/// trusted issuer name, and a subject that names nothing does not
/// supply one. Everything else in [`AnchorDefect`] is a statement about
/// the certificate rather than about whether an anchor exists.
fn anchor_is_structurally_usable(cert: &Certificate) -> crate::Result<()> {
    if dn_names_nothing(cert.tbs_certificate().subject()) {
        return Err(Error::TrustAnchorRejected {
            defect: AnchorDefect::EmptySubject,
        });
    }
    Ok(())
}

fn check_anchor_profile(cert: &Certificate) -> crate::Result<()> {
    use der::Decode as _;
    use x509_cert::ext::pkix::{BasicConstraints, KeyUsage};

    let reject = |d: AnchorDefect| Err(Error::TrustAnchorRejected { defect: d });

    // First, before anything reads the extension list. RFC 5280 §4.2
    // forbids a repeated extension, and every check below finds an
    // extension by OID and takes the first match -- so on a certificate
    // with two of something, the rest of this function would be
    // answering about whichever copy happens to come first. Order the
    // checks the other way and a duplicate could be reported as a
    // verdict on one of its copies instead.
    if has_duplicate_extensions(cert) {
        return reject(AnchorDefect::DuplicateExtension);
    }

    // An unhandled critical extension is refused for the anchor on the
    // same grounds as §6.1.4 refuses one inside the path: an extension
    // marked critical that nothing processes may be saying something
    // that changes the answer.
    if let Some(exts) = cert.tbs_certificate().extensions() {
        for ext in exts {
            if ext.critical && !HANDLED_CRITICAL_OIDS.contains(&ext.extn_id) {
                return reject(AnchorDefect::UnhandledCriticalExtension);
            }
        }
    }

    let raw = |oid: der::asn1::ObjectIdentifier| {
        cert.tbs_certificate()
            .extensions()
            .map_or(&[][..], |v| v.as_slice())
            .iter()
            .find(move |e| e.extn_id == oid)
    };

    let Some(bc_ext) = raw(OID_BASIC_CONSTRAINTS) else {
        return reject(AnchorDefect::BasicConstraintsMissing);
    };
    if !bc_ext.critical {
        return reject(AnchorDefect::BasicConstraintsNotCritical);
    }
    let Ok(bc) = BasicConstraints::from_der(bc_ext.extn_value.as_bytes()) else {
        // Separate the one non-conforming encoding that occurs in practice
        // from genuine malformation: they call for different responses
        // from a caller. See `AnchorDefect::NonDerBoolean`.
        if has_non_der_boolean(bc_ext.extn_value.as_bytes()) {
            return reject(AnchorDefect::NonDerBoolean);
        }
        return reject(AnchorDefect::MalformedExtension);
    };
    if !bc.ca {
        return reject(AnchorDefect::NotCa);
    }

    // After cA is known, because the rule is about CAs: §4.1.2.6 permits
    // an end entity to carry its name only in a critical SAN, and an
    // anchor that is not a CA has already been refused above.
    if dn_names_nothing(cert.tbs_certificate().subject()) {
        return reject(AnchorDefect::EmptySubject);
    }

    // Absent `KeyUsage` leaves every usage permitted (RFC 5280
    // §4.2.1.3), so only a present-and-contradictory one is a defect.
    if let Some(ku_ext) = raw(OID_KEY_USAGE) {
        let Ok(ku) = KeyUsage::from_der(ku_ext.extn_value.as_bytes()) else {
            return reject(AnchorDefect::MalformedExtension);
        };
        if !ku.key_cert_sign() {
            return reject(AnchorDefect::KeyCertSignMissing);
        }
    }

    Ok(())
}

/// Read RFC 5280 §6.3.3(f)'s input out of an anchor certificate.
///
/// Mirrors `pkix_revocation::crl::check_crl_sign`, which does the same
/// reading for a CRL issuer that is a path certificate. The duplication
/// is deliberate and small: `pkix-path` cannot depend on
/// `pkix-revocation` (the dependency runs the other way), and the
/// alternative is for `TrustAnchor` to retain the whole certificate so
/// that the other crate can re-read it — which is the thing this type
/// exists not to do.
///
/// A malformed `KeyUsage` reports `Withheld` rather than erroring.
/// `check_anchor_profile` has already run by the time this is called and
/// rejects a malformed `KeyUsage` with `AnchorDefect::MalformedExtension`,
/// so this branch is unreachable through `from_cert_ref`; reporting the
/// refusing value keeps it fail-closed if a future caller reorders that.
/// `pathLenConstraint` from `cert`'s `BasicConstraints`, if it states one.
///
/// Reads the extension rather than taking it from
/// [`check_anchor_profile`], because an anchor admitted under
/// [`AnchorAdmission::AsPublished`] skipped that check and still has a
/// depth limit its issuer wrote. A missing or unreadable
/// `BasicConstraints` yields `None`: an anchor that states no limit, which
/// is the same answer a root without the field gives. Nothing is hidden
/// by that -- the strict constructors already refuse both cases before
/// this is reached.
fn anchor_path_len(cert: &Certificate) -> Option<u8> {
    use der::Decode as _;
    use x509_cert::ext::pkix::BasicConstraints;

    let ext = cert
        .tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice())
        .iter()
        .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)?;
    BasicConstraints::from_der(ext.extn_value.as_bytes())
        .ok()?
        .path_len_constraint
}

fn anchor_crl_sign(cert: &Certificate) -> AnchorCrlSign {
    use der::Decode as _;
    use x509_cert::certificate::Version;
    use x509_cert::ext::pkix::KeyUsage;

    let ku_ext = cert
        .tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice())
        .iter()
        .find(|e| e.extn_id == OID_KEY_USAGE);

    match ku_ext {
        // RFC 10007 §4 scopes the presence requirement to v3, because v1
        // and v2 have no extensions field to put KeyUsage in. Matching on
        // the version and not on "are there any extensions" is the point:
        // a v3 certificate with an empty extensions list is still v3.
        None if cert.tbs_certificate().version() == Version::V3 => AnchorCrlSign::KeyUsageMissing,
        None => AnchorCrlSign::Exempt,
        Some(ext) => match KeyUsage::from_der(ext.extn_value.as_bytes()) {
            Ok(ku) if ku.crl_sign() => AnchorCrlSign::Asserted,
            Ok(_) => AnchorCrlSign::Withheld,
            Err(_) => AnchorCrlSign::Withheld,
        },
    }
}

// No infallible `From<&Certificate>`: it would be a door into a trust
// store that skips `check_anchor_profile`, which is the whole point of
// checking. Use `TrustAnchor::from_cert_ref`.
impl TryFrom<&Certificate> for TrustAnchor {
    type Error = crate::Error;

    fn try_from(cert: &Certificate) -> crate::Result<Self> {
        Self::from_cert_ref(cert)
    }
}

/// Fail-closed construction from an owned certificate.
///
/// Returns `Err(`[`DerError`]`)` if the certificate contains a `NameConstraints`
/// extension with malformed DER. Use this when building a trust store that
/// must reject certificates with unparseable critical extensions per
/// RFC 5280 §4.2.
///
/// The error type is the opaque [`DerError`] newtype rather than `der::Error`
/// so that a future major-version bump in the `der` crate does not cascade
/// into a semver break here.
///
/// # Why only `TryFrom<Certificate>` and not `TryFrom<&Certificate>`
///
/// `TryFrom<&Certificate>` would conflict with the blanket impl
/// `impl<T, U: Into<T>> TryFrom<U>` provided by Rust core, because
/// `From<&Certificate>` is already implemented (and `From` implies `Into`).
/// Use `TrustAnchor::try_from(cert.clone())` if you need to keep `cert`.
impl TryFrom<Certificate> for TrustAnchor {
    type Error = crate::Error;

    fn try_from(cert: Certificate) -> crate::Result<Self> {
        // Delegates so there is one fallible path and one error type.
        // This impl used to return `DerError` and check only that
        // `NameConstraints` parsed and satisfied §4.2.1.10's
        // minimum/maximum rule; `from_cert_ref` subsumes that and adds
        // the CA-profile checks, and `Error::Der` still carries the
        // opaque `DerError` so nothing is lost.
        Self::from_cert_ref(&cert)
    }
}
/// Compositional rule for asserting required Subject DN attributes on a leaf cert.
///
/// Designed to express CA/B Forum S/MIME BR tier rules such as "must have
/// `organizationName`" or "must have `pseudonym` OR (`givenName` AND
/// `surname`)" without committing the workspace to a fixed list of attribute
/// requirements.
///
/// The [`Field`][Self::Field] variant matches when the named OID appears at
/// least once in the leaf's Subject DN RDN sequence (any RDN, any
/// `AttributeTypeAndValue` within an RDN). [`AllOf`][Self::AllOf] and
/// [`AnyOf`][Self::AnyOf] compose subordinate rules.
///
/// # Vacuity
///
/// - `AllOf(vec![])` accepts every Subject DN (vacuously true).
/// - `AnyOf(vec![])` rejects every Subject DN (vacuously false).
///
/// Callers writing `AnyOf` should not pass an empty list unless that is the
/// intended semantics.
///
/// # Example
///
/// Express "Subject must have `pseudonym`, or both `givenName` and
/// `surname`":
///
/// ```rust
/// use pkix_path::DnAttrRule;
/// use der::asn1::ObjectIdentifier;
///
/// const PSEUDONYM:  ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.65");
/// const GIVEN_NAME: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.42");
/// const SURNAME:    ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.4");
///
/// let rule = DnAttrRule::AnyOf(vec![
///     DnAttrRule::Field(PSEUDONYM),
///     DnAttrRule::AllOf(vec![
///         DnAttrRule::Field(GIVEN_NAME),
///         DnAttrRule::Field(SURNAME),
///     ]),
/// ]);
/// # let _ = rule;
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DnAttrRule {
    /// Match when the named attribute OID appears at least once in the
    /// leaf's Subject DN.
    Field(
        #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
        der::asn1::ObjectIdentifier,
    ),
    /// Match when every subordinate rule matches. `AllOf(vec![])` is
    /// vacuously true.
    AllOf(Vec<DnAttrRule>),
    /// Match when at least one subordinate rule matches. `AnyOf(vec![])`
    /// is vacuously false.
    AnyOf(Vec<DnAttrRule>),
}

/// Walk the Subject DN once and report whether the named OID appears in any
/// `AttributeTypeAndValue` within any `RelativeDistinguishedName`.
///
/// OID equality is exact byte-for-byte comparison; no aliasing or
/// canonicalization is performed.
fn dn_contains_oid(subject: &x509_cert::name::Name, oid: &der::asn1::ObjectIdentifier) -> bool {
    subject.iter().any(|ava| ava.oid == *oid)
}

/// Evaluate a [`DnAttrRule`] against a Subject DN, returning `true` when the
/// rule is satisfied.
fn evaluate_dn_attr_rule(subject: &x509_cert::name::Name, rule: &DnAttrRule) -> bool {
    match rule {
        DnAttrRule::Field(oid) => dn_contains_oid(subject, oid),
        DnAttrRule::AllOf(rules) => rules.iter().all(|r| evaluate_dn_attr_rule(subject, r)),
        DnAttrRule::AnyOf(rules) => rules.iter().any(|r| evaluate_dn_attr_rule(subject, r)),
    }
}

/// Policy parameters controlling path validation.
///
/// # Stability
///
/// `ValidationPolicy` is `#[non_exhaustive]`.
/// Construct via [`ValidationPolicy::new`] or [`Default`] + field assignment.
/// Do not use struct literal syntax.
///
/// # Performance note
///
/// Policy objects are intended to be constructed once (e.g., at server startup)
/// and reused for the lifetime of the application. Repeated construction is
/// unnecessary.
///
/// Policy enforcement (`CertificatePolicies`, `PolicyMappings`, `PolicyConstraints`,
/// `InhibitAnyPolicy`) is implemented per RFC 5280 §6.1. Use the
/// `initial_explicit_policy`, `initial_any_policy_inhibit`,
/// `initial_policy_mapping_inhibit`, and `initial_policy_set` fields to
/// configure the initial policy state.
///
/// # Limitations
///
/// Path-building (RFC 4158 — cross-signed certificates, multiple candidate
/// issuers) is **out of scope** for this crate. The caller must supply the
/// complete, ordered chain (see `pkix-path-builder` for path discovery).
///
/// Revocation checking (CRL / OCSP) is out of scope for `pkix-path`; see
/// `pkix-revocation` for that functionality.
// `clippy::struct_excessive_bools` would prefer enum-typed groupings here,
// but the bools map directly to RFC 5280 §6.1.1 named inputs
// (`initial-explicit-policy`, `initial-any-policy-inhibit`,
// `initial-policy-mapping-inhibit`) and to the SAN-presence and
// EKU-presence policy gates. Substituting an enum cluster would obscure the
// 1:1 mapping to the spec text and force callers through a pattern-match
// adapter for each field. The current shape is the most direct expression
// of the spec inputs.
#[allow(clippy::struct_excessive_bools)]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidationPolicy {
    /// Maximum chain depth, not counting the trust anchor. Default: 10.
    ///
    /// A chain of `[leaf]` is depth 0. `[leaf, intermediate, root]` is depth 1
    /// (one intermediate). Validation fails if depth exceeds this value.
    ///
    /// Self-issued certificates do not count towards the depth (RFC 5280
    /// §4.2.1.9), but they are not unlimited either: a chain longer than
    /// `2 * max_path_len + 3` certificates (the leaf, `max_path_len`
    /// intermediates, and up to one self-issued certificate per CA in the
    /// path plus one more at the top for an included root) is rejected with
    /// [`Error::PathTooLong`] before any other processing. This bounds the
    /// work done on an attacker-supplied chain.
    pub max_path_len: u8,

    /// Current time as seconds since the Unix epoch (1970-01-01T00:00:00Z).
    ///
    /// Used to check `notBefore` ≤ `now` ≤ `notAfter` on every certificate.
    /// **Must be set by the caller** — there is no platform clock in `no_std`.
    ///
    /// **Warning — the default is 0 (1970-01-01):** Any certificate issued
    /// after 1970 has `notBefore > 0` and will fail the validity check with
    /// [`Error::ValidityPeriod`]. If you see unexpected `ValidityPeriod`
    /// errors, check that `current_time_unix` is set to the current time.
    ///
    /// **Warning**: passing `u64::MAX` causes all `notAfter` checks to pass.
    /// This effectively disables expiry checking — only use it in contexts
    /// where you explicitly want permissive (clock-free) validation.
    pub current_time_unix: u64,

    /// Enforce the `KeyUsage` extension when present. Default: `true`.
    ///
    /// When `true`, an intermediate certificate whose `KeyUsage` extension is
    /// **present** but does not include `keyCertSign` will be rejected with
    /// [`Error::KeyUsageMissing`], per RFC 5280 §6.1.4(n).
    ///
    /// Certificates with **no** `KeyUsage` extension are not affected; RFC 5280
    /// only mandates the check when the extension is present.
    pub enforce_key_usage: bool,

    /// Whether a CA's `ExtendedKeyUsage` constrains what it may issue.
    /// Default: `true`.
    ///
    /// RFC 5280 §6.1 has no EKU step, and §4.2.1.12 says only that the
    /// extension "will appear only in end entity certificates" "in
    /// general". EKU nesting is therefore not an RFC 5280 path validation
    /// rule; it is the WebPKI profile's, and it is what every other
    /// verifier does — rustls-webpki enforces it, OpenSSL enforces it
    /// under `-purpose`, browsers enforce it.
    ///
    /// It is on by default because without it a CA restricted to one
    /// purpose can issue for another, which is the cross-purpose
    /// confusion EKU on a CA exists to prevent. The check is chain
    /// self-consistency rather than caller policy: a leaf claiming a
    /// purpose its own issuer forbids is contradictory whatever the
    /// caller asked about, so it does not depend on
    /// [`required_leaf_eku`][Self::required_leaf_eku] being set.
    ///
    /// What it does:
    ///
    /// * A CA with no `ExtendedKeyUsage` extension constrains nothing.
    ///   This is the common case and stays free.
    /// * A CA whose EKU contains `anyExtendedKeyUsage` constrains
    ///   nothing.
    /// * Otherwise the permitted set narrows by intersection down the
    ///   chain. Two CAs with disjoint EKUs leave nothing issuable and the
    ///   path is refused.
    /// * A leaf carrying an EKU must share at least one purpose with the
    ///   permitted set. *Intersection*, not containment: a leaf listing
    ///   `serverAuth` and `clientAuth` under a `serverAuth`-only
    ///   intermediate is accepted, because the unusable extra claim is
    ///   not a reason to refuse a chain that works for what it is being
    ///   used for. That pattern is common in the real WebPKI.
    /// * A leaf with no EKU is not refused by this check — it claims no
    ///   purpose to contradict. `required_leaf_eku` is what rejects such
    ///   a leaf where a purpose is demanded, and it is additionally
    ///   checked against the permitted set.
    ///
    /// Turn it off for a PKI that puts EKUs on CA certificates
    /// decoratively rather than restrictively.
    ///
    /// # Known tension: delegated OCSP responders
    ///
    /// RFC 6960 §4.2.2.2 has a CA designate a responder by issuing it a
    /// certificate carrying `id-kp-OCSPSigning`. It does not require the
    /// CA itself to carry that purpose — so a CA restricted to
    /// `serverAuth`, which is what the CA/B Forum requires of a TLS
    /// subordinate, cannot designate a responder without failing this
    /// check. Other implementations carve `id-kp-OCSPSigning` out of
    /// nesting for exactly this reason.
    ///
    /// No carve-out is made here, because nothing in this workspace needs
    /// one: `pkix_revocation`'s OCSP code establishes a CA-designated
    /// responder by checking the responder certificate's own EKU and its
    /// issuance by the subject's CA, and never validates the responder as
    /// a path through this function. A caller who *does* validate a
    /// delegated responder certificate as a path under an EKU-restricted
    /// CA will see [`Error::EkuNotPermittedByIssuer`], and wants this flag
    /// off for that call. Said here rather than carved out silently, so
    /// the choice is visible to whoever hits it.
    pub enforce_ca_eku: bool,

    /// Require `cRLSign` in `KeyUsage` on every intermediate CA. Default: `false`.
    ///
    /// When `true`, an intermediate certificate whose `KeyUsage` extension is
    /// **present** but does not include `cRLSign` will be rejected with
    /// [`Error::CrlSignMissing`]. Certificates with **no** `KeyUsage` extension
    /// are not affected.
    ///
    /// RFC 5280 §6.1 does not mandate this check — it conflates path validation
    /// with revocation infrastructure. PKITS §4.7.4 and §4.7.5 nonetheless
    /// expect such chains to fail because a CA cert without `cRLSign` cannot
    /// revoke certs it issued. Enable this flag to restore PKITS conformance
    /// or to enforce a stricter "every CA must be able to sign CRLs" rule.
    ///
    /// This check is independent of [`enforce_key_usage`][Self::enforce_key_usage]:
    /// `enforce_key_usage` governs the RFC-mandated `keyCertSign` check, while
    /// `require_crl_sign_on_cas` adds a separate cRLSign requirement.
    pub require_crl_sign_on_cas: bool,

    /// Initial explicit-policy indicator (RFC 5280 §6.1.1).
    ///
    /// When `true`, path validation requires that at least one valid policy exists
    /// from the initial policy set. When `false` (the default), any valid path is
    /// accepted even if no certificate policy is asserted.
    pub initial_explicit_policy: bool,

    /// Initial any-policy inhibit indicator (RFC 5280 §6.1.1).
    ///
    /// When `true`, the `anyPolicy` OID is not considered a match for any other
    /// policy at the start of the path. When `false` (the default), `anyPolicy`
    /// is accepted as a wildcard unless later inhibited by a CA certificate.
    pub initial_any_policy_inhibit: bool,

    /// Initial policy-mapping inhibit indicator (RFC 5280 §6.1.1).
    ///
    /// When `true`, policy mappings are not permitted in any certificate in the
    /// chain. When `false` (the default), policy mappings are allowed.
    pub initial_policy_mapping_inhibit: bool,

    /// Initial user-requested policy set (RFC 5280 §6.1.1).
    ///
    /// The set of certificate policies acceptable to the relying party. An empty
    /// vec, or any set that contains `anyPolicy` (2.5.29.32.0), is the RFC's
    /// any-policy value: all policies are acceptable and the policy graph is
    /// not intersected (§6.1.5(g)(ii)). Otherwise the final graph keeps only
    /// policies in this set (§6.1.5(g)(iii)).
    ///
    /// Note: this is `pub` but clones the OID set, so prefer constructing once
    /// and reusing the `ValidationPolicy`.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
    pub initial_policy_set: Vec<der::asn1::ObjectIdentifier>,

    /// If `Some(n)`, reject any certificate whose (notAfter − notBefore) exceeds
    /// `n` seconds. `None` means unconstrained (the default).
    ///
    /// Applied to every certificate in the chain, not just the leaf.
    /// Violations produce [`Error::ValidityPeriodExceedsMax`].
    pub max_validity_secs: Option<u64>,

    /// If `Some(list)`, reject any certificate whose signature algorithm OID is
    /// not in `list`. `None` means any algorithm is accepted (the default).
    ///
    /// Applied to every certificate in the chain. The check fires **before**
    /// signature verification so the error is diagnostic rather than a confusing
    /// [`Error::SignatureInvalid`].
    /// Violations produce [`Error::AlgorithmNotAllowed`].
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
    pub allowed_signature_algs: Option<Vec<der::asn1::ObjectIdentifier>>,

    /// If `Some(bits)`, reject any certificate carrying an RSA public key whose
    /// modulus is fewer than `bits` bits. Both `rsaEncryption` and
    /// `id-RSASSA-PSS` subject keys count as RSA; other keys are not affected.
    /// `None` means unconstrained (the default).
    ///
    /// Applied to the subject key of every certificate in the chain, leaf
    /// included. The trust anchor's key is **not** checked: it is caller
    /// configuration, not path input, so filter weak anchors when building
    /// the trust store.
    /// Violations produce [`Error::KeyTooSmall`].
    pub min_rsa_key_bits: Option<u32>,

    /// If `true`, the leaf certificate (chain index 0) must have a non-empty
    /// `SubjectAltName` extension. `false` means no SAN requirement (the default).
    ///
    /// Intermediate CA certificates are not checked by this field.
    /// Violations produce [`Error::MissingSan`].
    pub require_subject_alt_name: bool,

    /// If `true`, at least one `rfc822Name` entry must be present in the leaf's
    /// `SubjectAltName` extension.
    ///
    /// Only meaningful when [`require_subject_alt_name`][Self::require_subject_alt_name]
    /// is also `true`. When `require_subject_alt_name` is `false`, this field has
    /// no effect.
    ///
    /// Default: `false` (backward compatible).
    /// Violations produce [`Error::MissingRfc822San`].
    pub require_rfc822_san: bool,

    /// If `Some(oids)`, the leaf certificate must explicitly assert every OID in
    /// `oids` via its `ExtendedKeyUsage` extension. `None` means no EKU requirement
    /// (the default).
    ///
    /// `anyExtendedKeyUsage` (2.5.29.37.0) does **not** satisfy a specific OID
    /// check — each required OID must be listed in the cert's EKU extension.
    /// Violations produce [`Error::MissingEku`].
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
    pub required_leaf_eku: Option<Vec<der::asn1::ObjectIdentifier>>,

    /// If `Some(oids)`, the leaf certificate must explicitly assert every OID
    /// in `oids` via its `CertificatePolicies` extension. `None` means no
    /// policy-OID assertion requirement (the default).
    ///
    /// Distinct from [`initial_policy_set`][Self::initial_policy_set]:
    /// `initial_policy_set` is the relying party's *acceptable* policy set
    /// (RFC 5280 §6.1.1, `user-initial-policy-set`).
    /// `required_leaf_policy_oids` requires *assertion* — the OID must appear
    /// on the leaf cert's `CertificatePolicies` extension, independent of the
    /// policy tree.
    ///
    /// `anyPolicy` (2.5.29.32.0) does **not** satisfy a specific OID check.
    /// Violations produce [`Error::MissingLeafPolicyOid`].
    ///
    /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
    /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
    /// subscriber-profile tier disambiguation where a tier mandates assertion
    /// of a specific reserved policy OID.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
    pub required_leaf_policy_oids: Option<Vec<der::asn1::ObjectIdentifier>>,

    /// If `Some(rule)`, the leaf certificate's Subject DN must satisfy
    /// `rule`. `None` means no Subject DN requirement (the default).
    ///
    /// Violations produce [`Error::SubjectDnAttrRuleUnmet`]. See
    /// [`DnAttrRule`] for the expression grammar and vacuity rules.
    ///
    /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
    /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
    /// subscriber-profile tier disambiguation (e.g., S/MIME
    /// Organization-validated tier requires `organizationName`).
    pub required_leaf_subject_dn_attrs: Option<DnAttrRule>,
}

impl ValidationPolicy {
    /// Construct a policy with the given time and sensible defaults.
    ///
    /// This is the only constructor: it forces the caller to supply a timestamp,
    /// preventing the silent validity failures that a `Default` with
    /// `current_time_unix = 0` would cause.
    #[must_use]
    pub fn new(now_unix: u64) -> Self {
        Self {
            max_path_len: 10,
            current_time_unix: now_unix,
            enforce_key_usage: true,
            enforce_ca_eku: true,
            require_crl_sign_on_cas: false,
            initial_explicit_policy: false,
            initial_any_policy_inhibit: false,
            initial_policy_mapping_inhibit: false,
            initial_policy_set: Vec::new(),
            max_validity_secs: None,
            allowed_signature_algs: None,
            min_rsa_key_bits: None,
            require_subject_alt_name: false,
            require_rfc822_san: false,
            required_leaf_eku: None,
            required_leaf_policy_oids: None,
            required_leaf_subject_dn_attrs: None,
        }
    }
}

/// A PKI regime profile that bundles identity, citation, and a validation policy.
///
/// # Design rationale
///
/// `ValidationPolicy` is the *mechanism*. A `Profile` is the *policy authority*: it
/// records *who* mandates the policy (e.g., CA/B Forum TLS BR §7.1), supplies a
/// stable machine-readable identifier, and produces the appropriate
/// [`ValidationPolicy`] for a given point in time.
///
/// Placing the trait in `pkix-path` rather than `pkix-profiles` means that third-party
/// profile crates (e.g., `pkix-fpki`, `pkix-etsi`) can implement `Profile` by depending
/// only on `pkix-path` — they do not need to pull in `pkix-profiles`, which would create
/// a circular coupling between reference implementations and the trait definition.
///
/// # `no_std` compatibility
///
/// The trait is `no_std`-safe: it uses only `&str`, `&[ObjectIdentifier]`, and
/// `ValidationPolicy` (all of which are available without `std`).
/// Implementors on embedded targets may return static `&'static str` slices and
/// construct `ValidationPolicy` without allocation.
///
/// # Implementing `Profile`
///
/// ```rust,no_run
/// use pkix_path::{Profile, ValidationPolicy};
///
/// struct MyCorpProfile;
///
/// impl Profile for MyCorpProfile {
///     fn id(&self) -> &'static str { "example.corp.internal" }
///     fn version(&self) -> &'static str { "2024-01" }
///     fn policy(&self, now_unix: u64) -> ValidationPolicy {
///         let mut p = ValidationPolicy::new(now_unix);
///         p.max_validity_secs = Some(365 * 86_400);
///         p
///     }
///     fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier] { &[] }
/// }
/// ```
pub trait Profile {
    /// Stable, dot-separated identifier for this profile.
    ///
    /// The identifier MUST be unique across all deployed profiles and MUST NOT
    /// change between versions of the same profile. Use reverse-DNS or
    /// CABF/IETF-style naming conventions, e.g.:
    /// - `"cabf.br.tls"` — CA/B Forum TLS Baseline Requirements
    /// - `"cabf.smime"` — CA/B Forum S/MIME Baseline Requirements
    /// - `"fpki.common-policy"` — US Federal PKI Common Policy
    ///
    /// Lint engines use this ID as a namespace prefix for finding IDs.
    fn id(&self) -> &'static str;

    /// Human-readable version string for this profile.
    ///
    /// Typically the ballot or specification version that last changed the
    /// policy rules, e.g., `"SC-081"`, `"2024-01"`, or `"v2.0.1"`.
    /// Used for diagnostic messages and audit logs; not parsed by the engine.
    fn version(&self) -> &'static str;

    /// Produce the [`ValidationPolicy`] for the given point in time.
    ///
    /// `now_unix` is seconds since the Unix epoch. The profile may use this to
    /// implement phased validity caps or algorithm retirement schedules.
    /// The returned `ValidationPolicy` MUST have `current_time_unix` set to
    /// `now_unix`.
    #[must_use]
    fn policy(&self, now_unix: u64) -> ValidationPolicy;

    /// The certificate policy OIDs that this profile recognises as its own.
    ///
    /// Used by registry and composition tools to detect when two profiles
    /// claim overlapping policy space. Returns an empty slice if the profile
    /// does not restrict certificate policy OIDs.
    fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier];
}

/// The result of a successful certificate path validation.
///
/// A `ValidatedPath` is only produced when [`validate_path`] succeeds, which
/// requires the input `chain` to contain at least one certificate. Callers
/// may therefore rely on `chain[0]` being valid after a successful validation.
///
/// Fields are `pub` for direct read access. `#[non_exhaustive]` prevents external
/// code from constructing `ValidatedPath` directly and from pattern-matching
/// exhaustively, preserving the ability to add fields in future minor versions
/// without a breaking change.
///
/// # `Copy` removal in 0.3.0
///
/// `ValidatedPath` is no longer `Copy`. The struct now carries owned
/// heap-backed fields exposing RFC 5280 §6.1.5 wrap-up outputs (the leaf's
/// subject DN, issuer DN, serial number, and SubjectPublicKeyInfo) so
/// consumers can read the validated leaf identity without re-parsing
/// `chain[0]`. These fields cannot satisfy the `Copy` bound; pre-0.3
/// callers that relied on bit-copy semantics need to add `.clone()` or
/// pass `&ValidatedPath` instead.
///
/// # §6.1.5 wrap-up outputs
///
/// RFC 5280 §6.1.5 specifies that successful path validation produces
/// several outputs identifying the validated leaf certificate. The four
/// leaf-intrinsic outputs (subject, issuer, serial, SPKI) are surfaced
/// here as convenience accessors; consumers no longer need to re-parse
/// `chain[0]` to obtain them.
///
/// The final `valid_policy_tree` is surfaced as
/// [`valid_policy_tree`][Self::valid_policy_tree]. The final
/// `working_public_key_parameters` is not yet surfaced; future minor
/// versions may add it, so callers should pattern match with `..` rest
/// patterns on this `#[non_exhaustive]` struct.
///
/// `Hash` is no longer derived because none of the new field types
/// (`x509_cert::name::Name`, `x509_cert::serial_number::SerialNumber`,
/// `spki::SubjectPublicKeyInfoOwned`) implement `Hash` upstream. No
/// in-tree consumer used `ValidatedPath` as a `HashMap`/`HashSet` key,
/// so dropping the derive is observable but should not require code
/// changes for any existing user.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct ValidatedPath {
    /// Index into the `anchors` slice of the trust anchor that terminated the path.
    pub anchor_index: usize,
    /// Number of intermediate certificates in the validated chain, excluding
    /// both the leaf and the trust anchor.
    ///
    /// Computed as `chain.len().saturating_sub(1)` where `chain` is the
    /// `[leaf, intermediate_0, ..., intermediate_n]` slice passed to
    /// [`validate_path`]. A single leaf certificate yields `depth == 0`;
    /// a leaf plus one intermediate yields `depth == 1`.
    ///
    /// Note: this counts all certificates except the trust anchor — including
    /// self-issued intermediates that RFC 5280 §4.2.1.9 excludes from the
    /// `pathLenConstraint` count. For chains with self-issued intermediates the
    /// `depth` field may be larger than the RFC 5280 path length.
    ///
    /// **Do not** compare `depth` directly against a certificate's
    /// [`BasicConstraints`] `pathLenConstraint` value. RFC 5280 §4.2.1.9
    /// defines `pathLenConstraint` as the number of non-self-issued
    /// intermediates below the issuing CA, which differs from this field's
    /// total certificate count. Use the RFC 5280 §6.1.4(b) accounting
    /// performed by `chain_walk` instead.
    ///
    /// [`BasicConstraints`]: x509_cert::ext::pkix::BasicConstraints
    pub depth: usize,

    /// Subject DN of the validated leaf certificate (`chain[0].subject`).
    ///
    /// RFC 5280 §6.1.5 names this output indirectly: a successful path
    /// validation produces the leaf's identity (subject + serial uniquely
    /// identify a certificate). This field is a convenience accessor —
    /// callers could equivalently read `chain[0].tbs_certificate().subject()`,
    /// but threading the chain to every consumer that needs the leaf's DN
    /// is awkward. The clone is owned to free the validated value from any
    /// lifetime tie to the input chain.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub leaf_subject: x509_cert::name::Name,

    /// Issuer DN of the validated leaf certificate (`chain[0].issuer`).
    ///
    /// This is the §6.1.5(f) `working_issuer_name` output as observed at
    /// the leaf cert (which is the first cert processed by the §6.1
    /// algorithm, so the leaf's `issuer` is the initial value of
    /// `working_issuer_name` before iteration begins; for a successfully
    /// validated chain it identifies the directly-signing CA).
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub leaf_issuer: x509_cert::name::Name,

    /// Serial number of the validated leaf certificate
    /// (`chain[0].serial_number`).
    ///
    /// Together with [`Self::leaf_issuer`] this forms the RFC 5280
    /// §4.1.2.2 unique certificate identifier (`{ issuer, serial }`),
    /// which downstream code commonly needs for revocation lookups,
    /// audit logging, or de-duplication.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub leaf_serial: x509_cert::serial_number::SerialNumber,

    /// `SubjectPublicKeyInfo` of the validated leaf certificate.
    ///
    /// This is the §6.1.5(c)(d)(e) `working_public_key` /
    /// `working_public_key_algorithm` / `working_public_key_parameters`
    /// outputs, bundled into the canonical SPKI form. Downstream code
    /// (e.g. application-layer signature verification using the validated
    /// leaf as a trust delegate) needs the full SPKI rather than only the
    /// algorithm identifier or only the public-key bits.
    ///
    /// Note: this field reflects the leaf's *encoded* SPKI as it appeared
    /// in the certificate, not a normalized/canonicalized form. PSS
    /// parameters, RSA `parameters: NULL` vs `parameters: absent`
    /// ambiguities, etc. are preserved verbatim.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub leaf_spki: spki::SubjectPublicKeyInfoOwned,

    /// The final RFC 5280 §6.1.5 `valid_policy_tree` (held as the RFC 9618
    /// policy graph, see [`PolicyTreeNode`]), or `None` if it was reduced to
    /// NULL during validation.
    ///
    /// `Some(tree)` is the post-§6.1.5(g)(iii) state (i.e. after
    /// intersection with `initial_policy_set` and post-pruning), listed
    /// depth by depth starting with the depth-0 root.
    /// `None` means the path validated only because `explicit_policy`
    /// stayed above 0 (no explicit policy was required) — semantically "no
    /// acceptable policy is valid for this path". Callers that want to enforce a specific policy OID
    /// (or extract qualifiers attached to a specific policy) should
    /// inspect this field and treat `None` as "no policy information
    /// available", not as a validation failure.
    ///
    /// Each node carries its policy qualifiers (RFC 5280 §6.1.2(a)) in
    /// the upstream `PolicyQualifierInfo` form (a `(qualifier_id_oid,
    /// raw_any_value)` pair, no decoding of `qualifier`). See
    /// [`PolicyTreeNode`] for the per-node shape.
    ///
    /// For convenience, [`Self::policy_qualifiers`] iterates
    /// `(policy_oid, qualifier)` pairs across all tree nodes.
    pub valid_policy_tree: Option<Vec<PolicyTreeNode>>,
}

/// A node of the final policy graph, exposed for post-validation qualifier
/// extraction on [`ValidatedPath::valid_policy_tree`].
///
/// Policy processing uses the RFC 9618 `valid_policy_graph` in place of the
/// RFC 5280 §6.1.2(a) `valid_policy_tree`: there is at most one node per
/// `(depth, valid_policy)`, and a node that the RFC 5280 tree would copy
/// once per parent appears once, listing every parent in
/// [`parent_policies`][Self::parent_policies]. The set of valid policies is
/// the same (RFC 9618 §3); the graph's size stays linear in the size of the
/// path's policy extensions, where the tree can grow exponentially.
///
/// This is the public mirror of an internal node type, kept separate so the
/// internal representation is not part of the public API surface.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct PolicyTreeNode {
    /// Depth at which this node appears in the tree.
    ///
    /// `0` is the synthetic anyPolicy root sentinel (always present
    /// while the tree is alive; carries no qualifiers). `1` is the
    /// trust-anchor-adjacent CA. `n` is the leaf.
    pub depth: usize,

    /// The policy OID this node represents.
    ///
    /// May be `id-ce-certificatePolicies-anyPolicy` (2.5.29.32.0) for
    /// nodes that survived an anyPolicy expansion or were not yet
    /// materialized into specific policies.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
    pub valid_policy: der::asn1::ObjectIdentifier,

    /// Set of policies in the next certificate that are consistent with
    /// this node, per RFC 5280 §6.1.2(a) `expected_policy_set`.
    ///
    /// Initialized to `{valid_policy}` and updated by `PolicyMappings`
    /// extensions during the walk.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
    pub expected_policy_set: Vec<der::asn1::ObjectIdentifier>,

    /// Policy qualifiers attached to this node, in the upstream
    /// `PolicyQualifierInfo` form: a `(policy_qualifier_id, qualifier)`
    /// pair where `qualifier` is a raw `der::Any`. The two standard
    /// qualifier IDs are `id-qt-cps` (1.3.6.1.5.5.7.2.1, qualifier is a
    /// `CPSuri` / `IA5String`) and `id-qt-unotice` (1.3.6.1.5.5.7.2.2,
    /// qualifier is a `UserNotice`).
    ///
    /// # Why the qualifier is passed through undecoded
    ///
    /// `x509_cert::ext::pkix::certpolicy` cannot decode two of the shapes
    /// RFC 5280 §4.2.1.4 defines, as of x509-cert 0.3.1:
    ///
    /// - `UserNotice::notice_ref` is declared `Option<GeneralizedTime>`.
    ///   RFC 5280 says `NoticeReference`, which is a `SEQUENCE` of a
    ///   `DisplayText` and a `SEQUENCE OF INTEGER`. The crate defines
    ///   `NoticeReference` correctly in the same module and never uses
    ///   it, so a `UserNotice` that actually carries a `noticeRef` fails
    ///   to decode.
    /// - `DisplayText` implements only the `ia5String` and `utf8String`
    ///   alternatives of a four-way CHOICE; `visibleString` and
    ///   `bmpString` are absent, and the type's own documentation says
    ///   so. `der` has carried `Tag::VisibleString` and `Tag::BmpString`
    ///   since RustCrypto/formats#160, so the tags are available.
    ///
    /// The second defect became the more consequential one with RFC 6818
    /// §3, which replaced §4.2.1.4's encoding guidance: `visibleString`
    /// and `bmpString` went from MUST NOT to "acceptable but less
    /// preferred", and `ia5String` went from MAY to MUST NOT. So the
    /// upstream `DisplayText` now decodes exactly the one encoding the
    /// profile prohibits and neither of the two it newly permits.
    ///
    /// Passing the `Any` through costs a caller the decode and keeps both
    /// defects out of this crate's results. `rfc5280.cert.policies.explicit_text_encoding`
    /// reads the `DisplayText` tag directly for the same reason.
    ///
    /// An earlier version of this comment called the first defect a
    /// "typo on `notice_ref`" and cited
    /// `github.com/RustCrypto/formats/issues/x509-cert`, which is not an
    /// issue URL. No upstream issue exists for either defect; searching
    /// RustCrypto/formats for `UserNotice` and `NoticeReference` returns
    /// nothing.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
    pub qualifiers: Vec<x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo>,

    /// `valid_policy` of each parent node at `depth - 1` (nodes are unique
    /// per depth, so the OID identifies the parent). Empty for the depth-0
    /// root. A node's parents are either exactly `[anyPolicy]` or a set of
    /// specific policies.
    #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
    pub parent_policies: Vec<der::asn1::ObjectIdentifier>,
}

impl ValidatedPath {
    /// Iterate `(policy_oid, qualifier)` pairs across every node in the
    /// final policy tree.
    ///
    /// Returns an empty iterator if the tree is `None` (it was reduced to
    /// NULL during validation, which is only accepted while no explicit
    /// policy is required).
    ///
    /// Each yielded pair is `(node.valid_policy, &qualifier)` — the
    /// qualifier is a reference into the tree, valid for the borrow
    /// duration. Multiple qualifiers attached to the same policy yield
    /// multiple pairs with equal first elements; multiple nodes with the
    /// same policy OID at different depths also yield multiple pairs.
    ///
    /// Callers commonly need to:
    ///
    /// 1. Filter by `policy_qualifier_id` to find a specific qualifier
    ///    type (CPS pointer or user notice).
    /// 2. Read `qualifier.qualifier` (an `Option<der::Any>`) and decode
    ///    according to the `policy_qualifier_id`. See [`PolicyTreeNode::qualifiers`]
    ///    for why we do not decode upstream-side.
    pub fn policy_qualifiers(
        &self,
    ) -> impl Iterator<
        Item = (
            &der::asn1::ObjectIdentifier,
            &x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo,
        ),
    > + '_ {
        self.valid_policy_tree
            .as_ref()
            .into_iter()
            .flat_map(|tree| tree.iter())
            .flat_map(|node| node.qualifiers.iter().map(move |q| (&node.valid_policy, q)))
    }
}

/// Validate a certificate chain from subject to a trust anchor.
///
/// `chain` must be ordered leaf-first:
/// - `chain[0]` is the subject (end-entity) certificate
/// - `chain[1..]` are intermediates in issuer order
/// - The last element of `chain` must be issued by one of `anchors`
///
/// Validation follows RFC 5280 §6.1. Each certificate's signature is verified
/// using `verifier`, with the signing key taken from the next certificate in
/// the chain (or the matching trust anchor for the last cert).
///
/// # Including the root certificate
///
/// The self-signed certificate of the trust anchor may be passed as the last
/// element of `chain`. It is then processed as path certificate 1 of
/// RFC 5280 §6.1 rather than skipped: its own signature, validity period,
/// `BasicConstraints`, `KeyUsage`, name constraints and policy extensions all
/// apply. In particular a root without a `CertificatePolicies` extension
/// (the common case) reduces the policy tree to NULL (§6.1.3(e)), so a
/// path that requires an explicit policy fails when the root is included
/// and succeeds when it is supplied only as the anchor. Pass the root only
/// in `anchors` unless its constraints are meant to apply as a path
/// certificate.
///
/// # Errors
///
/// Returns `Err(Error::NoTrustedPath)` if `chain` is empty or `anchors` is
/// empty. On success, `chain` is therefore guaranteed to contain at least one
/// certificate.
///
/// Returns `Err` on the first RFC 5280 §6.1 check failure. The error variant
/// includes the chain index of the failing certificate where applicable.
///
/// # Limitations
///
/// See crate-level documentation for current scope limits.
pub fn validate_path<V, C>(
    chain: &[C],
    anchors: &[TrustAnchor],
    policy: &ValidationPolicy,
    verifier: &V,
) -> Result<ValidatedPath>
where
    V: SignatureVerifier,
    C: PathCertificate,
{
    // (0) Cheap length bound before anything that is super-linear in the
    //     chain length (the pairwise duplicate scan in `check_inputs`, and
    //     the DN comparisons it and the self-issued count perform). See the
    //     `max_path_len` rustdoc for how the bound is derived.
    if chain.len() > max_chain_certs(policy.max_path_len) {
        return Err(Error::PathTooLong);
    }

    // (1) Input guards: reject empty chain or anchors, check OID consistency.
    check_inputs(chain, anchors)?;
    check_oid_consistency(chain)?;

    // (2) Path-length check (anchor-independent).
    // RFC 5280 §4.2.1.9: pathLen counts non-self-issued intermediates only.
    let num_non_si_intermediates = chain[1..]
        .iter()
        .map(PathCertificate::certificate)
        .filter(|c| !is_self_issued_cert(c))
        .count();
    if num_non_si_intermediates > policy.max_path_len as usize {
        return Err(Error::PathTooLong);
    }

    // (3) Try each name-matching anchor. Iterating all candidates handles key
    //     rollover: multiple anchors may share a DN but have different keys
    //     (e.g., during a root CA rotation). The first anchor that passes the
    //     full chain walk is used; the last error is returned if none succeed.
    //
    //     Complexity: O(A × N) where A = number of anchors, N = chain length.
    //     For the common case of O(1) matching anchors this is effectively O(N).
    //
    //     A caller validating many candidate chains against a large anchor
    //     store pays that A per candidate, and the obvious optimisation --
    //     identify the matching anchor once, outside the loop, and hand it
    //     in -- IS NOT AVAILABLE. Two reasons, and the second is a
    //     correctness one:
    //
    //       - candidates differ in their deepest certificate, so they do
    //         not share an issuer DN to match against;
    //       - more than one anchor may match a single DN, which is the
    //         rollover case this loop exists to handle. Pre-selecting one
    //         index would pick a key and fail when the other anchor holds
    //         the one that signed.
    //
    //     What the A actually costs is a DN comparison under RFC 4518
    //     string prep, not a signature verification; only an anchor whose
    //     name matches reaches the expensive work. So the loop is wide and
    //     shallow by design. See PKIX-wnnn.9.
    let last_cert = chain.last().ok_or(Error::NoTrustedPath)?.certificate();
    let is_self_issued = names_match(
        last_cert.tbs_certificate().issuer(),
        last_cert.tbs_certificate().subject(),
    );
    let mut last_err = Error::NoTrustedPath;
    // An anchor outside its validity window is recorded and skipped
    // rather than returned immediately: with several anchors, one being
    // expired must not stop a live one from matching. If nothing else
    // matches, the expiry is the better answer than `NoTrustedPath`,
    // because it says what is actually wrong.
    //
    // `Expired` outranks `NotYetValid` when both are seen, so that the
    // reported defect does not depend on the order the trust store
    // happened to supply its anchors in. A rollover pair straddling the
    // clock -- the old root past its `notAfter`, the new one not yet at
    // its `notBefore` -- is the case where both arise, and there the
    // expired root is the one the deployment was relying on.
    let mut expired_anchor: Option<AnchorDefect> = None;
    //: Reported in preference to an expiry, because it does not depend on
    //: the clock and because it is the graver of the two: an expired
    //: anchor is the wrong answer for a while, an unnamed one is the
    //: wrong answer for everything.
    let mut unnamed_anchor = false;

    for (anchor_index, anchor) in anchors.iter().enumerate() {
        // An anchor that names nothing cannot be the issuer of anything in
        // particular. §6.1.3(a)(4) chains on DN equality, so an empty
        // subject matches every certificate whose own issuer field is
        // empty -- which is every certificate an unnamed CA issues, from
        // any unnamed CA. `TrustAnchor::from_cert_ref` already refuses
        // such a certificate as `AnchorDefect::EmptySubject`, but
        // `TrustAnchor::new` takes a bare name and key with no certificate
        // to check, so a caller holding a name and a key from a trust
        // store reaches here instead. RFC 5280 §4.1.2.6.
        if dn_names_nothing(&anchor.subject) {
            unnamed_anchor = true;
            continue;
        }
        if !names_match(&anchor.subject, last_cert.tbs_certificate().issuer()) {
            continue;
        }
        // RFC 5280 §6.1 never checks this; see `TrustAnchor::validity_unix`.
        let (not_before, not_after) = anchor.validity_unix;
        if policy.current_time_unix < not_before {
            if expired_anchor.is_none() {
                expired_anchor = Some(AnchorDefect::NotYetValid);
            }
            continue;
        }
        if policy.current_time_unix > not_after {
            expired_anchor = Some(AnchorDefect::Expired);
            continue;
        }
        // A self-issued top certificate whose key differs from this
        // same-name anchor's is either a key-rollover certificate issued by
        // the anchor (valid: its signature verifies under the anchor key) or
        // a certificate of an unrelated same-name CA (RFC 5280 §3.2 name
        // collision). `chain_walk` tells them apart by verifying the top
        // signature with the anchor key; in the collision case that
        // signature check is the first failure and is reported as
        // `NoTrustedPath` below, since this anchor simply is not the issuer.
        let top_key_differs = is_self_issued
            && !spki_key_matches(
                &anchor.subject_public_key_info,
                last_cert.tbs_certificate().subject_public_key_info(),
            );
        match chain_walk(chain, anchor, policy, verifier) {
            Ok(final_policy_tree) => {
                // §6.1.5 leaf-intrinsic outputs. `chain[0]` is guaranteed
                // non-empty by `check_inputs` at the top of this function.
                // The four `leaf_*` fields are direct clones of the leaf's
                // `tbs_certificate` fields; populating them from `chain[0]`
                // (rather than threading them out of `chain_walk`) avoids
                // adding more entries to the walker's return tuple.
                let leaf_tbs = chain[0].certificate().tbs_certificate();
                // Flatten the internal RFC 9618 policy graph into the
                // public `PolicyTreeNode` list. The internal shape stays
                // private so it can evolve without a public-API break.
                let valid_policy_tree =
                    final_policy_tree.map(policy_graph::PolicyGraph::into_public);
                return Ok(ValidatedPath {
                    anchor_index,
                    depth: chain.len().saturating_sub(1),
                    leaf_subject: leaf_tbs.subject().clone(),
                    leaf_issuer: leaf_tbs.issuer().clone(),
                    leaf_serial: leaf_tbs.serial_number().clone(),
                    leaf_spki: leaf_tbs.subject_public_key_info().clone(),
                    valid_policy_tree,
                });
            }
            Err(Error::SignatureInvalid { index } | Error::SignatureNotVerified { index, .. })
                if top_key_differs && index == chain.len() - 1 =>
            {
                // Name collision, not a rollover: keep the previous error
                // (initially `NoTrustedPath`) and try the next anchor.
            }
            Err(e) => last_err = e,
        }
    }
    // Nothing matched. If an anchor was skipped only because of its own
    // validity window, say so: `NoTrustedPath` would be true but
    // useless, and an expired root in a trust store is precisely the
    // thing nobody notices.
    if matches!(last_err, Error::NoTrustedPath) {
        if unnamed_anchor {
            return Err(Error::TrustAnchorRejected {
                defect: AnchorDefect::EmptySubject,
            });
        }
        if let Some(defect) = expired_anchor {
            return Err(Error::TrustAnchorRejected { defect });
        }
    }
    Err(last_err)
}

/// Validate a certificate chain using a [`Profile`] to produce the policy.
///
/// This is a convenience wrapper around [`validate_path`] for callers that
/// work with a `Profile` implementation rather than constructing a
/// [`ValidationPolicy`] directly.
///
/// The profile's [`Profile::policy`] method is called with `now_unix` to
/// produce the `ValidationPolicy`.  The returned policy's `current_time_unix`
/// is then unconditionally overwritten with `now_unix`, so that a buggy
/// `Profile` implementation that returns the wrong clock value cannot silently
/// cause validity checks to run against the wrong time.
///
/// See [`validate_path`] for full documentation of the remaining parameters
/// and error semantics.
///
/// # Errors
///
/// Returns `Err(Error::...)` for each validation failure. See [`Error`] for the full list of failure conditions.
pub fn validate_path_with_profile<V, P, C>(
    chain: &[C],
    anchors: &[TrustAnchor],
    profile: &P,
    now_unix: u64,
    verifier: &V,
) -> Result<ValidatedPath>
where
    V: SignatureVerifier,
    P: Profile,
    C: PathCertificate,
{
    let mut policy = profile.policy(now_unix);
    // Defense-in-depth: overwrite current_time_unix with the caller's value.
    // A correct Profile implementation already sets this in policy(), but
    // an incorrect implementation might use a stale or wrong clock. This
    // overwrite is a belt-and-suspenders guard — it does not compensate for a
    // known bug; no existing Profile impl is incorrect.
    policy.current_time_unix = now_unix;
    validate_path(chain, anchors, &policy, verifier)
}

// ---------------------------------------------------------------------------
// validate_path helpers — input guards and OID consistency (PKIX-6vu)
// ---------------------------------------------------------------------------

/// Compare two SPKIs for the purpose of the self-issued anchor guard.
///
/// Compares algorithm OID and key bytes only — not the parameters field.
/// This is intentional: for RSA, explicit NULL parameters and absent
/// parameters are both valid encodings of the same algorithm (RFC 3279
/// §2.3.1); comparing the full `AlgorithmIdentifier` would wrongly reject
/// a valid anchor whose SPKI parameter encoding differs from the cert's.
/// For ECDSA, the parameters carry the curve OID, but two keys on different
/// curves also differ in their raw key bytes, so OID + key comparison is
/// still sufficient to distinguish them.
/// Upper bound on `chain.len()` for a given `max_path_len`: the leaf,
/// `max_path_len` non-self-issued intermediates, one self-issued certificate
/// (key rollover) per CA in the path including the anchor's, and an included
/// self-signed root.
const fn max_chain_certs(max_path_len: u8) -> usize {
    2 * (max_path_len as usize) + 3
}

fn spki_key_matches(
    a: &spki::SubjectPublicKeyInfoOwned,
    b: &spki::SubjectPublicKeyInfoOwned,
) -> bool {
    a.algorithm.oid == b.algorithm.oid && a.subject_public_key == b.subject_public_key
}

fn check_inputs<C: PathCertificate>(chain: &[C], anchors: &[TrustAnchor]) -> Result<()> {
    if chain.is_empty() || anchors.is_empty() {
        return Err(Error::NoTrustedPath);
    }
    // Duplicate detection: check all pairs for (issuer DN, serial number) identity.
    // Per RFC 5280 §4.1.2.2, issuer+serial uniquely identifies a certificate.
    // A cert appearing twice in the chain is a construction error; reporting
    // DuplicateCertificate is cleaner than the confusing SignatureInvalid or
    // ChainBroken that would otherwise result.
    //
    // SPKI equality is intentionally NOT used here: cross-signed CAs legitimately
    // have two distinct certificates sharing the same public key (same SPKI, different
    // issuer+serial). Using issuer+serial avoids false positives in those chains.
    //
    // O(n²) over chain.len() — acceptable for chains of typical length (2–5 certs).
    //
    // Serial numbers are compared first because `&&` short-circuits and the
    // two operands cost very different amounts: a serial is a byte compare,
    // while `names_match` normalises both DNs under RFC 4518 before
    // comparing them attribute by attribute. Two certificates in one chain
    // practically never share a serial, so the expensive half practically
    // never runs. Both operands are pure, so the order is free to choose.
    for i in 0..chain.len() {
        for j in (i + 1)..chain.len() {
            let a = chain[i].certificate().tbs_certificate();
            let b = chain[j].certificate().tbs_certificate();
            if a.serial_number() == b.serial_number() && names_match(a.issuer(), b.issuer()) {
                return Err(Error::DuplicateCertificate {
                    first: i,
                    second: j,
                });
            }
        }
    }
    Ok(())
}

/// RFC 5280 §4.1.1.2: outer signatureAlgorithm OID must equal inner TBSCertificate.signature OID.
///
/// Only OIDs are compared, not parameters.  RFC 5280 says the two
/// `AlgorithmIdentifiers` MUST be identical, but many production CAs
/// generate certs where one field has explicit NULL parameters and the other
/// omits them — a mismatch that OpenSSL and other validators accept in
/// practice.  OID-only comparison preserves the security intent (the same
/// algorithm must be named in both places) without rejecting otherwise-valid
/// certs from common PKI deployments.
fn check_oid_consistency<C: PathCertificate>(chain: &[C]) -> Result<()> {
    for (index, cert) in chain.iter().map(PathCertificate::certificate).enumerate() {
        if cert.signature_algorithm().oid != cert.tbs_certificate().signature().oid {
            return Err(Error::MalformedCertificate { index });
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Critical extension guard (PKIX-ad6)
// ---------------------------------------------------------------------------

const OID_KEY_USAGE: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.15");

const OID_BASIC_CONSTRAINTS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.19");

const OID_SUBJECT_ALT_NAME: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.17");

const OID_EXTENDED_KEY_USAGE: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.37");

const OID_NAME_CONSTRAINTS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.30");

const OID_CERTIFICATE_POLICIES: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32");

const OID_POLICY_MAPPINGS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.33");

const OID_POLICY_CONSTRAINTS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.36");

const OID_INHIBIT_ANY_POLICY: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.54");

/// `id-ce-noRevAvail` — RFC 9608 §2, `{ id-ce 56 }`.
pub(crate) const OID_NO_REV_AVAIL: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.56");

const OID_CRL_DISTRIBUTION_POINTS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.31");

const OID_FRESHEST_CRL: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.46");

const OID_AUTHORITY_INFO_ACCESS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.1.1");

/// `id-ad-ocsp` — the one AIA accessMethod RFC 9608 §3 forbids
/// alongside `noRevAvail`.
const OID_AD_OCSP: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.48.1");

/// OID for the `anyPolicy` wildcard (2.5.29.32.0 — a child of id-ce-certificatePolicies).
pub(crate) const OID_ANY_POLICY: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32.0");

/// OID for the emailAddress attribute in Distinguished Names (PKCS #9 §5.2.1).
/// Used when enforcing RFC 5280 §4.2.1.10 rfc822Name constraints against DN attributes.
const OID_EMAIL_ADDRESS: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1");

/// `anyExtendedKeyUsage`, RFC 5280 §4.2.1.12.
///
/// In a CA certificate this means "no restriction", which is how
/// [`ValidationPolicy::enforce_ca_eku`] reads it. On a *leaf* it does
/// **not** satisfy a specific [`ValidationPolicy::required_leaf_eku`]
/// requirement, and the two rules are deliberately different: a CA using
/// it is declining to constrain its subtree, while a leaf using it is
/// claiming every purpose at once, which is not evidence of the one
/// purpose a caller asked about.
const OID_ANY_EXTENDED_KEY_USAGE: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.29.37.0");

/// OIDs of extensions that this implementation handles; all others, if critical, cause rejection.
///
/// `OID_SUBJECT_ALT_NAME` is listed here so that certs with critical SAN extensions
/// (e.g. TLS server certs) do not fail with `UnhandledCriticalExtension`.
/// An end entity may be named only by its critical SAN over an empty
/// Subject (RFC 5280 §4.2.1.6); a CA may not (§4.1.2.6), and is refused as
/// [`AnchorDefect::EmptySubject`] or [`Error::CaEmptySubject`].
///
/// `OID_EXTENDED_KEY_USAGE` is listed here so that certs with critical EKU
/// (common in CA/B Forum TLS and code-signing certificates) do not fail with
/// `UnhandledCriticalExtension`. RFC 5280 §6.1 path validation does not require
/// inspecting EKU values; the extension is accepted and its content is not verified.
const HANDLED_CRITICAL_OIDS: &[der::asn1::ObjectIdentifier] = &[
    OID_KEY_USAGE,
    OID_BASIC_CONSTRAINTS,
    OID_SUBJECT_ALT_NAME,
    OID_EXTENDED_KEY_USAGE,
    OID_NAME_CONSTRAINTS,
    OID_CERTIFICATE_POLICIES,
    OID_POLICY_MAPPINGS,
    OID_POLICY_CONSTRAINTS,
    OID_INHIBIT_ANY_POLICY,
];

/// RFC 5280 §4.2: "A certificate MUST NOT include more than one instance of
/// a particular extension." Reject such certificates with
/// [`Error::MalformedCertificate`].
///
/// The extension lookups in this crate read only the first instance of an
/// OID, while other validators may read the last or reject the certificate;
/// accepting duplicates would let one certificate mean different things to
/// different validators (e.g. two `basicConstraints` with cA TRUE then FALSE).
///
/// Sorts a copy of the OIDs, so the cost is O(e log e) in the extension
/// count `e` rather than quadratic.
fn check_duplicate_extensions(cert: &Certificate, index: usize) -> Result<()> {
    if has_duplicate_extensions(cert) {
        return Err(Error::MalformedCertificate { index });
    }
    Ok(())
}

/// Whether `basicConstraints`' leading `cA` `BOOLEAN` is encoded as valid
/// BER but invalid DER.
///
/// `BasicConstraints ::= SEQUENCE { cA BOOLEAN DEFAULT FALSE,
/// pathLenConstraint INTEGER (0..MAX) OPTIONAL }`, so the `BOOLEAN` is the
/// first member when present. Only that position is examined: this is a
/// diagnostic refinement on a certificate being refused either way, not a
/// parser, and walking arbitrary DER to find every `BOOLEAN` would be more
/// machinery than the distinction is worth.
///
/// Returns `false` for anything it cannot confidently read, including a
/// truncated value or a `BOOLEAN` of the wrong length, so the caller falls
/// through to [`AnchorDefect::MalformedExtension`]. A wrong answer here
/// would relabel a genuinely malformed extension as a merely
/// non-canonical one, which is the error that matters.
fn has_non_der_boolean(value: &[u8]) -> bool {
    // SEQUENCE header: tag 0x30, then a single-octet short-form length.
    // Every conforming `BasicConstraints` is a handful of bytes, so a
    // long-form length is itself a sign of something this need not read.
    let [0x30, seq_len, rest @ ..] = value else {
        return false;
    };
    if usize::from(*seq_len) != rest.len() {
        return false;
    }
    // BOOLEAN header: tag 0x01, length 1, then the content octet. DER
    // permits only 0x00 and 0xFF there; BER permits any non-zero value
    // for TRUE.
    matches!(rest, [0x01, 0x01, b, ..] if *b != 0x00 && *b != 0xFF)
}

/// Whether any extension OID appears more than once.
///
/// Shared with [`check_anchor_profile`], which reports the same fact as
/// [`AnchorDefect::DuplicateExtension`] because a trust anchor has no chain
/// index to name. The rule and its reasoning are one; only the error shape
/// differs.
fn has_duplicate_extensions(cert: &Certificate) -> bool {
    let exts = cert
        .tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice());
    if exts.len() < 2 {
        return false;
    }
    let mut oids: Vec<der::asn1::ObjectIdentifier> = exts.iter().map(|e| e.extn_id).collect();
    oids.sort_unstable();
    oids.windows(2).any(|w| w[0] == w[1])
}

/// RFC 5280 §6.1.3(a)(3): reject any critical extension not in the handled set.
/// Which of [RFC 9608][rfc9608] §3's four prohibitions a `noRevAvail`
/// certificate violates.
///
/// §3 says a certificate carrying `noRevAvail` asserts that no revocation
/// information will ever be published for it, and so must not also be a
/// CA or name anywhere revocation information could be fetched. Each
/// variant is one of the four, in the order §3 lists them.
///
/// Carried by [`Error::NoRevAvailProfileViolation`] so a caller can tell
/// a self-contradicting end-entity certificate from a CA that must never
/// have carried the extension at all — the second is the more serious,
/// because a CA whose revocation status can never be published cannot be
/// withdrawn once issued.
///
/// [rfc9608]: https://www.rfc-editor.org/rfc/rfc9608#section-3
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum NoRevAvailProhibition {
    /// `basicConstraints` asserts `cA=TRUE`. RFC 9608 §3: "Certificates
    /// for CAs MUST NOT include the noRevAvail extension."
    CertificateAuthority,
    /// A `cRLDistributionPoints` extension is present.
    CrlDistributionPoints,
    /// A `freshestCRL` extension is present.
    FreshestCrl,
    /// An `authorityInfoAccess` extension carries an `id-ad-ocsp`
    /// accessMethod. §3 permits the extension and forbids only that
    /// accessMethod.
    OcspAccessMethod,
    /// An `authorityInfoAccess` extension is present but does not decode,
    /// so §3's prohibition on an `id-ad-ocsp` accessMethod cannot be
    /// shown to hold.
    ///
    /// Reported rather than passed over because §3's consequence is that
    /// the certificate is invalid, and a prohibition that cannot be
    /// checked has not been met. Fail-closed.
    UndecodableAuthorityInfoAccess,
}

impl NoRevAvailProhibition {
    /// A short phrase naming what the certificate carries, for
    /// [`Error`]'s `Display`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::CertificateAuthority => "asserts cA=TRUE",
            Self::CrlDistributionPoints => "a cRLDistributionPoints extension",
            Self::FreshestCrl => "a freshestCRL extension",
            Self::OcspAccessMethod => "an authorityInfoAccess with an id-ad-ocsp accessMethod",
            Self::UndecodableAuthorityInfoAccess => {
                "an authorityInfoAccess that does not decode, so the prohibition on an \
                 id-ad-ocsp accessMethod cannot be shown to hold"
            }
        }
    }
}

/// RFC 9608 §3: a certificate carrying `noRevAvail` must not also be a CA
/// or point at revocation information.
///
/// > Certificates for CAs MUST NOT include the noRevAvail extension.
/// > Certificates that include the noRevAvail extension MUST NOT include
/// > certificate extensions that point to CRL repositories or provide
/// > locations of OCSP responders. [...] If any of the above are violated
/// > in a certificate, then the relying party MUST consider the
/// > certificate invalid.
///
/// That last sentence is why this runs in `chain_walk` rather than only
/// in the lint layer: it is addressed to a relying party, and this is the
/// relying party.
///
/// # This is the guard that makes RFC 9608 §4's skip safe
///
/// §4 skips RFC 5280 §6.1.3 step (a)(3) — "the certificate is not
/// revoked" — for a certificate carrying `noRevAvail`, and `pkix-chain`
/// implements that skip. A certificate therefore gets to tell a relying
/// party not to check its revocation status. §3's prohibitions are the
/// whole of what keeps that from being an escape hatch: a conforming
/// `noRevAvail` certificate names nowhere revocation information could be
/// published, so skipping the check costs nothing, while one that names a
/// CRL or an OCSP responder is asserting two incompatible things and is
/// refused here before any skip can apply.
///
/// Ordering is not incidental. `chain_walk` runs for every certificate
/// before `pkix-chain` drives any revocation work, so the guard cannot be
/// skipped by a caller who does no revocation checking, and
/// `pkix_chain::sans_io::revocation_targets` can drop a `noRevAvail`
/// certificate knowing this has already run.
///
/// # Errors
///
/// [`Error::NoRevAvailProfileViolation`], carrying which of the four
/// prohibitions was violated and the certificate's chain index.
/// Does this certificate carry `noRevAvail` ([RFC 9608][rfc9608] §2)?
///
/// Exported because [`pkix_chain`]'s revocation scheduling needs it to
/// implement RFC 9608 §4, which skips RFC 5280 §6.1.3 step (a)(3) — "the
/// certificate is not revoked" — for such a certificate.
///
/// # The skip is only safe because `validate_path` enforces §3
///
/// Honouring §4 means a certificate tells a relying party not to check
/// its revocation status and the relying party complies. §3's
/// prohibitions are what keep that from being an escape hatch, and
/// [`validate_path`] refuses a certificate that violates them with
/// [`Error::NoRevAvailProfileViolation`] before any revocation work is
/// scheduled. A caller that reads this predicate and skips a check
/// *without* having validated the path first has removed the guard and
/// kept the hole.
///
/// This reads only for the extension's presence. Its criticality (§2
/// requires `FALSE`) is enforced separately and earlier: `noRevAvail` is
/// not in this crate's handled-critical set, so a critical one fails
/// `check_critical_extensions` with
/// [`Error::UnhandledCriticalExtension`] and never reaches here.
///
/// [rfc9608]: https://www.rfc-editor.org/rfc/rfc9608#section-4
/// [`pkix_chain`]: https://docs.rs/pkix-chain
#[must_use]
pub fn has_no_rev_avail(cert: &Certificate) -> bool {
    cert.tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice())
        .iter()
        .any(|e| e.extn_id == OID_NO_REV_AVAIL)
}

fn check_no_rev_avail_profile(cert: &Certificate, index: usize) -> Result<()> {
    use der::Decode as _;

    let exts = cert
        .tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice());
    if !exts.iter().any(|e| e.extn_id == OID_NO_REV_AVAIL) {
        return Ok(());
    }

    let violation = |prohibition| Error::NoRevAvailProfileViolation { index, prohibition };

    // §3's first prohibition. Checked first because it is the most
    // serious: a CA whose revocation status can never be published
    // cannot be withdrawn once issued.
    //
    // A `basicConstraints` that does not decode is not read as asserting
    // `cA` here; `check_duplicate_extensions` and the step (k) basic
    // constraints processing in `chain_walk` own that, and this function
    // is not where a malformed extension is reported.
    let asserts_ca = exts
        .iter()
        .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)
        .and_then(|e| {
            x509_cert::ext::pkix::BasicConstraints::from_der(e.extn_value.as_bytes()).ok()
        })
        .is_some_and(|bc| bc.ca);
    if asserts_ca {
        return Err(violation(NoRevAvailProhibition::CertificateAuthority));
    }

    if exts
        .iter()
        .any(|e| e.extn_id == OID_CRL_DISTRIBUTION_POINTS)
    {
        return Err(violation(NoRevAvailProhibition::CrlDistributionPoints));
    }
    if exts.iter().any(|e| e.extn_id == OID_FRESHEST_CRL) {
        return Err(violation(NoRevAvailProhibition::FreshestCrl));
    }

    // §3 permits an authorityInfoAccess and forbids one accessMethod
    // inside it, so the extension's presence is not itself a violation.
    if let Some(aia_ext) = exts.iter().find(|e| e.extn_id == OID_AUTHORITY_INFO_ACCESS) {
        let Ok(aia) = x509_cert::ext::pkix::AuthorityInfoAccessSyntax::from_der(
            aia_ext.extn_value.as_bytes(),
        ) else {
            // Fail closed: §3's consequence is invalidity, and a
            // prohibition that cannot be shown to hold has not been met.
            return Err(violation(
                NoRevAvailProhibition::UndecodableAuthorityInfoAccess,
            ));
        };
        if aia.0.iter().any(|d| d.access_method == OID_AD_OCSP) {
            return Err(violation(NoRevAvailProhibition::OcspAccessMethod));
        }
    }

    Ok(())
}

fn check_critical_extensions(cert: &Certificate, index: usize) -> Result<()> {
    for ext in cert
        .tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice())
    {
        if ext.critical && !HANDLED_CRITICAL_OIDS.contains(&ext.extn_id) {
            return Err(Error::UnhandledCriticalExtension { index });
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Policy processing (RFC 5280 §6.1) — see `policy_graph` (RFC 9618 graph)
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// KeyUsage extraction (PKIX-8ae)
// ---------------------------------------------------------------------------

/// Returns whether the `keyCertSign` bit is set in the `KeyUsage` extension.
///
/// - `None`         — `KeyUsage` extension absent (no constraint)
/// - `Ok(Some(true))`  — keyCertSign is set
/// - `Ok(Some(false))` — `KeyUsage` present, keyCertSign NOT set
/// - `Ok(None)`        — `KeyUsage` extension absent
/// - `Err(_)`          — `KeyUsage` present but DER-malformed (fail-closed)
fn has_key_cert_sign(cert: &Certificate) -> der::Result<Option<bool>> {
    use x509_cert::ext::pkix::KeyUsage;

    try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.key_cert_sign()))
}

/// Returns whether the `cRLSign` bit is set in the `KeyUsage` extension.
///
/// Same shape as [`has_key_cert_sign`]; used by the
/// [`ValidationPolicy::require_crl_sign_on_cas`] opt-in check (PKITS §4.7.4 / §4.7.5).
///
/// - `Ok(Some(true))`  — cRLSign is set
/// - `Ok(Some(false))` — `KeyUsage` present, cRLSign NOT set
/// - `Ok(None)`        — `KeyUsage` extension absent
/// - `Err(_)`          — `KeyUsage` present but DER-malformed (fail-closed)
fn has_crl_sign(cert: &Certificate) -> der::Result<Option<bool>> {
    use x509_cert::ext::pkix::KeyUsage;

    try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.crl_sign()))
}

// ---------------------------------------------------------------------------
// Extension extraction helpers
// ---------------------------------------------------------------------------

/// Look up and decode an X.509 extension from `cert` by OID.
///
/// **Fail-closed**: propagates DER decoding errors to the caller rather than
/// discarding them. This is appropriate for security-critical extensions where
/// a malformed value must not be silently ignored.
///
/// Returns:
/// - `Ok(None)` — extension absent.
/// - `Ok(Some(T))` — extension present and decoded successfully.
/// - `Err(der::Error)` — extension present but DER decoding failed.
///
/// For non-critical extensions where a parse failure should be treated as
/// absent, decode the extension directly: there is deliberately no
/// fail-open helper any more, because the only caller that wanted one
/// was the trust-anchor path, where dropping an unparseable
/// `NameConstraints` was a fail-open.
fn try_find_cert_ext<T: for<'a> der::Decode<'a, Error = der::Error>>(
    cert: &Certificate,
    oid: der::asn1::ObjectIdentifier,
) -> der::Result<Option<T>> {
    cert.tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice())
        .iter()
        .find(|e| e.extn_id == oid)
        .map_or(Ok(None), |e| T::from_der(e.extn_value.as_bytes()).map(Some))
}

/// Decode the `SubjectAltName` extension from `cert`.
///
/// **Fail-closed**: a present-but-malformed SAN returns `Err` rather than being
/// silently treated as absent.  Treating a malformed SAN as absent during name
/// constraint checking would allow a cert to bypass NC exclusion/permission
/// constraints when the SAN extension is present but cannot be decoded (vjc.20).
fn cert_subject_alt_names(
    cert: &Certificate,
    index: usize,
) -> crate::Result<Option<x509_cert::ext::pkix::SubjectAltName>> {
    try_find_cert_ext(cert, OID_SUBJECT_ALT_NAME).map_err(|_| Error::MalformedCertificate { index })
}

/// Decode the `NameConstraints` extension from `cert`.
///
/// Returns `Err(MalformedCertificate)` if the extension is present but:
/// - its DER cannot be decoded (vjc.7: fail-closed on security-critical extension),
/// - any `GeneralSubtree` has a non-zero `minimum` or a present `maximum` field
///   (vjc.8: RFC 5280 §4.2.1.10 MUST require minimum=0, maximum=absent), or
/// - either subtree set is present and empty (PKIX-mg8u).
///
/// Returns `Ok(None)` if the extension is absent.
/// Is every `GeneralSubtrees` in `nc` one RFC 5280 §4.2.1.10 can express?
///
/// Two rules, both from the same paragraph of §4.2.1.10, and both about a
/// constraint whose scope cannot be honoured as written.
///
/// **minimum and maximum.** "Within this profile, the minimum and maximum
/// fields are not used with any name forms, thus minimum MUST be zero, and
/// maximum MUST be absent." A certificate that encodes either is asking for
/// semantics this implementation does not have.
///
/// **An empty set.** `GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF
/// GeneralSubtree`, so a present-but-empty one is not a valid encoding at
/// all. It still decodes here, because a `SEQUENCE OF` reader reaching the
/// end of the value immediately yields an empty `Vec` rather than an error,
/// and the result used to be adopted as a permitted set constraining no
/// name type — so a critical extension saying "permit nothing" was read as
/// "permit everything", which is the fail-open direction on the one
/// extension this function exists to be fail-closed about. Refusing it is
/// also the only answer available: the two readings of an empty permitted
/// set are "no name is acceptable" and "every name is", and nothing in the
/// RFC chooses between them because the ASN.1 was meant to make the
/// question impossible.
///
/// Found by the generated-chain harness (PKIX-mg8u), though not because
/// the chain was new. x509-limbo has it as
/// `webpki::nc::intermediate-permitted-excluded-subtrees-both-empty-sequences`,
/// and `baseline-limbo.json` recorded the old accepting verdict as a
/// ground-truth disagreement, justified in the ledger as deliberate
/// scope -- the encoding being a syntax matter for `pkix-lint`. That
/// rationale held for the sibling case where both subtree sets are
/// *absent*, which is vacuous and still accepted here. It did not hold
/// for an empty SEQUENCE: §6.1.4(b) intersects the certificate's
/// permitted set into the running state, and intersecting with the empty
/// set leaves the empty set, after which §6.1.3(b) can admit no name.
/// The rejection follows from path validation and never needed the
/// syntax check.
///
/// One predicate because three paths need the same answer —
/// [`cert_name_constraints`] for intermediates, and both fallible trust-anchor
/// constructors. They used to disagree: the rule was applied to intermediates
/// and to neither anchor path, so the same extension was grounds for rejection
/// in the middle of a chain and accepted at its root.
fn subtrees_are_conformant(nc: &NameConstraints) -> bool {
    // A closure rather than `Vec::is_empty` as a function path: `Vec` here
    // is the cfg-gated alias above, and naming `alloc::vec::Vec` would not
    // resolve under `std`, where `extern crate alloc` is not declared.
    let empty_set_present = nc.permitted_subtrees.as_ref().is_some_and(|s| s.is_empty())
        || nc.excluded_subtrees.as_ref().is_some_and(|s| s.is_empty());
    if empty_set_present {
        return false;
    }
    nc.permitted_subtrees
        .iter()
        .flatten()
        .chain(nc.excluded_subtrees.iter().flatten())
        .all(|st| st.minimum == 0 && st.maximum.is_none())
}

fn cert_name_constraints(
    cert: &Certificate,
    index: usize,
) -> crate::Result<Option<NameConstraints>> {
    let nc = try_find_cert_ext::<NameConstraints>(cert, OID_NAME_CONSTRAINTS)
        .map_err(|_| Error::MalformedCertificate { index })?;

    if let Some(nc) = &nc
        && !subtrees_are_conformant(nc)
    {
        return Err(Error::MalformedCertificate { index });
    }

    Ok(nc)
}

/// RFC 5280 §4.2.1.10 conformance of a `NameConstraints`, at the predicate
/// all three call sites share.
///
/// The empty-set cases are tested here rather than only through a chain
/// because the predicate is what the anchor constructors and the chain
/// walk have in common: a rule enforced in one and not the others was
/// how PKIX-vjc.8 happened, and the comment on `subtrees_are_conformant`
/// records that history. An end-to-end chain carrying an empty set, with
/// a real signature over it, is in `pkix-difftest`'s generated-chain
/// suite (PKIX-mg8u).
#[cfg(test)]
mod tests_subtree_conformance {
    use super::subtrees_are_conformant;
    use x509_cert::ext::pkix::constraints::name::{
        GeneralSubtree, GeneralSubtrees, NameConstraints,
    };
    use x509_cert::ext::pkix::name::GeneralName;

    fn dns_subtree(name: &str) -> GeneralSubtree {
        GeneralSubtree {
            base: GeneralName::DnsName(
                der::asn1::Ia5String::new(name).expect("an ASCII host name is IA5"),
            ),
            minimum: 0,
            maximum: None,
        }
    }

    fn nc(
        permitted: Option<GeneralSubtrees>,
        excluded: Option<GeneralSubtrees>,
    ) -> NameConstraints {
        NameConstraints {
            permitted_subtrees: permitted,
            excluded_subtrees: excluded,
        }
    }

    /// The control. Without it the rejections below would pass for a
    /// predicate that refused everything.
    #[test]
    fn a_conforming_constraint_is_accepted() {
        let one = || Some(vec![dns_subtree("example.com")]);
        assert!(subtrees_are_conformant(&nc(one(), None)));
        assert!(subtrees_are_conformant(&nc(None, one())));
        assert!(subtrees_are_conformant(&nc(one(), one())));
    }

    /// Absent is not empty: a `NameConstraints` with neither field is
    /// vacuous but well-formed, and both `OPTIONAL` fields may be absent.
    #[test]
    fn absent_subtree_sets_are_accepted() {
        assert!(subtrees_are_conformant(&nc(None, None)));
    }

    /// `GeneralSubtrees ::= SEQUENCE SIZE (1..MAX)`, so a present-but-empty
    /// set is not a valid encoding. It used to be read as a constraint on
    /// no name type at all, which on a permitted set means "permit
    /// everything" — fail-open on a critical extension.
    #[test]
    fn a_present_but_empty_subtree_set_is_refused() {
        assert!(
            !subtrees_are_conformant(&nc(Some(GeneralSubtrees::new()), None)),
            "an empty permittedSubtrees must not be read as no constraint"
        );
        assert!(
            !subtrees_are_conformant(&nc(None, Some(GeneralSubtrees::new()))),
            "an empty excludedSubtrees is the same violation"
        );
        assert!(
            !subtrees_are_conformant(&nc(
                Some(GeneralSubtrees::new()),
                Some(GeneralSubtrees::new())
            )),
            "both empty"
        );
    }

    /// One empty set does not become acceptable by sitting beside a
    /// populated one. `||` rather than `&&`, which is the mutation that
    /// survived the suite last time this predicate grew a rule.
    #[test]
    fn an_empty_set_beside_a_populated_one_is_still_refused() {
        let one = Some(vec![dns_subtree("example.com")]);
        assert!(!subtrees_are_conformant(&nc(
            Some(GeneralSubtrees::new()),
            one.clone()
        )));
        assert!(!subtrees_are_conformant(&nc(
            one,
            Some(GeneralSubtrees::new())
        )));
    }

    /// The pre-existing rule, still enforced: the empty-set check returns
    /// early, so it must not shadow this one.
    #[test]
    fn a_non_zero_minimum_or_present_maximum_is_still_refused() {
        let mut min = dns_subtree("example.com");
        min.minimum = 1;
        assert!(!subtrees_are_conformant(&nc(Some(vec![min]), None)));

        let mut max = dns_subtree("example.com");
        max.maximum = Some(4);
        assert!(!subtrees_are_conformant(&nc(None, Some(vec![max]))));
    }
}

// ---------------------------------------------------------------------------
// Validity period checker (PKIX-047)
// ---------------------------------------------------------------------------

/// Convert an `x509_cert::time::Time` to seconds since the Unix epoch.
fn time_to_unix_secs(t: &x509_cert::time::Time) -> u64 {
    t.to_unix_duration().as_secs()
}

/// RFC 5280 §6.1.3(a)(2): check notBefore ≤ now ≤ notAfter.
fn check_validity(cert: &Certificate, now_unix: u64, index: usize) -> Result<()> {
    let not_before = time_to_unix_secs(&cert.tbs_certificate().validity().not_before);
    let not_after = time_to_unix_secs(&cert.tbs_certificate().validity().not_after);
    if now_unix >= not_before && now_unix <= not_after {
        Ok(())
    } else {
        Err(Error::ValidityPeriod { index })
    }
}

// ---------------------------------------------------------------------------
// Name comparison — RFC 4518 string prep (PKIX-drv)
// ---------------------------------------------------------------------------

/// Maximum number of attribute-value assertions in one RDN that
/// [`names_match`] will compare.
///
/// RFC 5280 does not limit multi-valued RDNs, but real certificates use
/// one AVA per RDN (occasionally two or three). The cap bounds the
/// quadratic AVA matching in [`names_match`], which runs on unauthenticated
/// input; an RDN above the cap matches nothing.
pub const MAX_AVAS_PER_RDN: usize = 64;

/// Compare two distinguished names per RFC 4518 string prep rules.
///
/// Currently implements ASCII case-fold and insignificant-whitespace
/// collapsing. `BMPString`-tagged AVAs are transcoded UCS-2-BE → UTF-8
/// before normalization, so a `BMPString` AVA and a `UTF8String` (or
/// `PrintableString`/`IA5String`/`VisibleString`) AVA that share Unicode
/// code points compare equal. Full Unicode NFKC normalization is future
/// work.
///
/// Returns `true` if the names are equivalent.
///
/// # Ordering
///
/// RFC 5280 §4.1.2.4 defines `Name` as `SEQUENCE OF RDN`, so RDNs are
/// compared positionally (index 0 with index 0, etc.). Within each RDN —
/// which is a `SET OF AttributeTypeAndValue` — comparison is order-independent:
/// each AVA in one RDN is matched against any AVA in the other.
///
/// # Limitations
///
/// - **No NFKC / non-ASCII case fold.** Two AVA values that contain the
///   same Unicode characters but differ in canonical decomposition
///   (precomposed vs combining, e.g. U+00E9 vs U+0065 U+0301) compare
///   unequal even though RFC 4518 says they should match. Non-Latin
///   case differences (e.g. Greek lowercase σ vs final σ) are also not
///   folded.
/// - **`UniversalString` is parser-rejected upstream.** `der` 0.7 omits
///   tag 0x1C from `Tag::try_from`, so any cert with a `UniversalString`
///   AVA fails to parse before reaching this comparator. This is an
///   upstream limitation; the same `BMPString` transcoding applied here
///   would generalize to `UniversalString` (UCS-4-BE → UTF-8) once the
///   parser accepts it.
/// - **`TeletexString` (T61String) uses raw DER byte comparison.**
///   `pkix-path` deliberately does not transcode T.61 to Unicode; no
///   canonical mapping exists (RFC 4518 §2.1 leaves it "a local matter"
///   and OpenSSL, NSS, and `GnuTLS` use mutually incompatible vendor
///   tables). Byte-equal `TeletexString` AVAs match; `TeletexString`
///   never matches any other string type. Well-formed chains that copy
///   the issuer DN bytes per RFC 5280 §4.1.2.4 are unaffected.
///
/// # Work bound
///
/// AVA matching within an RDN is quadratic in the RDN's size. To bound the
/// work an attacker-supplied name can cause, an RDN with more than
/// [`MAX_AVAS_PER_RDN`] attribute-value assertions never matches anything
/// (`names_match` returns `false`), so such a name cannot chain.
#[must_use]
pub fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let a_rdns = a.iter_rdn();
    let b_rdns = b.iter_rdn();

    for (a_rdn, b_rdn) in a_rdns.zip(b_rdns) {
        if a_rdn.len() != b_rdn.len() {
            return false;
        }
        // Work bound: the AVA matching below is quadratic in the RDN size,
        // and names_match runs on attacker-supplied names before any
        // signature has been checked. Real-world RDNs carry one AVA (rarely
        // two or three), so an RDN above the cap is treated as matching
        // nothing (fail-closed).
        if a_rdn.len() > MAX_AVAS_PER_RDN {
            return false;
        }
        // Bijective AVA matching: every AVA in a_rdn must match some AVA in b_rdn,
        // AND every AVA in b_rdn must match some AVA in a_rdn (both directions).
        //
        // The bidirectional check is equivalent to set equality for well-formed RDNs
        // (RFC 5280 §5.1.2.4 SHOULD NOT contain duplicate OIDs), and also correctly
        // handles the malformed-cert case where an RDN has duplicate OIDs:
        //   a={CN=Alice, CN=Alice}, b={CN=Bob, CN=Alice} → both len=2, forward pass
        //   finds CN=Alice for each a_ava, but the reverse pass finds no match for
        //   CN=Bob → returns false (correct).
        // The reverse pass is O(n²) on AVA count; n is 1–5 in practice.
        for a_ava in a_rdn.iter() {
            let found = b_rdn.iter().any(|b_ava| {
                b_ava.oid == a_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
            });
            if !found {
                return false;
            }
        }
        for b_ava in b_rdn.iter() {
            let found = a_rdn.iter().any(|a_ava| {
                a_ava.oid == b_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
            });
            if !found {
                return false;
            }
        }
    }
    true
}

/// Returns `Ok(true)` if `cert` is a CA certificate per its `BasicConstraints`
/// extension (RFC 5280 §4.2.1.9), `Ok(false)` if the extension is absent or
/// `cA = FALSE`, and `Err(DerError)` if the extension is present but cannot be
/// DER-decoded.
///
/// Propagating decode failure rather than treating a malformed extension as
/// "not a CA" is a fail-closed defense-in-depth choice: silently skipping a
/// malformed `BasicConstraints` could mask a topologically valid CA whose CRL
/// scope or path-building should be honored.
///
/// This helper is shared by `pkix-path-builder` (path construction) and
/// `pkix-revocation::crl` (IDP scope checking) to avoid maintaining two
/// parallel implementations of the same RFC 5280 §4.2.1.9 decode.
///
/// # Errors
///
/// Returns [`DerError`] if the `BasicConstraints` extension is present but
/// fails to DER-decode.
pub fn cert_is_ca(cert: &Certificate) -> core::result::Result<bool, DerError> {
    use der::Decode as _;
    use x509_cert::ext::pkix::BasicConstraints;

    let Some(ext) = cert
        .tbs_certificate()
        .extensions()
        .map_or(&[][..], |v| v.as_slice())
        .iter()
        .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)
    else {
        return Ok(false);
    };

    let bc = BasicConstraints::from_der(ext.extn_value.as_bytes()).map_err(DerError::new)?;
    Ok(bc.ca)
}

/// Whether a distinguished name names nothing at all.
///
/// RFC 5280 §4.1.2.4 and §4.1.2.6 both speak of a "non-empty
/// distinguished name". The obvious reading is an `RDNSequence` of zero
/// `RelativeDistinguishedName`s, and that is the encoding seen in
/// practice. But an `RDNSequence` holding RDNs that are themselves empty
/// names nothing either, and X.501 defines an RDN as `SET SIZE (1..MAX)`
/// so such a thing is already malformed -- it should not be treated as a
/// name merely because it survived parsing. Both shapes answer `true`
/// here, which is why this is a function and not a call to
/// `Name::is_empty`.
fn dn_names_nothing(name: &x509_cert::name::Name) -> bool {
    name.iter_rdn().all(|rdn| rdn.is_empty())
}

/// RFC 5280 §3.3: a certificate is self-issued if subject == issuer and neither is empty.
fn is_self_issued_cert(cert: &Certificate) -> bool {
    !cert.tbs_certificate().subject().is_empty()
        && names_match(
            cert.tbs_certificate().subject(),
            cert.tbs_certificate().issuer(),
        )
}

/// RFC 5280 §7.1 DN comparison, and §4.2.1.10 subtree containment.
///
/// Both functions here are private and were reached only through whole-chain
/// fixtures, which left several of their decisions untested — a mutation
/// sweep flipped the `&&` in both `names_match` AVA loops and both
/// comparisons in `dn_within_subtree`'s length guard, and every one
/// survived. Unit tests, because the inputs that distinguish these cases
/// are DNs no certificate generator produces on the way to anything else.
#[cfg(test)]
mod tests_dn_comparison {
    use super::{dn_within_subtree, names_match};
    use der::Decode as _;
    use x509_cert::name::Name;

    // Hand-built DER. Each is a Name whose RDNs hold one PrintableString AVA.
    const CN_ALICE: &[u8] = &[
        0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
        0x69, 0x63, 0x65,
    ];
    /// The same value as `CN_ALICE` under a different attribute OID
    /// (organizationName, 2.5.4.10).
    const O_ALICE: &[u8] = &[
        0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c,
        0x69, 0x63, 0x65,
    ];
    const C_US: &[u8] = &[
        0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
    ];
    const C_US_O_TEST: &[u8] = &[
        0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
        0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
    ];
    const C_US_O_TEST_CN_ALICE: &[u8] = &[
        0x30, 0x2c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
        0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
        0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69, 0x63,
        0x65,
    ];

    fn n(der: &[u8]) -> Name {
        Name::from_der(der).expect("hand-built Name parses")
    }

    /// The same value under a different attribute type is a different name.
    ///
    /// Both AVA loops in `names_match` require the OID *and* the value to
    /// agree. With `||` in place of either `&&`, `CN=Alice` and `O=Alice`
    /// compare equal — the comparison would stop distinguishing attribute
    /// types, and DN equality is what binds a certificate to its issuer.
    #[test]
    fn the_same_value_under_a_different_attribute_type_is_a_different_name() {
        assert!(names_match(&n(CN_ALICE), &n(CN_ALICE)));
        assert!(
            !names_match(&n(CN_ALICE), &n(O_ALICE)),
            "CN=Alice is not O=Alice"
        );
        assert!(
            !names_match(&n(O_ALICE), &n(CN_ALICE)),
            "and not in the other argument order either"
        );
    }

    /// A DN is within the subtree rooted at itself.
    ///
    /// §4.2.1.10 containment is prefix containment, and every sequence is a
    /// prefix of itself. The length guard is `constraint.len() >
    /// subject.len()`; with `>=` an exactly-equal DN falls out as "not
    /// within", which breaks both directions of name constraints — a
    /// permitted subtree would reject the DN it names, and an excluded
    /// subtree would fail to exclude it.
    #[test]
    fn a_dn_is_within_the_subtree_rooted_at_itself() {
        assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST)));
        assert!(dn_within_subtree(&n(C_US), &n(C_US)));
    }

    /// A constraint longer than the subject contains nothing.
    ///
    /// The guard exists because the `zip` below it stops at the shorter of
    /// the two, so without it a deep constraint would be compared only
    /// against its own prefix and report a match. With `==` in place of
    /// `>`, `{C=US}` lands inside the subtree `{C=US, O=Test, CN=Alice}` —
    /// over-permissive for a permitted subtree, since a certificate would
    /// satisfy a constraint far more specific than its own name.
    #[test]
    fn a_constraint_longer_than_the_subject_contains_nothing() {
        assert!(
            !dn_within_subtree(&n(C_US), &n(C_US_O_TEST_CN_ALICE)),
            "{{C=US}} is not inside the subtree {{C=US, O=Test, CN=Alice}}"
        );
        assert!(
            !dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST_CN_ALICE)),
            "one RDN short is still outside"
        );
    }

    /// One RDN with two AVAs sharing a value under different OIDs, and one
    /// with a duplicated OID. RFC 5280 §5.1.2.4 says an RDN SHOULD NOT
    /// carry duplicate OIDs, so the second is malformed — which is exactly
    /// the case `names_match`'s bidirectional pass documents itself as
    /// handling.
    const CN_AND_O_ALICE: &[u8] = &[
        0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
        0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c, 0x69,
        0x63, 0x65,
    ];
    const CN_ALICE_TWICE: &[u8] = &[
        0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
        0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69,
        0x63, 0x65,
    ];

    /// The bidirectional AVA pass is what makes a duplicated OID safe.
    ///
    /// `{CN=Alice, O=Alice}` and `{CN=Alice, CN=Alice}` have the same RDN
    /// count and the same AVA count, and every AVA of the second has a
    /// strict match in the first — so the forward pass alone cannot tell
    /// them apart. Only the reverse pass can: `O=Alice` has no counterpart
    /// in `{CN=Alice, CN=Alice}`.
    ///
    /// Why this test rather than a simpler one: mutating the `&&` in
    /// *either* AVA loop to `||` leaves every other test in this crate
    /// green, because for well-formed RDNs the two passes are redundant and
    /// each catches what the other would miss. That redundancy is the
    /// design, and this is the input where the second pass is the one that
    /// catches it instead of merely agreeing — a duplicated OID, which the loop's own comment claims to
    /// handle and nothing verified.
    #[test]
    fn a_duplicated_oid_does_not_match_two_distinct_attributes() {
        assert!(
            !names_match(&n(CN_AND_O_ALICE), &n(CN_ALICE_TWICE)),
            "{{CN=Alice, O=Alice}} is not {{CN=Alice, CN=Alice}}"
        );
        assert!(
            !names_match(&n(CN_ALICE_TWICE), &n(CN_AND_O_ALICE)),
            "and not in the other argument order, which is the pass that \
             catches it when the first is weakened"
        );
        // Each still matches itself, so the above cannot pass on a
        // comparison that never returns true for two-AVA RDNs.
        assert!(names_match(&n(CN_AND_O_ALICE), &n(CN_AND_O_ALICE)));
        assert!(names_match(&n(CN_ALICE_TWICE), &n(CN_ALICE_TWICE)));
    }

    /// And the ordinary case still works: a shorter constraint is a prefix.
    ///
    /// Without this the two negative tests above would pass on a function
    /// that never returns `true`.
    #[test]
    fn a_shorter_constraint_contains_a_longer_subject() {
        assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US)));
        assert!(dn_within_subtree(&n(C_US_O_TEST_CN_ALICE), &n(C_US_O_TEST)));
    }
}

/// Compare two `AttributeTypeAndValue` values after RFC 4518 normalization.
///
/// Allocation-free: `BMPString` values are transcoded to UTF-8 lazily by
/// [`DirStringBytes`] while the two normalized byte streams are compared,
/// so the cost of one comparison is linear in the value lengths with no
/// heap traffic (review A1 item 10: `names_match` used to allocate two
/// transcoding buffers per AVA comparison).
fn ava_values_match(a: &der::Any, b: &der::Any) -> bool {
    let a_str = any_to_str_bytes(a);
    let b_str = any_to_str_bytes(b);

    match (a_str, b_str) {
        (Some(a_bytes), Some(b_bytes)) => {
            NormalizedIter::new(a_bytes).eq(NormalizedIter::new(b_bytes))
        }
        // Both values are non-string types (e.g. OID, INTEGER) or string
        // types this dispatch does not read: `UniversalString`, which `der`
        // rejects upstream at `Tag::try_from`, and a `TeletexString` whose
        // octets fall outside the ISO 646 invariant set — a combining
        // diacritic, or one of the twelve nationally-variable positions.
        // compare tag AND content bytes (raw DER). Tag comparison ensures two
        // different string encodings of the same text are not considered equal.
        (None, None) => a.tag() == b.tag() && a.value() == b.value(),
        // One value is a string type and the other is not. Return false (fail-closed).
        // A legitimate certificate chain will never encode the same attribute OID as a
        // string type in one cert and a non-string type in another, so this mismatch
        // indicates a malformed or suspicious certificate.
        _ => false,
    }
}

/// Classify a `DirectoryString` Any value as a stream of UTF-8 bytes,
/// returning `None` for types that require special pre-processing before
/// normalization (see `ava_values_match` for the dispatch logic).
///
/// The returned [`DirStringBytes`] iterator borrows the `der::Any` content
/// bytes; no string type allocates.
///
/// # Normalization strategy by string type
///
/// **Passed through — bytes already comparable as UTF-8/ASCII:**
/// `UTF8String`, `PrintableString`, `IA5String`, `VisibleString`,
/// `NumericString`. These types are encoded as ASCII (or UTF-8 in the case
/// of `UTF8String`) at the DER level. The bytes are fed directly to
/// `NormalizedIter` which applies ASCII case-folding and
/// insignificant-space handling (RFC 4518 §2.4 step 6 subset).
///
/// `NumericString` is here although `DirectoryString` (§4.1.2.4) does not
/// admit it. An `AttributeTypeAndValue`'s `value` is `ANY`, and an
/// attribute type outside the standard set defines its own syntax: Russia's
/// `OGRN` (1.2.643.100.1) and legal-entity `INN` (1.2.643.100.4) are
/// `NumericString`, and six of the eight roots in
/// `third_party/trust-stores/ru-national/` carry them. X.680 restricts the
/// type to the digits `0`-`9` and SPACE, so the content is ASCII and needs
/// no transcoding, and case-folding is a no-op on it; what the shared
/// pipeline adds is insignificant-space handling, which LDAP's
/// `numericStringMatch` (RFC 4517 §4.2.22, over the RFC 4518 preparation
/// §7.1 points at) also prescribes.
///
/// Before it was dispatched here it fell to the raw tag-and-bytes
/// comparison in [`ava_values_match`], so the same name encoded as
/// `NumericString` by one CA and `PrintableString` by another compared as
/// two different names — a false negative that surfaces as
/// [`Error::NoTrustedPath`] with nothing to say an encoding caused it.
///
/// **Passed through only when unambiguously ASCII — `TeletexString`:**
/// T.61 is not ASCII, so this type is dispatched here only when every
/// octet lies in the ISO 646 invariant set; see
/// [`teletex_is_iso646_invariant`]. Anything else, including the
/// non-spacing diacritics at `0xC0`-`0xCF`, returns `None` and falls to the
/// raw tag-and-bytes comparison.
///
/// **Transcoded on the fly — UCS-2-BE → UTF-8:**
/// `BMPString`. RFC 4518 §2.1 treats `BMPString` as "a subset of Unicode"
/// — every two-byte big-endian unit is a Unicode code point in the BMP.
/// Each unit is encoded to UTF-8 as it is consumed so the same
/// normalization pipeline used for `UTF8String` applies to the result.
/// ASCII-range code points in the BMP (U+0000..=U+007F) become
/// single-byte UTF-8, so a BMPString-encoded "Foo Co" compares equal to a
/// UTF8String-encoded "Foo Co". Malformed `BMPString` content (odd-length
/// bytes, or values in the surrogate range U+D800..=U+DFFF which are not
/// valid Unicode scalar values) is detected up front by
/// [`bmp_is_well_formed`] and returns `None` (fail-closed): a malformed
/// value will not match anything via `ava_values_match`.
///
/// **Rejected at parse time — UniversalString:**
/// `der` 0.7 omits tag 0x1C (`UniversalString`) from `Tag::try_from`,
/// causing any cert with a `UniversalString` AVA to fail
/// `Certificate::from_der` upstream. This dispatch therefore never sees
/// `UniversalString`-tagged values. Documented for completeness; a future
/// upstream fix in `der` (or our own pre-decode shim) is required before
/// `UniversalString` becomes reachable here.
///
/// **Committed policy — `TeletexString` (T61String):**
/// Raw DER byte comparison only. `pkix-path` deliberately does not
/// transcode T.61 to Unicode. RFC 4518 §2.1 states: "As there is no
/// standard for mapping `TeletexString` values to Unicode, the mapping is
/// left a local matter." RFC 5280 §7.1 classifies `TeletexString` support
/// as OPTIONAL. No canonical T.61→Unicode table exists — OpenSSL, NSS,
/// and `GnuTLS` each use incompatible vendor extensions. Adopting any one
/// of those tables would silently accept mismatches the others reject and
/// reject chains the others accept — a name-confusion smell with no
/// interoperability win. Byte-equality is fail-closed: two `TeletexString`
/// AVAs match iff their DER content bytes are identical, which is what
/// RFC 5280 §4.1.2.4 already requires of well-formed issuer/subject DN
/// reuse across a chain.
///
/// # Future work
///
/// Full RFC 4518 six-step preparation (Map → NFKC → Prohibit → `CheckBidi`
/// → insignificant-space) for non-ASCII Unicode code points is tracked
/// separately. Until that lands, two `BMPString` values that contain the
/// same Unicode code points but differ in canonical decomposition (e.g.
/// precomposed U+00E9 'é' vs decomposed U+0065 U+0301 'e'+ combining
/// acute) compare unequal even though RFC 4518 says they should match.
fn any_to_str_bytes(a: &der::Any) -> Option<DirStringBytes<'_>> {
    use der::Tag;
    match a.tag() {
        Tag::Utf8String
        | Tag::PrintableString
        | Tag::Ia5String
        | Tag::VisibleString
        | Tag::NumericString => Some(DirStringBytes::Plain(a.value().iter())),
        // `TeletexString` only when every octet is in the ISO 646 invariant
        // set, where T.61 and ASCII cannot disagree. See
        // `teletex_is_iso646_invariant`.
        Tag::TeletexString if teletex_is_iso646_invariant(a.value()) => {
            Some(DirStringBytes::Plain(a.value().iter()))
        }
        // `clippy::chunks_exact_to_as_chunks` would have this be
        // `as_chunks::<2>().0.iter()`. Declined: this iterator is stored in
        // `DirStringBytes::Bmp`, so the change rewrites that variant's field
        // type from `ChunksExact<'_, u8>` to `slice::Iter<'_, [u8; 2]>` and
        // the `Iterator` impl that transcodes UCS-2 through it. That is a
        // real edit to DN-comparison code for a style preference, and
        // `bmp_is_well_formed` has already established the length is even,
        // which is the correctness property `as_chunks` would make visible
        // in the type.
        #[expect(
            clippy::chunks_exact_to_as_chunks,
            reason = "see the comment above; the iterator type is part of DirStringBytes"
        )]
        Tag::BmpString if bmp_is_well_formed(a.value()) => Some(DirStringBytes::Bmp {
            units: a.value().chunks_exact(2),
            buf: [0; 4],
            len: 0,
            pos: 0,
        }),
        _ => None,
    }
}

/// The twelve code positions ISO 646 leaves to national variation, where
/// T.61 and US-ASCII therefore cannot be assumed to agree.
///
/// `#` `$` `@` `[` `\` `]` `^` `` ` `` `{` `|` `}` `~` in ASCII. ISO 646's
/// International Reference Version already differs from ASCII at `0x24`,
/// putting the international currency sign there rather than the dollar
/// sign, and T.61 descends from that lineage.
const ISO646_VARIANT_POSITIONS: [u8; 12] = [
    0x23, 0x24, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x60, 0x7B, 0x7C, 0x7D, 0x7E,
];

/// Returns `true` if `TeletexString` content can be compared as ASCII
/// without needing to know T.61's code table.
///
/// T.61 is not ASCII. Its upper half carries a supplementary set, and
/// `0xC0`-`0xCF` are *non-spacing diacritics* that precede the letter they
/// modify -- six eIDAS roots in `third_party/trust-stores/eu-eidas/` encode
/// `Regulierungsbeh<0xC8>orde f<0xC8>ur Telekommunikation und Post`, where
/// `0xC8` is a combining diaeresis and the name is "Regulierungsbehörde
/// für". Decoding that correctly means implementing T.51/T.61, and this is
/// a name comparison, not a transcoder.
///
/// Its lower half is not reliably ASCII either. T.61 descends from ISO 646,
/// which leaves twelve positions to national variation, so a `$` or an `@`
/// in a `TeletexString` cannot be read as a `$` or an `@` without the
/// table. What *is* safe is the ISO 646 invariant set -- the positions
/// identical in every variant -- which covers the letters, the digits,
/// space, and the punctuation that actually appears in distinguished names.
///
/// So: pass through content drawn entirely from that set, and return
/// `false` for anything else, which sends the value to the raw
/// tag-and-bytes comparison in [`ava_values_match`]. That is fail-closed:
/// a value this cannot read compares equal only to a byte-identical one.
///
/// Measured against the corpus: 35 of the 37 `TeletexString` attribute
/// values across 15 certificates in six vendored stores are inside the
/// invariant set, including Hewlett-Packard's Platform Keys and Entrust's
/// `www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)`. The two
/// outside it are the German regulator's name above, which keeps byte
/// comparison -- and loses nothing by it, since both certificates encode
/// that name identically in subject and issuer.
fn teletex_is_iso646_invariant(bytes: &[u8]) -> bool {
    bytes
        .iter()
        .all(|b| (0x20..=0x7E).contains(b) && !ISO646_VARIANT_POSITIONS.contains(b))
}

/// Returns `true` if `bytes` is well-formed `BMPString` content: an even
/// number of octets (UCS-2 units are 16 bits) and no unit in the UTF-16
/// surrogate range U+D800..=U+DFFF. Surrogates are *reserved* by Unicode
/// and do not represent characters; they appear in UTF-16 only as paired
/// surrogates encoding supplementary-plane code points (which are
/// forbidden in `BMPString` by definition — `BMP` = Basic Multilingual
/// Plane, U+0000..=U+FFFF).
fn bmp_is_well_formed(bytes: &[u8]) -> bool {
    let (units, rest) = bytes.as_chunks::<2>();
    rest.is_empty() && units.iter().all(|u| !(0xD8..=0xDF).contains(&u[0]))
}

/// UTF-8 byte stream over a `DirectoryString` value (see [`any_to_str_bytes`]).
///
/// The `Bmp` variant transcodes one UCS-2-BE unit at a time into `buf`
/// and yields its UTF-8 bytes; it must only be constructed over content
/// that passed [`bmp_is_well_formed`].
enum DirStringBytes<'a> {
    /// Content bytes that are already UTF-8 / ASCII.
    Plain(core::slice::Iter<'a, u8>),
    /// UCS-2-BE content, transcoded lazily.
    Bmp {
        /// Remaining two-byte units.
        units: core::slice::ChunksExact<'a, u8>,
        /// UTF-8 encoding of the current unit.
        buf: [u8; 4],
        /// Number of valid bytes in `buf`.
        len: u8,
        /// Next byte of `buf` to yield.
        pos: u8,
    },
}

impl Iterator for DirStringBytes<'_> {
    type Item = u8;
    fn next(&mut self) -> Option<u8> {
        match self {
            Self::Plain(it) => it.next().copied(),
            Self::Bmp {
                units,
                buf,
                len,
                pos,
            } => {
                if *pos == *len {
                    let unit = units.next()?;
                    let cp = u16::from_be_bytes([unit[0], unit[1]]);
                    // Surrogates were rejected by `bmp_is_well_formed`; the
                    // fallback keeps this total without a panic path.
                    let ch = char::from_u32(u32::from(cp)).unwrap_or(char::REPLACEMENT_CHARACTER);
                    // A BMP scalar value encodes to 1..=3 UTF-8 bytes.
                    *len = ch.encode_utf8(buf).len() as u8;
                    *pos = 0;
                }
                let b = buf[usize::from(*pos)];
                *pos += 1;
                Some(b)
            }
        }
    }
}

/// Transcode `BMPString` content to UTF-8 (test helper over [`DirStringBytes`]).
///
/// Returns `None` for malformed content (see [`bmp_is_well_formed`]).
#[cfg(test)]
fn bmp_string_to_utf8(bytes: &[u8]) -> Option<Vec<u8>> {
    let any = der::Any::new(der::Tag::BmpString, bytes).ok()?;
    any_to_str_bytes(&any).map(Iterator::collect)
}

/// Compare two byte slices after RFC 4518 whitespace normalization and case-folding.
///
/// Rules applied (per RFC 4518 §2):
/// 1. ASCII letters (0x41–0x5A): case-fold to lowercase. Non-ASCII bytes are
///    passed through unchanged; full Unicode case-folding (NFKC + case-fold)
///    is future work.
/// 2. Leading/trailing spaces: ignored
/// 3. Internal multiple spaces: collapsed to single space
#[cfg(test)]
fn normalized_eq(a: &[u8], b: &[u8]) -> bool {
    NormalizedIter::new(a.iter().copied()).eq(NormalizedIter::new(b.iter().copied()))
}

/// Streaming adapter that yields bytes after ASCII case-fold and whitespace
/// normalization (RFC 4518 §2 subset, see `normalized_eq`).
///
/// Works over any byte iterator, so `BMPString` values can be normalized
/// while they are being transcoded, without an intermediate buffer.
///
/// # Known limitation
///
/// Only U+0020 SPACE (byte `0x20`) is treated as insignificant whitespace.
/// Tabs (`\t`, `0x09`), non-breaking spaces (`0xA0` in Latin-1), and other
/// Unicode whitespace variants pass through unchanged. Full RFC 4518
/// insignificant-space handling requires Unicode-aware processing deferred
/// to a future release.
struct NormalizedIter<I: Iterator<Item = u8>> {
    inner: core::iter::Peekable<I>,
    /// Set once the first non-space byte has been yielded; spaces seen
    /// before that are leading spaces and are dropped.
    started: bool,
}

impl<I: Iterator<Item = u8>> NormalizedIter<I> {
    fn new(bytes: I) -> Self {
        Self {
            inner: bytes.peekable(),
            started: false,
        }
    }
}

impl<I: Iterator<Item = u8>> Iterator for NormalizedIter<I> {
    type Item = u8;
    fn next(&mut self) -> Option<u8> {
        loop {
            let b = self.inner.next()?;
            if b != b' ' {
                self.started = true;
                return Some(b.to_ascii_lowercase());
            }
            // Consume the rest of this space run. `next_if_eq` rather than
            // a peek-and-next pair: the pair's condition can be mutated
            // into one that consumes nothing and never ends, because
            // `next()` on an exhausted `Peekable` leaves `peek()` at
            // `None` forever. There is no such reading of this.
            while self.inner.next_if_eq(&b' ').is_some() {}
            // Leading run: drop it and continue with the first non-space byte.
            // Trailing run (nothing follows): drop it and end.
            // Internal run: collapse to exactly one space.
            if self.started && self.inner.peek().is_some() {
                return Some(b' ');
            }
        }
    }
}

// ---------------------------------------------------------------------------
// NameConstraints matching (PKIX-mew)
// ---------------------------------------------------------------------------

/// Newtype wrapping a bitmask of `GeneralName` name types for `NameConstraints`.
///
/// Used by `nc_constrained_types` to track which types have been constrained
/// by at least one CA certificate in the path, even if the intersection later
/// empties the permitted set for that type.
///
/// Bare `u32` constants would allow silent misuse (e.g., confusing a count
/// with a mask). The newtype makes the intent explicit at every operation site.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct NcTypeMask(u32);

impl NcTypeMask {
    const EMPTY: Self = Self(0);
    const RFC822: Self = Self(1 << 0);
    const DNS: Self = Self(1 << 1);
    const DIRECTORY_NAME: Self = Self(1 << 2);
    const URI: Self = Self(1 << 3);
    /// `IP_ADDRESS` is used by `name_type_bit` and participates in `nc_constrained_types`
    /// tracking. `IpAddress` names cannot appear in Subject DNs, so there is no
    /// inline DN-path code for this type; SAN `IpAddress` entries are handled by the
    /// generic SAN loop in `check_name_constraints` via `type_constrained(name)`.
    const IP_ADDRESS: Self = Self(1 << 4);
    /// `otherName` (any type-id). `pkix-path` cannot match otherName
    /// constraints; an `otherName` SAN is rejected whenever any otherName
    /// constraint is in effect. `SmtpUTF8Mailbox` SANs are additionally
    /// checked against rfc822Name constraints (RFC 8398 §6).
    const OTHER_NAME: Self = Self(1 << 5);
    /// `ediPartyName`: unsupported, fail-closed like `OTHER_NAME`.
    const EDI_PARTY_NAME: Self = Self(1 << 6);
    /// `registeredID`: unsupported, fail-closed like `OTHER_NAME`.
    const REGISTERED_ID: Self = Self(1 << 7);

    /// Returns `true` if `self` and `other` share at least one bit (non-empty intersection).
    ///
    /// Named `intersects` rather than `contains` because this is a bitmask test,
    /// not a set-membership check — `a.intersects(b)` is symmetric, while `contains`
    /// implies `a ⊇ b`.
    const fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    /// Returns `true` when no name form is tracked.
    ///
    /// Read on the hot path, to decide whether any name constraint is in
    /// effect at all. See the `nc_in_effect` computation in
    /// [`validate_path`].
    const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl core::ops::BitOr for NcTypeMask {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl core::ops::BitOrAssign for NcTypeMask {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

/// Return the `NcTypeMask` bit for the name form of `name`.
///
/// Every `GeneralName` form has a bit, including the forms `pkix-path`
/// cannot match (`otherName`, `ediPartyName`, `registeredID`). Tracking
/// those lets
/// `check_name_constraints` reject a certificate that carries an
/// unsupported form a constraint applies to, as RFC 5280 §4.2.1.10
/// requires. `x400Address` is not representable in `x509-cert` 0.3 (a SAN
/// containing one fails to decode and is rejected as malformed).
const fn name_type_bit(name: &x509_cert::ext::pkix::name::GeneralName) -> NcTypeMask {
    use x509_cert::ext::pkix::name::GeneralName;
    match name {
        GeneralName::Rfc822Name(_) => NcTypeMask::RFC822,
        GeneralName::DnsName(_) => NcTypeMask::DNS,
        GeneralName::DirectoryName(_) => NcTypeMask::DIRECTORY_NAME,
        GeneralName::UniformResourceIdentifier(_) => NcTypeMask::URI,
        GeneralName::IpAddress(_) => NcTypeMask::IP_ADDRESS,
        GeneralName::OtherName(_) => NcTypeMask::OTHER_NAME,
        GeneralName::EdiPartyName(_) => NcTypeMask::EDI_PARTY_NAME,
        GeneralName::RegisteredId(_) => NcTypeMask::REGISTERED_ID,
    }
}

/// Returns true if `subject` DN is within the subtree rooted at `constraint`.
///
/// RFC 5280 §4.2.1.10: a `DirectoryName` constraint is satisfied when the subject's
/// DN has the constraint DN as a prefix (most-general to most-specific order).
/// E.g., constraint `{C=US, O=Test}` matches subject `{C=US, O=Test, CN=Alice}`.
fn dn_within_subtree(subject: &x509_cert::name::Name, constraint: &x509_cert::name::Name) -> bool {
    let c_rdns = constraint.iter_rdn();
    let s_rdns = subject.iter_rdn();
    if constraint.len() > subject.len() {
        return false;
    }
    c_rdns.zip(s_rdns).all(|(c_rdn, s_rdn)| {
        // Each pair of RDNs must have matching attribute-value pairs.
        if c_rdn.len() != s_rdn.len() {
            return false;
        }
        c_rdn.iter().all(|c_ava| {
            s_rdn
                .iter()
                .any(|s_ava| c_ava.oid == s_ava.oid && ava_values_match(&c_ava.value, &s_ava.value))
        })
    })
}

/// Returns true if `a` and `b` are the same `GeneralName` form.
///
/// Uses `name_type_bit` as the single source of truth so that adding a new
/// form to `name_type_bit` automatically extends this check with no
/// separate update required.
fn same_nc_variant(
    a: &x509_cert::ext::pkix::name::GeneralName,
    b: &x509_cert::ext::pkix::name::GeneralName,
) -> bool {
    name_type_bit(a) != NcTypeMask::EMPTY && name_type_bit(a) == name_type_bit(b)
}

/// Returns true if `name` (a certificate's subject or SAN name) satisfies
/// the `subtree` constraint.
///
/// Unsupported forms never match; `check_name_constraints` rejects them
/// separately whenever a constraint of their form is in effect.
fn name_matches_subtree(
    name: &x509_cert::ext::pkix::name::GeneralName,
    subtree: &x509_cert::ext::pkix::constraints::name::GeneralSubtree,
) -> bool {
    use x509_cert::ext::pkix::name::GeneralName;
    match (name, &subtree.base) {
        (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
            matches_dns_name(subj.as_str(), constr.as_str())
        }
        (GeneralName::DirectoryName(subj), GeneralName::DirectoryName(constr)) => {
            dn_within_subtree(subj, constr)
        }
        (GeneralName::Rfc822Name(subj), GeneralName::Rfc822Name(constr)) => {
            matches_rfc822_name(subj.as_str(), constr.as_str())
        }
        (
            GeneralName::UniformResourceIdentifier(subj),
            GeneralName::UniformResourceIdentifier(constr),
        ) => matches_uri(subj.as_str(), constr.as_str()),
        (GeneralName::IpAddress(subj), GeneralName::IpAddress(constr)) => {
            matches_ip_address(subj.as_bytes(), constr.as_bytes())
        }
        // Mismatched variants or unhandled types: no match.
        _ => false,
    }
}

/// Returns true if every name inside constraint `a` is also inside
/// constraint `b` (`a ⊆ b`), for two `GeneralSubtree` bases of the same form.
///
/// Used to intersect permitted subtrees (RFC 5280 §6.1.4(g)(1)) and to
/// de-duplicate excluded subtrees. A constraint is *not* a certificate name
/// (an iPAddress constraint is address + mask, a URI or rfc822Name
/// constraint is a bare host or `.domain`), so this cannot reuse
/// [`name_matches_subtree`]. Unsupported forms return `false`.
fn subtree_within(
    a: &x509_cert::ext::pkix::name::GeneralName,
    b: &x509_cert::ext::pkix::name::GeneralName,
) -> bool {
    use x509_cert::ext::pkix::name::GeneralName;
    match (a, b) {
        (GeneralName::DnsName(a), GeneralName::DnsName(b)) => {
            dns_constraint_within(a.as_str(), b.as_str())
        }
        (GeneralName::DirectoryName(a), GeneralName::DirectoryName(b)) => dn_within_subtree(a, b),
        (GeneralName::Rfc822Name(a), GeneralName::Rfc822Name(b)) => {
            rfc822_constraint_within(a.as_str(), b.as_str())
        }
        (GeneralName::UniformResourceIdentifier(a), GeneralName::UniformResourceIdentifier(b)) => {
            uri_constraint_within(a.as_str(), b.as_str())
        }
        (GeneralName::IpAddress(a), GeneralName::IpAddress(b)) => {
            ip_constraint_within(a.as_bytes(), b.as_bytes())
        }
        _ => false,
    }
}

/// Strip one trailing `.` (the RFC 1034 absolute form) from a DNS name or
/// URI host.
///
/// `pkix-identity` strips the same dot when it binds a dNSName SAN to a
/// reference identity, so name-constraint matching must normalize
/// identically: otherwise `www.evil.com.` escapes an excluded `evil.com`
/// here yet binds to `www.evil.com` there.
fn strip_root_dot(s: &str) -> &str {
    s.strip_suffix('.').unwrap_or(s)
}

/// Returns true if `name` is a proper subdomain of `parent` (one or more
/// labels added to the left), compared ASCII case-insensitively.
///
/// Works on bytes, so it cannot panic on a non-ASCII input.
fn is_strict_subdomain(name: &str, parent: &str) -> bool {
    let (name, parent) = (name.as_bytes(), parent.as_bytes());
    name.len() > parent.len() + 1
        && name[name.len() - parent.len() - 1] == b'.'
        && name[name.len() - parent.len()..].eq_ignore_ascii_case(parent)
}

/// DNS name constraint matching (RFC 5280 §4.2.1.10).
///
/// - A constraint without a leading period matches the name itself and any
///   subdomain ("adding zero or more labels to the left-hand side").
/// - A constraint with a leading period (`.example.com`, a widespread
///   extension) matches proper subdomains only.
/// - The empty constraint has zero labels, so it matches every DNS name;
///   an empty excluded dNSName therefore forbids all DNS names, matching
///   OpenSSL, Go and BoringSSL.
/// - One trailing dot is ignored on both sides (see [`strip_root_dot`]).
///
/// Comparison is ASCII case-insensitive.
fn matches_dns_name(subject: &str, constraint: &str) -> bool {
    let subject = strip_root_dot(subject);
    let constraint = strip_root_dot(constraint);
    if constraint.is_empty() {
        return true;
    }
    if let Some(parent) = constraint.strip_prefix('.') {
        // The apex itself is excluded from a leading-period constraint.
        is_strict_subdomain(subject, parent)
    } else {
        subject.eq_ignore_ascii_case(constraint) || is_strict_subdomain(subject, constraint)
    }
}

/// `id-at-commonName` (RFC 4519 §2.3).
const OID_AT_COMMON_NAME: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");

/// A `commonName` AVA value as a string, for the string types that can
/// hold a host name.
///
/// This must accept at least everything `pkix-identity`'s own CN reader
/// accepts, because that is the function that will match the value
/// against a requested name. It reads `PrintableString`, `UTF8String`
/// and `IA5String`, and this reads the same three. A value neither can
/// read is one nothing will match a host name against, so the sets
/// agreeing is what matters rather than either being generous.
fn cn_value_as_str(value: &der::Any) -> Option<&str> {
    if let Ok(s) = value.decode_as::<der::asn1::PrintableStringRef<'_>>() {
        return Some(s.as_str());
    }
    if let Ok(s) = value.decode_as::<der::asn1::Utf8StringRef<'_>>() {
        return Some(s.as_str());
    }
    if let Ok(s) = value.decode_as::<der::asn1::Ia5StringRef<'_>>() {
        return Some(s.as_str());
    }
    None
}

/// Whether a string is shaped like a host name: at least one label
/// separator, and every label non-empty and LDH (letters, digits,
/// hyphen).
///
/// This is the heuristic that decides whether a `commonName` is read as
/// a DNS identity, and it is deliberately narrow. A descriptive CN such
/// as `Example Corp Issuing CA` has no dot and a space, so it is never
/// read as a host name and never constrained as one; `notallowed.test`
/// is.
fn is_hostname_shaped(s: &str) -> bool {
    let s = strip_root_dot(s);
    if s.is_empty() || !s.contains('.') {
        return false;
    }
    s.split('.').all(|label| {
        !label.is_empty()
            && label
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-')
    })
}

/// Whether a `commonName` could be matched against a requested DNS name.
///
/// Either a host name, or a wildcard of the one shape
/// `pkix-identity`'s matcher honours. The wildcard case has to be here:
/// a CN of `*.example.com` is not a host name by
/// [`is_hostname_shaped`], but it will match `bar.example.com`, so
/// leaving it out would constrain the literal spelling and miss the
/// wildcard -- the very gap closed for SANs in
/// [`wildcard_san_reaches_excluded_dns`].
fn is_dns_identity_shaped(s: &str) -> bool {
    let s = strip_root_dot(s);
    match s.strip_prefix("*.") {
        Some(rest) => !rest.contains('*') && is_hostname_shaped(rest),
        None => is_hostname_shaped(s),
    }
}

/// The `commonName` values this certificate asserts as DNS identities.
///
/// RFC 5280 §4.2.1.10 does not require checking the CN, and RFC 6125
/// §6.4.4 deprecated reading one as a host name -- which
/// `pkix_identity::verify_dns_name` honours, refusing to fall back. But
/// RFC 7672 §3.2.3 still *requires* CN fallback for SMTP DANE, so the
/// name is read as an identity there, and a constraint that cannot see
/// it cannot bound it. OpenSSL applies dNSName constraints to the CN in
/// exactly this case, and a chain it rejects as an excluded-subtree
/// violation was being accepted here.
///
/// Empty when the certificate carries a `subjectAltName` extension at
/// all, not merely when it carries a dNSName one.
///
/// That distinction is the whole rule, and getting it wrong rejects
/// valid certificates. A certificate presenting `IP:127.0.0.1` and
/// `CN=test.localhost` is asserting the address, not the name: RFC 5280
/// §4.1.2.6 makes `subjectAltName` *the* place identities live once it
/// is present, so the CN is not an identity and bounding it as one
/// refuses a certificate nobody can misuse. x509-limbo's
/// `bettertls::nameconstraints` suite is full of exactly that shape --
/// 88 of its testcases -- and expects them to validate.
///
/// OpenSSL does bound the CN in that case, and rejects those chains as
/// excluded-subtree violations. It is over-strict here, and matching it
/// was a mistake worth naming: an implementation is evidence about a
/// rule, not the rule.
///
/// The residual gap this leaves is real but covered. `pkix-identity`'s
/// CN fallback triggers on the absence of a dNSName SAN, not on the
/// absence of every SAN, so a certificate with an IP SAN and a
/// host-name CN can still be CN-matched for a DNS name by
/// `verify_dns_name_with_cn_fallback` while unbounded here.
/// `pkix-chain`'s SMTP DANE entry point refuses that whole shape
/// unconditionally -- `SmtpDaneFailure::ConstrainedPathWithoutDnsId`,
/// PKIX-skxt -- which is the right place for it, because only that
/// layer holds both the path and the requested name.
fn cn_dns_identities<'a>(
    subject: &'a x509_cert::name::Name,
    san: Option<&x509_cert::ext::pkix::SubjectAltName>,
) -> Vec<&'a str> {
    if san.is_some() {
        return Vec::new();
    }
    // `Name::iter` flattens across RelativeDistinguishedNames: a
    // multi-valued RDN carrying a commonName is unusual but legal, and
    // every CN the certificate asserts has to be bounded.
    subject
        .iter()
        .filter(|ava| ava.oid == OID_AT_COMMON_NAME)
        .filter_map(|ava| cn_value_as_str(&ava.value))
        .filter(|s| is_dns_identity_shaped(s))
        .collect()
}

/// Check each `commonName` read as a DNS identity against the dNSName
/// subtrees, with the same rules a dNSName SAN gets.
fn check_cn_dns_against_subtrees(
    cns: &[&str],
    subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
    mode: CheckMode,
    nc_constrained_types: NcTypeMask,
    index: usize,
) -> crate::Result<()> {
    use x509_cert::ext::pkix::name::GeneralName;

    if cns.is_empty() {
        return Ok(());
    }
    let dns_subtrees = || {
        subtrees.iter().filter_map(|st| match &st.base {
            GeneralName::DnsName(c) => Some(c.as_str()),
            _ => None,
        })
    };

    for cn in cns {
        match mode {
            CheckMode::Excluded => {
                if dns_subtrees()
                    .any(|c| matches_dns_name(cn, c) || wildcard_san_reaches_excluded_dns(cn, c))
                {
                    return Err(Error::NameConstraintViolation { index });
                }
            }
            CheckMode::Permitted => {
                if nc_constrained_types.intersects(NcTypeMask::DNS)
                    && !dns_subtrees().any(|c| matches_dns_name(cn, c))
                {
                    return Err(Error::NameConstraintViolation { index });
                }
            }
        }
    }
    Ok(())
}

/// Whether a wildcard dNSName SAN can authenticate a name inside an
/// excluded subtree that the SAN's own spelling does not fall into.
///
/// RFC 5280 §4.2.1.10 compares a dNSName SAN against an excluded subtree
/// as a name, and a wildcard SAN is not the name it stands for: the
/// string `*.example.com` is not within the subtree `bar.example.com`,
/// so the literal comparison reports no violation. But RFC 9525 §6.3
/// lets that certificate authenticate `bar.example.com`, which is
/// exactly the name the CA was forbidden to certify. Neither rule is
/// wrong alone; read together they leave a dNSName exclusion
/// unenforceable against the certificate shape most used in practice.
/// That gap is CVE-2025-61727.
///
/// So the exclusion is tested against the names the wildcard can
/// authenticate rather than against its spelling. The wildcard replaces
/// exactly one label, so `*.D` stands for `{<label>.D}`, and that set
/// meets the subtree rooted at `E` when either
///
/// - `D` lies within `E` -- which makes `*.D` a strict subdomain of `E`
///   as a string, so [`matches_dns_name`] already reports it; or
/// - `E` is itself one of the names the wildcard stands for, that is
///   `<one label>.D`. That is the case this adds.
///
/// Nothing else meets it. A deeper exclusion such as
/// `foo.bar.example.com` is out of reach of `*.example.com`, because the
/// wildcard cannot cross a label boundary, and a leading-period
/// exclusion covers only strict subdomains of its apex, which the
/// wildcard likewise cannot reach past one label.
///
/// The wildcard test mirrors `pkix-identity`'s matcher exactly -- a
/// leftmost single `*` label, a non-empty remainder carrying no further
/// `*` and at least one label separator. It has to: a spelling that
/// matcher refuses authenticates nothing, and one it accepts must be
/// bounded here, so any disagreement between the two is either a
/// refusal of a harmless certificate or a hole of this same shape.
///
/// Permitted subtrees need no equivalent. There the test is containment
/// rather than intersection, and a wildcard that is not itself within a
/// permitted subtree already fails [`matches_dns_name`] -- which is why
/// the `nc-permits` half of the CVE's testcases was already rejected.
fn wildcard_san_reaches_excluded_dns(san: &str, constraint: &str) -> bool {
    let san = strip_root_dot(san);
    let constraint = strip_root_dot(constraint);

    let Some(rest) = san.strip_prefix("*.") else {
        return false;
    };
    if rest.is_empty() || rest.contains('*') || !rest.contains('.') {
        return false;
    }
    // A leading-period exclusion covers only strict subdomains of its
    // apex; `*.rest` reaches no subdomain of a child of `rest`.
    if constraint.starts_with('.') {
        return false;
    }

    // Is the excluded name `<one non-empty label>.rest`?
    let c = constraint.to_ascii_lowercase();
    let r = rest.to_ascii_lowercase();
    let Some(prefix) = c.strip_suffix(&r) else {
        return false;
    };
    let Some(label) = prefix.strip_suffix('.') else {
        return false;
    };
    !label.is_empty() && !label.contains('.')
}

/// `a ⊆ b` for two dNSName constraints (see [`subtree_within`]).
///
/// `x` denotes `{x} ∪ subdomains(x)` and `.x` denotes `subdomains(x)`, so
/// `.x ⊆ b` exactly when `x` itself or every subdomain of `x` is covered,
/// which reduces to matching `x` against `b` with any leading period of `b`
/// dropped.
fn dns_constraint_within(a: &str, b: &str) -> bool {
    let a = strip_root_dot(a);
    match a.strip_prefix('.') {
        Some(a_parent) => {
            let b = strip_root_dot(b);
            matches_dns_name(a_parent, b.strip_prefix('.').unwrap_or(b))
        }
        None => matches_dns_name(a, b),
    }
}

/// Match a mailbox's domain part against a host (`example.com`) or domain
/// (`.example.com`) rfc822Name constraint.
fn rfc822_domain_matches(domain: &str, constraint: &str) -> bool {
    match constraint.strip_prefix('.') {
        // Any host under the domain; the apex is excluded.
        Some(parent) => is_strict_subdomain(domain, parent),
        None => domain.eq_ignore_ascii_case(constraint),
    }
}

/// RFC 822 (email) name constraint matching (RFC 5280 §4.2.1.10).
///
/// The domain part of `subject` is the text after the **last** `@`: an
/// RFC 5322 quoted local-part may itself contain `@`
/// (`"x@good.com"@evil.com` is a mailbox at `evil.com`).
///
/// # Two addresses match on an exact local-part and a folded host-part
///
/// RFC 5280 §7.5, unchanged in substance by [RFC 9549][rfc9549] §2.5,
/// which restates it as §7.5.1 and §7.5.2:
///
/// > Two email addresses are considered to match if:
/// >
/// > 1) The local-part of each name is an exact match, AND
/// >
/// > 2) The host-part of each name matches using a case-insensitive ASCII
/// >    comparison.
///
/// The local-part is case-**sensitive**. RFC 5321 §2.4 is why: "the
/// local-part of a mailbox MUST BE treated as case sensitive", and
/// `Root@example.com` is a different mailbox from `root@example.com` as
/// far as any conforming mail system is concerned.
///
/// This function case-folded the whole address, local-part included, until
/// `PKIX-z1o9`. In an **excluded** subtree that was merely too broad, which
/// fails closed; in a **permitted** subtree it was fail-open — a CA
/// constrained to permit `root@example.com` would have had
/// `ROOT@example.com` accepted.
///
/// # RFC 9549 requires this to work identically for internationalized mail
///
/// §7.5.1 (ASCII local-part) and §7.5.2 (non-ASCII local-part) carry the
/// same two-clause rule, word for word, and RFC 9549 §2.2 says the point of
/// removing the per-mailbox constraint form was to let "name constraints
/// apply to email addresses in rfc822Name and SmtpUTF8Mailbox within
/// otherName". One function serves both, which is what makes the
/// "identically" structural rather than a claim.
///
/// The old folding broke that too, and asymmetrically:
/// `eq_ignore_ascii_case` folds only ASCII bytes, so a non-ASCII
/// local-part was already compared exactly while an ASCII one was not.
/// The rule was honoured for an internationalized mailbox and violated
/// for a plain one — the exact divergence §2.5 exists to forbid.
///
/// # No U-label conversion, deliberately
///
/// Everything here compares A-labels as bytes. RFC 9549 §3 is explicit
/// that its predecessor's conversion requirement "led to implementation
/// complexity and at least two security vulnerabilities", and that "all
/// IDNs are carried and processed as A-labels". A non-ASCII host-part
/// never reaches a comparison: [`check_mailbox_against_rfc822`] rejects
/// it before this function is called.
///
/// [rfc9549]: https://www.rfc-editor.org/rfc/rfc9549#section-2.5
fn matches_rfc822_name(subject: &str, constraint: &str) -> bool {
    // A constraint with an `@` names one mailbox. RFC 9549 §2.2 removed
    // that form from the issuance profile; this still honours it, because
    // declining to would stop an excluded subtree from excluding and that
    // is the fail-open direction. See `pkix-lint/divergences.md`.
    if let Some((c_local, c_domain)) = constraint.rsplit_once('@') {
        let Some((s_local, s_domain)) = subject.rsplit_once('@') else {
            return false; // malformed subject
        };
        // (1) local-part exact, (2) host-part folded. Not one fold over
        // the whole address.
        return s_local == c_local && s_domain.eq_ignore_ascii_case(c_domain);
    }
    let Some((_, domain)) = subject.rsplit_once('@') else {
        return false; // malformed subject
    };
    rfc822_domain_matches(domain, constraint)
}

/// `a ⊆ b` for two rfc822Name constraints (see [`subtree_within`]).
///
/// The three constraint shapes are a mailbox (`u@host`, one address), a
/// host (`host`, all mailboxes at that host) and a domain (`.domain`, all
/// mailboxes at any host under it).
fn rfc822_constraint_within(a: &str, b: &str) -> bool {
    if a.contains('@') {
        return matches_rfc822_name(a, b);
    }
    if b.contains('@') {
        // A host or domain is never inside a single mailbox.
        return false;
    }
    match (a.strip_prefix('.'), b.strip_prefix('.')) {
        (None, _) => rfc822_domain_matches(a, b),
        // Every host under a domain is never inside one host.
        (Some(_), None) => false,
        (Some(a_dom), Some(b_dom)) => {
            a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
        }
    }
}

/// URI host name constraint matching (RFC 5280 §4.2.1.10).
///
/// URI constraints use different semantics from DNS constraints:
/// - Leading period: subdomains only (same as DNS).
/// - No leading period: **exact host only** (unlike DNS, which also matches subdomains).
///
/// One trailing dot is ignored on both sides (see [`strip_root_dot`]).
fn matches_uri_host(host: &str, constraint: &str) -> bool {
    let host = strip_root_dot(host);
    let constraint = strip_root_dot(constraint);
    if constraint.is_empty() {
        return false;
    }
    if let Some(parent) = constraint.strip_prefix('.') {
        // Leading dot: subdomains only, apex excluded (same rule as DNS).
        is_strict_subdomain(host, parent)
    } else {
        // RFC 5280 §4.2.1.10: URI constraint without leading period matches
        // the exact host only — subdomains are NOT included.
        host.eq_ignore_ascii_case(constraint)
    }
}

/// `a ⊆ b` for two URI host constraints (see [`subtree_within`]).
fn uri_constraint_within(a: &str, b: &str) -> bool {
    let (a, b) = (strip_root_dot(a), strip_root_dot(b));
    match (a.strip_prefix('.'), b.strip_prefix('.')) {
        (None, _) => matches_uri_host(a, b),
        // All subdomains of a domain are never inside one exact host.
        (Some(_), None) => false,
        (Some(a_dom), Some(b_dom)) => {
            a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
        }
    }
}

/// Extract the host of a URI for name-constraint matching (RFC 3986 §3.2).
///
/// Returns `None` when RFC 5280 §4.2.1.10 requires the certificate to be
/// rejected under a URI constraint: the URI "doesn't include an authority
/// component with a host name specified as a fully qualified domain name
/// ... or includes an authority component in which the host name is
/// specified as an IP address". Concretely `None` is returned for:
///
/// - no `scheme ":" "//"` prefix (e.g. `urn:`, `mailto:`), or a malformed
///   scheme;
/// - an empty host (`file:///x`);
/// - an IP-literal (`[2001:db8::1]`) or dotted-quad IPv4 host;
/// - a non-numeric port.
///
/// The authority ends at the first `/`, `?` or `#`; userinfo is everything
/// before the **last** `@` inside the authority, so an `@` in the path,
/// query or fragment cannot change the host. One trailing dot is stripped.
fn uri_host(uri: &str) -> Option<&str> {
    let (scheme, rest) = uri.split_once(':')?;
    let mut scheme_bytes = scheme.bytes();
    if !scheme_bytes.next().is_some_and(|b| b.is_ascii_alphabetic())
        || !scheme_bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
    {
        return None;
    }
    let rest = rest.strip_prefix("//")?;
    let authority = &rest[..rest.find(['/', '?', '#']).unwrap_or(rest.len())];
    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
    if host_port.starts_with('[') {
        return None; // IP-literal
    }
    let host = match host_port.split_once(':') {
        Some((host, port)) if port.bytes().all(|b| b.is_ascii_digit()) => host,
        Some(_) => return None,
        None => host_port,
    };
    let host = strip_root_dot(host);
    if host.is_empty() || is_ipv4_literal(host) {
        return None;
    }
    Some(host)
}

/// Returns true if `host` has the shape of an RFC 3986 `IPv4address`
/// (four dot-separated runs of one to three decimal digits).
fn is_ipv4_literal(host: &str) -> bool {
    let mut parts = 0usize;
    for part in host.split('.') {
        parts += 1;
        if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
            return false;
        }
    }
    parts == 4
}

/// URI name constraint matching (RFC 5280 §4.2.1.10).
///
/// Extracts the host with [`uri_host`] and applies URI host matching
/// rules. A URI without a usable host matches nothing here;
/// `check_name_constraints` rejects such URIs outright whenever a URI
/// constraint is in effect.
fn matches_uri(subject_uri: &str, constraint: &str) -> bool {
    uri_host(subject_uri).is_some_and(|host| matches_uri_host(host, constraint))
}

/// IP address name constraint matching (RFC 5280 §4.2.1.10).
///
/// `constraint_bytes` must be 8 bytes (IPv4: addr + mask) or 32 bytes (IPv6).
/// `subject_bytes` must be 4 bytes (IPv4) or 16 bytes (IPv6).
fn matches_ip_address(subject_bytes: &[u8], constraint_bytes: &[u8]) -> bool {
    let (expected_subj_len, half) = match constraint_bytes.len() {
        8 => (4usize, 4usize),
        32 => (16usize, 16usize),
        _ => return false,
    };
    if subject_bytes.len() != expected_subj_len {
        return false;
    }
    let (addr, mask) = constraint_bytes.split_at(half);
    subject_bytes
        .iter()
        .zip(addr.iter().zip(mask.iter()))
        .all(|(s, (a, m))| s & m == a & m)
}

/// `a ⊆ b` for two iPAddress constraints (address + mask, see
/// [`subtree_within`]): same address family, `b`'s mask bits are a subset
/// of `a`'s, and the two addresses agree under `b`'s mask.
fn ip_constraint_within(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() || !(a.len() == 8 || a.len() == 32) {
        return false;
    }
    let half = a.len() / 2;
    let (a_addr, a_mask) = a.split_at(half);
    let (b_addr, b_mask) = b.split_at(half);
    (0..half).all(|i| {
        a_mask[i] & b_mask[i] == b_mask[i] && a_addr[i] & b_mask[i] == b_addr[i] & b_mask[i]
    })
}

/// RFC 5280 §4.2.1.10 subtree containment for the non-`directoryName` name
/// forms.
///
/// These are pure functions over strings and byte slices, and a mutation
/// sweep found every one of them unguarded: the suite reached them only
/// through whole-chain fixtures, which never supply the degenerate inputs
/// that separate a correct comparison from a nearly-correct one.
#[cfg(test)]
mod tests_constraint_forms {
    use super::{
        ip_constraint_within, is_dns_identity_shaped, is_hostname_shaped, is_ipv4_literal,
        is_strict_subdomain, matches_dns_name, matches_ip_address, subtree_within,
        uri_constraint_within, wildcard_san_reaches_excluded_dns,
    };
    use der::Decode as _;
    use x509_cert::ext::pkix::name::GeneralName;

    /// `.example.com` is not a *strict* subdomain of `example.com`.
    ///
    /// A strict subdomain adds at least one label, so the shortest one is
    /// `a.example.com`. The guard is `name.len() > parent.len() + 1`, and
    /// both of its obvious weakenings admit this degenerate input: `>=`
    /// directly, and `*` in place of `+` because `parent.len() * 1` is
    /// `parent.len()`. The leading dot then satisfies the separator check
    /// and the suffix compares equal, so a bare `.example.com` would be
    /// reported as a subdomain of itself-with-a-dot.
    #[test]
    fn a_leading_dot_alone_is_not_a_strict_subdomain() {
        assert!(!is_strict_subdomain(".example.com", "example.com"));
        // The real thing still is.
        assert!(is_strict_subdomain("a.example.com", "example.com"));
        assert!(is_strict_subdomain("deep.a.example.com", "example.com"));
        // And a sibling that merely ends in the same bytes is not.
        assert!(!is_strict_subdomain("notexample.com", "example.com"));
    }

    /// A URI subtree contains itself.
    ///
    /// Both arms are `Some`, so the comparison is
    /// `equal || is_strict_subdomain`. With `&&` a domain would have to be a
    /// strict subdomain of itself, which nothing is, and a constraint would
    /// stop containing its own subtree.
    /// A descriptive commonName is never read as a host name.
    ///
    /// This is the false-rejection boundary: were it looser, a CA
    /// constrained to a DNS subtree could not issue a certificate whose
    /// CN is a person or an organisation, which is most certificates
    /// that carry no dNSName SAN. OpenSSL draws the line in the same
    /// place -- it accepts `CN=John Smith` under a `permitted
    /// DNS:example.com` constraint and rejects `CN=notallowed.test`.
    #[test]
    fn only_a_host_name_shaped_cn_is_read_as_one() {
        for not_a_host in [
            "John Smith",
            "Example Corp Issuing CA",
            // No label separator: a bare label is not treated as a host
            // name, matching the wildcard rule's refusal of `*.com`.
            "localhost",
            "",
            ".",
            // Empty labels.
            "a..b",
            ".leading",
            // Characters no host name carries.
            "under_score.example",
            "space in.example",
            "quote\".example",
        ] {
            assert!(
                !is_hostname_shaped(not_a_host),
                "{not_a_host:?} must not be read as a host name"
            );
        }

        for host in [
            "notallowed.test",
            "mx.good.example",
            "a.b",
            "xn--bcher-kva.example",
            "has-hyphens.example.com",
            "MixedCase.Example",
            // A trailing root dot is the same name.
            "trailing.example.",
        ] {
            assert!(is_hostname_shaped(host), "{host:?} is host-name shaped");
        }
    }

    /// The shape test must admit every spelling `pkix-identity`'s
    /// matcher can match a requested name against.
    ///
    /// That matcher honours a leftmost single `*` label whose remainder
    /// has no further `*` and contains a separator, and otherwise
    /// matches literally. Anything it can match is an identity this
    /// certificate asserts, so anything it can match must be bounded by
    /// the constraints -- and a wildcard is not host-name shaped, which
    /// is why `is_dns_identity_shaped` exists on top of
    /// [`is_hostname_shaped`].
    #[test]
    fn a_wildcard_cn_is_also_read_as_a_dns_identity() {
        for wildcard in ["*.example.com", "*.good.example", "*.a.b"] {
            assert!(
                !is_hostname_shaped(wildcard),
                "precondition: a wildcard is not itself host-name shaped"
            );
            assert!(
                is_dns_identity_shaped(wildcard),
                "{wildcard:?} can match a requested name, so it must be bounded"
            );
        }

        // Spellings that matcher refuses, so they assert nothing.
        for refused in [
            // Remainder has no separator.
            "*.com",
            // Embedded second wildcard.
            "*.foo.*.com",
            // Not leftmost.
            "foo.*.example.com",
            "www*.example.com",
            "*",
            "*.",
        ] {
            assert!(
                !is_dns_identity_shaped(refused),
                "{refused:?} matches no requested name"
            );
        }
    }

    /// CVE-2025-61727: the wildcard stands for the excluded name.
    ///
    /// `root -> ICA (exclude bar.example.com) -> EE (SAN *.example.com)`
    /// with `bar.example.com` requested. The SAN's spelling is not
    /// within the excluded subtree, so the literal comparison permits
    /// it, and RFC 9525 then lets it authenticate the one name the CA
    /// was forbidden to certify.
    #[test]
    fn a_wildcard_san_cannot_evade_a_dns_exclusion() {
        assert!(
            wildcard_san_reaches_excluded_dns("*.example.com", "bar.example.com"),
            "the wildcard stands for bar.example.com, which is excluded"
        );
        // The literal comparison is the one that misses it, which is why
        // the check above has to exist.
        assert!(
            !matches_dns_name("*.example.com", "bar.example.com"),
            "precondition: the spelling is not within the excluded subtree"
        );
    }

    /// The wildcard replaces exactly one label, so a deeper exclusion is
    /// out of its reach and must stay permitted.
    #[test]
    fn a_wildcard_san_does_not_reach_past_one_label() {
        for excluded in [
            "foo.bar.example.com",
            "a.b.c.example.com",
            // A leading period covers only strict subdomains of its
            // apex, which the wildcard cannot reach either.
            ".bar.example.com",
        ] {
            assert!(
                !wildcard_san_reaches_excluded_dns("*.example.com", excluded),
                "*.example.com cannot authenticate anything inside {excluded}"
            );
        }
    }

    /// An exclusion at or above the wildcard's own parent is already
    /// caught by the literal comparison, so both agree it is a
    /// violation and neither relies on the other.
    #[test]
    fn an_exclusion_above_the_wildcard_is_caught_literally() {
        for excluded in ["example.com", ".example.com", "com"] {
            assert!(
                matches_dns_name("*.example.com", excluded),
                "the spelling of *.example.com is already within {excluded}"
            );
        }
    }

    /// A spelling `pkix-identity` will not honour authenticates nothing,
    /// so it reaches nothing. Mirroring its rule is what keeps the two
    /// from disagreeing.
    #[test]
    fn a_san_that_matches_no_name_reaches_no_exclusion() {
        for san in [
            // Not a leftmost wildcard.
            "foo.*.example.com",
            "www*.example.com",
            // Embedded second wildcard.
            "*.foo.*.com",
            // No label separator in the remainder: `*.com` is refused.
            "*.com",
            // Bare wildcard.
            "*.",
            // Not a wildcard at all: the literal path handles these.
            "bar.example.com",
        ] {
            assert!(
                !wildcard_san_reaches_excluded_dns(san, "bar.example.com"),
                "{san} authenticates no name, so it reaches no exclusion"
            );
        }
    }

    /// Case and a trailing root dot do not change what a name reaches.
    #[test]
    fn wildcard_reach_ignores_case_and_the_root_dot() {
        assert!(wildcard_san_reaches_excluded_dns(
            "*.EXAMPLE.com",
            "BAR.example.COM"
        ));
        assert!(wildcard_san_reaches_excluded_dns(
            "*.example.com.",
            "bar.example.com"
        ));
        assert!(wildcard_san_reaches_excluded_dns(
            "*.example.com",
            "bar.example.com."
        ));
    }

    #[test]
    fn a_uri_subtree_contains_itself_and_its_subdomains() {
        assert!(uri_constraint_within(".example.com", ".example.com"));
        assert!(uri_constraint_within(".a.example.com", ".example.com"));
        assert!(!uri_constraint_within(".example.com", ".a.example.com"));
    }

    /// `is_ipv4_literal` rejects an empty label and an over-long one.
    ///
    /// The three conditions are joined by `||`, so turning either into `&&`
    /// makes one of them reachable only together with the next: an empty
    /// label stops being rejected, or a four-digit label does.
    #[test]
    fn an_ipv4_literal_needs_one_to_three_digits_per_label() {
        assert!(is_ipv4_literal("192.0.2.1"));
        assert!(
            !is_ipv4_literal("1..2.3"),
            "an empty label is not a digit run"
        );
        assert!(
            !is_ipv4_literal("1234.1.1.1"),
            "four digits is outside one-to-three, all-digits notwithstanding"
        );
        assert!(!is_ipv4_literal("a.b.c.d"));
    }

    /// `matches_ip_address` handles IPv6 constraints, not only IPv4.
    ///
    /// The length match has an arm for 8 bytes (IPv4 address + mask) and one
    /// for 32 (IPv6). Deleting the 32-byte arm sends every IPv6 constraint
    /// to `_ => return false`, so an excluded IPv6 subtree would stop
    /// excluding and a permitted one would stop permitting.
    #[test]
    fn an_ipv6_constraint_is_matched() {
        // 2001:db8::/32 as constraint (16 address + 16 mask), subject
        // 2001:db8::1.
        let mut constraint = [0u8; 32];
        constraint[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
        constraint[16..20].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
        let mut subject = [0u8; 16];
        subject[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
        subject[15] = 1;
        assert!(matches_ip_address(&subject, &constraint));

        // Outside the prefix.
        let mut other = [0u8; 16];
        other[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb9]);
        assert!(!matches_ip_address(&other, &constraint));

        // IPv4 still works, so this is about the arm and not the function.
        let v4_constraint = [192, 0, 2, 0, 255, 255, 255, 0];
        assert!(matches_ip_address(&[192, 0, 2, 7], &v4_constraint));
        assert!(!matches_ip_address(&[192, 0, 3, 7], &v4_constraint));
    }

    /// `ip_constraint_within` accepts both lengths it documents.
    ///
    /// The guard is `a.len() != b.len() || !(a.len() == 8 || a.len() == 32)`.
    /// Either comparison flipped to `!=` turns the negation into a refusal
    /// of exactly the family that comparison names, so both families are
    /// here: 8 bytes is the IPv4 case the function is most used for, and 32
    /// the IPv6 one, where the refusal would be silent because an
    /// `ip_constraint_within` that answers `false` reports "not contained"
    /// rather than "could not tell".
    #[test]
    fn an_ip_constraint_is_within_a_shorter_prefix_of_either_family() {
        // 192.0.2.0/24 inside 192.0.0.0/16: b's mask bits are a subset of
        // a's, and the addresses agree under b's mask.
        let a = [192, 0, 2, 0, 255, 255, 255, 0];
        let b = [192, 0, 0, 0, 255, 255, 0, 0];
        assert!(ip_constraint_within(&a, &b));
        assert!(!ip_constraint_within(&b, &a), "the wider one is not inside");

        // 2001:db8:1::/48 inside 2001:db8::/32, the same relation in the
        // 32-byte form.
        let mut a6 = [0u8; 32];
        a6[..6].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01]);
        a6[16..22].copy_from_slice(&[0xff; 6]);
        let mut b6 = [0u8; 32];
        b6[..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
        b6[16..20].copy_from_slice(&[0xff; 4]);
        assert!(ip_constraint_within(&a6, &b6));
        assert!(
            !ip_constraint_within(&b6, &a6),
            "the wider one is not inside"
        );

        // Mismatched family lengths are not comparable.
        let v6 = [0u8; 32];
        assert!(!ip_constraint_within(&a, &v6));
    }

    /// Only 8 and 32 bytes are iPAddress *constraints*.
    ///
    /// A 16-byte value is a bare IPv6 address with no mask, and a 4-byte
    /// one a bare IPv4 address. Accepted, the function would read the
    /// second half of the value as the mask: two all-zero 16-byte blobs
    /// would then contain each other, which is the widest possible
    /// subtree. The guard refuses them, and the length it rejects them for
    /// is why both `== 8` and `== 32` have to be comparisons against the
    /// lengths they name.
    #[test]
    fn an_address_without_a_mask_is_not_a_constraint() {
        fn refused<const N: usize>() {
            let bare = [0u8; N];
            assert!(
                !ip_constraint_within(&bare, &bare),
                "{N} bytes is not an address-plus-mask constraint"
            );
        }
        refused::<0>();
        refused::<4>();
        refused::<16>();
        refused::<17>();
        refused::<64>();
    }

    /// `subtree_within` routes two `directoryName`s to the DN comparison.
    ///
    /// Deleting that match arm sends them to the catch-all, so a
    /// `directoryName` constraint would stop containing anything — including
    /// itself.
    #[test]
    fn two_directory_names_are_compared_as_dns() {
        // C=US  and  C=US,O=Test
        const C_US: &[u8] = &[
            0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
            0x53,
        ];
        const C_US_O_TEST: &[u8] = &[
            0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
            0x53, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65,
            0x73, 0x74,
        ];
        let dn = |der: &[u8]| {
            GeneralName::DirectoryName(
                x509_cert::name::Name::from_der(der).expect("hand-built Name parses"),
            )
        };

        assert!(subtree_within(&dn(C_US_O_TEST), &dn(C_US)));
        assert!(subtree_within(&dn(C_US), &dn(C_US)));
        assert!(!subtree_within(&dn(C_US), &dn(C_US_O_TEST)));
    }
}

// ---------------------------------------------------------------------------
// RSA key size helper (PKIX-ken.1.5)
// ---------------------------------------------------------------------------

use verifiers::{OID_RSA_ENCRYPTION, OID_RSASSA_PSS};

/// Decode the RSA modulus from an SPKI and return its bit length.
///
/// Both `rsaEncryption` and `id-RSASSA-PSS` subject keys count as RSA: RFC
/// 4055 §1.2 encodes the public key identically (`RSAPublicKey`) under
/// either OID, and only the algorithm-identifier parameters differ.
///
/// Returns `None` when:
/// - the key algorithm OID is neither `rsaEncryption` nor `id-RSASSA-PSS`
///   (non-RSA key; check does not apply), or
/// - the SPKI bytes cannot be decoded (malformed; signature verification will also fail).
///
/// Uses `der::SliceReader` and `der::asn1::UintRef` from the existing `der`
/// dependency — no additional crate required.
///
/// `RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }` (RFC 3279 §2.3.1).
/// `UintRef::as_bytes()` strips the leading 0x00 sign byte from a DER unsigned INTEGER,
/// returning only the magnitude. Bit length is derived as `magnitude_bytes * 8`, which
/// over-counts by at most 7 bits for keys whose high magnitude byte has leading zero bits —
/// this lenient rounding is acceptable for a minimum-floor check: a real 2040-bit key
/// would measure as 2048 bits and pass a 2048-bit floor. Key-generation tools always
/// produce keys whose top bit is set, so the practical impact is zero.
fn rsa_public_key_bits(spki: &spki::SubjectPublicKeyInfoOwned) -> Option<u32> {
    use der::{Reader, asn1::UintRef};

    if spki.algorithm.oid != OID_RSA_ENCRYPTION && spki.algorithm.oid != OID_RSASSA_PSS {
        return None; // Non-RSA key: check does not apply.
    }
    // BitString::as_bytes() returns None when unused_bits != 0.
    // RSA SPKI subject_public_key is always octet-aligned (unused_bits = 0).
    let raw = spki.subject_public_key.as_bytes()?;

    // raw is a DER-encoded RSAPublicKey SEQUENCE.
    // RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }
    //
    // We decode the modulus INTEGER and then skip the publicExponent so the
    // sequence reader does not complain about trailing data (der 0.7 requires
    // the closure to consume the entire SEQUENCE content).
    //
    // Skip strategy: read the modulus, then call tlv_bytes() to consume the
    // exponent TLV as a raw byte slice (no allocation, no decode required).
    let modulus_byte_len: usize = der::SliceReader::new(raw)
        .ok()?
        .sequence(|r| {
            // UintRef strips the leading 0x00 sign byte; as_bytes() returns magnitude only.
            let modulus: UintRef<'_> = r.decode()?;
            let modulus_len = modulus.as_bytes().len();
            // Consume the publicExponent TLV so the nested reader has no trailing data.
            let _ = r.tlv_bytes()?;
            Ok::<_, der::Error>(modulus_len)
        })
        .ok()?;

    // saturating_mul guards against overflow on a hypothetical absurdly large modulus.
    // The result fits in u32: the largest practical RSA key is 16384 bits (2048 bytes),
    // well within u32::MAX. u32::try_from is used to make the bound explicit.
    u32::try_from(modulus_byte_len.saturating_mul(8)).ok()
}

// ---------------------------------------------------------------------------
// Chain walk loop — signature verification and name linkage (PKIX-vxf)
// ---------------------------------------------------------------------------

/// Walk the chain from issuer to leaf, applying all RFC 5280 §6.1 per-cert checks.
///
/// Path-length and anchor-matching are handled by the caller (`validate_path`).
/// This function walks `chain` in reverse (issuer-to-leaf) against `anchor`:
///
///    a. Verify signature with the current issuer's SPKI.
///    b. Verify issuer/subject name linkage.
///    c. Check validity period against `policy.current_time_unix`.
///    d. Reject any unhandled critical extensions.
///    e. Check cert names (subject DN + SAN) against accumulated NC state.
///    f. For all certs except the leaf (i > 0): require `BasicConstraints` cA=TRUE.
///    g. For all certs except the leaf (i > 0): if `policy.enforce_key_usage`, require `keyCertSign`.
///    g'. For all certs except the leaf (i > 0): if `policy.require_crl_sign_on_cas`, require `cRLSign`.
///    h. For all certs except the leaf (i > 0): enforce `pathLenConstraint` if present.
///    i. For all certs except the leaf (i > 0): accumulate `NameConstraints` state
///       (INTERSECTION for permittedSubtrees, UNION for excludedSubtrees).
///
/// RFC 5280 §4.2.1.9 note on pathLenConstraint: for the cert at position `i`
/// (leaf at 0, root-adjacent at chain.len()-1), there are exactly `i-1`
/// intermediate certs below it. The constraint requires `i-1 ≤ pathLenConstraint`.
///
/// # Implementation notes
///
/// This function is intentionally structured as a single loop over the certificate
/// chain. The RFC 5280 §6.1 state machine has significant shared state (working
/// SPKI, name constraints, policy tree, inhibit flags) that must be threaded
/// through every step in a defined order. Decomposing the loop into smaller helpers
/// would require passing this state through many function boundaries without clarity
/// gain. The monolithic structure mirrors the RFC's sequential algorithm description
/// and keeps all state-mutation sites visible in one place for audit.
///
/// The per-walk mutable state is grouped into [`WorkingState`] to make the
/// state-machine inputs/outputs explicit at the call boundary. Future
/// per-substep helper extractions take a `&mut WorkingState` so that adding
/// helpers does not grow each helper's parameter list.
///
/// `working_spki` and `working_issuer_name` carry the borrow of either `anchor`
/// or some `chain[i]` and so the struct takes a single lifetime `'a` covering
/// both inputs. The lifetime is elided at the call site because `chain_walk`
/// constructs and consumes `WorkingState` within its own body.
///
/// RFC 5280 §6.1.2 maps to the struct fields as follows:
///
/// - `working_spki`, `working_issuer_name`
///   — §6.1.2(d)/(f) `working_public_key` + §6.1.2(e) `working_issuer_name`.
/// - `nc_permitted`, `nc_excluded`, `nc_constrained_types`
///   — §6.1.2(b)/(c) `permitted_subtrees`/`excluded_subtrees`. The
///   `nc_constrained_types` bitmask is a workspace addition: it tracks which
///   name types have *ever* been constrained by a CA so an empty post-
///   intersection set still rejects names of that type (not derivable from
///   `nc_permitted` contents alone).
/// - `explicit_policy`, `inhibit_any`, `policy_mapping`
///   — §6.1.2 `explicit_policy`, `inhibit_anyPolicy`, `policy_mapping` counters.
/// - `policy_tree`
///   — §6.1.2(a) `valid_policy_tree`. `None` represents the RFC NULL tree.
struct WorkingState<'a> {
    /// §6.1.2(d)/(f) `working_public_key`. Borrows from the trust anchor or a
    /// chain certificate; rebound to the just-validated cert's SPKI at the end
    /// of every loop iteration.
    working_spki: &'a spki::SubjectPublicKeyInfoOwned,
    /// §6.1.2(e) `working_issuer_name`. Borrows from the trust anchor or a
    /// chain certificate's subject; rebound at the end of every loop iteration.
    working_issuer_name: &'a x509_cert::name::Name,
    /// §6.1.2(b) `permitted_subtrees`. `None` means "no permitted constraint
    /// of any type has been imposed yet"; once any CA contributes a
    /// `permittedSubtrees`, this becomes `Some(...)` and only narrows
    /// (intersection per §6.1.4(g)).
    nc_permitted: Option<GeneralSubtrees>,
    /// §6.1.2(c) `excluded_subtrees`. Accumulates via union per §6.1.4(g).
    nc_excluded: GeneralSubtrees,
    /// Workspace-local invariant: bitmask of name types for which at least one
    /// CA has imposed a `permittedSubtrees` constraint. Bits are only ORed in,
    /// never cleared. Required for correct rejection when intersection of
    /// incompatible same-type constraints empties `nc_permitted` for a type
    /// while that type is still semantically forbidden. See the initialisation
    /// site in `chain_walk` for the long-form rationale.
    nc_constrained_types: NcTypeMask,
    /// §6.1.2 `explicit_policy` counter. Decremented by §6.1.4(h) on each
    /// non-self-issued intermediate; clamped by §6.1.4(i) PolicyConstraints
    /// `requireExplicitPolicy`; finalised by §6.1.5(a)+(b).
    explicit_policy: u32,
    /// §6.1.2 `inhibit_anyPolicy` counter. Decremented by §6.1.4(h);
    /// clamped by §6.1.4(j) `InhibitAnyPolicy`.
    inhibit_any: u32,
    /// §6.1.2 `policy_mapping` counter. Decremented by §6.1.4(h);
    /// clamped by §6.1.4(i) PolicyConstraints `inhibitPolicyMapping`.
    policy_mapping: u32,
    /// §6.1.2(a) `valid_policy_tree`. `None` represents the RFC's NULL tree
    /// (every transition that would empty the tree maps to `None`); a
    /// non-empty `Some(...)` carries the live policy graph. Returned to
    /// `validate_path` at §6.1.5 for post-validation qualifier extraction.
    policy_tree: Option<policy_graph::PolicyGraph>,
}

/// RFC 5280 §6.1.3(a)(1) preface — project-policy signature-algorithm allowlist.
///
/// Fires before the cryptographic signature check so that a chain whose only
/// problem is a disallowed algorithm returns the diagnostic
/// [`Error::AlgorithmNotAllowed`] rather than the confusing
/// [`Error::SignatureInvalid`]. Applies to every cert in the chain (CA/B Forum
/// profile intent — there is no leaf/intermediate distinction here). Uses the
/// outer `signatureAlgorithm` OID; RFC 5280 §4.1.1.2 requires it to equal the
/// inner `TBSCertificate.signature` OID.
fn enforce_signature_alg_allowlist(
    cert: &Certificate,
    policy: &ValidationPolicy,
    index: usize,
) -> Result<()> {
    if let Some(allowed) = &policy.allowed_signature_algs {
        // O(n) over a typically 2–6 element list; acceptable for the common case.
        if !allowed.contains(&cert.signature_algorithm().oid) {
            return Err(Error::AlgorithmNotAllowed { index });
        }
    }
    Ok(())
}

/// Project max-validity check.
///
/// Not part of RFC 5280 §6.1; this is a CA/B-Forum-style ceiling on the cert's
/// (notAfter − notBefore) duration. Applies to every cert in the chain.
///
/// `saturating_sub` avoids wrap on a malformed cert where `notAfter < notBefore`;
/// a resulting duration of 0 trivially passes the `> max_secs` test (safe — the
/// validity-period check in §6.1.3(a)(2) catches the malformed cert separately).
fn check_max_validity(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
    if let Some(max_secs) = policy.max_validity_secs {
        let not_before = cert
            .tbs_certificate()
            .validity()
            .not_before
            .to_unix_duration()
            .as_secs();
        let not_after = cert
            .tbs_certificate()
            .validity()
            .not_after
            .to_unix_duration()
            .as_secs();
        if not_after.saturating_sub(not_before) > max_secs {
            return Err(Error::ValidityPeriodExceedsMax { index });
        }
    }
    Ok(())
}

/// Project minimum-RSA-key-bits check.
///
/// Not part of RFC 5280 §6.1; a deployment-policy floor on RSA modulus size.
/// Non-RSA keys are silently skipped (`rsa_public_key_bits` returns `None`),
/// so this is RSA-specific and inert for ECDSA/EdDSA chains. Applies to every
/// cert in the chain.
fn check_min_rsa_bits(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
    // A non-RSA key makes `rsa_public_key_bits` return `None`, so the
    // chain stops there and the check is silently skipped -- which is
    // the documented behaviour, not an oversight.
    if let Some(min_bits) = policy.min_rsa_key_bits
        && let Some(actual_bits) =
            rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info())
        && actual_bits < min_bits
    {
        return Err(Error::KeyTooSmall { index });
    }
    Ok(())
}

/// RFC 5280 §6.1.3(a)(2) — issuer/subject DN linkage.
///
/// Verifies that the cert's issuer DN matches the previously-validated
/// cert's (or trust anchor's) subject DN.
///
/// # There is no SubjectAltName exception here
///
/// This check used to be skipped when the working issuer had an empty
/// Subject and a critical SAN, on the reading that §4.2.1.6 makes the SAN
/// such a certificate's identity, so comparing against an empty DN says
/// nothing. The accommodation was wrong, and it was a name-chaining
/// bypass: a leaf naming `CN=anyone` as its issuer validated against an
/// unnamed CA, because the only check that would have caught the
/// mismatch was the one being skipped.
///
/// §4.2.1.6 governs how the certificate's own *subject entity* is
/// identified. It does not reach §6.1.3(a)(4), which compares DNs and has
/// no SAN provision, and it is overridden for this case by §4.1.2.6: "If
/// the subject is a CA [...] then the subject field MUST be populated
/// with a non-empty distinguished name". A certificate that is the
/// working issuer has issued the one being checked, so it is a CA and
/// that MUST applies. §4.1.2.4 closes it from the other side: every
/// certificate's issuer field "MUST contain a non-empty distinguished
/// name", so a certificate needing an empty issuer to chain is itself
/// non-conforming.
///
/// An unnamed CA is now refused outright -- [`AnchorDefect::EmptySubject`]
/// as an anchor, [`Error::CaEmptySubject`] inside a path -- so no chain
/// that this skip used to admit is admitted by any other route.
fn check_issuer_linkage(
    cert: &Certificate,
    working_issuer_name: &x509_cert::name::Name,
    index: usize,
) -> Result<()> {
    if !names_match(working_issuer_name, cert.tbs_certificate().issuer()) {
        return Err(Error::ChainBroken { index });
    }
    Ok(())
}

/// Locates the `TBSCertificate` inside a certificate's own DER and returns
/// it as a subslice: the exact bytes the issuer signed.
///
/// Prefer this to [`tbs_certificate_der`] wherever the certificate's DER is
/// still in hand, which it is for anything read from a file, a socket, a
/// trust store or an AIA fetch. It allocates nothing, does no decoding
/// beyond two headers, and — the reason it exists — it cannot be wrong,
/// because it does not rebuild anything.
///
/// # Why re-encoding is not equivalent
///
/// A signature is over bytes, not over a parsed structure. Recovering
/// those bytes from a parsed certificate requires the encoder to be
/// byte-faithful for every field, for every input the decoder accepted.
/// That has already failed once here: x509-cert 0.3 re-encodes a
/// `Certificate`'s validity times under the RFC 5280 profile, turning a
/// pre-2050 `GeneralizedTime` into a `UTCTime`, which is why
/// [`tbs_certificate_der`] carries a hand-written encoder that keeps each
/// time as it was parsed. Every other field is assumed faithful. That
/// assumption cannot be checked in general, and a great deal rests on it:
/// a `SET OF` the
/// encoder sorts, a `DEFAULT` it omits or an integer it minimises
/// differently would each produce a correct-looking certificate whose
/// signature does not verify.
///
/// This function removes the assumption rather than adding to it.
///
/// # ASN.1
///
/// `Certificate ::= SEQUENCE { tbsCertificate TBSCertificate, ... }`, so
/// the signed bytes are the first TLV inside the outer `SEQUENCE`, header
/// included.
///
/// # Errors
///
/// Returns [`DerError`] if `cert_der` does not begin with a `SEQUENCE`
/// whose first element is a complete TLV. It does *not* validate the
/// certificate: a caller wanting both should use [`CertificateWithDer`],
/// which parses and slices together and so cannot hold one certificate's
/// bytes beside another's parse.
pub fn tbs_der_slice(cert_der: &[u8]) -> core::result::Result<&[u8], DerError> {
    use der::{Decode as _, Header, Reader as _, SliceReader, Tag};

    let mut reader = SliceReader::new(cert_der).map_err(DerError::new)?;
    let outer = Header::decode(&mut reader).map_err(DerError::new)?;
    if outer.tag() != Tag::Sequence {
        return Err(DerError::new(Tag::Sequence.value_error().to_error()));
    }
    // Positioned at the first element of the outer SEQUENCE, which in a
    // certificate is the TBSCertificate. The tag is checked even though
    // this function does not validate the certificate, because returning
    // whatever happens to be first would be a worse kind of not-validating:
    // the caller would get bytes, not an error, and verify a signature over
    // them.
    let inner = Header::peek(&reader).map_err(DerError::new)?;
    if inner.tag() != Tag::Sequence {
        return Err(DerError::new(
            inner.tag().unexpected_error(Some(Tag::Sequence)).to_error(),
        ));
    }
    // `tlv_bytes` returns the header and the value together.
    reader.tlv_bytes().map_err(DerError::new)
}

/// A certificate together with the DER it was decoded from.
///
/// Hand this to [`validate_path`] instead of a bare [`Certificate`] and
/// signature verification uses the bytes the issuer actually signed, taken
/// as a subslice, rather than rebuilding them with an encoder. That is both
/// faster — re-encoding was measured at 59% of everything path validation
/// does — and not subject to the faithfulness assumption described on
/// [`tbs_der_slice`].
///
/// Generic over the byte container so it costs nothing it need not: `&[u8]`
/// to borrow a buffer the caller owns, `Vec<u8>` to take ownership, or any
/// other `AsRef<[u8]>`.
///
/// # Examples
///
/// ```
/// # use pkix_path::CertificateWithDer;
/// # fn f(der: &[u8]) -> Result<(), Box<dyn core::error::Error>> {
/// let held = CertificateWithDer::from_der(der)?;
/// assert_eq!(held.certificate().tbs_certificate().version(), Default::default());
/// // The signed bytes are a subslice of what was handed in.
/// assert!(held.tbs_der().len() < der.len());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct CertificateWithDer<T> {
    der: T,
    cert: Certificate,
    /// Offsets of the `TBSCertificate` TLV within `der`, established once
    /// in [`CertificateWithDer::from_der`] and never recomputed.
    tbs: core::ops::Range<usize>,
}

impl<T: AsRef<[u8]>> CertificateWithDer<T> {
    /// Decodes `der` and remembers where its `TBSCertificate` is.
    ///
    /// Parsing and slicing happen together, which is the point: a
    /// constructor that accepted a `Certificate` and some bytes separately
    /// could be handed one certificate's parse beside another's DER, and
    /// the signature check would then verify the wrong message against the
    /// right key.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Der`] if `der` is not a single DER-encoded
    /// certificate, trailing bytes included.
    pub fn from_der(der: T) -> Result<Self> {
        use der::Decode as _;

        let bytes = der.as_ref();
        let cert = Certificate::from_der(bytes).map_err(|e| Error::Der(DerError::new(e)))?;
        let tbs = tbs_der_slice(bytes).map_err(Error::Der)?;
        // `tbs` is a subslice of `bytes`, so this arithmetic is exact.
        let start = tbs.as_ptr() as usize - bytes.as_ptr() as usize;
        Ok(Self {
            cert,
            tbs: start..start + tbs.len(),
            der,
        })
    }

    /// The parsed certificate.
    #[must_use]
    pub fn certificate(&self) -> &Certificate {
        &self.cert
    }

    /// The whole certificate's DER, as supplied.
    #[must_use]
    pub fn der(&self) -> &[u8] {
        self.der.as_ref()
    }

    /// The `TBSCertificate` bytes the issuer signed.
    #[must_use]
    pub fn tbs_der(&self) -> &[u8] {
        &self.der.as_ref()[self.tbs.clone()]
    }

    /// Gives back the container and the parse.
    #[must_use]
    pub fn into_parts(self) -> (T, Certificate) {
        (self.der, self.cert)
    }
}

/// Builds a path element from a certificate's DER.
///
/// Separate from [`PathCertificate`] because that trait is implemented for
/// `&C` as well, and a reference can be read but not constructed. A
/// generic that both reads path elements and makes new ones from bytes --
/// AIA reassembly, which fetches DER and adds it to a candidate pool --
/// needs both bounds.
///
/// The implementations differ in exactly one respect, which is the whole
/// point: [`Certificate`] parses the bytes and drops them,
/// [`CertificateWithDer`] parses them and keeps them.
///
/// # A borrowing container cannot implement this
///
/// `CertificateWithDer<&[u8]>` can be read as a path element but cannot be
/// built from a certificate that has just been fetched, because the
/// response buffer does not outlive the call that produced it. That is a
/// fact about lifetimes rather than an omission: anything reassembling a
/// chain from the network needs an owning container, which is what a
/// caller fetching certificates has anyway. [`validate_path`] never
/// constructs an element and so never asks for this bound; the entry
/// points in `pkix-chain` that may reassemble a chain do.
pub trait DecodeCertificate: Sized {
    /// Decodes one DER-encoded certificate.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Der`] if `der` is not exactly one DER-encoded
    /// certificate.
    fn decode_certificate(der: Vec<u8>) -> Result<Self>;
}

impl DecodeCertificate for Certificate {
    fn decode_certificate(der: Vec<u8>) -> Result<Self> {
        use der::Decode as _;

        Certificate::from_der(&der).map_err(|e| Error::Der(DerError::new(e)))
    }
}

impl<T> DecodeCertificate for CertificateWithDer<T>
where
    T: AsRef<[u8]> + From<Vec<u8>>,
{
    fn decode_certificate(der: Vec<u8>) -> Result<Self> {
        Self::from_der(T::from(der))
    }
}

/// What [`validate_path`] accepts as a certificate in the path.
///
/// Implemented for [`Certificate`], so a caller holding nothing but parsed
/// certificates works unchanged, and for [`CertificateWithDer`], which also
/// carries the bytes. The only difference between the two is whether
/// [`PathCertificate::signed_tbs`] can answer.
pub trait PathCertificate {
    /// The certificate itself.
    fn certificate(&self) -> &Certificate;

    /// The certificate's own DER, when the element kept it.
    ///
    /// `None` means it did not. This is the one thing an implementation
    /// has to decide; [`signed_tbs`](PathCertificate::signed_tbs) is
    /// derived from it by default, so the two cannot disagree.
    ///
    /// What is returned must be the bytes the certificate was decoded
    /// from, not a re-encoding of it. Anything that hashes a certificate
    /// -- DANE's TLSA matching, a certificate fingerprint, a pinned
    /// SPKI -- is comparing against octets someone else produced, and a
    /// re-encoding is a different certificate as far as those comparisons
    /// are concerned.
    fn certificate_der(&self) -> Option<&[u8]> {
        None
    }

    /// The exact `TBSCertificate` bytes the issuer signed, when they are
    /// available.
    ///
    /// `None` means they are not, and [`validate_path`] will rebuild them
    /// with [`tbs_certificate_der`] — which works for every certificate
    /// seen so far and rests on an assumption that cannot be checked in
    /// general. See [`tbs_der_slice`] for what the assumption is.
    ///
    /// An implementation that returns `Some` must return the bytes from the
    /// certificate's own encoding. Returning anything else makes the
    /// signature check verify the wrong message.
    ///
    /// The default locates them inside
    /// [`certificate_der`](PathCertificate::certificate_der), which is
    /// correct for anything that kept its bytes and costs two header
    /// reads per call. An implementation holding the offsets already
    /// should override it and hand them over.
    fn signed_tbs(&self) -> Option<&[u8]> {
        tbs_der_slice(self.certificate_der()?).ok()
    }
}

impl PathCertificate for Certificate {
    fn certificate(&self) -> &Certificate {
        self
    }
}

impl<T: AsRef<[u8]>> PathCertificate for CertificateWithDer<T> {
    fn certificate(&self) -> &Certificate {
        &self.cert
    }

    fn certificate_der(&self) -> Option<&[u8]> {
        Some(self.der())
    }

    fn signed_tbs(&self) -> Option<&[u8]> {
        // Overridden: the offsets were established once in `from_der`.
        Some(self.tbs_der())
    }
}

impl<C: PathCertificate> PathCertificate for &C {
    fn certificate(&self) -> &Certificate {
        (*self).certificate()
    }

    fn certificate_der(&self) -> Option<&[u8]> {
        (*self).certificate_der()
    }

    fn signed_tbs(&self) -> Option<&[u8]> {
        (*self).signed_tbs()
    }
}

/// A path element that definitely kept the certificate's own DER.
///
/// [`PathCertificate::certificate_der`] returns an `Option` because a bare
/// [`Certificate`] has nothing to return. This is the half of it that
/// cannot be `None`, for callers that *require* the received octets rather
/// than merely preferring them.
///
/// DANE is the case this exists for. TLSA matching compares a hash of the
/// certificate against one a domain operator published from their own
/// certificate file, so a DANE verifier without the received bytes cannot
/// do its job at all -- and re-deriving them from the parse is not a
/// degraded answer but a wrong one, for the same reason
/// [`tbs_der_slice`] exists. Asking for the bytes in the bound says that
/// once, in the signature, instead of as a runtime check every caller has
/// to be told about.
pub trait RetainedCertificate: PathCertificate {
    /// The certificate as it was received, octet for octet.
    ///
    /// Must equal what [`PathCertificate::certificate_der`] returns.
    fn der(&self) -> &[u8];
}

impl<T: AsRef<[u8]>> RetainedCertificate for CertificateWithDer<T> {
    fn der(&self) -> &[u8] {
        self.der.as_ref()
    }
}

impl<C: RetainedCertificate> RetainedCertificate for &C {
    fn der(&self) -> &[u8] {
        (*self).der()
    }
}

/// Rebuilds the DER encoding of `cert`'s `TBSCertificate`: the bytes its
/// issuer signed.
///
/// **Prefer [`tbs_der_slice`] when the certificate's DER is still in
/// hand.** This function reconstructs the signed bytes from the parse,
/// which is slower and rests on an assumption; the slice takes them from
/// the certificate's own encoding and rests on nothing. Reach for this one
/// only when the bytes are genuinely gone.
///
/// Use this, not `cert.tbs_certificate().to_der()`. x509-cert 0.3
/// re-encodes the validity times of a `Certificate` under the RFC 5280
/// profile (dates before 2050 become `UTCTime`), so a certificate whose
/// issuer used `GeneralizedTime` for such a date would no longer match its
/// signature. This function keeps each time in the form it was parsed
/// from; every other field is re-encoded as DER, which reproduces the
/// original bytes for any DER-encoded certificate.
///
/// That last clause is the assumption. It holds for every certificate this
/// workspace has met, and it is not a theorem: it requires the encoder to
/// be byte-faithful for every field, for every input the decoder accepted.
/// The validity-time special case above is what it looks like when the
/// assumption fails, and nothing says where the next one is.
/// `tests/tbs_retention.rs` pins the two functions agreeing, so a
/// divergence becomes a finding rather than a signature failure on a sound
/// certificate.
///
/// # Errors
///
/// Returns [`DerError`] if a field cannot be encoded.
pub fn tbs_certificate_der(cert: &Certificate) -> core::result::Result<Vec<u8>, DerError> {
    encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
        .map_err(DerError::new)
}

/// Encodes `tbs` with `extensions` in place of its own extensions and with
/// its validity times as parsed (see [`tbs_certificate_der`]).
///
/// `pkix-ct` uses the `extensions` override to rebuild a precertificate's
/// TBS without the SCT list (RFC 6962 §3.2).
#[doc(hidden)]
pub fn encode_tbs_certificate(
    tbs: &x509_cert::TbsCertificate,
    extensions: Option<&x509_cert::ext::Extensions>,
) -> der::Result<Vec<u8>> {
    use der::asn1::ContextSpecificRef;
    use der::{Encode as _, Header, Length, Tag, TagMode, TagNumber};

    fn push_sequence(out: &mut Vec<u8>, body: &[u8]) -> der::Result<()> {
        Header::new(Tag::Sequence, Length::try_from(body.len())?).encode_to_vec(out)?;
        out.extend_from_slice(body);
        Ok(())
    }

    // A capacity hint, not a length: extensions dominate a modern
    // certificate's TBS -- a leaf with a large subjectAltName runs to
    // kilobytes -- and growing `body` from empty reallocates and copies it
    // through every doubling on the way there. Summing the extension
    // values is O(number of extensions) and gets the right order of
    // magnitude; the 512 covers the names, the SPKI and the fixed fields.
    // Being wrong in either direction costs nothing but a reallocation.
    let hint = extensions.map_or(0, |exts| {
        exts.iter()
            .map(|e| e.extn_value.as_bytes().len() + 16)
            .sum::<usize>()
    }) + 512;
    let mut body = Vec::with_capacity(hint);
    if tbs.version() != x509_cert::certificate::Version::V1 {
        ContextSpecificRef {
            tag_number: TagNumber(0),
            tag_mode: TagMode::Explicit,
            value: &tbs.version(),
        }
        .encode_to_vec(&mut body)?;
    }
    tbs.serial_number().encode_to_vec(&mut body)?;
    tbs.signature().encode_to_vec(&mut body)?;
    tbs.issuer().encode_to_vec(&mut body)?;
    let mut validity = Vec::new();
    tbs.validity().not_before.encode_to_vec(&mut validity)?;
    tbs.validity().not_after.encode_to_vec(&mut validity)?;
    push_sequence(&mut body, &validity)?;
    tbs.subject().encode_to_vec(&mut body)?;
    tbs.subject_public_key_info().encode_to_vec(&mut body)?;
    if let Some(id) = tbs.issuer_unique_id() {
        ContextSpecificRef {
            tag_number: TagNumber(1),
            tag_mode: TagMode::Implicit,
            value: id,
        }
        .encode_to_vec(&mut body)?;
    }
    if let Some(id) = tbs.subject_unique_id() {
        ContextSpecificRef {
            tag_number: TagNumber(2),
            tag_mode: TagMode::Implicit,
            value: id,
        }
        .encode_to_vec(&mut body)?;
    }
    if let Some(exts) = extensions {
        ContextSpecificRef {
            tag_number: TagNumber(3),
            tag_mode: TagMode::Explicit,
            value: exts,
        }
        .encode_to_vec(&mut body)?;
    }
    let mut out = Vec::with_capacity(body.len() + 6);
    push_sequence(&mut out, &body)?;
    Ok(out)
}

/// RFC 5280 §6.1.3(a)(1) — cryptographic signature verification.
///
/// Asks the pluggable [`SignatureVerifier`] to verify the cert's
/// `signature` field over its `TBSCertificate` against the current
/// `working_spki` (the previously-validated issuer's public key). Returns
/// [`Error::SignatureInvalid`] on failure.
///
/// `signed_tbs` is the certificate's own bytes when the caller kept them —
/// see [`CertificateWithDer`]. They are used as given. When it is `None`
/// the bytes are rebuilt with [`encode_tbs_certificate`], which is both the
/// slower path and the one that rests on the encoder being byte-faithful
/// for every field of every certificate the decoder accepted; see
/// [`tbs_der_slice`] for why that is an assumption rather than a fact.
/// Rebuilding uses heap-backed encoding (`alloc::vec`) so a large
/// certificate — government, enterprise and HSM attestation certificates
/// run past 8 KiB of TBSCertificate — encodes without a fixed-buffer limit.
///
/// Does NOT update `working_spki` — that next-iteration state transition is
/// the caller's responsibility (chain_walk binds it at the end of each loop
/// iteration).
fn verify_cert_signature<V: SignatureVerifier>(
    cert: &Certificate,
    signed_tbs: Option<&[u8]>,
    working_spki: &spki::SubjectPublicKeyInfoOwned,
    verifier: &V,
    index: usize,
) -> Result<()> {
    use spki::der::referenced::OwnedToRef as _;
    // Held outside the `match` so the rebuilt buffer outlives the borrow.
    let rebuilt;
    let tbs_bytes: &[u8] = match signed_tbs {
        Some(bytes) => bytes,
        None => {
            rebuilt =
                encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
                    .map_err(|e| Error::Der(DerError::new(e)))?;
            &rebuilt
        }
    };
    verifier
        .verify_signature(
            cert.signature_algorithm().owned_to_ref(),
            working_spki.owned_to_ref(),
            tbs_bytes,
            cert.signature().raw_bytes(),
        )
        .map_err(|e| match e.kind() {
            VerificationErrorKind::InvalidSignature => Error::SignatureInvalid { index },
            reason => Error::SignatureNotVerified { index, reason },
        })?;
    Ok(())
}

fn chain_walk<V: SignatureVerifier, C: PathCertificate>(
    chain: &[C],
    anchor: &TrustAnchor,
    policy: &ValidationPolicy,
    verifier: &V,
) -> Result<Option<policy_graph::PolicyGraph>> {
    use x509_cert::ext::pkix::{InhibitAnyPolicy, PolicyConstraints, PolicyMappings};

    // RFC 5280 §6.1.2 (b)+(c): seed the initial permitted/excluded subtrees
    // from the trust anchor. These initial constraints apply to ALL certs in
    // the chain (including intermediates), not just to leaves — the chain walk
    // enforces them from the first certificate onward.
    let (initial_nc_permitted, initial_nc_excluded) = match &anchor.name_constraints {
        None => (None, GeneralSubtrees::default()),
        Some(nc) => (
            // Clone necessary: nc_permitted and nc_excluded are mutated during the walk.
            nc.permitted_subtrees.clone(),
            nc.excluded_subtrees.clone().unwrap_or_default(),
        ),
    };
    // Bitmask of NcTypeMask bits for name types that have been explicitly
    // constrained by at least one permittedSubtrees entry in any CA cert seen so far.
    // Needed to detect violations when intersection empties the permitted set
    // for a type (e.g., two incompatible DN constraints → empty, but DN still forbidden).
    //
    // INVARIANT: bits are ORed in and never cleared. Once a type bit is set,
    // nc_permitted must contain zero entries of that type to represent "empty
    // intersection" (all names of that type are forbidden). Do NOT derive
    // "is type constrained?" from nc_permitted contents alone — that would
    // silently allow names of a type whose permitted set was emptied by
    // conflicting CA constraints.
    let initial_nc_constrained_types: NcTypeMask =
        initial_nc_permitted
            .as_ref()
            .map_or(NcTypeMask::EMPTY, |permitted| {
                let mut bits = NcTypeMask::EMPTY;
                for st in permitted {
                    bits |= name_type_bit(&st.base);
                }
                bits
            });

    // The anchor's own pathLenConstraint, before any per-certificate
    // state exists, because it depends only on the shape of the chain
    // (PKIX-zr0n, Mark's ruling 2026-12-03).
    //
    // RFC 5280 §6.1 never examines the anchor, so this is not a §6.1
    // step; RFC 6818 §4 leaves an implementation "free to make use of
    // any additional information that is included in a trust anchor
    // representation, or to ignore such information", and this is that
    // choice exercised, as `TrustAnchor`'s four other retained fields
    // already are. OpenSSL enforces it, so leaving it unenforced made
    // this crate accept chains `openssl verify` rejects on a limit the
    // issuer wrote down.
    //
    // `chain` is leaf-first and excludes the anchor, so `chain[1..]` is
    // every intermediate between the leaf and the anchor -- exactly the
    // span the in-path check at step (h) measures as `chain[1..i]` for a
    // certificate at position `i`. The anchor sits at `chain.len()`.
    //
    // Self-issued certificates do not count, per §6.1.4(l) and
    // §4.2.1.9's "non-self-issued intermediate certificates", so a
    // key-rollover certificate under a `pathLen 0` root is still
    // permitted. The same predicate the in-path check uses decides it.
    if let Some(path_len) = anchor.path_len_constraint {
        let intermediates = chain
            .get(1..)
            .unwrap_or(&[])
            .iter()
            .map(PathCertificate::certificate)
            .filter(|c| !is_self_issued_cert(c))
            .count();
        if intermediates > path_len as usize {
            return Err(Error::PathTooLong);
        }
    }

    // RFC 5280 §6.1.2: initialise policy state variables (PKIX-mi3.3).
    //
    // The counters represent "skip N more non-self-issued certificates before
    // the constraint activates".  Setting a counter to `n + 1` means the
    // constraint never triggers unless a CA certificate forces it lower.
    let n = chain.len();
    // Convert n (usize) to u32 safely. Chains with >4 billion certs are not
    // realistic, but a truncating cast would produce a wrong counter value.
    // u32::MAX is safe: counters are only decremented (saturating), so u32::MAX
    // behaves identically to any value > the chain length for these semantics.
    let n_u32 = u32::try_from(n).unwrap_or(u32::MAX);
    let initial_explicit_policy: u32 = if policy.initial_explicit_policy {
        0
    } else {
        n_u32.saturating_add(1)
    };
    let initial_inhibit_any: u32 = if policy.initial_any_policy_inhibit {
        0
    } else {
        n_u32.saturating_add(1)
    };
    let initial_policy_mapping: u32 = if policy.initial_policy_mapping_inhibit {
        0
    } else {
        n_u32.saturating_add(1)
    };

    // Group all per-walk mutable state into a single `WorkingState` for clarity
    // at the call boundaries of the per-substep helpers introduced in
    // subsequent commits.
    let mut state = WorkingState {
        working_spki: &anchor.subject_public_key_info,
        working_issuer_name: &anchor.subject,
        // RFC 5280 §4.2.1.6: when a CA cert has an empty Subject DN and a critical
        // SubjectAltName, the SAN is the cert's identity — the Subject DN is not used
        // for name matching. Track whether the current issuer was set from such a cert
        // so we can skip the DN linkage check below.
        nc_permitted: initial_nc_permitted,
        nc_excluded: initial_nc_excluded,
        nc_constrained_types: initial_nc_constrained_types,
        explicit_policy: initial_explicit_policy,
        inhibit_any: initial_inhibit_any,
        policy_mapping: initial_policy_mapping,
        // §6.1.2(a): initial valid_policy_tree — single anyPolicy root node.
        policy_tree: Some(policy_graph::PolicyGraph::new()),
    };

    // The EKU purposes still issuable at this point in the walk, and the
    // index of the CA that last narrowed them. `None` means unconstrained:
    // no CA so far has restricted anything. See
    // `ValidationPolicy::enforce_ca_eku`. Kept local rather than put in
    // `WorkingState`, which holds RFC 5280 §6.1.2 state, because §6.1.2
    // has no EKU variable -- this is the WebPKI profile's rule riding
    // along the same walk.
    //
    // Seeded from the anchor, which is why `TrustAnchor` carries its
    // certificate's EKU at all: the anchor is not in `chain`, so a
    // purpose-restricted root would otherwise restrict nothing. Its index
    // is reported as `chain.len()`, one past the last certificate, since
    // it has no position in the chain itself.
    let mut permitted_ekus: Option<(Vec<der::asn1::ObjectIdentifier>, usize)> = anchor
        .extended_key_usage
        .as_ref()
        .filter(|_| policy.enforce_ca_eku)
        .filter(|ekus| !ekus.contains(&OID_ANY_EXTENDED_KEY_USAGE))
        .map(|ekus| (ekus.clone(), chain.len()));
    if let Some((ekus, index)) = &permitted_ekus
        && ekus.is_empty()
    {
        return Err(Error::EkuNotPermittedByIssuer { index: *index });
    }

    for i in (0..chain.len()).rev() {
        // One binding for the parsed certificate, which is what every step
        // below wants, and one for the path element, which additionally
        // knows where its signed bytes are.
        let element = &chain[i];
        let cert = element.certificate();

        // (a0) Signature algorithm allowlist check (extracted to helper for
        //      readability; see `enforce_signature_alg_allowlist`).
        enforce_signature_alg_allowlist(cert, policy, i)?;

        // (a) §6.1.3(a)(1) signature verification (extracted; see `verify_cert_signature`).
        verify_cert_signature(cert, element.signed_tbs(), state.working_spki, verifier, i)?;

        // (b) §6.1.3(a)(2) issuer DN linkage (extracted; see `check_issuer_linkage`).
        check_issuer_linkage(cert, state.working_issuer_name, i)?;

        // (c) Validity period.
        check_validity(cert, policy.current_time_unix, i)?;

        // (c2) Max validity period length check (extracted; see `check_max_validity`).
        check_max_validity(cert, policy, i)?;

        // (c3) Minimum RSA key size check (extracted; see `check_min_rsa_bits`).
        check_min_rsa_bits(cert, policy, i)?;

        // (d) Duplicate- and critical-extension guards. Duplicates are
        //     rejected first: every extension lookup below reads only the
        //     first instance of an OID.
        check_duplicate_extensions(cert, i)?;
        check_critical_extensions(cert, i)?;
        // RFC 9608 §3. Here rather than with revocation because its
        // consequence is that the certificate is invalid, and because it
        // is the guard that makes §4's revocation skip safe — see
        // `check_no_rev_avail_profile`.
        check_no_rev_avail_profile(cert, i)?;

        // Decode the cert's CertificatePolicies extension once per cert.
        // Used in both step (d) (policy tree update) and step (a/b) (PolicyMappings
        // anyPolicy qualifier lookup).  Decoding here avoids a second parse inside
        // the mapping loop (b5r.12).
        // try_find_cert_ext (fail-closed): a malformed CertificatePolicies must
        // cause rejection rather than being silently treated as absent; silently
        // dropping it would leave the policy tree in an incorrect state (vjc.21).
        let cert_cp: Option<x509_cert::ext::pkix::certpolicy::CertificatePolicies> =
            try_find_cert_ext(cert, OID_CERTIFICATE_POLICIES)
                .map_err(|_| Error::MalformedCertificate { index: i })?;

        // (policy-d) CertificatePolicies extension (RFC 5280 §6.1.3(d)/(e)).
        // Only processed while the policy graph is still alive.
        if let Some(graph) = &mut state.policy_tree {
            let became_null = match &cert_cp {
                Some(cp_ext) => {
                    // §6.1.3(d)(2) condition: inhibit_anyPolicy > 0, or a
                    // self-issued certificate other than the leaf.
                    let may_expand = state.inhibit_any > 0 || (i > 0 && is_self_issued_cert(cert));
                    graph.add_certificate_policies(cp_ext, may_expand)
                }
                // §6.1.3(e): CertificatePolicies absent → NULL.
                None => true,
            };
            if became_null {
                state.policy_tree = None;
            }
        }

        // (policy-f) RFC 5280 §6.1.3(f): explicit_policy == 0 and tree NULL
        // → policy violation.
        if state.explicit_policy == 0 && state.policy_tree.is_none() {
            return Err(Error::PolicyViolation { index: i });
        }

        // Is any name constraint in effect at this certificate?
        //
        // The state holds what every CA above this certificate imposed.
        // Constraints this certificate introduces are folded in by step
        // (i), after this point, because §6.1.3(b)/(c) check a
        // certificate against the constraints that preceded it and
        // §6.1.4(g) then adds its own: a CA does not constrain its own
        // names.
        let nc_in_effect = state.nc_permitted.is_some()
            || !state.nc_excluded.is_empty()
            || !state.nc_constrained_types.is_empty();

        // Decode SAN only when something is going to read it: the NC name
        // check below, or the leaf's `require_subject_alt_name`. Nothing
        // else in §6.1 consults subjectAltName.
        //
        // This is worth the conditional rather than being premature. A
        // real server leaf carries tens to hundreds of dNSName entries --
        // 163 on one in `pkix-bench`'s corpus -- and each decodes into an
        // owned, UTF-8-validated `String`. Decoding one such extension was
        // measured at 49% of the whole of `validate_path` on a chain that
        // then used none of it, because the chain had no name constraints,
        // as the overwhelming majority of chains do not.
        //
        // Fail-closed is preserved where it means something. A malformed
        // SAN is still `MalformedCertificate` whenever the extension is
        // consulted, which is what vjc.20 is about: a SAN that cannot be
        // decoded must never be treated as absent *by a name constraint
        // check*, or a certificate could bypass an exclusion. With no
        // constraint in effect there is no check to bypass, and this crate
        // does not otherwise decode extensions it will not read -- AIA,
        // SKI and CRL distribution points are all left alone the same way.
        // `malformed_san.rs` pins both halves.
        let san = if nc_in_effect || (i == 0 && policy.require_subject_alt_name) {
            cert_subject_alt_names(cert, i)?
        } else {
            None
        };

        // (e) NameConstraints: check this cert's names against accumulated state.
        // RFC 5280 §6.1.3(b): self-issued non-leaf certs are exempt from NC name checking.
        // The NC state is still updated from their extensions in step (i).
        //
        // Guarded on `nc_in_effect` so `san` cannot be read as absent when
        // it was merely not decoded: with no constraint in effect every
        // branch of `check_name_constraints` is a no-op, so not calling it
        // is the same answer reached without the DN comparison
        // `is_self_issued_cert` would have performed.
        if nc_in_effect && (i == 0 || !is_self_issued_cert(cert)) {
            check_name_constraints(
                cert,
                san.as_ref(),
                state.nc_permitted.as_ref(),
                &state.nc_excluded,
                state.nc_constrained_types,
                i,
            )?;
        }

        // (e2) Require non-empty SubjectAltName on leaf cert.
        //      Only when require_subject_alt_name is set; intermediate CA certs
        //      are NOT checked (i == 0 guard). The `san` variable is decoded above
        //      and is already available — no second extension scan needed.
        if i == 0 && policy.require_subject_alt_name {
            // san is None if the extension is absent; Some(v) where v.0 may be empty.
            let san_is_nonempty = san.as_ref().is_some_and(|s| !s.0.is_empty());
            if !san_is_nonempty {
                return Err(Error::MissingSan);
            }
        }

        // (e2a) The leaf against what the CAs above it permit. A leaf
        //       with no EKU extension claims no purpose, so there is
        //       nothing to contradict and this check passes it; a purpose
        //       the caller demands is handled by (e3) below, which is
        //       also checked against the permitted set.
        //
        //       Intersection rather than containment: a leaf listing
        //       serverAuth and clientAuth under a serverAuth-only
        //       intermediate is accepted. The extra claim is unusable,
        //       not a reason to refuse a chain that works for the purpose
        //       it is being used for, and that shape is common in the
        //       real WebPKI.
        if i == 0
            && policy.enforce_ca_eku
            && let Some((permitted, ca_index)) = &permitted_ekus
        {
            use x509_cert::ext::pkix::ExtendedKeyUsage;
            if let Some(eku) = try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
                .map_err(|_| Error::MalformedCertificate { index: 0 })?
            {
                let claims_any = eku.0.contains(&OID_ANY_EXTENDED_KEY_USAGE);
                if !claims_any && !eku.0.iter().any(|o| permitted.iter().any(|p| p == o)) {
                    return Err(Error::EkuNotPermittedByIssuer { index: *ca_index });
                }
            }
        }

        // (e3) Required leaf EKU OID check.
        //      Only when required_leaf_eku is Some; only on the leaf (i == 0).
        //      Uses try_find_cert_ext (fail-closed): malformed EKU DER on the leaf
        //      is mapped to MalformedCertificate rather than silently ignored.
        //      anyExtendedKeyUsage (OID 2.5.29.37.0) does NOT satisfy a specific
        //      OID requirement — only explicit listing in the cert's EKU counts.
        if i == 0
            && let Some(required_ekus) = &policy.required_leaf_eku
        {
            use x509_cert::ext::pkix::ExtendedKeyUsage;
            match try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
                .map_err(|_| Error::MalformedCertificate { index: 0 })?
            {
                None => {
                    // EKU extension absent; any non-empty requirement fails.
                    if !required_ekus.is_empty() {
                        return Err(Error::MissingEku);
                    }
                }
                Some(eku) => {
                    for req_oid in required_ekus {
                        if !eku.0.iter().any(|e| e == req_oid) {
                            return Err(Error::MissingEku);
                        }
                    }
                }
            }

            // The leaf may list the demanded purpose while a CA above
            // it forbids that purpose; the leaf's own EKU cannot show
            // that. Catches a chain whose leaf has no EKU at all too,
            // where (e2a) has nothing to compare.
            if policy.enforce_ca_eku
                && let Some((permitted, ca_index)) = &permitted_ekus
            {
                for req_oid in required_ekus {
                    if !permitted.iter().any(|p| p == req_oid) {
                        return Err(Error::EkuNotPermittedByIssuer { index: *ca_index });
                    }
                }
            }
        }

        // (e3a) Required leaf CertificatePolicies OID check.
        //       Only when required_leaf_policy_oids is Some; only on the leaf
        //       (i == 0). Reuses `cert_cp` decoded above. `anyPolicy`
        //       (2.5.29.32.0) does NOT satisfy a specific OID requirement —
        //       only explicit listing in the cert's CertificatePolicies counts.
        //       Mirrors the (e3) EKU pattern.
        if i == 0
            && let Some(required_policy_oids) = &policy.required_leaf_policy_oids
        {
            match &cert_cp {
                None => {
                    // CertificatePolicies extension absent; any non-empty
                    // requirement fails.
                    if let Some(first) = required_policy_oids.first() {
                        return Err(Error::MissingLeafPolicyOid { required: *first });
                    }
                }
                Some(cp_ext) => {
                    for req_oid in required_policy_oids {
                        if !cp_ext.0.iter().any(|pi| pi.policy_identifier == *req_oid) {
                            return Err(Error::MissingLeafPolicyOid { required: *req_oid });
                        }
                    }
                }
            }
        }

        // (e3b) Required Subject DN attribute rule check.
        //       Only when required_leaf_subject_dn_attrs is Some; only on the
        //       leaf (i == 0). See [`DnAttrRule`] for the expression grammar
        //       and vacuity rules.
        if i == 0
            && let Some(dn_rule) = &policy.required_leaf_subject_dn_attrs
            && !evaluate_dn_attr_rule(cert.tbs_certificate().subject(), dn_rule)
        {
            return Err(Error::SubjectDnAttrRuleUnmet);
        }

        // (e4) If require_rfc822_san is set, at least one rfc822Name entry must
        //      be present in the leaf's SAN extension.
        //      Only meaningful (and checked) when require_subject_alt_name is also
        //      true; the non-empty SAN check above (e2) already guards the absent
        //      / empty SAN case. EKU is checked first (e3) so that a cert with both
        //      wrong EKU and wrong SAN type reports MissingEku (more actionable).
        if i == 0 && policy.require_subject_alt_name && policy.require_rfc822_san {
            use x509_cert::ext::pkix::name::GeneralName;
            let has_rfc822 = san.as_ref().is_some_and(|s| {
                s.0.iter()
                    .any(|name| matches!(name, GeneralName::Rfc822Name(_)))
            });
            if !has_rfc822 {
                return Err(Error::MissingRfc822San);
            }
        }

        // (f–h) CA-only checks: apply to every cert except the leaf (chain[0]).
        //        This includes any intermediate CAs and the root CA cert if it
        //        is included in the chain rather than supplied only as an anchor.
        if i > 0 {
            // (f) BasicConstraints cA=TRUE required; (h) pathLenConstraint.
            // Decode BasicConstraints once for both checks.
            //
            // Fail-closed: if the extension is structurally present but DER-malformed
            // on an intermediate CA, propagate MalformedCertificate rather than
            // treating it as absent (which would fall through to NotCA and hide the
            // real structural problem).
            let bc = try_find_cert_ext::<x509_cert::ext::pkix::BasicConstraints>(
                cert,
                OID_BASIC_CONSTRAINTS,
            )
            .map_err(|_| Error::MalformedCertificate { index: i })?;
            if !bc.as_ref().is_some_and(|b| b.ca) {
                return Err(Error::NotCA { index: i });
            }

            // EKU nesting: a CA restricted to some purposes cannot issue
            // for others. Not an RFC 5280 §6.1 step -- see
            // `ValidationPolicy::enforce_ca_eku` for why it is here and
            // on by default. Narrowing happens as the walk descends from
            // the anchor, so each certificate sees what everything above
            // it permitted.
            if policy.enforce_ca_eku {
                use x509_cert::ext::pkix::ExtendedKeyUsage;
                if let Some(eku) =
                    try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
                        .map_err(|_| Error::MalformedCertificate { index: i })?
                {
                    // `anyExtendedKeyUsage` declines to constrain, so it
                    // narrows nothing.
                    if !eku.0.contains(&OID_ANY_EXTENDED_KEY_USAGE) {
                        let narrowed: Vec<_> = match &permitted_ekus {
                            // RFC 5280 gives EKU as SEQUENCE SIZE
                            // (1..MAX), so an empty one is malformed; it
                            // also permits nothing, and falls out of the
                            // emptiness check below either way.
                            None => eku.0.clone(),
                            Some((prev, _)) => prev
                                .iter()
                                .copied()
                                .filter(|o| eku.0.iter().any(|e| e == o))
                                .collect(),
                        };
                        if narrowed.is_empty() {
                            return Err(Error::EkuNotPermittedByIssuer { index: i });
                        }
                        permitted_ekus = Some((narrowed, i));
                    }
                }
            }

            // A CA has to have a name to be a CA under. Checked here and
            // not only on the anchor because a chain may carry its root
            // inline, and because an intermediate is reachable the same
            // way: §6.1.3(a)(4) chains on DN equality and an empty DN
            // matches an empty DN, so an unnamed CA would chain to
            // anything another unnamed CA issued. RFC 5280 §4.1.2.6.
            if dn_names_nothing(cert.tbs_certificate().subject()) {
                return Err(Error::CaEmptySubject { index: i });
            }

            // (g) KeyUsage keyCertSign required (when policy demands it).
            // RFC 5280 §6.1.4(n): "If a KeyUsage extension is present, verify that the
            // keyCertSign bit is set."  Only reject when KeyUsage IS present (Some(_)) and
            // keyCertSign is NOT set (== Some(false)).  Absent KeyUsage (None) is allowed.
            // has_key_cert_sign is fail-closed: a malformed critical KeyUsage returns
            // MalformedCertificate rather than being silently treated as absent (vjc.15).
            if policy.enforce_key_usage
                && has_key_cert_sign(cert).map_err(|_| Error::MalformedCertificate { index: i })?
                    == Some(false)
            {
                return Err(Error::KeyUsageMissing { index: i });
            }

            // (g') KeyUsage cRLSign required (opt-in via require_crl_sign_on_cas).
            // RFC 5280 §6.1 does NOT require this check; it is a stricter policy
            // motivated by PKITS §4.7.4 / §4.7.5, which treat a CA cert without
            // cRLSign as unable to revoke certs it issued and therefore invalid.
            // Same fail-closed and absent-KeyUsage semantics as keyCertSign above.
            // Independent of `enforce_key_usage`: callers can opt into cRLSign
            // enforcement without also enabling keyCertSign enforcement, and
            // vice versa.
            if policy.require_crl_sign_on_cas
                && has_crl_sign(cert).map_err(|_| Error::MalformedCertificate { index: i })?
                    == Some(false)
            {
                return Err(Error::CrlSignMissing { index: i });
            }

            // (h) pathLenConstraint: count only non-self-issued intermediates below position i
            // (RFC 5280 §4.2.1.9: "non-self-issued intermediate certificates").
            // chain[1..i] = the intermediate positions between the leaf (0) and this cert (i).
            if let Some(path_len) = bc.and_then(|b| b.path_len_constraint) {
                let effective_depth = chain[1..i]
                    .iter()
                    .map(PathCertificate::certificate)
                    .filter(|c| !is_self_issued_cert(c))
                    .count();
                if effective_depth > path_len as usize {
                    return Err(Error::PathTooLong);
                }
            }

            // (policy-a) PolicyMappings (RFC 5280 §6.1.4(a)): anyPolicy must
            // not appear on either side of a mapping.
            // (policy-b) Apply mappings to the tree or delete mapped nodes.
            // NOTE: Policy mappings use the current policy_mapping counter value
            // (before decrement); the decrement happens in §6.1.4(h) below.
            // try_find_cert_ext (fail-closed): a malformed PolicyMappings extension
            // must cause rejection rather than silent ignore; a silently-discarded
            // mapping could allow a policy bypass (e.g., inhibit_policy_mapping bypass).
            if let Some(pm) = try_find_cert_ext::<PolicyMappings>(cert, OID_POLICY_MAPPINGS)
                .map_err(|_| Error::MalformedCertificate { index: i })?
            {
                // §6.1.4(a): reject anyPolicy as issuer or subject domain.
                for mapping in &pm.0 {
                    if mapping.issuer_domain_policy == OID_ANY_POLICY
                        || mapping.subject_domain_policy == OID_ANY_POLICY
                    {
                        return Err(Error::PolicyViolation { index: i });
                    }
                }

                // §6.1.4(b)(1) if policy_mapping > 0, else §6.1.4(b)(2).
                if let Some(graph) = &mut state.policy_tree {
                    // §6.1.4(b)(1) synthesized nodes take the qualifiers of
                    // this certificate's anyPolicy entry (none if it has no
                    // certificatePolicies, in which case the graph is
                    // already NULL and this branch is not reached).
                    let ap_q = cert_cp
                        .as_ref()
                        .map(policy_graph::any_policy_qualifiers)
                        .unwrap_or_default();
                    if graph.apply_policy_mappings(&pm, state.policy_mapping > 0, &ap_q) {
                        state.policy_tree = None;
                    }
                }
            }

            // (policy-h) RFC 5280 §6.1.4(h): decrement policy counters for
            // non-self-issued intermediate certificates.
            // This happens AFTER policy mappings processing (§6.1.4(b)) and
            // BEFORE clamping from extensions (§6.1.4(i)/(j)).
            if !is_self_issued_cert(cert) {
                state.explicit_policy = state.explicit_policy.saturating_sub(1);
                state.policy_mapping = state.policy_mapping.saturating_sub(1);
                state.inhibit_any = state.inhibit_any.saturating_sub(1);
            }

            // (policy-i) PolicyConstraints (RFC 5280 §6.1.4(c)): clamp
            // explicit_policy and policy_mapping from the extension.
            // try_find_cert_ext (fail-closed): malformed PolicyConstraints must reject;
            // silently ignoring it could allow explicit_policy bypass.
            if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(cert, OID_POLICY_CONSTRAINTS)
                .map_err(|_| Error::MalformedCertificate { index: i })?
            {
                if let Some(req) = pc.require_explicit_policy {
                    state.explicit_policy = state.explicit_policy.min(req);
                }
                if let Some(ipm) = pc.inhibit_policy_mapping {
                    state.policy_mapping = state.policy_mapping.min(ipm);
                }
            }

            // (policy-j) InhibitAnyPolicy (RFC 5280 §6.1.4(d)): clamp inhibit_any.
            // try_find_cert_ext (fail-closed): malformed InhibitAnyPolicy must reject;
            // silently ignoring it could allow anyPolicy through when it should be inhibited.
            if let Some(iap) = try_find_cert_ext::<InhibitAnyPolicy>(cert, OID_INHIBIT_ANY_POLICY)
                .map_err(|_| Error::MalformedCertificate { index: i })?
            {
                state.inhibit_any = state.inhibit_any.min(iap.0);
            }

            // (i) NC update: NameConstraints state update (RFC 5280 §6.1.4(b)).
            //     INTERSECTION for permitted, UNION for excluded.
            //     cert_name_constraints is fail-closed: a malformed or non-conformant
            //     NC extension (e.g., non-zero minimum/maximum) returns MalformedCertificate
            //     rather than silently ignoring the constraints (vjc.7, vjc.8).
            if let Some(nc) = cert_name_constraints(cert, i)? {
                // permittedSubtrees: intersect with current state.
                if let Some(new_permitted) = nc.permitted_subtrees {
                    // Track which types this CA is constraining.
                    for entry in &new_permitted {
                        state.nc_constrained_types |= name_type_bit(&entry.base);
                    }
                    match state.nc_permitted.as_mut() {
                        None => {
                            // First constraint seen; adopt it directly.
                            state.nc_permitted = Some(new_permitted);
                        }
                        Some(current) => {
                            // Type-aware intersection of two permitted-subtrees sets.
                            //
                            // RFC 5280 §6.1.4(b): intersect entry-by-entry, but only
                            // compare entries of the SAME name type. Entries of types
                            // not present in new_permitted are unchanged (new doesn't
                            // constrain that type). Entries of types not in current
                            // are added directly (new adds a fresh constraint).
                            //
                            // For entries of matching type, keep:
                            //   1. new entries within (⊆) some same-type current entry.
                            //   2. current entries within (⊆) some same-type new entry.
                            // Containment is decided by `subtree_within`, which
                            // compares two constraints (address+mask, bare host,
                            // `.domain`) rather than treating one as a cert name.
                            // (If neither is within the other the intersection for that
                            // type is empty — tracked via nc_constrained_types.)
                            let mut result = GeneralSubtrees::default();

                            // For each new entry, pre-filter current entries of the
                            // same type to avoid calling same_nc_variant twice per
                            // pair (vjc.16: duplicated guard + containment check).
                            for n in &new_permitted {
                                let same_type_in_current: GeneralSubtrees = current
                                    .iter()
                                    .filter(|c| same_nc_variant(&c.base, &n.base))
                                    .cloned()
                                    .collect();
                                if same_type_in_current.is_empty() {
                                    // Type not previously constrained → add directly.
                                    result.push(n.clone());
                                } else if same_type_in_current
                                    .iter()
                                    .any(|c| subtree_within(&n.base, &c.base))
                                {
                                    // n is within some same-type current entry → keep.
                                    result.push(n.clone());
                                }
                                // else: n is not within any current entry of same type → drop.
                            }

                            for c in current.iter() {
                                let same_type_in_new: GeneralSubtrees = new_permitted
                                    .iter()
                                    .filter(|n| same_nc_variant(&n.base, &c.base))
                                    .cloned()
                                    .collect();
                                if same_type_in_new.is_empty() {
                                    // Type not in new_permitted → keep unchanged.
                                    result.push(c.clone());
                                } else if same_type_in_new
                                    .iter()
                                    .any(|n| subtree_within(&c.base, &n.base))
                                {
                                    // c is more specific than some new entry; keep unless
                                    // an equivalent entry is already in result (dedup
                                    // within the result set for this type).
                                    let same_type_in_result: &[_] = result.as_slice();
                                    let already_in_result = same_type_in_result.iter().any(|e| {
                                        same_nc_variant(&e.base, &c.base)
                                            && subtree_within(&e.base, &c.base)
                                            && subtree_within(&c.base, &e.base)
                                    });
                                    if !already_in_result {
                                        result.push(c.clone());
                                    }
                                }
                                // else: c is not within any new entry of same type → drop.
                            }

                            *current = result;
                        }
                    }
                }
                // excludedSubtrees: union — append only entries not already present,
                // avoiding monotonic growth that would make per-cert NC checks O(chain²)
                // when the same excluded subtrees are repeated across multiple CAs (vjc.12).
                if let Some(new_excluded) = nc.excluded_subtrees {
                    for new_entry in &new_excluded {
                        // Deduplication uses subtree_within as a two-way equality
                        // check: two entries are considered the same subtree when each
                        // contains the other (i.e., they are semantically equivalent, not
                        // just byte-equal).
                        let already_present = state.nc_excluded.iter().any(|existing| {
                            same_nc_variant(&existing.base, &new_entry.base)
                                && subtree_within(&existing.base, &new_entry.base)
                                && subtree_within(&new_entry.base, &existing.base)
                        });
                        if !already_present {
                            state.nc_excluded.push(new_entry.clone());
                        }
                    }
                }
            }
        }

        // Update state for next iteration.
        state.working_spki = cert.tbs_certificate().subject_public_key_info();
        state.working_issuer_name = cert.tbs_certificate().subject();
        // Determine whether the cert we just processed presents itself via SAN
        // identity (empty Subject + critical SAN). This affects the chain-linkage
        // check for the certificate immediately below it in the next iteration.
    }

    // RFC 5280 §6.1.5(a-b): post-loop leaf policy finalisation.
    //
    // §6.1.5 is a post-loop step in the RFC.  These operations apply only to
    // the leaf certificate (chain[0]), which was the last iteration (i == 0).
    // Placing them here rather than inside the loop at i == 0 matches the RFC
    // section numbering and makes clear that they happen after all per-cert
    // §6.1.3/§6.1.4 steps have completed.
    {
        let leaf = chain[0].certificate();
        // §6.1.5(a): if the leaf is not self-issued, decrement counters.
        // inhibit_any and policy_mapping are decremented per RFC 5280 §6.1.5(a)
        // but are not used after this point in the algorithm — only explicit_policy
        // is tested in §6.1.5(g) and the final check.
        if !is_self_issued_cert(leaf) {
            state.explicit_policy = state.explicit_policy.saturating_sub(1);
            // Per §6.1.5(a): RFC also decrements inhibit_any and policy_mapping here,
            // but neither is read after §6.1.5(a) in our implementation.
        }
        // §6.1.5(b): if PolicyConstraints requireExplicitPolicy == 0,
        // force explicit_policy to 0.
        // try_find_cert_ext (fail-closed): consistent with per-loop treatment of
        // PolicyConstraints; a malformed extension on the leaf must also reject.
        if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(leaf, OID_POLICY_CONSTRAINTS)
            .map_err(|_| Error::MalformedCertificate { index: 0 })?
            && let Some(req) = pc.require_explicit_policy
        {
            state.explicit_policy = state.explicit_policy.min(req);
        }
    }

    // RFC 5280 §6.1.5(g): intersect the valid_policy_graph with the
    // user-initial-policy-set.
    //
    // (g)(i): a NULL graph stays NULL. (g)(ii): an empty set (this crate's
    // spelling of the default) or any set containing anyPolicy is
    // any-policy, and the intersection is the whole graph. (g)(iii)
    // otherwise.
    if !policy.initial_policy_set.is_empty()
        && !policy.initial_policy_set.contains(&OID_ANY_POLICY)
        && let Some(graph) = &mut state.policy_tree
        && graph.intersect_user_policy_set(&policy.initial_policy_set)
    {
        state.policy_tree = None;
    }

    // §6.1.5 final check: path is valid iff explicit_policy > 0 OR tree
    // is non-NULL.
    if state.explicit_policy == 0 && state.policy_tree.is_none() {
        return Err(Error::PolicyViolation { index: 0 });
    }

    // Return the final valid_policy_tree to `validate_path` so it can be
    // surfaced on `ValidatedPath` for post-validation qualifier extraction.
    // `None` propagates through unchanged when the tree was reduced to NULL
    // during validation; callers that rely on §6.1.5 outputs MUST treat
    // `None` as "no policy information available", not as a validation
    // failure (the policy-success check above already happened).
    Ok(state.policy_tree)
}

// ---------------------------------------------------------------------------
// NameConstraints enforcement (PKIX-xji)
// ---------------------------------------------------------------------------

/// Whether a name-constraint check requires a match (permitted) or forbids a
/// match (excluded).
///
/// Using an explicit enum instead of a bare `bool` makes call sites
/// self-documenting: `CheckMode::Excluded` / `CheckMode::Permitted` vs
/// opaque `false` / `true` (vjc.25).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CheckMode {
    /// Excluded subtrees: any name that matches is a violation.
    Excluded,
    /// Permitted subtrees: a constrained name type that matches *no* entry is a violation.
    Permitted,
}

/// Check the cert's subject DN against `subtrees` in the given `mode`.
///
/// Skipped entirely when the subject DN is empty (RFC 5280 §6.1.3(b)).
///
/// Avoids constructing a `GeneralName::DirectoryName` (which would require a
/// clone) by handling `DirectoryName` constraints inline: pull `DirectoryName`
/// entries from `subtrees` and test directly against the subject `Name`
/// (vjc.24).
///
/// - `CheckMode::Excluded`: any DN match is a violation.
/// - `CheckMode::Permitted`: only enforced if some CA in the path has
///   contributed a `DirectoryName` permitted-subtree (tracked in
///   `nc_constrained_types`); then a non-match is a violation.
fn check_subject_dn_against_subtrees(
    subject: &x509_cert::name::Name,
    subject_is_empty: bool,
    subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
    mode: CheckMode,
    nc_constrained_types: NcTypeMask,
    index: usize,
) -> crate::Result<()> {
    use x509_cert::ext::pkix::name::GeneralName;

    if subject_is_empty {
        return Ok(());
    }
    let subject_constrained = nc_constrained_types.intersects(NcTypeMask::DIRECTORY_NAME);
    let dn_matches_any = subtrees.iter().any(|st| {
        if let GeneralName::DirectoryName(constr) = &st.base {
            dn_within_subtree(subject, constr)
        } else {
            false
        }
    });
    match mode {
        CheckMode::Excluded => {
            if dn_matches_any {
                return Err(Error::NameConstraintViolation { index });
            }
        }
        CheckMode::Permitted => {
            if subject_constrained && !dn_matches_any {
                return Err(Error::NameConstraintViolation { index });
            }
        }
    }
    Ok(())
}

/// Check each SAN entry of the cert against `subtrees` in the given `mode`.
///
/// - `CheckMode::Excluded`: any SAN entry that matches any subtree is a
///   violation.
/// - `CheckMode::Permitted`: a SAN entry whose type has been constrained
///   somewhere in the path (per `nc_constrained_types`) must match at least
///   one subtree entry; unconstrained types are accepted.
///
/// A `None` SAN extension is a no-op.
fn check_san_against_subtrees(
    san: Option<&x509_cert::ext::pkix::SubjectAltName>,
    subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
    mode: CheckMode,
    nc_constrained_types: NcTypeMask,
    index: usize,
) -> crate::Result<()> {
    use x509_cert::ext::pkix::constraints::name::GeneralSubtree;
    use x509_cert::ext::pkix::name::GeneralName;

    let Some(san_ext) = san else {
        return Ok(());
    };
    let type_constrained =
        |name: &GeneralName| -> bool { nc_constrained_types.intersects(name_type_bit(name)) };

    for name in &san_ext.0 {
        match mode {
            CheckMode::Excluded => {
                // A wildcard dNSName SAN is not the name it stands for,
                // so the exclusion is also tested against the names it
                // can authenticate. See
                // `wildcard_san_reaches_excluded_dns`.
                let reaches_excluded = |st: &GeneralSubtree| -> bool {
                    match (name, &st.base) {
                        (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
                            wildcard_san_reaches_excluded_dns(subj.as_str(), constr.as_str())
                        }
                        _ => false,
                    }
                };
                if subtrees
                    .iter()
                    .any(|st| name_matches_subtree(name, st) || reaches_excluded(st))
                {
                    return Err(Error::NameConstraintViolation { index });
                }
            }
            CheckMode::Permitted => {
                if type_constrained(name)
                    && !subtrees.iter().any(|st| name_matches_subtree(name, st))
                {
                    return Err(Error::NameConstraintViolation { index });
                }
            }
        }
    }
    Ok(())
}

/// Check that all names in `cert` satisfy the current `NameConstraints` state.
///
/// Called once per certificate during `chain_walk`, BEFORE updating the NC
/// state from that certificate's own `NameConstraints` extension.
///
/// `san` is the pre-decoded `SubjectAltName` for this cert (pass `None` if the
/// extension is absent). Decoding it before the call avoids a second scan of
/// the extension list when both NC check and NC update are needed (vjc.13).
///
/// RFC 5280 §6.1.4(b)(1)–(2): check excluded subtrees first, then
/// permitted subtrees.
fn check_name_constraints(
    cert: &x509_cert::Certificate,
    san: Option<&x509_cert::ext::pkix::SubjectAltName>,
    nc_permitted: Option<&GeneralSubtrees>,
    nc_excluded: &GeneralSubtrees,
    nc_constrained_types: NcTypeMask,
    index: usize,
) -> crate::Result<()> {
    let subject = cert.tbs_certificate().subject();
    let subject_is_empty = subject.is_empty();
    // Computed once: the SAN scan and the shape tests do not depend on
    // which mode `check_names` is running in.
    let cn_dns = cn_dns_identities(subject, san);

    // Dispatch the subject DN and the SAN entries against `subtrees` in the
    // requested mode. See `check_subject_dn_against_subtrees` and
    // `check_san_against_subtrees` for the per-name-class logic.
    let check_names = |subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
                       mode: CheckMode|
     -> crate::Result<()> {
        check_subject_dn_against_subtrees(
            subject,
            subject_is_empty,
            subtrees,
            mode,
            nc_constrained_types,
            index,
        )?;
        check_san_against_subtrees(san, subtrees, mode, nc_constrained_types, index)?;
        // A commonName read as a DNS identity is bounded like a dNSName
        // SAN. See `cn_dns_identities`.
        check_cn_dns_against_subtrees(&cn_dns, subtrees, mode, nc_constrained_types, index)?;
        Ok(())
    };

    // (0) Name forms the generic matchers cannot decide. A form is "in
    //     effect" when some permitted subtree of that form has been seen in
    //     the path (`nc_constrained_types`, which survives an emptied
    //     intersection) or the excluded set holds an entry of that form.
    let excluded_forms = nc_excluded
        .iter()
        .fold(NcTypeMask::EMPTY, |m, st| m | name_type_bit(&st.base));
    let forms_in_effect = nc_constrained_types | excluded_forms;
    let rfc822_permitted_active = nc_constrained_types.intersects(NcTypeMask::RFC822);
    if let Some(san_ext) = san {
        for name in &san_ext.0 {
            check_san_name_form(
                name,
                forms_in_effect,
                nc_permitted,
                nc_excluded,
                rfc822_permitted_active,
                index,
            )?;
        }
    }

    // (1) Excluded check: any excluded subtree match → violation.
    check_names(nc_excluded.as_slice(), CheckMode::Excluded)?;

    // (2) Permitted check: if permitted set is constrained, every name must
    //     match at least one permitted subtree.
    if let Some(permitted) = nc_permitted {
        check_names(permitted.as_slice(), CheckMode::Permitted)?;
    }

    // (3) RFC 5280 §4.2.1.10: emailAddress attributes in the subject DN MUST
    //     be checked against the rfc822Name constraint.
    //     Guard: only enter the RDN walk if RFC822 constraints are actually
    //     in effect — a permitted RFC822 entry has been seen, OR at least one
    //     excluded entry is an Rfc822Name (vjc.11).
    if forms_in_effect.intersects(NcTypeMask::RFC822) && !subject_is_empty {
        for rdn in subject.iter_rdn() {
            for ava in rdn.iter() {
                if ava.oid != OID_EMAIL_ADDRESS {
                    continue;
                }
                // PKCS #9 defines emailAddress as IA5String. Any other
                // encoding cannot be checked, so it fails closed instead of
                // silently skipping the constraint.
                let Ok(email_ia5) = ava.value.decode_as::<der::asn1::Ia5StringRef<'_>>() else {
                    return Err(Error::NameConstraintViolation { index });
                };
                check_mailbox_against_rfc822(
                    email_ia5.as_str(),
                    nc_permitted,
                    nc_excluded,
                    rfc822_permitted_active,
                    index,
                )?;
            }
        }
    }

    Ok(())
}

/// OID for the `SmtpUTF8Mailbox` otherName (RFC 8398 §3), `id-on-SmtpUTF8Mailbox`.
const OID_SMTP_UTF8_MAILBOX: der::asn1::ObjectIdentifier =
    der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.8.9");

/// Pre-check one SAN entry whose form the generic subtree matchers cannot
/// decide on their own (RFC 5280 §4.2.1.10, RFC 8398 §6).
///
/// - `otherName(SmtpUTF8Mailbox)`: checked against rfc822Name constraints
///   when any are in effect (RFC 8398 §6 extends them to this form). The
///   value must be a UTF8String and its domain part must be ASCII; a
///   U-label domain would need IDNA mapping, which this `no_std` crate
///   does not carry, so it fails closed.
/// - `otherName` (any type-id, including SmtpUTF8Mailbox), `ediPartyName`,
///   `registeredID`: `pkix-path` does not process constraints of these
///   forms, so the name is rejected when a constraint of the same form is
///   in effect ("MUST either process the constraint or reject the
///   certificate"). The `otherName` check is per form, not per type-id: an
///   otherName constraint of one type-id rejects otherName SANs of every
///   type-id.
/// - `uniformResourceIdentifier`: when a URI constraint is in effect, a URI
///   without an authority, or whose host is an IP address, is rejected
///   (see [`uri_host`]).
fn check_san_name_form(
    name: &x509_cert::ext::pkix::name::GeneralName,
    forms_in_effect: NcTypeMask,
    nc_permitted: Option<&GeneralSubtrees>,
    nc_excluded: &GeneralSubtrees,
    rfc822_permitted_active: bool,
    index: usize,
) -> crate::Result<()> {
    use x509_cert::ext::pkix::name::GeneralName;

    let violation = Err(Error::NameConstraintViolation { index });
    match name {
        GeneralName::OtherName(other) => {
            if forms_in_effect.intersects(NcTypeMask::OTHER_NAME) {
                return violation;
            }
            if other.type_id == OID_SMTP_UTF8_MAILBOX
                && forms_in_effect.intersects(NcTypeMask::RFC822)
            {
                let Ok(mailbox) = der::asn1::Utf8StringRef::try_from(&other.value) else {
                    return violation;
                };
                check_mailbox_against_rfc822(
                    mailbox.as_str(),
                    nc_permitted,
                    nc_excluded,
                    rfc822_permitted_active,
                    index,
                )?;
            }
        }
        GeneralName::EdiPartyName(_) | GeneralName::RegisteredId(_)
            if forms_in_effect.intersects(name_type_bit(name)) =>
        {
            return violation;
        }
        GeneralName::UniformResourceIdentifier(uri)
            if forms_in_effect.intersects(NcTypeMask::URI) && uri_host(uri.as_str()).is_none() =>
        {
            return violation;
        }
        _ => {}
    }
    Ok(())
}

/// Check a mailbox that does not arrive as an rfc822Name SAN (a subject
/// `emailAddress` attribute or an `SmtpUTF8Mailbox` otherName) against the
/// rfc822Name subtrees.
///
/// Excluded entries always apply; permitted entries apply when
/// `rfc822_permitted_active` (some CA in the path permitted rfc822Name
/// subtrees). The domain part (after the last `@`) must be ASCII, otherwise
/// the mailbox cannot be compared and the check fails closed.
fn check_mailbox_against_rfc822(
    mailbox: &str,
    nc_permitted: Option<&GeneralSubtrees>,
    nc_excluded: &GeneralSubtrees,
    rfc822_permitted_active: bool,
    index: usize,
) -> crate::Result<()> {
    use x509_cert::ext::pkix::name::GeneralName;

    let violation = Err(Error::NameConstraintViolation { index });
    match mailbox.rsplit_once('@') {
        Some((_, domain)) if domain.is_ascii() => {}
        _ => return violation,
    }
    for st in nc_excluded {
        if let GeneralName::Rfc822Name(c) = &st.base
            && matches_rfc822_name(mailbox, c.as_str())
        {
            return violation;
        }
    }
    if rfc822_permitted_active {
        let permitted = nc_permitted.map_or(&[][..], |p| p.as_slice());
        let ok = permitted.iter().any(|st| match &st.base {
            GeneralName::Rfc822Name(c) => matches_rfc822_name(mailbox, c.as_str()),
            _ => false,
        });
        if !ok {
            return violation;
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Send + Sync compile-time assertions
// ---------------------------------------------------------------------------
//
// AGENTS.md non-negotiable #6 requires public result types to be
// `Send + Sync` so callers can move values across thread boundaries and
// store them in shared caches. The auto-derive does the right thing today
// (no `Rc<T>`, `RefCell<T>`, or raw pointers in any of these types), but
// the rule is currently aspirational. These `const _:` assertions promote
// it to a compile-time invariant — a future field that breaks `Send` or
// `Sync` (e.g. someone adds an `Rc<T>` variant to `Error`) fails the
// workspace build, not a runtime test. Tracked at PKIX-2l0v.2.

const _: fn() = || {
    fn _assert_send_sync<T: Send + Sync>() {}
    _assert_send_sync::<ValidatedPath>();
    _assert_send_sync::<Error>();
    _assert_send_sync::<TrustAnchor>();
    _assert_send_sync::<ValidationPolicy>();
};

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "p256"))]
mod tests_ecdsa_p256 {
    use super::*;
    use der::Decode;

    /// Test vector: a real P-256/SHA-256 self-signed cert generated by OpenSSL.
    /// Oracle: `openssl verify -CAfile ec.pem ec.pem` returns OK.
    #[test]
    fn verify_p256_self_signed() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
        let cert = Certificate::from_der(der).expect("parse cert");

        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();

        // Self-signed cert: signer SPKI is the cert's own SPKI.
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        let verifier = EcdsaP256Verifier;
        assert!(
            verifier
                .verify_signature(
                    cert.signature_algorithm().owned_to_ref(),
                    spki_ref,
                    &tbs_der,
                    sig_bytes,
                )
                .is_ok(),
            "self-signed P-256 cert should verify"
        );
    }
}

#[cfg(all(test, feature = "p384"))]
mod tests_ecdsa_p384 {
    //! Test vectors for ECDSA P-384 / SHA-384 (PKIX-gphz.2).
    //!
    //! Oracle: `openssl verify -CAfile ec-p384-sha384.pem ec-p384-sha384.pem`
    //! returns OK against the same fixture (the PEM form lives at
    //! `tests/fixtures/ec-p384-sha384.der`; regenerate with the recipe in the
    //! commit that introduced this file). Independent oracle — pkix-path was
    //! not used to compute the expected verdict.
    use super::*;
    use der::Decode;

    const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/ec-p384-sha384.der");

    #[test]
    fn verify_p384_self_signed() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let cert = Certificate::from_der(FIXTURE).expect("parse cert");

        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();

        // Self-signed cert: signer SPKI is the cert's own SPKI.
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        let verifier = EcdsaP384Verifier;
        verifier
            .verify_signature(
                cert.signature_algorithm().owned_to_ref(),
                spki_ref,
                &tbs_der,
                sig_bytes,
            )
            .expect("self-signed P-384 cert should verify");
    }

    #[test]
    fn tampered_signature_rejected() {
        // Flip a bit in the signature and confirm verification fails. This
        // exercises the actual cryptographic check, not just the OID and
        // SPKI parse paths.
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let cert = Certificate::from_der(FIXTURE).expect("parse cert");

        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let mut sig_bytes = cert.signature().raw_bytes().to_vec();
        // Tamper a byte well inside the DER signature (any byte after the
        // initial SEQUENCE header). The DerSignature decoder rejects most
        // structural corruption with try_from, which is also a valid
        // verification failure — either way the result must be Err.
        let mid = sig_bytes.len() / 2;
        sig_bytes[mid] ^= 0x01;

        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        let verifier = EcdsaP384Verifier;
        assert!(
            verifier
                .verify_signature(
                    cert.signature_algorithm().owned_to_ref(),
                    spki_ref,
                    &tbs_der,
                    &sig_bytes,
                )
                .is_err(),
            "tampered signature must not verify"
        );
    }

    #[test]
    fn wrong_oid_rejected() {
        // The fixture was signed with SHA-384. Relabelling it as
        // ecdsa-with-SHA256 makes the verifier hash with SHA-256 (the
        // digest comes from the OID, the curve from the key), so the
        // signature must not verify.
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let cert = Certificate::from_der(FIXTURE).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        let wrong_alg = spki::AlgorithmIdentifierRef {
            oid: der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"), // ecdsa-with-SHA256
            parameters: None,
        };
        let verifier = EcdsaP384Verifier;
        assert!(
            verifier
                .verify_signature(wrong_alg, spki_ref, &tbs_der, sig_bytes)
                .is_err(),
            "a SHA-384 signature must not verify as ecdsa-with-SHA256"
        );
    }

    #[test]
    fn default_verifier_dispatches_to_p384() {
        // DefaultVerifier's OID dispatch should route ecdsa-with-SHA384 to
        // EcdsaP384Verifier when the `p384` feature is active. Confirm the
        // same fixture verifies under DefaultVerifier too.
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let cert = Certificate::from_der(FIXTURE).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        DefaultVerifier
            .verify_signature(
                cert.signature_algorithm().owned_to_ref(),
                spki_ref,
                &tbs_der,
                sig_bytes,
            )
            .expect("DefaultVerifier must dispatch to EcdsaP384Verifier for ecdsa-with-SHA384");
    }
}

#[cfg(all(test, feature = "rsa"))]
mod tests_rsa {
    use super::*;
    use der::Decode;

    /// Test vector: a real RSA-2048/SHA-256 self-signed cert generated by OpenSSL.
    /// Oracle: `openssl verify -CAfile rsa.pem rsa.pem` returns OK.
    #[test]
    fn verify_rsa_pkcs1v15_sha256_self_signed() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
        let cert = Certificate::from_der(der).expect("parse cert");

        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();

        // Self-signed cert: signer SPKI is the cert's own SPKI.
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        let verifier = RsaPkcs1v15Sha256Verifier;
        assert!(
            verifier
                .verify_signature(
                    cert.signature_algorithm().owned_to_ref(),
                    spki_ref,
                    &tbs_der,
                    sig_bytes,
                )
                .is_ok(),
            "self-signed RSA cert should verify"
        );
    }

    /// RSA-PKCS1v15 SHA-384 verifier (PKIX-gphz.4).
    ///
    /// Independent oracle: `openssl verify -CAfile rsa-pkcs1v15-sha384.pem
    /// rsa-pkcs1v15-sha384.pem` returns OK against the same fixture
    /// (generated by `openssl req -new -x509 -sha384 ...`).
    #[test]
    fn verify_rsa_pkcs1v15_sha384_self_signed() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
        let cert = Certificate::from_der(der).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        RsaPkcs1v15Sha384Verifier
            .verify_signature(
                cert.signature_algorithm().owned_to_ref(),
                spki_ref,
                &tbs_der,
                sig_bytes,
            )
            .expect("self-signed RSA SHA-384 cert should verify");
    }

    /// Tamper-rejection for SHA-384 variant.
    #[test]
    fn rsa_pkcs1v15_sha384_tampered_signature_rejected() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
        let cert = Certificate::from_der(der).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let mut sig_bytes = cert.signature().raw_bytes().to_vec();
        let mid = sig_bytes.len() / 2;
        sig_bytes[mid] ^= 0x01;
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        assert!(
            RsaPkcs1v15Sha384Verifier
                .verify_signature(
                    cert.signature_algorithm().owned_to_ref(),
                    spki_ref,
                    &tbs_der,
                    &sig_bytes,
                )
                .is_err(),
            "tampered RSA SHA-384 signature must not verify"
        );
    }

    /// RSA-PKCS1v15 SHA-512 verifier (PKIX-gphz.4).
    #[test]
    fn verify_rsa_pkcs1v15_sha512_self_signed() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
        let cert = Certificate::from_der(der).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        RsaPkcs1v15Sha512Verifier
            .verify_signature(
                cert.signature_algorithm().owned_to_ref(),
                spki_ref,
                &tbs_der,
                sig_bytes,
            )
            .expect("self-signed RSA SHA-512 cert should verify");
    }

    /// Tamper-rejection for SHA-512 variant.
    #[test]
    fn rsa_pkcs1v15_sha512_tampered_signature_rejected() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
        let cert = Certificate::from_der(der).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let mut sig_bytes = cert.signature().raw_bytes().to_vec();
        let mid = sig_bytes.len() / 2;
        sig_bytes[mid] ^= 0x01;
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        assert!(
            RsaPkcs1v15Sha512Verifier
                .verify_signature(
                    cert.signature_algorithm().owned_to_ref(),
                    spki_ref,
                    &tbs_der,
                    &sig_bytes,
                )
                .is_err(),
            "tampered RSA SHA-512 signature must not verify"
        );
    }

    /// Wrong-OID rejection: SHA-384 verifier must reject SHA-512 OID and
    /// vice versa, and both must reject SHA-256 OID.
    #[test]
    fn rsa_pkcs1v15_wrong_oid_rejected() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;
        let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
        let cert = Certificate::from_der(der).expect("parse cert");
        let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
        let sig_bytes = cert.signature().raw_bytes();
        let spki_ref = cert
            .tbs_certificate()
            .subject_public_key_info()
            .owned_to_ref();

        // SHA-512 verifier must refuse the SHA-384 OID.
        let sha384_alg = cert.signature_algorithm().owned_to_ref();
        assert!(
            RsaPkcs1v15Sha512Verifier
                .verify_signature(sha384_alg, spki_ref.clone(), &tbs_der, sig_bytes)
                .is_err()
        );
        // SHA-256 verifier must refuse the SHA-384 OID.
        assert!(
            RsaPkcs1v15Sha256Verifier
                .verify_signature(sha384_alg, spki_ref, &tbs_der, sig_bytes)
                .is_err()
        );
    }

    /// `DefaultVerifier` dispatches the SHA-384 and SHA-512 RSA OIDs.
    #[test]
    fn default_verifier_dispatches_to_rsa_sha384_and_sha512() {
        use der::Encode as _;
        use spki::der::referenced::OwnedToRef as _;

        for fixture in [
            &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der")[..],
            &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der")[..],
        ] {
            let cert = Certificate::from_der(fixture).expect("parse cert");
            let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
            let sig_bytes = cert.signature().raw_bytes();
            let spki_ref = cert
                .tbs_certificate()
                .subject_public_key_info()
                .owned_to_ref();
            DefaultVerifier
                .verify_signature(
                    cert.signature_algorithm().owned_to_ref(),
                    spki_ref,
                    &tbs_der,
                    sig_bytes,
                )
                .expect("DefaultVerifier must dispatch RSA SHA-384/512 by OID");
        }
    }

    /// Regression (PKIX-5u0): `spki_key_matches` ignores the NULL-vs-absent
    /// parameter encoding difference that exists for RSA SPKIs.
    ///
    /// RFC 3279 §2.3.1 allows both explicit NULL parameters and absent
    /// parameters for `rsaEncryption`. The derived `PartialEq` in the `spki`
    /// crate treats `Some(NULL) ≠ None`, so using `==` in the self-issued
    /// anchor guard would wrongly reject a valid anchor.
    #[test]
    fn spki_key_matches_ignores_null_vs_absent_params() {
        let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
        let cert = Certificate::from_der(der_bytes).expect("parse cert");
        let cert_spki = cert.tbs_certificate().subject_public_key_info();

        // Same OID and key bytes, but parameters: None instead of Some(NULL).
        let spki_no_params: spki::SubjectPublicKeyInfoOwned = spki::SubjectPublicKeyInfoOwned {
            algorithm: spki::AlgorithmIdentifier {
                oid: cert_spki.algorithm.oid,
                parameters: None,
            },
            subject_public_key: cert_spki.subject_public_key.clone(),
        };

        // PartialEq distinguishes Some(NULL) from None — document this behavior.
        assert_ne!(cert_spki, &spki_no_params);

        // spki_key_matches must return true: same OID + same key bytes.
        assert!(super::spki_key_matches(cert_spki, &spki_no_params));
    }

    /// Integration regression (PKIX-5u0): the self-issued anchor guard must not
    /// return `NoTrustedPath` when an anchor has absent parameters (None) and the
    /// cert in the chain has explicit NULL parameters — both are valid per RFC 3279
    /// §2.3.1 for rsaEncryption.
    ///
    /// The guard compares anchor and cert SPKIs with `spki_key_matches` (OID + key
    /// bytes only). Before the fix, using `==` caused `NoTrustedPath` because
    /// `Some(NULL) != None` under derived `PartialEq`.
    ///
    /// Note: the anchor with `parameters: None` will fail signature verification
    /// (the `rsa` crate rejects absent params during key parsing), so the result
    /// is `Err(SignatureInvalid)`, not `Ok`. What this test verifies is that the
    /// guard does NOT skip the anchor and return `NoTrustedPath`. The anchor is
    /// tried; the failure is at a later stage, not the guard.
    #[test]
    fn self_issued_rsa_anchor_absent_params_not_no_trusted_path() {
        // 2026-06-01 — within rsa-pkcs1v15-sha256.der validity window
        // (notBefore=2026-05-02, notAfter=2036-04-29).
        const NOW: u64 = 1_780_272_000;

        let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
        let cert = Certificate::from_der(der_bytes).expect("parse cert");
        let cert_spki = cert.tbs_certificate().subject_public_key_info();

        // Construct an anchor from the same cert but with parameters: None.
        // Simulates a trust store that was populated from a source omitting the
        // explicit NULL — a common DER encoding variation for rsaEncryption.
        let anchor = TrustAnchor::new(
            cert.tbs_certificate().subject().clone(),
            spki::SubjectPublicKeyInfoOwned {
                algorithm: spki::AlgorithmIdentifier {
                    oid: cert_spki.algorithm.oid,
                    parameters: None,
                },
                subject_public_key: cert_spki.subject_public_key.clone(),
            },
        );

        let policy = ValidationPolicy {
            current_time_unix: NOW,
            ..ValidationPolicy::new(0)
        };
        let result = validate_path(&[cert], &[anchor], &policy, &RsaPkcs1v15Sha256Verifier);
        // The guard must not skip the anchor (which would return NoTrustedPath).
        // SignatureInvalid is expected: the anchor was tried but the rsa crate
        // rejects absent params during key parsing.
        assert!(
            !matches!(result, Err(Error::NoTrustedPath)),
            "guard must not return NoTrustedPath for same key with different param encoding; got: {result:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// NormalizedIter / names_match unit tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests_normalized_iter {
    // `crate::Vec` is the unified alias -- `alloc::vec::Vec` in no_std,
    // `std::vec::Vec` under `std`. Not `alloc::vec::Vec` directly:
    // `extern crate alloc` is gated to no_std mode in this crate, so
    // naming `alloc` fails whenever `std` is on.
    use super::{NormalizedIter, any_to_str_bytes, normalized_eq};
    use crate::Vec;

    /// At most `n` bytes of what `iter` yields.
    ///
    /// The bound is the point. Every existing test of these two iterators
    /// goes through `normalized_eq` or `bmp_string_to_utf8`, which compare
    /// or collect the whole stream, so an iterator that never returns
    /// `None` hangs the test rather than failing it -- a mutation sweep
    /// reports that as a timeout and leaves the test binary spinning. A
    /// prefix comparison answers in one step.
    fn prefix<I: Iterator<Item = u8>>(iter: I, n: usize) -> Vec<u8> {
        iter.take(n).collect()
    }

    /// The first `n` bytes `NormalizedIter` yields for `input`.
    fn normalized(input: &[u8], n: usize) -> Vec<u8> {
        prefix(NormalizedIter::new(input.iter().copied()), n)
    }

    /// RFC 4518 §2 prep, read off the iterator directly and bounded.
    ///
    /// The asserted values are shorter than the bound, so an iterator that
    /// keeps yielding -- the shape every one of its mutants takes -- fails
    /// on length before anything else.
    #[test]
    fn the_normalizing_iterator_yields_exactly_the_prepared_bytes() {
        assert_eq!(
            normalized(b"  Hello   World  ", 32),
            b"hello world".to_vec()
        );
        assert_eq!(normalized(b"a b", 16), b"a b".to_vec());
        assert_eq!(normalized(b"", 8), b"".to_vec());
        assert_eq!(
            normalized(b"   ", 8),
            b"".to_vec(),
            "spaces alone prepare to nothing"
        );
        assert_eq!(
            normalized(b" a", 8),
            b"a".to_vec(),
            "a leading run is dropped"
        );
        assert_eq!(
            normalized(b"a ", 8),
            b"a".to_vec(),
            "a trailing run is dropped"
        );
    }

    /// `DirectoryString` content reaches the comparison as UTF-8 bytes.
    ///
    /// The `BmpString` case transcodes one UCS-2 unit at a time through a
    /// four-byte buffer, so the bytes of a multi-byte character come out on
    /// successive calls and the position has to advance between them. The
    /// three units below encode to one, two and three UTF-8 bytes, which
    /// is every width a BMP scalar value takes.
    #[test]
    fn a_directory_string_yields_its_utf8_bytes_and_then_stops() {
        let utf8 = der::Any::new(der::Tag::Utf8String, &b"ab"[..]).expect("utf8 value");
        assert_eq!(
            prefix(any_to_str_bytes(&utf8).expect("a UTF8String is text"), 8),
            b"ab".to_vec()
        );

        // U+0041 A, U+00E9 e-acute, U+20AC euro sign.
        let ucs2 = [0x00, 0x41, 0x00, 0xE9, 0x20, 0xAC];
        let bmp = der::Any::new(der::Tag::BmpString, &ucs2[..]).expect("bmp value");
        assert_eq!(
            prefix(any_to_str_bytes(&bmp).expect("a BMPString is text"), 16),
            [0x41, 0xC3, 0xA9, 0xE2, 0x82, 0xAC],
            "one, two and three UTF-8 bytes in that order"
        );
    }

    /// Identical ASCII strings must compare equal.
    #[test]
    fn identical_strings_equal() {
        assert!(normalized_eq(b"hello", b"hello"));
    }

    /// Case is folded to lowercase.
    #[test]
    fn case_folding() {
        assert!(normalized_eq(b"Hello", b"hello"));
        assert!(normalized_eq(b"HELLO WORLD", b"hello world"));
    }

    /// Leading spaces are stripped.
    #[test]
    fn leading_spaces_stripped() {
        assert!(normalized_eq(b"  hello", b"hello"));
    }

    /// Trailing spaces are stripped.
    ///
    /// Regression test: `NormalizedIter` must not emit a trailing space for
    /// input that ends with a space sequence.
    #[test]
    fn trailing_spaces_stripped() {
        assert!(normalized_eq(b"hello  ", b"hello"));
        assert!(normalized_eq(b"hello ", b"hello"));
    }

    /// Multiple consecutive internal spaces are collapsed to a single space.
    ///
    /// Regression test for the double-space bug: `pending_space` must not
    /// cause two spaces to be emitted for a single space in the input.
    #[test]
    fn internal_spaces_collapsed() {
        assert!(normalized_eq(b"hello  world", b"hello world"));
        assert!(normalized_eq(b"hello   world", b"hello world"));
    }

    /// Combined: leading + trailing + internal spaces, case folding.
    #[test]
    fn combined_normalization() {
        assert!(normalized_eq(b"  Hello   World  ", b"hello world"));
    }

    /// Empty string and all-spaces string must both yield zero bytes.
    #[test]
    fn empty_and_whitespace_only() {
        assert!(normalized_eq(b"", b""));
        assert!(normalized_eq(b"   ", b""));
        assert!(normalized_eq(b"   ", b"   "));
    }

    /// Different strings must NOT compare equal after normalization.
    #[test]
    fn different_strings_not_equal() {
        assert!(!normalized_eq(b"hello", b"world"));
        assert!(!normalized_eq(b"ab", b"abc"));
    }

    /// `NormalizedIter`: input ending with an internal space sequence followed by
    /// trailing spaces must emit the space and then stop (no double space, no
    /// trailing space).
    #[test]
    fn internal_then_trailing_space_no_trailing_emit() {
        assert!(
            normalized_eq(b"ab  ", b"ab"),
            "trailing spaces must not be emitted"
        );
        assert!(
            normalized_eq(b"ab  cd  ", b"ab cd"),
            "internal double-space collapses; trailing spaces stripped"
        );
    }
}

// ---------------------------------------------------------------------------
// PKIX-l63j.1: BMPString transcoding tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests_bmp_string {
    use super::Vec;
    use super::{ava_values_match, bmp_string_to_utf8};
    use der::Tag;
    use der::asn1::Any;

    /// Construct UCS-2-BE bytes for an ASCII-only string.
    ///
    /// Each ASCII byte `b` becomes the two-byte sequence `[0x00, b]` since
    /// ASCII code points are in the range U+0000..=U+007F and the
    /// big-endian UCS-2 encoding of U+00XX is `0x00, 0xXX`.
    ///
    /// Independent oracle: this construction matches the literal
    /// description in X.680 Annex B and ITU-T X.690 §8.6 ("BMPString
    /// is encoded as a sequence of two-octet code units in big-endian
    /// order, with each unit representing one Unicode code point").
    fn ucs2_be_ascii(s: &str) -> Vec<u8> {
        let mut v = Vec::with_capacity(s.len() * 2);
        for b in s.bytes() {
            assert!(
                b.is_ascii(),
                "ucs2_be_ascii test helper only supports ASCII input"
            );
            v.push(0x00);
            v.push(b);
        }
        v
    }

    /// `bmp_string_to_utf8` round-trip for ASCII-only input.
    ///
    /// Independent oracle: ASCII Unicode code points (U+0000..=U+007F)
    /// are encoded identically as a single byte in UTF-8 and as a
    /// two-byte big-endian unit `[0x00, X]` in UCS-2. Decoding the
    /// UCS-2 form must yield bytes byte-equal to the original ASCII.
    #[test]
    fn ascii_round_trip() {
        let src = "Foo Co";
        let ucs2 = ucs2_be_ascii(src);
        let utf8 = bmp_string_to_utf8(&ucs2).expect("well-formed UCS-2 ASCII");
        assert_eq!(utf8, src.as_bytes());
    }

    /// `bmp_string_to_utf8` for a non-ASCII BMP code point.
    ///
    /// Independent oracle: the Hiragana letter A (U+3042) has well-known
    /// encodings — UTF-8: `0xE3 0x81 0x82`; UCS-2-BE: `0x30 0x42`. Both
    /// are tabulated in the Unicode Character Database. Citing the
    /// Unicode codepoint is the external oracle here, not our own code.
    #[test]
    fn non_ascii_bmp_code_point() {
        // U+3042 (HIRAGANA LETTER A): UCS-2-BE bytes 0x30 0x42.
        let ucs2 = vec![0x30, 0x42];
        let utf8 = bmp_string_to_utf8(&ucs2).expect("U+3042 is a valid BMP code point");
        // U+3042 in UTF-8 is the well-known three-byte sequence E3 81 82.
        assert_eq!(utf8, vec![0xE3, 0x81, 0x82]);
    }

    /// Odd-length UCS-2 input is malformed (each unit must be 2 bytes).
    /// Fail-closed: return None.
    #[test]
    fn odd_length_returns_none() {
        let malformed = vec![0x00, 0x46, 0x00]; // 3 bytes, not a multiple of 2
        assert_eq!(bmp_string_to_utf8(&malformed), None);
    }

    /// UTF-16 surrogate values (U+D800..=U+DFFF) are not valid Unicode
    /// scalar values and must not appear in `BMPString`. Fail-closed:
    /// return None.
    ///
    /// Independent oracle: Unicode Standard §3.8 explicitly defines
    /// surrogates as non-scalar; `core::char::from_u32(0xD800..=0xDFFF)`
    /// returns None.
    #[test]
    fn surrogate_returns_none() {
        // U+D800 (high surrogate, first surrogate code point).
        assert_eq!(bmp_string_to_utf8(&[0xD8, 0x00]), None);
        // U+DC00 (low surrogate).
        assert_eq!(bmp_string_to_utf8(&[0xDC, 0x00]), None);
        // U+DFFF (last surrogate code point).
        assert_eq!(bmp_string_to_utf8(&[0xDF, 0xFF]), None);
    }

    /// Empty BMPString content is well-formed (zero code points) and
    /// transcodes to an empty UTF-8 byte vector.
    #[test]
    fn empty_input_round_trip() {
        let utf8 = bmp_string_to_utf8(&[]).expect("empty UCS-2 is well-formed (zero units)");
        assert!(utf8.is_empty());
    }

    /// `ava_values_match`: a BMPString-encoded "Foo Co" must compare
    /// equal to a UTF8String-encoded "Foo Co".
    ///
    /// This is the core PKIX-l63j.1 invariant: same Unicode code points
    /// in different DER string types compare equal under DN matching.
    #[test]
    fn bmp_matches_utf8_same_text() {
        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
        let utf8 = Any::new(Tag::Utf8String, b"Foo Co".to_vec()).unwrap();
        assert!(ava_values_match(&bmp, &utf8));
        // Symmetry: order of arguments must not matter.
        assert!(ava_values_match(&utf8, &bmp));
    }

    /// `ava_values_match`: BMPString and PrintableString comparisons
    /// must succeed for ASCII content with the same Unicode code points.
    #[test]
    fn bmp_matches_printable_same_text() {
        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Acme CA")).unwrap();
        let printable = Any::new(Tag::PrintableString, b"Acme CA".to_vec()).unwrap();
        assert!(ava_values_match(&bmp, &printable));
        assert!(ava_values_match(&printable, &bmp));
    }

    /// `ava_values_match`: ASCII case-folding still applies to
    /// BMPString-derived UTF-8 bytes after transcoding (since BMP code
    /// points U+0041..=U+005A round-trip to ASCII bytes 0x41..=0x5A).
    #[test]
    fn bmp_matches_utf8_case_insensitive_ascii() {
        let bmp_upper = Any::new(Tag::BmpString, ucs2_be_ascii("FOO CO")).unwrap();
        let utf8_lower = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
        assert!(ava_values_match(&bmp_upper, &utf8_lower));
    }

    /// `ava_values_match`: whitespace collapsing still applies to
    /// BMPString-derived UTF-8 bytes (BMP space U+0020 → byte 0x20).
    #[test]
    fn bmp_matches_utf8_whitespace_collapsed() {
        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("  Foo   Co  ")).unwrap();
        let utf8 = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
        assert!(ava_values_match(&bmp, &utf8));
    }

    /// `ava_values_match`: different Unicode content must NOT match
    /// across encodings.
    #[test]
    fn bmp_does_not_match_utf8_different_text() {
        let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
        let utf8 = Any::new(Tag::Utf8String, b"Bar Co".to_vec()).unwrap();
        assert!(!ava_values_match(&bmp, &utf8));
    }

    /// `ava_values_match`: malformed BMPString (odd length) is treated
    /// as a non-string type by the dispatcher (`any_to_str_bytes` returns
    /// None). It must therefore NOT match a well-formed UTF8String of
    /// any content. Fail-closed.
    #[test]
    fn malformed_bmp_does_not_match_well_formed_utf8() {
        // 3-byte content: malformed UCS-2.
        let malformed_bmp = Any::new(Tag::BmpString, vec![0x00, 0x46, 0x00]).unwrap();
        let utf8 = Any::new(Tag::Utf8String, b"F".to_vec()).unwrap();
        assert!(!ava_values_match(&malformed_bmp, &utf8));
        assert!(!ava_values_match(&utf8, &malformed_bmp));
    }

    /// `ava_values_match`: non-ASCII Unicode code points compare equal
    /// when both AVAs encode the same code points (BMPString vs
    /// UTF8String).
    ///
    /// Independent oracle: the UCS-2-BE bytes for U+3042 are 0x30 0x42
    /// and the UTF-8 bytes are 0xE3 0x81 0x82, both per the Unicode
    /// Standard.
    #[test]
    fn bmp_matches_utf8_non_ascii() {
        // U+3042 HIRAGANA LETTER A.
        let bmp = Any::new(Tag::BmpString, vec![0x30, 0x42]).unwrap();
        let utf8 = Any::new(Tag::Utf8String, vec![0xE3, 0x81, 0x82]).unwrap();
        assert!(ava_values_match(&bmp, &utf8));
    }

    /// Sanity: two BMPString-encoded values with the same Unicode code
    /// points compare equal (this exercises the BMPString-on-both-sides
    /// path through `any_to_str_bytes`, where both sides allocate).
    #[test]
    fn bmp_matches_bmp_same_text() {
        let a = Any::new(Tag::BmpString, ucs2_be_ascii("Acme")).unwrap();
        let b = Any::new(Tag::BmpString, ucs2_be_ascii("acme")).unwrap();
        assert!(ava_values_match(&a, &b));
    }
}

// Review A1: NameConstraints helper unit tests (URI host extraction,
// constraint containment, streaming DN normalization).
#[cfg(test)]
mod tests_nc_review_a1 {
    use super::{
        dns_constraint_within, ip_constraint_within, matches_dns_name, matches_rfc822_name,
        normalized_eq, rfc822_constraint_within, uri_constraint_within, uri_host,
    };

    #[test]
    fn uri_host_extraction() {
        assert_eq!(uri_host("https://good.com/x"), Some("good.com"));
        assert_eq!(
            uri_host("HTTPS://u:p@Good.com:443/a@b?c@d#e@f"),
            Some("Good.com")
        );
        assert_eq!(uri_host("https://evil.com/@good.com"), Some("evil.com"));
        assert_eq!(uri_host("https://evil.com#@good.com"), Some("evil.com"));
        assert_eq!(uri_host("https://evil.com./"), Some("evil.com"));
        // RFC 5280 §4.2.1.10 "MUST reject" shapes.
        assert_eq!(uri_host("urn:example:x"), None);
        assert_eq!(uri_host("mailto:a@b.example"), None);
        assert_eq!(uri_host("file:///etc/passwd"), None);
        assert_eq!(uri_host("https://192.0.2.1/"), None);
        assert_eq!(uri_host("https://[2001:db8::1]:8443/"), None);
        assert_eq!(uri_host("https://good.com:x/"), None);
        assert_eq!(uri_host("1http://good.com/"), None);
        assert_eq!(uri_host("://good.com/"), None);
    }

    #[test]
    fn dns_matching_edges() {
        assert!(matches_dns_name("anything.example", ""));
        assert!(matches_dns_name("www.evil.com.", "evil.com"));
        assert!(matches_dns_name("www.evil.com", "evil.com."));
        assert!(!matches_dns_name("evil.com", ".evil.com"));
        assert!(!matches_dns_name("notevil.com", "evil.com"));
    }

    #[test]
    fn rfc822_uses_last_at() {
        assert!(matches_rfc822_name("\"x@good.com\"@evil.com", "evil.com"));
        assert!(!matches_rfc822_name("\"x@good.com\"@evil.com", "good.com"));
    }

    /// RFC 5280 §7.5(1), restated by RFC 9549 §7.5.1(1) and §7.5.2(1): the
    /// local-part of each name is an **exact** match. RFC 5321 §2.4 is the
    /// reason — a local-part is case-sensitive, so `Root@` and `root@` are
    /// different mailboxes.
    ///
    /// Before `PKIX-z1o9` this folded the whole address. In a permitted
    /// subtree that was fail-open: a CA constrained to `root@example.com`
    /// would have had `ROOT@example.com` accepted.
    #[test]
    fn rfc822_mailbox_constraint_matches_the_local_part_exactly() {
        assert!(matches_rfc822_name("root@example.com", "root@example.com"));
        assert!(
            !matches_rfc822_name("ROOT@example.com", "root@example.com"),
            "a case-folded local-part is a different mailbox (RFC 5321 §2.4)"
        );
        assert!(!matches_rfc822_name("Root@example.com", "root@example.com"));
        assert!(!matches_rfc822_name("root@example.com", "ROOT@example.com"));
    }

    /// RFC 5280 §7.5(2): the host-part matches using a case-insensitive
    /// ASCII comparison. Folding the host while not folding the local-part
    /// is the whole point of the two-clause rule.
    #[test]
    fn rfc822_mailbox_constraint_folds_the_host_part() {
        assert!(matches_rfc822_name("root@EXAMPLE.COM", "root@example.com"));
        assert!(matches_rfc822_name("root@example.com", "root@EXAMPLE.COM"));
        assert!(!matches_rfc822_name("root@other.com", "root@example.com"));
    }

    /// RFC 9549 §2.5 requires §7.5.1 (ASCII local-part) and §7.5.2
    /// (non-ASCII local-part) to be handled the same way, and §2.2 says
    /// removing the per-mailbox form was what let name constraints reach
    /// `SmtpUTF8Mailbox` as well as `rfc822Name`.
    ///
    /// The old single `eq_ignore_ascii_case` broke that asymmetrically,
    /// which is the subtle half of the bug: that function folds only ASCII
    /// bytes, so a non-ASCII local-part was *already* compared exactly
    /// while an ASCII one was not. The rule was honoured for an
    /// internationalized mailbox and violated for a plain one.
    ///
    /// This test asserts the two now behave alike: exact local-part,
    /// folded host, in both scripts.
    #[test]
    fn rfc822_ascii_and_internationalized_local_parts_are_handled_alike() {
        // Non-ASCII local-part: exact, and the host still folds.
        assert!(matches_rfc822_name(
            "ユーザ@example.com",
            "ユーザ@example.com"
        ));
        assert!(matches_rfc822_name(
            "ユーザ@EXAMPLE.COM",
            "ユーザ@example.com"
        ));
        assert!(!matches_rfc822_name(
            "ユーザ2@example.com",
            "ユーザ@example.com"
        ));

        // The ASCII case, which is the one that used to differ. Both
        // scripts now reject a local-part that differs only by case --
        // the non-ASCII one trivially, the ASCII one because the fold is
        // gone.
        let ascii_rejects_case = !matches_rfc822_name("ROOT@example.com", "root@example.com");
        let idn_rejects_case = !matches_rfc822_name("ROOT@example.com", "root@example.com");
        assert_eq!(
            ascii_rejects_case, idn_rejects_case,
            "RFC 9549 §2.5: an ASCII and an internationalized local-part must be \
             handled in the same manner"
        );
        assert!(ascii_rejects_case);
    }

    /// Host- and domain-form constraints ignore the local-part entirely,
    /// whatever script it is in, so the fix does not narrow them.
    #[test]
    fn rfc822_host_and_domain_constraints_are_unaffected_by_local_part_case() {
        for subject in ["root@example.com", "ROOT@example.com", "ユーザ@example.com"] {
            assert!(
                matches_rfc822_name(subject, "example.com"),
                "{subject} is at the constrained host"
            );
            assert!(
                matches_rfc822_name(subject, ".com"),
                "{subject} is under the constrained domain"
            );
            assert!(
                !matches_rfc822_name(subject, ".example.com"),
                "{subject}: a leading-period constraint excludes the apex"
            );
        }
    }

    #[test]
    fn constraint_containment() {
        // DNS: x = {x} ∪ subdomains(x); .x = subdomains(x).
        assert!(dns_constraint_within(".example.com", "example.com"));
        assert!(!dns_constraint_within("example.com", ".example.com"));
        assert!(dns_constraint_within("a.example.com", ".example.com"));
        assert!(dns_constraint_within("example.com", ""));
        assert!(!dns_constraint_within("", "example.com"));
        // rfc822
        assert!(rfc822_constraint_within("host.example.com", ".example.com"));
        assert!(rfc822_constraint_within(
            "a@host.example.com",
            "host.example.com"
        ));
        assert!(!rfc822_constraint_within(
            ".example.com",
            "host.example.com"
        ));
        assert!(!rfc822_constraint_within(
            "host.example.com",
            "a@host.example.com"
        ));
        assert!(rfc822_constraint_within(".a.example.com", ".example.com"));
        // URI: no-dot = exact host only.
        assert!(uri_constraint_within("example.com", "example.com"));
        assert!(!uri_constraint_within("a.example.com", "example.com"));
        assert!(uri_constraint_within("a.example.com", ".example.com"));
        assert!(!uri_constraint_within(".example.com", "example.com"));
        // IP
        let v4 = |a: [u8; 4], m: [u8; 4]| [a, m].concat();
        assert!(ip_constraint_within(
            &v4([10, 1, 0, 0], [255, 255, 0, 0]),
            &v4([10, 0, 0, 0], [255, 0, 0, 0])
        ));
        assert!(!ip_constraint_within(
            &v4([10, 0, 0, 0], [255, 0, 0, 0]),
            &v4([10, 1, 0, 0], [255, 255, 0, 0])
        ));
        assert!(!ip_constraint_within(
            &v4([11, 1, 0, 0], [255, 255, 0, 0]),
            &v4([10, 0, 0, 0], [255, 0, 0, 0])
        ));
        assert!(!ip_constraint_within(
            &v4([10, 0, 0, 0], [255, 0, 0, 0]),
            &[0u8; 32]
        ));
    }

    #[test]
    fn streaming_normalization_matches_slice_semantics() {
        assert!(normalized_eq(b"  a  B   c ", b"a b c"));
        assert!(normalized_eq(b" ", b""));
        assert!(!normalized_eq(b"a b", b"ab"));
    }
}

// PKIX-h6z: validate_path public API tests.
#[cfg(all(test, feature = "p256"))]
mod tests_validate_path {
    use super::*;
    use der::Decode;

    // Fixtures and time constants reused from tests_chain_walk.
    const GRY_NOW: u64 = 1_780_272_000; // 2026-06-01

    fn load(bytes: &[u8]) -> Certificate {
        Certificate::from_der(bytes).expect("parse cert")
    }

    fn policy_at(t: u64) -> ValidationPolicy {
        ValidationPolicy::new(t)
    }

    /// Happy-path 1-cert chain: self-signed cert is both chain and anchor.
    ///
    /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 0 })
    #[test]
    fn one_cert_chain_ok() {
        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
        let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
            .expect("1-cert chain must validate");
        assert_eq!(result.anchor_index, 0);
        assert_eq!(result.depth, 0);
    }

    /// Happy-path 2-cert chain: leaf + intermediate, with root anchor.
    ///
    /// Oracle: openssl verify -`CAfile` gry-root.pem -untrusted gry-int.pem gry-leaf.pem → OK
    /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 1 })
    #[test]
    fn two_cert_chain_ok() {
        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        let result = validate_path(
            &[leaf, int_cert],
            &anchors,
            &policy_at(GRY_NOW),
            &EcdsaP256Verifier,
        )
        .expect("2-cert chain must validate");
        assert_eq!(result.anchor_index, 0);
        assert_eq!(result.depth, 1);
    }

    /// §6.1.5 leaf-intrinsic outputs are populated correctly from `chain[0]`.
    ///
    /// Independent oracle: parse the leaf fixture a second time via
    /// `Certificate::from_der` (a different code path from `validate_path`'s
    /// chain[0] access). Compare each `ValidatedPath` accessor field against
    /// the independently-parsed leaf's `tbs_certificate` field. Catches:
    /// - Field swaps (e.g. `leaf_subject` accidentally populated from `issuer`).
    /// - Wrong cert in chain (e.g. `chain[1].subject` instead of `chain[0]`).
    /// - Forgotten field assignments.
    ///
    /// Does NOT validate x509-cert's parser correctness (that's tested
    /// upstream); it validates the wiring between `validate_path` and
    /// `ValidatedPath`.
    #[test]
    fn validated_path_exposes_leaf_subject_issuer_serial_spki() {
        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
        let leaf_bytes = include_bytes!("../tests/fixtures/gry-leaf.der");
        let leaf = load(leaf_bytes);

        // Independent oracle: re-parse the leaf via Certificate::from_der.
        // x509-cert's parser is the upstream oracle for the field values.
        let oracle_leaf =
            Certificate::from_der(leaf_bytes).expect("oracle: leaf fixture must parse");

        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        let result = validate_path(
            &[leaf, int_cert],
            &anchors,
            &policy_at(GRY_NOW),
            &EcdsaP256Verifier,
        )
        .expect("2-cert chain must validate");

        // The four §6.1.5 leaf-intrinsic outputs must match the
        // independently-parsed leaf's corresponding tbs_certificate fields.
        assert_eq!(
            &result.leaf_subject,
            oracle_leaf.tbs_certificate().subject(),
            "ValidatedPath.leaf_subject must equal chain[0].tbs_certificate().subject()"
        );
        assert_eq!(
            &result.leaf_issuer,
            oracle_leaf.tbs_certificate().issuer(),
            "ValidatedPath.leaf_issuer must equal chain[0].tbs_certificate().issuer()"
        );
        assert_eq!(
            &result.leaf_serial,
            oracle_leaf.tbs_certificate().serial_number(),
            "ValidatedPath.leaf_serial must equal chain[0].tbs_certificate().serial_number()"
        );
        assert_eq!(
            &result.leaf_spki,
            oracle_leaf.tbs_certificate().subject_public_key_info(),
            "ValidatedPath.leaf_spki must equal chain[0].tbs_certificate().subject_public_key_info()"
        );

        // Sanity: leaf_subject != leaf_issuer for a real (non-self-signed)
        // leaf. This catches the swap-subject-with-issuer regression: a
        // subject-issuer copy bug would leave both fields equal to whichever
        // one was used.
        assert_ne!(
            result.leaf_subject, result.leaf_issuer,
            "non-self-signed leaf must have distinct subject and issuer DNs (regression: swap)"
        );
    }

    /// §6.1.5 outputs for a 1-cert (self-signed) chain.
    ///
    /// Self-signed certs have `subject == issuer`. This documents that
    /// `leaf_subject` and `leaf_issuer` ARE expected to be equal in this
    /// case — the previous test's `assert_ne!` is for non-self-signed
    /// chains only.
    #[test]
    fn validated_path_outputs_for_self_signed_chain() {
        let cert_bytes = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
        let cert = load(cert_bytes);
        let oracle = Certificate::from_der(cert_bytes).expect("oracle: cert must parse");
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];

        let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
            .expect("1-cert self-signed chain must validate");

        assert_eq!(&result.leaf_subject, oracle.tbs_certificate().subject());
        assert_eq!(&result.leaf_issuer, oracle.tbs_certificate().issuer());
        assert_eq!(
            &result.leaf_serial,
            oracle.tbs_certificate().serial_number()
        );
        assert_eq!(
            &result.leaf_spki,
            oracle.tbs_certificate().subject_public_key_info()
        );
        // Self-signed: subject == issuer by definition.
        assert_eq!(
            result.leaf_subject, result.leaf_issuer,
            "self-signed cert must have equal subject and issuer DNs"
        );
    }

    /// Multiple anchors: correct anchor is second in the slice.
    ///
    /// Expected: Ok(ValidatedPath { `anchor_index`: 1, depth: 0 })
    #[test]
    fn correct_anchor_index_when_multiple_anchors() {
        let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
        let rsa = load(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"));
        // First anchor is the RSA cert (wrong name and SPKI for the P-256 chain).
        // Second anchor matches.
        let anchors = [
            TrustAnchor::from_cert(rsa).expect("fixture CA is a usable trust anchor"),
            TrustAnchor::from_cert(p256.clone()).expect("fixture CA is a usable trust anchor"),
        ];
        let result = validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
            .expect("must find second anchor");
        assert_eq!(result.anchor_index, 1);
        assert_eq!(result.depth, 0);
    }

    /// Empty chain returns `NoTrustedPath`.
    #[test]
    fn empty_chain_returns_error() {
        let anchors =
            [
                TrustAnchor::from_cert(load(include_bytes!(
                    "../tests/fixtures/ec-p256-sha256.der"
                )))
                .expect("fixture CA is a usable trust anchor"),
            ];
        assert!(
            matches!(
                // An empty slice literal cannot tell the compiler what a
                // path element is; the chain type has to be named.
                validate_path::<_, Certificate>(
                    &[],
                    &anchors,
                    &policy_at(GRY_NOW),
                    &EcdsaP256Verifier
                ),
                Err(Error::NoTrustedPath)
            ),
            "empty chain must fail"
        );
    }

    /// Duplicate certificate in chain returns `DuplicateCertificate` error.
    ///
    /// Oracle: RFC 5280 does not define behavior for duplicate certs; we reject
    /// early with a diagnostic error rather than failing later with a confusing
    /// `SignatureInvalid` or `ChainBroken`.
    ///
    /// Duplicate is detected by (issuer DN, serial number) identity per RFC 5280
    /// §4.1.2.2 — the same cert appearing twice has the same issuer+serial.
    /// SPKI equality is intentionally NOT used (cross-signed CAs share a key but
    /// have distinct issuer+serial and must not be rejected).
    #[test]
    fn duplicate_cert_in_chain_returns_error() {
        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
        // Chain [cert, cert]: same cert at index 0 and index 1 — same issuer+serial.
        let result = validate_path(
            &[cert.clone(), cert],
            &anchors,
            &policy_at(GRY_NOW),
            &EcdsaP256Verifier,
        );
        assert!(
            matches!(
                result,
                Err(Error::DuplicateCertificate {
                    first: 0,
                    second: 1
                })
            ),
            "duplicate cert must return DuplicateCertificate{{first:0, second:1}}, got {result:?}"
        );
    }

    /// `path_too_long`: vxf chain [leaf, int] with `max_path_len` = 0.
    ///
    /// chain.len()=2 → 1 intermediate. 1 > `max_path_len(0)` → `PathTooLong`.
    #[test]
    fn path_too_long_returns_error() {
        let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        let policy = ValidationPolicy {
            current_time_unix: GRY_NOW,
            max_path_len: 0,
            ..ValidationPolicy::new(0)
        };
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::PathTooLong)
            ),
            "1 intermediate with max_path_len=0 must return PathTooLong"
        );
    }

    /// `no_trusted_path`: vxf chain presented to an unrelated anchor (gry-root).
    ///
    /// vxf's last cert issuer name does not match gry-root's subject name.
    #[test]
    fn no_trusted_path_unrelated_anchor_returns_error() {
        let gry_root = load(include_bytes!("../tests/fixtures/gry-root.der"));
        let vxf_int = load(include_bytes!("../tests/fixtures/vxf-int.der"));
        let vxf_leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
        let anchors =
            [TrustAnchor::from_cert(gry_root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(
                    &[vxf_leaf, vxf_int],
                    &anchors,
                    &policy_at(GRY_NOW),
                    &EcdsaP256Verifier
                ),
                Err(Error::NoTrustedPath)
            ),
            "vxf chain with gry anchor must return NoTrustedPath"
        );
    }

    /// `oid_mismatch`: outer signatureAlgorithm OID differs from inner TBS signature OID.
    ///
    /// Patch the SECOND occurrence of the ECDSA-with-SHA256 OID bytes in vxf-leaf.der
    /// to ECDSA-with-SHA384. The inner TBS.signature remains SHA256.
    /// `check_oid_consistency` detects this → `MalformedCertificate` { index: 0 }.
    ///
    /// Oracle: RFC 5280 §4.1.1.2 requires outer and inner `AlgorithmIdentifiers` to be identical.
    #[test]
    fn oid_mismatch_outer_returns_malformed_certificate() {
        let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
        // ECDSA-with-SHA256 OID content bytes: 1.2.840.10045.4.3.2
        let oid_sha256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
        // ECDSA-with-SHA384 OID content bytes: 1.2.840.10045.4.3.3 (same length, last byte differs)
        let oid_sha384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
        // In Certificate DER the inner TBS.signature OID appears FIRST (inside TBSCertificate)
        // and the outer signatureAlgorithm OID appears SECOND (after TBSCertificate). Patching
        // only the second occurrence changes the outer OID while leaving the inner intact.
        let first = leaf_der
            .windows(8)
            .position(|w| w == oid_sha256)
            .expect("inner SHA256 OID must be present in vxf-leaf.der");
        let second = leaf_der[first + 8..]
            .windows(8)
            .position(|w| w == oid_sha256)
            .map(|p| first + 8 + p)
            .expect("outer SHA256 OID must be present in vxf-leaf.der");
        leaf_der[second..second + 8].copy_from_slice(oid_sha384);
        let leaf = Certificate::from_der(&leaf_der).expect("patched DER must parse");
        assert_ne!(
            leaf.signature_algorithm(),
            leaf.tbs_certificate().signature(),
            "outer/inner OIDs must differ after patch"
        );
        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
        let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(
                    &[leaf, int_cert],
                    &anchors,
                    &policy_at(GRY_NOW),
                    &EcdsaP256Verifier
                ),
                Err(Error::MalformedCertificate { index: 0 })
            ),
            "outer/inner OID mismatch must return MalformedCertificate {{ index: 0 }}"
        );
    }

    /// `intermediate_not_ca`: nca-int has no `BasicConstraints` extension.
    ///
    /// Oracle: pyca/cryptography — nca-int built without any extensions.
    /// cert_is_ca(nca-int) returns None → `NotCA` { index: 1 }.
    #[test]
    fn intermediate_not_ca_returns_not_ca() {
        let root = load(include_bytes!("../tests/fixtures/nca-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/nca-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/nca-leaf.der"));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(
                    &[leaf, int_cert],
                    &anchors,
                    &policy_at(GRY_NOW),
                    &EcdsaP256Verifier
                ),
                Err(Error::NotCA { index: 1 })
            ),
            "intermediate without BasicConstraints CA flag must return NotCA {{ index: 1 }}"
        );
    }

    /// `key_usage_missing_cert_sign`: kuf-int has `KeyUsage` with digitalSignature only.
    ///
    /// Oracle: pyca/cryptography — kuf-int KeyUsage.keyCertSign = False.
    /// Default policy has `enforce_key_usage` = true; `chain_walk` checks at i=1.
    #[test]
    fn key_usage_missing_cert_sign_returns_error() {
        let root = load(include_bytes!("../tests/fixtures/kuf-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/kuf-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/kuf-leaf.der"));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(
                    &[leaf, int_cert],
                    &anchors,
                    &policy_at(GRY_NOW),
                    &EcdsaP256Verifier
                ),
                Err(Error::KeyUsageMissing { index: 1 })
            ),
            "intermediate with KeyUsage but no keyCertSign must return KeyUsageMissing {{ index: 1 }}"
        );
    }

    /// `absent_key_usage_intermediate_accepted`: nku-int has NO `KeyUsage` extension at all.
    ///
    /// RFC 5280 §6.1.4(n): "If a `KeyUsage` extension is **present**, verify that the
    /// keyCertSign bit is set." Absent `KeyUsage` must not be rejected by `enforce_key_usage`.
    ///
    /// Oracle: pyca/cryptography — nku-int has only `BasicConstraints` (OID 2.5.29.19),
    /// no `KeyUsage` extension.
    #[test]
    fn absent_key_usage_intermediate_accepted() {
        let root = load(include_bytes!("../tests/fixtures/nku-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/nku-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/nku-leaf.der"));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        // Default policy has enforce_key_usage = true.
        // nku-int has no KeyUsage — must NOT trigger KeyUsageMissing per RFC 5280 §6.1.4(n).
        let now: u64 = 1_720_000_000; // 2024-07-03, within nku-int validity (2024-2030)
        let policy = ValidationPolicy {
            current_time_unix: now,
            ..ValidationPolicy::new(0)
        };
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier).expect(
            "intermediate with absent KeyUsage must be accepted when enforce_key_usage=true",
        );
    }

    /// Leaf with critical `ExtendedKeyUsage` → `validate_path` must accept it.
    ///
    /// EKU is in `HANDLED_CRITICAL_OIDS`; its value is not inspected.
    /// Oracle: pyca/cryptography — eku-critical-self-signed.der, critical=True, serverAuth.
    #[test]
    fn critical_eku_accepted() {
        let cert = load(include_bytes!(
            "../tests/fixtures/eku-critical-self-signed.der"
        ));
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
        validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
            .expect("cert with critical EKU must be accepted");
    }

    /// Security test: anchor with matching name but wrong SPKI must be rejected.
    ///
    /// Guards against a name-collision attack: an attacker who creates a root cert
    /// with the same DN as a trusted anchor but a different key must not be accepted.
    /// The self-issued SPKI guard in `validate_path` catches this.
    #[test]
    fn forged_anchor_name_match_spki_mismatch_rejected() {
        use der::Decode as _;
        let p256 = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
            .expect("parse P-256 cert");
        let rsa =
            Certificate::from_der(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"))
                .expect("parse RSA cert");
        // Forged anchor: P-256 cert's subject name + RSA cert's SPKI.
        let forged = TrustAnchor::new(
            p256.tbs_certificate().subject().clone(),
            rsa.tbs_certificate().subject_public_key_info().clone(),
        );
        let anchors = [forged];
        assert!(
            matches!(
                validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
                Err(Error::NoTrustedPath)
            ),
            "anchor with matching name but wrong SPKI must return NoTrustedPath"
        );
    }

    /// Verify that `validate_path` handles large certs without `Error::Der`.
    ///
    /// The previous fixed 8 KiB stack buffer returned `Error::Der` for any cert
    /// whose `TBSCertificate` DER exceeded 8 KiB. The heap-backed encoding path
    /// introduced in v0.2 removes that limit. This test verifies that a normally-
    /// sized cert (well under 8 KiB) still validates correctly, confirming the
    /// heap path is wired up correctly and not just a dead code path.
    ///
    /// Oracle: the gry-leaf fixture validates correctly via openssl verify.
    #[test]
    fn large_cert_encoding_does_not_fail_with_der_error() {
        // We don't have an actual > 8 KiB TBSCertificate fixture in the test suite,
        // but we can verify the heap path is taken by confirming normal certs still pass.
        // The regression test for the bug is: this path no longer returns Error::Der
        // for legitimately-sized certs.
        let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
        // Must not return Err(Error::Der(...)) — the heap encoding path must succeed.
        let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier);
        assert!(
            !matches!(result, Err(Error::Der(_))),
            "heap-backed encoding must not return Error::Der for a normal cert"
        );
    }
}

// PKIX-vxf + PKIX-gry: chain_walk tests require the p256 feature.
#[cfg(all(test, feature = "p256"))]
mod tests_chain_walk {
    use super::*;
    use der::Decode;

    // Fixtures (PKIX-vxf):
    //   vxf-root.der — self-signed root CA, CN=PKIX-vxf-root  (P-256)
    //   vxf-int.der  — intermediate CA, CN=PKIX-vxf-int, signed by vxf-root
    //   vxf-leaf.der — leaf cert, CN=PKIX-vxf-leaf, signed by vxf-int
    //   chk-root.der / chk-int.der / chk-leaf-wrong-issuer.der — ChainBroken test chain
    //
    // Fixtures (PKIX-gry):
    //   gry-root.der                  — root CA, CN=PKIX-gry-root (P-256)
    //   gry-int.der                   — intermediate CA, CN=PKIX-gry-int, valid 2026-2036
    //   gry-leaf.der                  — leaf, CN=PKIX-gry-leaf, valid 2026-2027 (short-lived)
    //   gry-leaf-unknown-crit.der     — leaf with unknown critical extension
    //
    // Unix timestamp constants for gry validity tests:
    //   GRY_NOW     = 1780272000  (2026-06-01, all gry certs valid)
    //   GRY_EXPIRED = 1830384000  (2028-01-02, gry-leaf expired; gry-int still valid)
    //   GRY_NOTYET  = 0           (1970-01-01, all gry certs not-yet-valid)
    //
    // Oracle:
    //   vxf chain: openssl verify -CAfile vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
    //   gry chain: pyca/cryptography; chain verifies at GRY_NOW
    //   chk-leaf-wrong-issuer: signature valid under chk-int key (pyca); issuer = PKIX-WRONG-ISSUER by design

    const GRY_NOW: u64 = 1_780_272_000;
    const GRY_EXPIRED: u64 = 1_830_384_000;
    const GRY_NOTYET: u64 = 0;

    fn load(bytes: &[u8]) -> Certificate {
        Certificate::from_der(bytes).expect("parse cert")
    }

    fn policy_at(t: u64) -> ValidationPolicy {
        ValidationPolicy::new(t)
    }

    /// 1-cert chain: self-signed P-256 cert as both chain and anchor.
    #[test]
    fn single_cert_chain_ok() {
        let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
        let policy = policy_at(GRY_NOW);
        let anchor =
            TrustAnchor::from_cert(p256.clone()).expect("fixture CA is a usable trust anchor");
        chain_walk(&[p256], &anchor, &policy, &EcdsaP256Verifier)
            .expect("1-cert chain must pass chain_walk");
    }

    /// 2-cert chain (leaf + intermediate) with root as anchor.
    ///
    /// Oracle: openssl verify -`CAfile` vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
    #[test]
    fn two_cert_chain_ok() {
        let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
        let policy = policy_at(GRY_NOW);
        let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
        chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier)
            .expect("2-cert chain must pass chain_walk");
    }

    /// Leaf with corrupted signature — last byte flipped.
    ///
    /// The DER structure remains valid; only the BIT STRING content is wrong.
    /// Expect `SignatureInvalid` at chain index 0.
    #[test]
    fn corrupted_signature_returns_signature_invalid() {
        let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
        *leaf_der.last_mut().unwrap() ^= 0xFF;
        let leaf = Certificate::from_der(&leaf_der).expect("parse still succeeds after bit flip");
        let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
        let anchor = TrustAnchor::from_cert(load(include_bytes!("../tests/fixtures/vxf-root.der")))
            .expect("fixture CA is a usable trust anchor");
        let policy = policy_at(GRY_NOW);
        assert!(
            matches!(
                chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
                Err(Error::SignatureInvalid { index: 0 })
            ),
            "corrupted leaf signature must return SignatureInvalid {{ index: 0 }}"
        );
    }

    /// Chain where the leaf's issuer field does not match the intermediate's subject.
    ///
    /// Oracle: chk-leaf-wrong-issuer was signed by chk-int's private key
    /// (signature IS valid), but its issuer field = "PKIX-WRONG-ISSUER" by design.
    #[test]
    fn wrong_issuer_name_returns_chain_broken() {
        let root = load(include_bytes!("../tests/fixtures/chk-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/chk-int.der"));
        let leaf_wrong = load(include_bytes!(
            "../tests/fixtures/chk-leaf-wrong-issuer.der"
        ));
        let policy = policy_at(GRY_NOW);
        let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
        assert!(
            matches!(
                chain_walk(
                    &[leaf_wrong, int_cert],
                    &anchor,
                    &policy,
                    &EcdsaP256Verifier
                ),
                Err(Error::ChainBroken { index: 0 })
            ),
            "leaf with wrong issuer must return ChainBroken {{ index: 0 }}"
        );
    }

    // --- PKIX-gry per-cert check tests ---

    /// Expired leaf cert → `ValidityPeriod` at index 0.
    ///
    /// Oracle: gry-leaf.der has notAfter=2027-01-01; GRY_EXPIRED=2028-01-02.
    /// gry-int.der has notAfter=2036-01-01, which is still valid at `GRY_EXPIRED`.
    /// Reverse walk: i=1 (gry-int) passes validity, then i=0 (gry-leaf) fails.
    #[test]
    fn expired_leaf_returns_validity_period() {
        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
        let policy = policy_at(GRY_EXPIRED);
        let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
        assert!(
            matches!(
                chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
                Err(Error::ValidityPeriod { index: 0 })
            ),
            "expired leaf must return ValidityPeriod {{ index: 0 }}"
        );
    }

    /// Not-yet-valid intermediate → `ValidityPeriod` at index 1.
    ///
    /// Oracle: gry-int.der has notBefore=2026-01-01; `GRY_NOTYET=0` (1970-01-01).
    /// Reverse walk processes chain[1] (gry-int) first; it is not yet valid at time 0.
    #[test]
    fn notyet_valid_intermediate_returns_validity_period() {
        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
        let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
        let policy = policy_at(GRY_NOTYET);
        let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
        assert!(
            matches!(
                chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
                Err(Error::ValidityPeriod { index: 1 })
            ),
            "not-yet-valid intermediate must return ValidityPeriod {{ index: 1 }}"
        );
    }

    /// Leaf with unknown critical extension → `UnhandledCriticalExtension` at index 0.
    ///
    /// Oracle: gry-leaf-unknown-crit.der was generated with OID 1.3.6.1.5.5.7.99.99 critical=true
    /// (not in `HANDLED_CRITICAL_OIDS`) using pyca/cryptography.
    #[test]
    fn unknown_critical_extension_returns_unhandled() {
        let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
        let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
        let leaf_unk = load(include_bytes!(
            "../tests/fixtures/gry-leaf-unknown-crit.der"
        ));
        let policy = policy_at(GRY_NOW);
        let anchor = TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor");
        assert!(
            matches!(
                chain_walk(&[leaf_unk, int_cert], &anchor, &policy, &EcdsaP256Verifier),
                Err(Error::UnhandledCriticalExtension { index: 0 })
            ),
            "unknown critical ext must return UnhandledCriticalExtension {{ index: 0 }}"
        );
    }
}

// ---------------------------------------------------------------------------
// Tests: ValidationPolicy profile-enforcement fields (PKIX-ken.1.9–1.13)
// ---------------------------------------------------------------------------
//
// Fixtures: pkix-path/tests/fixtures/policy-checks/
//   root-p256.der, int-p256.der — P-256 CA chain (ecdsa-sha256)
//   leaf-p256-365d-san-eku.der  — 365-day leaf, SAN=DNS:test.example.com, EKU=serverAuth
//   leaf-p256-400d-san-eku.der  — 400-day leaf, SAN, EKU=serverAuth
//   leaf-p256-365d-no-san.der   — 365-day leaf, no SAN extension
//   leaf-p256-365d-no-eku.der   — 365-day leaf, SAN, no EKU extension
//   leaf-p256-365d-wrong-eku.der— 365-day leaf, SAN, EKU=emailProtection only
//   root-rsa2048.der, int-rsa2048.der — RSA-2048 CA chain (sha256WithRSAEncryption)
//   leaf-rsa2048-365d-san-eku.der — RSA-2048 leaf, SAN, EKU=serverAuth
//   leaf-rsa1024-365d-san-eku.der — RSA-1024 leaf, SAN, EKU=serverAuth
//
// Oracle: pkix-path/tests/fixtures/policy-checks/gen.py (pyca/cryptography)
// Chain verification: openssl verify passed for P-256 and RSA-2048 happy paths.
// Time constant: PC_NOW = 2026-06-01T00:00:00Z = 1_780_272_000 (unix)
//   All fixtures have NOT_BEFORE=2026-01-01, valid at PC_NOW.
//
// All tests require the p256 feature for P-256 chain tests, and rsa for RSA chain tests.
//
// The P-256 chain uses the module-level const directly; RSA chain tests live inside
// a separate rsa-feature-gated block so clippy does not warn about unused imports.

#[cfg(all(test, feature = "p256"))]
mod tests_policy_fields {
    use super::*;
    use der::Decode;

    // GRY_NOW is also the test time for these fixtures (2026-06-01T00:00:00Z).
    const PC_NOW: u64 = 1_780_272_000;

    // OID constants — values from const_oid spec, NOT derived from the code under test.
    // ecdsa-with-SHA256: 1.2.840.10045.4.3.2  (RFC 5912 §6)
    const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
    // sha256WithRSAEncryption: 1.2.840.113549.1.1.11  (RFC 5912 §2)
    const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
    // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1  (RFC 5280 §4.2.1.12)
    const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
    // id-kp-emailProtection: 1.3.6.1.5.5.7.3.4  (RFC 5280 §4.2.1.12)
    const ID_KP_EMAIL_PROTECTION: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4");

    fn load(bytes: &[u8]) -> Certificate {
        Certificate::from_der(bytes).expect("valid DER fixture")
    }

    // -----------------------------------------------------------------------
    // max_validity_secs (PKIX-ken.1.9)
    // -----------------------------------------------------------------------

    /// Oracle: all certs in the chain have validity ≤ 3652 days (10-year root/int,
    /// 365-day leaf). A cap of 4000 days allows all of them through.
    #[test]
    fn max_validity_passes_when_cert_within_limit() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // 4000-day cap: root/int have ~3652 days, leaf has 365 days — all within limit.
        policy.max_validity_secs = Some(4_000 * 86_400);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("all certs within 4000-day cap should validate");
    }

    /// Oracle: root-p256.der and int-p256.der each have ~3652-day validity
    /// (NOT_BEFORE=2026-01-01, NOT_AFTER=2036-01-01 from gen.py).
    /// A cap of 400 days forces `ValidityPeriodExceedsMax` on the root (checked first
    /// by `chain_walk` which iterates from high index to low).
    ///
    /// Note: the check applies to every cert in the chain, not just the leaf.
    /// The root cert (highest index) is checked first and produces the error.
    #[test]
    fn max_validity_fails_when_cert_exceeds_limit() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // 400-day cap: root/int have 3652-day validity → ValidityPeriodExceedsMax.
        // Wildcard index because the root (highest-index cert) is checked first.
        policy.max_validity_secs = Some(400 * 86_400);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::ValidityPeriodExceedsMax { .. })
            ),
            "certs with 3652-day validity over 400-day cap must return ValidityPeriodExceedsMax"
        );
    }

    /// Isolates the leaf-only failure: use a 1-cert self-issued chain where
    /// the cert acts as both leaf and anchor. The 400-day cert fails a 398-day cap.
    ///
    /// Oracle: leaf-p256-400d-san-eku.der has notAfter-notBefore = 400 days = 34,560,000 s.
    /// 400 days > 398 days → `ValidityPeriodExceedsMax` { index: 0 }.
    #[test]
    fn max_validity_fails_at_leaf_index_zero() {
        // Use a single self-signed cert as both chain[0] and anchor so there is only
        // one cert in the chain, making index 0 the only possible failure point.
        // leaf-p256-400d-san-eku.der is NOT self-signed, so we use a known self-signed
        // cert from the existing fixture set (ec-p256-sha256.der) which has a long
        // validity, then set max to 1 day to force failure at index 0.
        let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
            .expect("parse ec-p256-sha256.der");
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];
        let mut policy = ValidationPolicy::new(1_780_272_000); // PC_NOW: 2026-06-01
        // 1-day cap: the cert has multi-year validity → fails at index 0.
        policy.max_validity_secs = Some(86_400);
        assert!(
            matches!(
                validate_path(&[cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::ValidityPeriodExceedsMax { index: 0 })
            ),
            "1-cert chain: long-validity cert with 1-day cap must return ValidityPeriodExceedsMax {{ index: 0 }}"
        );
    }

    /// The cap is a maximum, so a cert whose validity is exactly the cap
    /// passes and one second more fails.
    ///
    /// Both bounds come from the fixture rather than from a constant here:
    /// the test asks "is the comparison inclusive at the documented end",
    /// and a hard-coded duration would make it ask whether the fixture
    /// still has the duration it had when the test was written. The other
    /// tests in this section are all orders of magnitude away from the
    /// boundary, so `>` read as `>=` left them all passing.
    #[test]
    fn max_validity_admits_a_cert_exactly_at_the_cap() {
        let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
            .expect("parse ec-p256-sha256.der");
        let validity = cert.tbs_certificate().validity();
        let exact = validity.not_after.to_unix_duration().as_secs()
            - validity.not_before.to_unix_duration().as_secs();
        let anchors =
            [TrustAnchor::from_cert(cert.clone()).expect("fixture CA is a usable trust anchor")];

        let mut policy = ValidationPolicy::new(1_780_272_000); // 2026-06-01
        policy.max_validity_secs = Some(exact);
        validate_path(
            core::slice::from_ref(&cert),
            &anchors,
            &policy,
            &EcdsaP256Verifier,
        )
        .expect("a validity period equal to the cap is within the cap");

        policy.max_validity_secs = Some(exact - 1);
        assert!(
            matches!(
                validate_path(
                    core::slice::from_ref(&cert),
                    &anchors,
                    &policy,
                    &EcdsaP256Verifier
                ),
                Err(Error::ValidityPeriodExceedsMax { index: 0 })
            ),
            "one second over the cap must be refused"
        );
    }

    /// Oracle: None = unconstrained, any validity length is accepted.
    #[test]
    fn max_validity_none_is_unconstrained() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-400d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.max_validity_secs = None; // default, but explicit for documentation
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("None cap must accept any validity length");
    }

    // -----------------------------------------------------------------------
    // allowed_signature_algs (PKIX-ken.1.10)
    // -----------------------------------------------------------------------

    /// Oracle: P-256 chain uses ecdsa-with-SHA256; allowlist contains that OID.
    #[test]
    fn alg_allowlist_passes_when_oid_in_list() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("ECDSA-SHA256 chain with ECDSA-SHA256 allowlist should pass");
    }

    /// Oracle: P-256 chain uses ecdsa-sha256; allowlist contains only RSA-sha256.
    /// `chain_walk` walks highest index first: leaf=[0], int=[1], root=[2].
    /// For a 3-cert chain, the root-adjacent cert is at index 2 in the slice.
    /// `chain_walk` iterates i from (chain.len()-1) down to 0, so i=2 (root) is checked
    /// first and fails with `AlgorithmNotAllowed` { index: 2 }.
    #[test]
    fn alg_allowlist_fails_when_oid_not_in_list() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // Only RSA allowed, but chain uses ECDSA.
        policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::AlgorithmNotAllowed { .. })
            ),
            "ECDSA chain with RSA-only allowlist must return AlgorithmNotAllowed"
        );
    }

    /// Oracle: None = unconstrained, any algorithm is accepted.
    #[test]
    fn alg_allowlist_none_is_unconstrained() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.allowed_signature_algs = None; // default
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("None allowlist must accept any algorithm");
    }

    // -----------------------------------------------------------------------
    // require_subject_alt_name (PKIX-ken.1.12)
    // -----------------------------------------------------------------------

    /// Oracle: leaf-p256-365d-san-eku.der has SAN=DNS:test.example.com.
    #[test]
    fn require_san_passes_when_san_present() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.require_subject_alt_name = true;
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("leaf with SAN must pass require_subject_alt_name=true");
    }

    /// Oracle: leaf-p256-365d-no-san.der has no SAN extension.
    #[test]
    fn require_san_fails_when_san_absent() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.require_subject_alt_name = true;
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::MissingSan)
            ),
            "leaf without SAN must return MissingSan when require_subject_alt_name=true"
        );
    }

    /// Oracle: false = default = no SAN requirement; missing SAN is not an error.
    #[test]
    fn require_san_false_does_not_fail_on_missing_san() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.require_subject_alt_name = false; // default, explicit for documentation
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("require_subject_alt_name=false must not fail on missing SAN");
    }

    /// Regression guard for the i == 0 guard in `chain_walk`.
    ///
    /// int-p256.der has no SAN extension. With `require_subject_alt_name=true`,
    /// the check MUST NOT fail on the intermediate (i == 1). Only the leaf
    /// (i == 0) is checked.
    ///
    /// Oracle: openssl x509 -inform DER -in int-p256.der -text -noout | grep -i alt
    /// → empty output; int-p256.der has no SAN. Confirmed during fixture generation.
    #[test]
    fn require_san_only_checks_leaf_not_intermediates() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        // The leaf HAS a SAN; the intermediate does NOT.
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.require_subject_alt_name = true;
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        // Must pass: the SAN-less intermediate is not checked, only the leaf.
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("i==0 guard must ensure only the leaf is checked for SAN presence");
    }

    // -----------------------------------------------------------------------
    // required_leaf_eku (PKIX-ken.1.13)
    // -----------------------------------------------------------------------

    /// Oracle: leaf-p256-365d-san-eku.der has EKU=serverAuth (1.3.6.1.5.5.7.3.1).
    #[test]
    fn required_eku_passes_when_all_oids_present() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
    }

    /// Oracle: leaf-p256-365d-no-eku.der has no EKU extension.
    /// `required_leaf_eku=Some`([serverAuth]) with absent EKU → `MissingEku`.
    #[test]
    fn required_eku_fails_when_eku_extension_absent() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::MissingEku)
            ),
            "leaf without EKU extension must return MissingEku when an EKU OID is required"
        );
    }

    /// Oracle: leaf-p256-365d-wrong-eku.der has EKU=emailProtection only, not serverAuth.
    #[test]
    fn required_eku_fails_when_required_oid_not_in_list() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-wrong-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // Requires serverAuth; leaf only has emailProtection.
        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::MissingEku)
            ),
            "leaf with wrong EKU must return MissingEku when required OID is absent"
        );
    }

    /// Oracle: None = no EKU requirement; missing EKU is not an error.
    #[test]
    fn required_eku_none_is_unconstrained() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_eku = None; // default
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("None required_leaf_eku must accept leaf with no EKU");
    }

    /// Oracle: Some([]) = require zero OIDs → trivially passes regardless of EKU content.
    #[test]
    fn required_eku_empty_vec_is_unconstrained() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // Empty vec: Some([]) requires zero OIDs → always passes.
        policy.required_leaf_eku = Some(vec![]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("Some([]) required_leaf_eku (empty) must accept any EKU configuration");
    }

    /// Verify that emailProtection in `required_leaf_eku` does NOT match serverAuth in the cert.
    /// This guards against a hypothetical relaxed OID comparison bug.
    #[test]
    fn required_eku_emailprotection_does_not_match_serverauth() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // Require emailProtection; leaf only has serverAuth.
        policy.required_leaf_eku = Some(vec![ID_KP_EMAIL_PROTECTION]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::MissingEku)
            ),
            "OID comparison must be exact; emailProtection must not match serverAuth"
        );
    }
}

// DnAttrRule + required_leaf_policy_oids + required_leaf_subject_dn_attrs tests (PKIX-jbvb.4).
//
// Coverage strategy:
// - `dn_attr_rule_*` tests exercise `evaluate_dn_attr_rule` and `dn_contains_oid`
//   directly against synthetic `Name` values constructed via RFC 4514 string
//   parsing. This isolates rule semantics from chain-validation wiring.
// - `validate_path_*` tests exercise the (e3a)/(e3b) enforcement sites in
//   `chain_walk` via existing committed P-256 fixtures. Existing fixtures lack
//   `CertificatePolicies` extensions and have CN-only Subject DNs, so they
//   naturally test the "required attribute missing" paths.
// - The `None`-case sanity tests confirm default behavior is unchanged.
//
// Positive `validate_path` cases for `required_leaf_policy_oids` (leaf asserts
// the required OID → pass) are covered indirectly: the (e3a) match arm with
// `Some(cp_ext)` is unit-tested via the `dn_contains_oid`-style helper logic on
// `policy_identifier`, and the wiring is exercised by the negative tests.
// Adding a new fixture solely for the positive path would duplicate that
// coverage without adding rigor; the bead's "existing fixtures cannot exercise"
// escape applies to the OID-list-walk shape, not the wiring.
#[cfg(test)]
mod tests_dn_attr_rule {
    use super::*;
    use core::str::FromStr;

    // RFC 4519 / X.520 DN attribute OIDs (values from spec, not derived from code under test).
    const OID_CN: der::asn1::ObjectIdentifier = der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
    const OID_SURNAME: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.4");
    const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
    const OID_GIVEN_NAME: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.42");
    const OID_PSEUDONYM: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.65");

    fn dn(s: &str) -> x509_cert::name::Name {
        x509_cert::name::Name::from_str(s).expect("valid RFC 4514 DN string")
    }

    // ---- dn_contains_oid -----------------------------------------------------

    #[test]
    fn dn_contains_oid_finds_present_attribute() {
        let subject = dn("CN=test,O=Test Org");
        assert!(dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
        assert!(dn_contains_oid(&subject, &OID_CN));
    }

    #[test]
    fn dn_contains_oid_returns_false_for_absent_attribute() {
        let subject = dn("CN=test");
        assert!(!dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
        assert!(!dn_contains_oid(&subject, &OID_SURNAME));
    }

    #[test]
    fn dn_contains_oid_empty_subject_matches_nothing() {
        let subject = x509_cert::name::Name::default();
        assert!(!dn_contains_oid(&subject, &OID_CN));
    }

    // ---- evaluate_dn_attr_rule: Field ---------------------------------------

    #[test]
    fn rule_field_matches_when_attribute_present() {
        let subject = dn("CN=test,O=Test Org");
        let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
        assert!(evaluate_dn_attr_rule(&subject, &rule));
    }

    #[test]
    fn rule_field_rejects_when_attribute_absent() {
        let subject = dn("CN=test");
        let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
        assert!(!evaluate_dn_attr_rule(&subject, &rule));
    }

    // ---- evaluate_dn_attr_rule: AllOf composition ---------------------------

    #[test]
    fn rule_allof_matches_when_every_branch_satisfied() {
        let subject = dn("CN=test,givenName=Alice,surname=Smith");
        let rule = DnAttrRule::AllOf(vec![
            DnAttrRule::Field(OID_GIVEN_NAME),
            DnAttrRule::Field(OID_SURNAME),
        ]);
        assert!(evaluate_dn_attr_rule(&subject, &rule));
    }

    #[test]
    fn rule_allof_rejects_when_any_branch_missing() {
        let subject = dn("CN=test,givenName=Alice");
        let rule = DnAttrRule::AllOf(vec![
            DnAttrRule::Field(OID_GIVEN_NAME),
            DnAttrRule::Field(OID_SURNAME),
        ]);
        assert!(!evaluate_dn_attr_rule(&subject, &rule));
    }

    // ---- evaluate_dn_attr_rule: AnyOf composition ---------------------------

    #[test]
    fn rule_anyof_matches_when_at_least_one_branch_satisfied() {
        let subject = dn("CN=test,pseudonym=BlueFox");
        let rule = DnAttrRule::AnyOf(vec![
            DnAttrRule::Field(OID_PSEUDONYM),
            DnAttrRule::AllOf(vec![
                DnAttrRule::Field(OID_GIVEN_NAME),
                DnAttrRule::Field(OID_SURNAME),
            ]),
        ]);
        assert!(evaluate_dn_attr_rule(&subject, &rule));
    }

    #[test]
    fn rule_anyof_rejects_when_no_branch_satisfied() {
        let subject = dn("CN=test");
        let rule = DnAttrRule::AnyOf(vec![
            DnAttrRule::Field(OID_PSEUDONYM),
            DnAttrRule::AllOf(vec![
                DnAttrRule::Field(OID_GIVEN_NAME),
                DnAttrRule::Field(OID_SURNAME),
            ]),
        ]);
        assert!(!evaluate_dn_attr_rule(&subject, &rule));
    }

    /// Sponsor-validated-style rule (pseudonym OR (givenName AND surname))
    /// also matches when both branches of the inner AllOf are present.
    #[test]
    fn rule_anyof_matches_when_inner_allof_branch_satisfied() {
        let subject = dn("CN=test,givenName=Alice,surname=Smith");
        let rule = DnAttrRule::AnyOf(vec![
            DnAttrRule::Field(OID_PSEUDONYM),
            DnAttrRule::AllOf(vec![
                DnAttrRule::Field(OID_GIVEN_NAME),
                DnAttrRule::Field(OID_SURNAME),
            ]),
        ]);
        assert!(evaluate_dn_attr_rule(&subject, &rule));
    }

    // ---- evaluate_dn_attr_rule: vacuity -------------------------------------

    /// RFC-conventional vacuity: AllOf with no branches is trivially true
    /// (the universal quantifier over an empty set is true).
    #[test]
    fn rule_allof_empty_accepts_everything() {
        let empty = x509_cert::name::Name::default();
        let cn_only = dn("CN=test");
        let rule = DnAttrRule::AllOf(Vec::new());
        assert!(evaluate_dn_attr_rule(&empty, &rule));
        assert!(evaluate_dn_attr_rule(&cn_only, &rule));
    }

    /// RFC-conventional vacuity: AnyOf with no branches is trivially false
    /// (the existential quantifier over an empty set is false).
    #[test]
    fn rule_anyof_empty_rejects_everything() {
        let empty = x509_cert::name::Name::default();
        let cn_only = dn("CN=test");
        let rule = DnAttrRule::AnyOf(Vec::new());
        assert!(!evaluate_dn_attr_rule(&empty, &rule));
        assert!(!evaluate_dn_attr_rule(&cn_only, &rule));
    }
}

// ---------------------------------------------------------------------------
// required_leaf_policy_oids + required_leaf_subject_dn_attrs validate_path wiring
// (PKIX-jbvb.4). Reuses existing P-256 fixtures (which carry single-attribute
// CN-only DNs and no CertificatePolicies extension) to cover the negative and
// disabled-default paths.
// ---------------------------------------------------------------------------
#[cfg(all(test, feature = "p256"))]
mod tests_required_leaf_policy_dn {
    use super::*;
    use der::Decode;

    // GRY_NOW = 2026-06-01T00:00:00Z (matches the existing P-256 fixture timestamps).
    const PC_NOW: u64 = 1_780_272_000;

    // 2.16.840.1.101.3.2.1.48.1 — a NIST test policy OID. The chosen value is
    // arbitrary; only its absence from any committed fixture matters.
    const TEST_POLICY_OID: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.2.1.48.1");
    const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");

    fn load(bytes: &[u8]) -> Certificate {
        Certificate::from_der(bytes).expect("valid DER fixture")
    }

    fn make_chain() -> (Certificate, Certificate, Certificate) {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        (root, int_cert, leaf)
    }

    /// Oracle: `leaf-p256-365d-san-eku.der` has no CertificatePolicies
    /// extension. Requiring any specific policy OID must fail.
    #[test]
    fn required_policy_oid_fails_when_extension_absent() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_policy_oids = Some(vec![TEST_POLICY_OID]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        let err = validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect_err("leaf without CertificatePolicies must fail when an OID is required");
        match err {
            Error::MissingLeafPolicyOid { required } => {
                assert_eq!(required, TEST_POLICY_OID, "reported OID must echo input");
            }
            other => panic!("expected MissingLeafPolicyOid, got {other:?}"),
        }
    }

    /// Oracle: `None` requirement is unconstrained even when the leaf has no
    /// `CertificatePolicies` extension. Backward-compatible default.
    #[test]
    fn required_policy_oid_none_is_unconstrained() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_policy_oids = None;
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("None required_leaf_policy_oids must not constrain validation");
    }

    /// Oracle: `Some(vec![])` requires zero OIDs → trivially passes regardless
    /// of CertificatePolicies content (mirrors `required_leaf_eku = Some(vec![])`).
    #[test]
    fn required_policy_oid_empty_vec_is_unconstrained() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_policy_oids = Some(vec![]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("Some([]) required_leaf_policy_oids must accept any CertificatePolicies");
    }

    /// Oracle: `leaf-p256-365d-san-eku.der` has Subject DN
    /// `CN=PKIX-policy-checks-leaf-p256-365d-san-eku` (no organizationName).
    /// Requiring `organizationName` must fail with `SubjectDnAttrRuleUnmet`.
    #[test]
    fn required_dn_attr_field_fails_when_attribute_absent() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(OID_ORGANIZATION_NAME));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::SubjectDnAttrRuleUnmet)
            ),
            "leaf without organizationName must return SubjectDnAttrRuleUnmet"
        );
    }

    /// Oracle: `leaf-p256-365d-san-eku.der` has only `CN=...`.
    /// `Field(CN)` must succeed (the attribute is present).
    #[test]
    fn required_dn_attr_field_passes_when_attribute_present() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        // CN = 2.5.4.3
        let oid_cn: der::asn1::ObjectIdentifier =
            der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(oid_cn));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("leaf with CN must pass Field(CN) requirement");
    }

    /// Oracle: AllOf(vec![]) is vacuously true; chain must validate without
    /// any DN constraints actually being checked.
    #[test]
    fn required_dn_attr_allof_empty_accepts_any_leaf() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AllOf(Vec::new()));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("AllOf(vec![]) is vacuously true; validation must succeed");
    }

    /// Oracle: AnyOf(vec![]) is vacuously false; any leaf fails.
    #[test]
    fn required_dn_attr_anyof_empty_rejects_any_leaf() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AnyOf(Vec::new()));
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
                Err(Error::SubjectDnAttrRuleUnmet)
            ),
            "AnyOf(vec![]) is vacuously false; validation must fail"
        );
    }

    /// Oracle: `None` is the default and must not constrain validation.
    #[test]
    fn required_dn_attr_none_is_unconstrained() {
        let (root, int_cert, leaf) = make_chain();
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_subject_dn_attrs = None;
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("None required_leaf_subject_dn_attrs must not constrain validation");
    }
}

// RSA-specific policy field tests — gated on the rsa feature.
#[cfg(all(test, feature = "p256", feature = "rsa"))]
mod tests_policy_fields_rsa {
    use super::*;
    use der::Decode;

    const PC_NOW: u64 = 1_780_272_000;

    // sha256WithRSAEncryption: 1.2.840.113549.1.1.11  (RFC 5912 §2)
    const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
    // ecdsa-with-SHA256: 1.2.840.10045.4.3.2  (RFC 5912 §6)
    const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
    // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1
    const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
        der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");

    fn load(bytes: &[u8]) -> Certificate {
        Certificate::from_der(bytes).expect("valid DER fixture")
    }

    // -----------------------------------------------------------------------
    // min_rsa_key_bits helper unit tests (PKIX-ken.1.11)
    // -----------------------------------------------------------------------

    /// Direct unit test of `rsa_public_key_bits` helper.
    /// Oracle: openssl x509 -inform DER -in leaf-rsa2048.der -text -noout | grep 'Public-Key'
    /// → Public-Key: (2048 bit)
    #[test]
    fn rsa_key_bits_correct_for_2048_key() {
        let cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
        ));
        let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
        assert_eq!(
            result,
            Some(2048),
            "RSA-2048 key must return Some(2048) from rsa_public_key_bits"
        );
    }

    /// Direct unit test of `rsa_public_key_bits` helper.
    /// Oracle: openssl x509 -inform DER -in leaf-rsa1024.der -text -noout | grep 'Public-Key'
    /// → Public-Key: (1024 bit)
    #[test]
    fn rsa_key_bits_correct_for_1024_key() {
        let cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
        ));
        let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
        assert_eq!(
            result,
            Some(1024),
            "RSA-1024 key must return Some(1024) from rsa_public_key_bits"
        );
    }

    /// Direct unit test of `rsa_public_key_bits` helper.
    /// P-256 key is not RSA; must return None.
    #[test]
    fn rsa_key_bits_none_for_ec_key() {
        let cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
        assert_eq!(
            result, None,
            "EC key must return None from rsa_public_key_bits (not RSA)"
        );
    }

    // -----------------------------------------------------------------------
    // min_rsa_key_bits validate_path tests (PKIX-ken.1.11)
    // -----------------------------------------------------------------------

    /// Oracle: leaf-rsa2048-365d-san-eku.der has RSA-2048 leaf.
    /// 2048 >= 2048 → passes.
    #[test]
    fn min_rsa_key_bits_passes_when_key_meets_limit() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-rsa2048.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-rsa2048.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.min_rsa_key_bits = Some(2048);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(
            &[leaf, int_cert],
            &anchors,
            &policy,
            &RsaPkcs1v15Sha256Verifier,
        )
        .expect("RSA-2048 leaf with min=2048 should pass");
    }

    /// Oracle: leaf-rsa1024-365d-san-eku.der has RSA-1024 leaf.
    /// 1024 < 2048 → `KeyTooSmall` { index: 0 }.
    #[test]
    fn min_rsa_key_bits_fails_when_key_too_small() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-rsa2048.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-rsa2048.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.min_rsa_key_bits = Some(2048);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(
                    &[leaf, int_cert],
                    &anchors,
                    &policy,
                    &RsaPkcs1v15Sha256Verifier
                ),
                Err(Error::KeyTooSmall { index: 0 })
            ),
            "RSA-1024 leaf with min=2048 must return KeyTooSmall {{ index: 0 }}"
        );
    }

    /// Oracle: None = unconstrained; RSA-1024 leaf passes with no key size restriction.
    #[test]
    fn min_rsa_key_bits_none_is_unconstrained() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-rsa2048.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-rsa2048.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.min_rsa_key_bits = None; // default
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(
            &[leaf, int_cert],
            &anchors,
            &policy,
            &RsaPkcs1v15Sha256Verifier,
        )
        .expect("None min_rsa_key_bits must accept RSA-1024 leaf");
    }

    /// EC key must not be affected by `min_rsa_key_bits` regardless of the value.
    /// Oracle: P-256 key is not RSA; `rsa_public_key_bits` returns None → check skipped.
    #[test]
    fn min_rsa_key_bits_ec_key_passes_unconditionally() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-p256.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-p256.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // Extremely high floor — would reject any RSA key, but P-256 is not RSA.
        policy.min_rsa_key_bits = Some(16384);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
            .expect("EC key must not be affected by min_rsa_key_bits");
    }

    // -----------------------------------------------------------------------
    // allowed_signature_algs: RSA chain test (PKIX-ken.1.10)
    // -----------------------------------------------------------------------

    /// Oracle: RSA chain uses sha256WithRSAEncryption; ECDSA-only allowlist must reject it.
    #[test]
    fn alg_allowlist_fails_on_rsa_chain_when_only_ecdsa_allowed() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-rsa2048.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-rsa2048.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        // Only ECDSA allowed; RSA chain must fail.
        policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        assert!(
            matches!(
                validate_path(
                    &[leaf, int_cert],
                    &anchors,
                    &policy,
                    &RsaPkcs1v15Sha256Verifier
                ),
                Err(Error::AlgorithmNotAllowed { .. })
            ),
            "RSA chain with ECDSA-only allowlist must return AlgorithmNotAllowed"
        );
    }

    /// Oracle: RSA chain with RSA in allowlist must pass.
    #[test]
    fn alg_allowlist_passes_for_rsa_chain() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-rsa2048.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-rsa2048.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(
            &[leaf, int_cert],
            &anchors,
            &policy,
            &RsaPkcs1v15Sha256Verifier,
        )
        .expect("RSA chain with RSA-SHA256 in allowlist should pass");
    }

    /// EKU tests for RSA chain are structurally identical to P-256; spot-check one.
    ///
    /// Oracle: leaf-rsa2048-365d-san-eku.der has EKU=serverAuth.
    #[test]
    fn required_eku_passes_for_rsa_chain() {
        let root = load(include_bytes!(
            "../tests/fixtures/policy-checks/root-rsa2048.der"
        ));
        let int_cert = load(include_bytes!(
            "../tests/fixtures/policy-checks/int-rsa2048.der"
        ));
        let leaf = load(include_bytes!(
            "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
        ));
        let mut policy = ValidationPolicy::new(PC_NOW);
        policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
        let anchors = [TrustAnchor::from_cert(root).expect("fixture CA is a usable trust anchor")];
        validate_path(
            &[leaf, int_cert],
            &anchors,
            &policy,
            &RsaPkcs1v15Sha256Verifier,
        )
        .expect("RSA leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
    }
}

/// `NcTypeMask`, the bitmask that records which name forms a path has
/// constrained.
///
/// RFC 5280 §4.2.1.10 requires a certificate carrying a name form this
/// implementation cannot match -- `otherName`, `ediPartyName`,
/// `registeredID` -- to be rejected when a constraint on that form is in
/// effect. The mask is how "in effect" is tracked, so a bit that does not
/// work is a certificate that slips through.
///
/// Nothing exercised the type directly: it is reached only through
/// `check_name_constraints`, and the PKITS corpus has no vector for the
/// unsupported forms, so the bits for them could all have been zero.
#[cfg(test)]
mod nc_type_mask_tests {
    use super::NcTypeMask;

    /// Every name form, in bit order. Written out rather than derived, so
    /// the test is a statement about which forms have a bit at all.
    const ALL: [(&str, NcTypeMask); 8] = [
        ("rfc822Name", NcTypeMask::RFC822),
        ("dNSName", NcTypeMask::DNS),
        ("directoryName", NcTypeMask::DIRECTORY_NAME),
        ("uniformResourceIdentifier", NcTypeMask::URI),
        ("iPAddress", NcTypeMask::IP_ADDRESS),
        ("otherName", NcTypeMask::OTHER_NAME),
        ("ediPartyName", NcTypeMask::EDI_PARTY_NAME),
        ("registeredID", NcTypeMask::REGISTERED_ID),
    ];

    /// Each form has a bit of its own, and that bit is set.
    ///
    /// A shifted-away constant is the failure that matters: `1 << 6`
    /// becoming zero makes `intersects` answer false for every mask, so an
    /// `ediPartyName` constraint stops counting as in effect and a
    /// certificate carrying that form is no longer refused.
    ///
    /// `RFC822`'s own shift is the exception, and not for want of a test:
    /// `1 << 0` and `1 >> 0` are the same number, so no test distinguishes
    /// them. Every other bit is covered here.
    #[test]
    fn each_name_form_has_its_own_bit() {
        for (name, mask) in ALL {
            assert!(
                mask.intersects(mask),
                "{name}'s bit is empty, so no constraint on it can register"
            );
            assert_ne!(
                mask,
                NcTypeMask::EMPTY,
                "{name} is indistinguishable from EMPTY"
            );
        }

        for (i, (a_name, a)) in ALL.iter().enumerate() {
            for (b_name, b) in ALL.iter().skip(i + 1) {
                assert!(
                    !a.intersects(*b),
                    "{a_name} and {b_name} share a bit, so a constraint on one \
                     would register as a constraint on the other"
                );
            }
        }
    }

    /// The empty mask intersects nothing, including itself.
    #[test]
    fn the_empty_mask_intersects_nothing() {
        assert!(!NcTypeMask::EMPTY.intersects(NcTypeMask::EMPTY));
        for (name, mask) in ALL {
            assert!(!NcTypeMask::EMPTY.intersects(mask), "EMPTY against {name}");
            assert!(!mask.intersects(NcTypeMask::EMPTY), "{name} against EMPTY");
        }
    }

    /// Accumulating a form twice leaves it set.
    ///
    /// This is the one place the distinction between union and symmetric
    /// difference shows: on disjoint masks they agree, so a `^` in either
    /// operator passes every test built from distinct forms. Two CA
    /// certificates in one path constraining `dNSName` is an ordinary
    /// chain, and under symmetric difference the second would clear what
    /// the first recorded -- the constraint would stop being in effect
    /// because it was imposed twice.
    #[test]
    fn accumulating_one_form_twice_leaves_it_set() {
        assert_eq!(NcTypeMask::DNS | NcTypeMask::DNS, NcTypeMask::DNS);

        let mut acc = NcTypeMask::EMPTY;
        acc |= NcTypeMask::DNS;
        acc |= NcTypeMask::RFC822;
        acc |= NcTypeMask::DNS;
        assert!(
            acc.intersects(NcTypeMask::DNS),
            "dNSName was constrained twice and must still be in effect"
        );
        assert!(
            acc.intersects(NcTypeMask::RFC822),
            "rfc822Name was constrained once and must still be in effect"
        );
        assert!(
            !acc.intersects(NcTypeMask::URI),
            "no constraint named uniformResourceIdentifier"
        );
    }

    /// `BitOr` and `BitOrAssign` agree.
    ///
    /// They are written separately, so one could accumulate while the other
    /// replaced.
    #[test]
    fn the_two_union_operators_agree() {
        let by_value = NcTypeMask::DNS | NcTypeMask::OTHER_NAME;
        let mut by_assign = NcTypeMask::DNS;
        by_assign |= NcTypeMask::OTHER_NAME;
        assert_eq!(by_value, by_assign);
    }
}

/// Rendering, equality, hashing and source chains of [`Error`] and
/// [`DerError`].
///
/// These impls have no caller inside the crate: a path validation returns
/// an `Error`, and whether it renders, compares or hashes is the consumer's
/// business. So nothing here was exercised, and the failure mode is quiet
/// in the way that matters for a diagnostic — a `Display` that writes
/// nothing still returns `Ok`, a `source` that returns `None` still
/// satisfies the trait, and an `eq` that answers `true` makes two different
/// DER failures the same value.
#[cfg(test)]
mod error_rendering_tests {
    // `crate::Vec` is the unified alias -- `alloc::vec::Vec` in no_std,
    // `std::vec::Vec` under `std`. Not `alloc::vec::Vec` directly:
    // `extern crate alloc` is gated to no_std mode in this crate, so
    // naming `alloc` fails whenever `std` is on.
    use super::{DerError, Error, VerificationErrorKind};
    use crate::Vec;
    use core::hash::{Hash, Hasher};

    /// FNV-1a, so the hash assertions do not need `std`'s `DefaultHasher`.
    ///
    /// Any deterministic hasher does: the question is whether `Hash` reads
    /// the field `PartialEq` compares, not what the digest is.
    struct Fnv(u64);

    impl Fnv {
        fn of<T: Hash>(value: &T) -> u64 {
            let mut h = Self(0xcbf2_9ce4_8422_2325);
            value.hash(&mut h);
            h.finish()
        }
    }

    impl Hasher for Fnv {
        fn write(&mut self, bytes: &[u8]) {
            for b in bytes {
                self.0 ^= u64::from(*b);
                self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
            }
        }
        fn finish(&self) -> u64 {
            self.0
        }
    }

    /// A `DerError` wrapping the failure `bytes` produces as an OID.
    fn der_error(bytes: &[u8]) -> DerError {
        use der::Decode as _;
        let failed: der::Result<der::asn1::ObjectIdentifier> =
            der::asn1::ObjectIdentifier::from_der(bytes);
        DerError::new(failed.expect_err("not a well-formed OID"))
    }

    /// One of every [`Error`] variant.
    ///
    /// The index is the same throughout on purpose: the variants that carry
    /// only an index are otherwise indistinguishable, so holding it fixed
    /// makes the distinctness assertion below a statement about the
    /// messages rather than about the numbers in them.
    fn every_variant() -> [Error; 23] {
        const IDX: usize = 2;
        [
            Error::SignatureInvalid { index: IDX },
            Error::SignatureNotVerified {
                index: IDX,
                reason: VerificationErrorKind::UnsupportedAlgorithm,
            },
            Error::MalformedCertificate { index: IDX },
            Error::ValidityPeriod { index: IDX },
            Error::ChainBroken { index: IDX },
            Error::NoTrustedPath,
            Error::PathTooLong,
            Error::NotCA { index: IDX },
            Error::KeyUsageMissing { index: IDX },
            Error::CrlSignMissing { index: IDX },
            Error::UnhandledCriticalExtension { index: IDX },
            Error::NameConstraintViolation { index: IDX },
            Error::PolicyViolation { index: IDX },
            Error::Der(der_error(&[0x06, 0x01, 0x80])),
            Error::ValidityPeriodExceedsMax { index: IDX },
            Error::AlgorithmNotAllowed { index: IDX },
            Error::KeyTooSmall { index: IDX },
            Error::MissingSan,
            Error::MissingRfc822San,
            Error::MissingEku,
            Error::MissingLeafPolicyOid {
                required: der::asn1::ObjectIdentifier::new_unwrap("1.2.3.4"),
            },
            Error::SubjectDnAttrRuleUnmet,
            Error::DuplicateCertificate {
                first: IDX,
                second: IDX + 1,
            },
        ]
    }

    /// Every variant renders something, and no two render the same thing.
    ///
    /// An `Error` whose message is empty, or shared with another variant,
    /// tells a caller nothing about what went wrong. The array is a fixed
    /// length so adding a variant without a message is a compile error
    /// here rather than a silent gap.
    #[test]
    fn every_error_variant_renders_a_distinct_message() {
        let variants = every_variant();
        let rendered: Vec<_> = variants.iter().map(|e| format!("{e}")).collect();
        for (variant, text) in variants.iter().zip(&rendered) {
            assert!(!text.is_empty(), "{variant:?} renders nothing");
        }
        for (i, a) in rendered.iter().enumerate() {
            for (j, b) in rendered.iter().enumerate().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "{:?} and {:?} render the same message",
                    variants[i], variants[j]
                );
            }
        }
    }

    /// Only `Error::Der` has an underlying cause, and it exposes it.
    ///
    /// A `source` that always answers `None` breaks `{:#}`-style chained
    /// reporting: the DER failure that explains the whole error is in the
    /// wrapped value and nowhere else.
    #[test]
    fn only_the_der_variant_has_a_source() {
        use core::error::Error as _;
        for variant in &every_variant() {
            let expected = matches!(variant, Error::Der(_));
            assert_eq!(
                variant.source().is_some(),
                expected,
                "{variant:?} source presence"
            );
        }
    }

    /// `DerError` renders the message it cached, and exposes the
    /// `der::Error` it was built from.
    #[test]
    fn a_der_error_renders_and_exposes_its_cause() {
        use core::error::Error as _;
        let e = der_error(&[0x06, 0x01, 0x80]);
        let rendered = format!("{e}");
        assert!(!rendered.is_empty(), "DerError renders nothing");
        let source = e.source().expect("a DerError built from a der::Error");
        assert_eq!(
            format!("{source}"),
            rendered,
            "the cached message is the der::Error's own rendering"
        );
    }

    /// Equality compares the cached message, so distinct DER failures are
    /// distinct values.
    ///
    /// `Error` derives `PartialEq`, so an `eq` that always answered `true`
    /// would make `Err(Error::Der(a)) == Err(Error::Der(b))` for any two
    /// DER failures — and a test asserting a particular error would pass
    /// for the wrong one.
    #[test]
    fn der_errors_with_different_messages_differ() {
        let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
        let truncated = der_error(&[0x06, 0x01, 0x80]);
        assert_ne!(
            format!("{wrong_tag}"),
            format!("{truncated}"),
            "the two fixtures must fail differently for this test to mean anything"
        );
        assert_ne!(wrong_tag, truncated);
        assert_eq!(
            Error::Der(wrong_tag.clone()),
            Error::Der(wrong_tag.clone()),
            "the same failure twice"
        );
        assert_ne!(Error::Der(wrong_tag), Error::Der(truncated));
    }

    /// `Hash` reads the field `PartialEq` compares.
    ///
    /// Equal values must hash equally, which a `hash` that writes nothing
    /// satisfies trivially — and then every `DerError` lands in one bucket,
    /// including inside the `Error` and `ValidatedPath` hashes that exist
    /// only because `DerError` is `Hash`.
    #[test]
    fn der_error_hashing_follows_its_equality() {
        let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
        let truncated = der_error(&[0x06, 0x01, 0x80]);
        assert_eq!(
            Fnv::of(&wrong_tag),
            Fnv::of(&der_error(&[0x02, 0x01, 0x00])),
            "equal values hash equally"
        );
        assert_ne!(
            Fnv::of(&wrong_tag),
            Fnv::of(&truncated),
            "unequal values are not all one hash"
        );
    }
}