polyjose 0.2.0

Pure-Rust JOSE: JWA, JWK, JWS, JWE and JWT per the RFCs, with no OpenSSL
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
//! Shared conformance vector runner (ADR 0008 layer 4), Rust side.
//!
//! Loads every `*.json` file under `conformance/vectors/` (recursively,
//! `third_party/` included), checks each against the rules of
//! `conformance/schema.json`, runs it through the public API and collects
//! every failure before failing. A failure message names the file and the
//! vector's `source`.
//!
//! The rules the WASM, Node, Kotlin and Swift runners must follow too
//! (conformance/README.md):
//!
//! - a schema-invalid vector fails the run;
//! - a vector whose `operation` the runner does not implement fails the run,
//!   whether the schema reserves the operation or not; nothing is skipped;
//! - an empty or missing vectors directory fails the run;
//! - for `jws.sign` and `jws.verify` (RFC 7515), the step order of
//!   conformance/README.md: JWK import, then headers or options, then the
//!   call, the first error being the outcome; and the round trip of a
//!   randomized signature (`verify_with`);
//! - for `jwe.encrypt` and `jwe.decrypt` (RFC 7516), the same step order,
//!   and the round trip of a randomized encryption (`decrypt_with`);
//! - for `keys.import_pem` and `keys.export_pem` (ADR 0018 §3), the PEM
//!   import gives the expected JWK, and the export, after the JWK import,
//!   gives the exact PEM text;
//! - for `keys.import_der`, `der_b64u` is decoded (a non-canonical value is
//!   a broken vector, never an outcome) and imported in the named `format`;
//!   `keys.export_der` gives the exact DER, as canonical base64url;
//! - for `keys.generate_for` (ADR 0018 §5), `alg` is resolved in the one
//!   RFC 7518 §7.1 registry, and a generated key, being random, is compared
//!   by its shape, after the runner checks it is private, has exactly the
//!   RFC members plus `alg`, and imports back unchanged;
//! - for `jwks.select` (ADR 0054 §1–§4), the step order of
//!   conformance/README.md: import `jwks`, then build the selector from
//!   `kid`, `alg` and `key_use` in that order, then select, the first error
//!   being the outcome (ADR 0054 §4 precedence); the selected key is
//!   compared as a JSON value;
//! - for `jwt.validate` and `jwt.issue` (RFC 7519), a fixed clock built
//!   from `now` and no other (ADR 0028 §4); the step order of
//!   conformance/README.md (`decrypt.key`, `decrypt`'s lists, `key` or
//!   `jwks`, the policy; or `key`, `claims`, `encrypt.key`, sign, encrypt),
//!   the first error, a JWK or JWK Set import error included, being the
//!   outcome; claims compared as JSON values; and an issued token checked
//!   exactly, or by validating it with `validate`;
//! - a success expectation lists exactly the outputs, so an optional one
//!   (`key_index`) can't be left out unnoticed;
//! - a vector whose optional top-level `features` names a cargo feature
//!   this build does not enable, or whose `features_absent` names one it
//!   enables (ADR 0056), is reported **SKIPPED**, with the feature names;
//!   it is never counted as passing.
//!
//! The schema is enforced by a strict hand-written check (no JSON Schema
//! crate, ADR 0016). `schema_and_runner_agree` parses `schema.json` and
//! fails if its operations, member names, member kinds, `required` lists,
//! `allOf` signer rules, patterns or error codes drift from the tables
//! below. `jws_and_keys_vectors_are_binding_ready`, `jwe_vectors_are_binding_ready`
//! and `jwt_vectors_are_binding_ready` check that every JWS, JWE, keys and
//! JWT vector is readable unchanged by every binding's JSON parser. Vector files are
//! parsed with
//! polyjose's own `json` module, and their inputs reach the library through
//! it.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] // test code: a panic is a failed assertion

use std::collections::BTreeMap;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::{Path, PathBuf};

use polyjose::Error;
use polyjose::header::Header;
use polyjose::json::{self, Number, Object, Value};
use polyjose::jwa::{ContentEncAlg, KeyMgmtAlg, SigningAlg};
use polyjose::jwe::{self, DecryptPolicy, Encryptor, JsonForm, Recipient};
use polyjose::jwk::{EcCurve, Jwk, JwkSelector, JwkSet, KeyAlg, KeyUse, OkpCurve, ThumbprintHash};
use polyjose::jws::{self, ProtectedHeader, SignOptions, Signer, VerifyOptions};
use polyjose::jwt::{self, Claims, FixedClock, IssueOptions, Keys, Policy, VerifiedJwt};
use polyjose::keys::{JoseAlg, KeyFormat, KeySpec, generate, generate_for};
use polyjose::util::{b64url_decode, b64url_encode};
// The vector-set digest's SHA-256 (ADR 0060 §5): the `sha2` crate called
// directly as a test oracle, never polyjose's API under test.
use sha2::{Digest, Sha256};

/// Top-level members of a vector; all required (schema `required`).
const TOP_LEVEL: &[&str] = &["source", "description", "operation", "input", "expect"];

/// The optional top-level members, after [`TOP_LEVEL`] in the schema's
/// `properties`.
const TOP_LEVEL_OPTIONAL: &[&str] = &["features", "features_absent"];

/// The names a vector's top-level `features` may list, each with the cargo
/// feature of `polyjose` it stands for. A vector needing one this build
/// does not enable is SKIPPED, naming the cargo feature, never passed.
///
/// The test RNG feature is written `fixed-rng` in vector files:
/// `scripts/check-test-vectors-off.sh` allows its cargo name only in
/// `crates/polyjose`, the script and Markdown, so that no file outside the
/// core can switch it on (ADR 0005), and vector JSON is not exempt.
const FEATURES: &[(&str, &str)] = &[
    ("deflate", "deflate"),
    ("fixed-rng", "insecure-test-vectors"),
];

/// The cargo feature a [`FEATURES`] name stands for.
fn cargo_feature(name: &str) -> &'static str {
    FEATURES
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, cargo)| *cargo)
        .expect("a validated features name")
}

/// The [`FEATURES`] names whose cargo feature this build enables.
fn enabled_features() -> Vec<&'static str> {
    let mut enabled = Vec::new();
    if cfg!(feature = "deflate") {
        enabled.push("deflate");
    }
    if cfg!(feature = "insecure-test-vectors") {
        enabled.push("fixed-rng");
    }
    enabled
}

/// The vector-file names of [`FEATURES`], in schema order.
fn feature_names() -> Vec<&'static str> {
    FEATURES.iter().map(|(name, _)| *name).collect()
}

/// Every operation `schema.json` names, in schema order. Only those with an
/// [`OpSpec`] have a defined input and expectation; the others are reserved
/// for the features that will define them.
const OPERATIONS: &[&str] = &[
    "b64url.encode",
    "b64url.decode",
    "jwk.thumbprint",
    "jwks.select",
    "jws.sign",
    "jws.verify",
    "keys.import_pem",
    "keys.export_pem",
    "keys.import_der",
    "keys.export_der",
    "keys.generate_for",
    "keys.generate_oct",
    "keys.generate_ec",
    "keys.generate_okp",
    "jwe.encrypt",
    "jwe.decrypt",
    "jwt.validate",
    "jwt.issue",
];

/// `$defs/hex/pattern`: lowercase hex, two digits per octet.
const HEX_PATTERN: &str = "^([0-9a-f]{2})*$";
/// `$defs/base64url/pattern`: the RFC 4648 §5 alphabet, no padding.
const BASE64URL_PATTERN: &str = "^[A-Za-z0-9_-]*$";
/// `$defs/text/pattern`: at least one non-whitespace character.
const TEXT_PATTERN: &str = "\\S";
/// `$defs/count/maximum`: an unsigned 32-bit integer (ADR 0030 `u32`), so
/// every binding holds a count natively and exactly.
const COUNT_MAX: u64 = u32::MAX as u64;
/// `$defs/seconds/maximum` (and, negated, `minimum`): 2^53 − 1, the
/// NumericDate and clock range (RFC 7493 §2.2; ADR 0027 §2, ADR 0028 §1),
/// which every binding holds exactly, JavaScript's numbers included.
const SECONDS_MAX: i64 = 9_007_199_254_740_991;

/// What a member's value must be. Each kind maps to one schema spelling
/// (see `schema_kind`).
#[derive(Debug, Clone, Copy)]
enum Kind {
    /// `{"$ref": "#/$defs/hex"}`
    Hex,
    /// `{"$ref": "#/$defs/base64url"}`
    Base64url,
    /// `{"type": "string"}`
    String,
    /// `{"type": "object"}`
    Object,
    /// `{"enum": [...]}` of strings
    Enum(&'static [&'static str]),
    /// `{"$ref": "#/$defs/count"}`: an integer in `0..=COUNT_MAX`
    Count,
    /// `{"$ref": "#/$defs/jws"}`: a string (compact) or an object (JSON)
    Jws,
    /// `{"$ref": "#/$defs/alg_list"}`: an array of strings
    AlgList,
    /// `{"$ref": "#/$defs/jwe"}`: a string (compact) or an object (JSON)
    Jwe,
    /// `{"type": "array", "items": {"type": "string"}}`
    StringList,
    /// `{"type": "boolean"}`
    Bool,
    /// `{"$ref": "#/$defs/<def>"}` of a closed object definition
    Nested(&'static Shape),
    /// `{"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/<def>"}}`
    List(&'static Shape),
    /// `{"$ref": "#/$defs/seconds"}`: an integer in `-SECONDS_MAX..=SECONDS_MAX`
    Seconds,
    /// `{"type": ["string", "array"], "items": {"type": "string"}}`
    StringOrList,
    /// `{"type": ["string", "null"]}`
    StringOrNull,
}

impl Kind {
    /// The shared `$defs` entry a `$ref` kind points at.
    fn def(self) -> Option<&'static str> {
        match self {
            Kind::Hex => Some("hex"),
            Kind::Base64url => Some("base64url"),
            Kind::Count => Some("count"),
            Kind::Jws => Some("jws"),
            Kind::AlgList => Some("alg_list"),
            Kind::Jwe => Some("jwe"),
            Kind::Nested(shape) => Some(shape.def),
            Kind::Seconds => Some("seconds"),
            Kind::String
            | Kind::Object
            | Kind::Enum(_)
            | Kind::Bool
            | Kind::List(_)
            | Kind::StringList
            | Kind::StringOrList
            | Kind::StringOrNull => None,
        }
    }
}

/// One member of a [`Shape`].
#[derive(Debug)]
struct Member {
    name: &'static str,
    kind: Kind,
    /// Listed in the definition's `required`.
    required: bool,
}

/// A required member.
const fn req(name: &'static str, kind: Kind) -> Member {
    Member {
        name,
        kind,
        required: true,
    }
}

/// An optional member.
const fn opt(name: &'static str, kind: Kind) -> Member {
    Member {
        name,
        kind,
        required: false,
    }
}

/// A closed object definition in `$defs` (`additionalProperties: false`):
/// the listed members, no others, and its `allOf` rules.
#[derive(Debug)]
struct Shape {
    /// Its name under `$defs`.
    def: &'static str,
    members: &'static [Member],
    /// Its `allOf` rules, in schema order.
    rules: &'static [Rule],
}

/// One entry of a closed definition's `allOf`: a constraint across its
/// members, which the per-member kinds cannot say.
#[derive(Debug)]
enum Rule {
    /// The per-serialization signer limits of `jws_sign_input`.
    Signers(SignerRule),
    /// Exactly one of these members is present. In the schema:
    ///
    /// ```json
    /// {"oneOf": [{"required": ["key"]}, {"required": ["jwks"]}]}
    /// ```
    ExactlyOne(&'static [&'static str]),
    /// `dependent` is required when `member` is `value`, and not allowed
    /// otherwise. In the schema:
    ///
    /// ```json
    /// {"if": {"properties": {"mode": {"const": "exact"}}},
    ///  "then": {"required": ["value"]},
    ///  "else": {"properties": {"value": false}}}
    /// ```
    OnlyWhen {
        member: &'static str,
        value: &'static str,
        dependent: &'static str,
    },
}

/// One `allOf` rule of `jws_sign_input`: when `serialization` is
/// `serialization`, `signers` has at most `max_signers` entries, each with
/// every `requires` member and none of the `forbids` members. In the
/// schema:
///
/// ```json
/// {"if": {"properties": {"serialization": {"const": "compact"}}},
///  "then": {"properties": {"signers": {"maxItems": 1,
///    "items": {"required": ["protected_b64u"], "properties": {"header": false}}}}}}
/// ```
#[derive(Debug)]
struct SignerRule {
    serialization: &'static str,
    max_signers: usize,
    requires: &'static [&'static str],
    forbids: &'static [&'static str],
}

/// The input and success shapes of an operation (schema `$defs`).
#[derive(Debug)]
struct OpSpec {
    name: &'static str,
    input: &'static Shape,
    /// The success expectations; `"ok": true` is implicit in each. With
    /// more than one, a vector matches exactly one (schema `oneOf`).
    ok: &'static [&'static Shape],
    /// Whether `{"ok": false, "error": <code>}` is allowed.
    can_fail: bool,
}

// RFC 7515 §2 base64url encoding (RFC 4648 §5, no padding).
const B64URL_ENCODE_INPUT: Shape = Shape {
    def: "b64url_encode_input",
    members: &[req("bytes_hex", Kind::Hex)],
    rules: &[],
};
const B64URL_ENCODE_OK: Shape = Shape {
    def: "b64url_encode_ok",
    members: &[req("b64u", Kind::Base64url)],
    rules: &[],
};
// RFC 7515 §2 decoding; non-canonical input is rejected (RFC 4648 §3.5).
const B64URL_DECODE_INPUT: Shape = Shape {
    def: "b64url_decode_input",
    members: &[req("b64u", Kind::String)],
    rules: &[],
};
const B64URL_DECODE_OK: Shape = Shape {
    def: "b64url_decode_ok",
    members: &[req("bytes_hex", Kind::Hex)],
    rules: &[],
};
// RFC 7638 §3 JWK Thumbprint and RFC 9278 §3 JWK Thumbprint URI. `hash`
// is optional and any string (ADR 0054 §8.2): an unknown name is a vector
// outcome, not a schema error.
const JWK_THUMBPRINT_INPUT: Shape = Shape {
    def: "jwk_thumbprint_input",
    members: &[req("jwk", Kind::Object), opt("hash", Kind::String)],
    rules: &[],
};
const JWK_THUMBPRINT_OK: Shape = Shape {
    def: "jwk_thumbprint_ok",
    members: &[
        req("thumbprint", Kind::Base64url),
        req("thumbprint_uri", Kind::String),
    ],
    rules: &[],
};
/// The binding `JwkSelector` (ADR 0030 §4, ADR 0054 §9): every member
/// optional, `{}` selecting every member (ADR 0054 §1.3). `alg` and
/// `key_use` are any string: an unsupported one is a vector outcome
/// (`UnsupportedAlgorithm`, ADR 0054 §1.1), not a schema error.
const JWKS_SELECTOR: Shape = Shape {
    def: "jwks_selector",
    members: &[
        opt("kid", Kind::String),
        opt("alg", Kind::String),
        opt("key_use", Kind::String),
    ],
    rules: &[],
};
// ADR 0054 §1–§4: one key from a JWK Set (RFC 7517 §5). `jwks` is
// unconstrained, since import errors and skipped members are under test.
const JWKS_SELECT_INPUT: Shape = Shape {
    def: "jwks_select_input",
    members: &[
        req("jwks", Kind::Object),
        req("selector", Kind::Nested(&JWKS_SELECTOR)),
    ],
    rules: &[],
};
/// The one matching member's core serialization, compared as a JSON value.
const JWKS_SELECT_OK: Shape = Shape {
    def: "jwks_select_ok",
    members: &[req("jwk", Kind::Object)],
    rules: &[],
};

// RFC 7515 §5.2 validation through `jws::verify_compact` (a string `jws`,
// RFC 7515 §7.1) or `jws::verify_json` (an object, §7.2), with the
// options of ADR 0026: allow-list, detached payload (Appendix F), limits.
const JWS_VERIFY_INPUT: Shape = Shape {
    def: "jws_verify_input",
    members: &[
        req("jws", Kind::Jws),
        req("key", Kind::Object),
        req("allowed_algs", Kind::AlgList),
        opt("detached_payload_b64u", Kind::Base64url),
        opt("max_input_len", Kind::Count),
        opt("max_signatures", Kind::Count),
    ],
    rules: &[],
};
const JWS_VERIFY_OK: Shape = Shape {
    def: "jws_verify_ok",
    members: &[
        req("payload_b64u", Kind::Base64url),
        req("alg", Kind::String),
        req("signature_index", Kind::Count),
    ],
    rules: &[],
};

/// The signer of a `jws.sign` vector: its JWS Protected Header as exact
/// octets (RFC 7515 §5.1 step 3; RFC 7515 A.1's CRLF header can only be
/// given this way), its JWS Unprotected Header (§7.2.1), and its key.
const JWS_SIGNER: Shape = Shape {
    def: "jws_signer",
    members: &[
        opt("protected_b64u", Kind::Base64url),
        opt("header", Kind::Object),
        req("key", Kind::Object),
    ],
    rules: &[],
};
// RFC 7515 §5.1 through `jws::sign_compact` (§7.1), `jws::sign_flattened`
// (§7.2.2) or `jws::sign_general` (§7.2.1), attached or detached
// (Appendix F).
const JWS_SIGN_INPUT: Shape = Shape {
    def: "jws_sign_input",
    members: &[
        req(
            "serialization",
            Kind::Enum(&["compact", "flattened", "general"]),
        ),
        req("payload_b64u", Kind::Base64url),
        req("detached", Kind::Bool),
        req("signers", Kind::List(&JWS_SIGNER)),
    ],
    rules: &[
        // RFC 7515 §7.1: one signature over a JWS Protected Header only.
        Rule::Signers(SignerRule {
            serialization: "compact",
            max_signers: 1,
            requires: &["protected_b64u"],
            forbids: &["header"],
        }),
        // RFC 7515 §7.2.2: one signature.
        Rule::Signers(SignerRule {
            serialization: "flattened",
            max_signers: 1,
            requires: &[],
            forbids: &[],
        }),
    ],
};
/// A deterministic signature's exact output: a string for compact, an
/// object for JSON, compared as JSON values (member order ignored,
/// RFC 8259 §4).
const JWS_SIGN_EXACT: Shape = Shape {
    def: "jws_sign_exact",
    members: &[req("jws", Kind::Jws)],
    rules: &[],
};
const JWS_VERIFY_WITH: Shape = Shape {
    def: "jws_verify_with",
    members: &[req("key", Kind::Object), req("allowed_algs", Kind::AlgList)],
    rules: &[],
};
/// A randomized signature (ECDSA): the runner verifies its own output with
/// `verify_with` and checks the payload, instead of comparing bytes.
const JWS_SIGN_ROUND_TRIP: Shape = Shape {
    def: "jws_sign_roundtrip",
    members: &[req("verify_with", Kind::Nested(&JWS_VERIFY_WITH))],
    rules: &[],
};

// ---------------------------------------------------------------------------
// jwe.* shapes (RFC 7516). Kept apart from the jws.* ones so later edits to
// either merge mechanically.
// ---------------------------------------------------------------------------

/// One recipient of a `jwe.encrypt` vector (RFC 7516 §5.1 steps 1-8): its
/// `alg`, its key, its Per-Recipient Unprotected Header (§7.2.1, JSON only)
/// and the key management options of RFC 7518 §4.6.1.2-§4.6.1.3 (`apu`,
/// `apv`) and §4.8.1.1-§4.8.1.2 (`p2s` length, `p2c`).
const JWE_RECIPIENT: Shape = Shape {
    def: "jwe_recipient",
    members: &[
        req("alg", Kind::String),
        req("key", Kind::Object),
        opt("header", Kind::Object),
        opt("apu_b64u", Kind::Base64url),
        opt("apv_b64u", Kind::Base64url),
        opt("p2c", Kind::Count),
        opt("p2s_len", Kind::Count),
    ],
    rules: &[],
};
// RFC 7516 §5.1 through `Encryptor::encrypt_compact` (§7.1),
// `encrypt_json` (§7.2), or, with `rng_b64u` or `protected_b64u`,
// `encrypt_reproducible` (feature `insecure-test-vectors`).
const JWE_ENCRYPT_INPUT: Shape = Shape {
    def: "jwe_encrypt_input",
    members: &[
        req(
            "serialization",
            Kind::Enum(&["compact", "flattened", "general"]),
        ),
        req("enc", Kind::String),
        req("plaintext_b64u", Kind::Base64url),
        req("recipients", Kind::List(&JWE_RECIPIENT)),
        opt("protected", Kind::Object),
        opt("protected_b64u", Kind::Base64url),
        opt("unprotected", Kind::Object),
        opt("aad_b64u", Kind::Base64url),
        opt("compress", Kind::Bool),
        opt("rng_b64u", Kind::Base64url),
    ],
    rules: &[],
};
/// A reproducible encryption's exact output: a string for compact, an
/// object for JSON, compared as JSON values (member order ignored,
/// RFC 8259 §4).
const JWE_ENCRYPT_EXACT: Shape = Shape {
    def: "jwe_encrypt_exact",
    members: &[req("jwe", Kind::Jwe)],
    rules: &[],
};
const JWE_DECRYPT_WITH: Shape = Shape {
    def: "jwe_decrypt_with",
    members: &[
        req("key", Kind::Object),
        req("allowed_algs", Kind::AlgList),
        req("allowed_enc", Kind::AlgList),
    ],
    rules: &[],
};
/// A randomized encryption: the runner decrypts its own output with
/// `decrypt_with` and checks the plaintext, instead of comparing bytes.
const JWE_ENCRYPT_ROUND_TRIP: Shape = Shape {
    def: "jwe_encrypt_roundtrip",
    members: &[req("decrypt_with", Kind::Nested(&JWE_DECRYPT_WITH))],
    rules: &[],
};
// RFC 7516 §5.2 through `jwe::decrypt_compact` (a string `jwe`, §7.1) or
// `jwe::decrypt_json` (an object, §7.2), with a `DecryptPolicy` (RFC 8725
// §3.1, ADR 0007, ADR 0023, ADR 0017, ADR 0026 §7).
const JWE_DECRYPT_INPUT: Shape = Shape {
    def: "jwe_decrypt_input",
    members: &[
        req("jwe", Kind::Jwe),
        req("key", Kind::Object),
        req("allowed_algs", Kind::AlgList),
        req("allowed_enc", Kind::AlgList),
        opt("understood_crit", Kind::StringList),
        opt("max_input_len", Kind::Count),
        opt("max_recipients", Kind::Count),
        opt("max_pbes2_count", Kind::Count),
        opt("max_decompressed_len", Kind::Count),
    ],
    rules: &[],
};
const JWE_DECRYPT_OK: Shape = Shape {
    def: "jwe_decrypt_ok",
    members: &[
        req("plaintext_b64u", Kind::Base64url),
        req("recipient", Kind::Count),
    ],
    rules: &[],
};

// ADR 0018 §3 PEM import through `Jwk::from_pem`: the label selects the
// structure (RFC 7468 §2), the key type comes from the DER.
const KEYS_IMPORT_PEM_INPUT: Shape = Shape {
    def: "keys_import_pem_input",
    members: &[req("pem", Kind::String)],
    rules: &[],
};
/// The imported JWK, compared as a JSON value (member order ignored).
const KEYS_IMPORT_PEM_OK: Shape = Shape {
    def: "keys_import_pem_ok",
    members: &[req("jwk", Kind::Object)],
    rules: &[],
};
/// The `format` names of the keys.* operations, in schema order, and the
/// library format each selects.
const KEY_FORMATS: &[(&str, KeyFormat)] = &[
    ("pkcs8", KeyFormat::Pkcs8),
    ("sec1", KeyFormat::Sec1),
    ("spki", KeyFormat::Spki),
    ("pkcs1", KeyFormat::Pkcs1),
];
/// The `format` enum of the keys.* operations: the names of [`KEY_FORMATS`].
const KEY_FORMAT_NAMES: &[&str] = &["pkcs8", "sec1", "spki", "pkcs1"];
// ADR 0018 §3 PEM export through `Jwk::from_object` then `Jwk::to_pem`.
const KEYS_EXPORT_PEM_INPUT: Shape = Shape {
    def: "keys_export_pem_input",
    members: &[
        req("jwk", Kind::Object),
        req("format", Kind::Enum(KEY_FORMAT_NAMES)),
    ],
    rules: &[],
};
/// The exact PEM text, compared as a string.
const KEYS_EXPORT_PEM_OK: Shape = Shape {
    def: "keys_export_pem_ok",
    members: &[req("pem", Kind::String)],
    rules: &[],
};
// ADR 0018 §3 DER import through `Jwk::from_der`: the caller names the
// structure, there is no format sniffing (ADR 0007), and the key type comes
// from the DER (ADR 0018 §2).
const KEYS_IMPORT_DER_INPUT: Shape = Shape {
    def: "keys_import_der_input",
    members: &[
        req("der_b64u", Kind::Base64url),
        req("format", Kind::Enum(KEY_FORMAT_NAMES)),
    ],
    rules: &[],
};
/// The imported JWK, compared as a JSON value (member order ignored).
const KEYS_IMPORT_DER_OK: Shape = Shape {
    def: "keys_import_der_ok",
    members: &[req("jwk", Kind::Object)],
    rules: &[],
};
// ADR 0018 §3 DER export through `Jwk::from_object` then `Jwk::to_der`.
const KEYS_EXPORT_DER_INPUT: Shape = Shape {
    def: "keys_export_der_input",
    members: &[
        req("jwk", Kind::Object),
        req("format", Kind::Enum(KEY_FORMAT_NAMES)),
    ],
    rules: &[],
};
/// The exact DER, as canonical base64url, compared as a string.
const KEYS_EXPORT_DER_OK: Shape = Shape {
    def: "keys_export_der_ok",
    members: &[req("der_b64u", Kind::Base64url)],
    rules: &[],
};
// ADR 0018 §5 generation through `keys::generate_for`: a JWS `alg`, a JWE
// `alg` or a JWE `enc` name, any string (unknown names are under test).
const KEYS_GENERATE_FOR_INPUT: Shape = Shape {
    def: "keys_generate_for_input",
    members: &[req("alg", Kind::String)],
    rules: &[],
};
/// What a generated key is, without its random material: `kty`, `crv`
/// (EC and OKP), the `alg` it is bound to (RFC 7517 §4.4) and the length
/// of `k` in octets (`oct`). Compared as a JSON value, so a member the
/// generated key has and the vector omits fails too.
const KEYS_GENERATED_SHAPE: Shape = Shape {
    def: "keys_generated_shape",
    members: &[
        req("kty", Kind::Enum(&["EC", "OKP", "oct"])),
        opt("crv", Kind::String),
        req("alg", Kind::String),
        opt("k_octets", Kind::Count),
    ],
    rules: &[],
};
/// A generated key is random, so only its shape is expected; the runner
/// checks the rest itself (see [`generated_shape`]).
const KEYS_GENERATE_FOR_OK: Shape = Shape {
    def: "keys_generate_for_ok",
    members: &[
        req("shape", Kind::Nested(&KEYS_GENERATED_SHAPE)),
        opt("use_with", Kind::Nested(&KEYS_USE_WITH)),
    ],
    rules: &[],
};
/// A use round trip of a generated key (ADR 0034 §6), checked by the
/// runner (see [`check_use_with`]): a JWS `alg` alone, or a JWE `alg` and
/// `enc`.
const KEYS_USE_WITH: Shape = Shape {
    def: "keys_use_with",
    members: &[req("alg", Kind::String), opt("enc", Kind::String)],
    rules: &[],
};
// ADR 0018 §5 generation through `keys::generate` (ADR 0030
// `jwk_generate_oct`, `jwk_generate_ec`, `jwk_generate_okp`): an `oct` key
// of `len_bytes` octets (RFC 7518 §6.4.1), or a key pair on a curve
// polyjose generates (RFC 7518 §6.2, RFC 8812 §3.1, RFC 8037 §2).
const KEYS_GENERATE_OCT_INPUT: Shape = Shape {
    def: "keys_generate_oct_input",
    members: &[req("len_bytes", Kind::Count)],
    rules: &[],
};
/// The EC curves of [`EC_CURVES`], by their RFC 7518 §6.2.1.1 names.
const EC_CURVE_NAMES: &[&str] = &["P-256", "P-384", "P-521", "secp256k1"];
const KEYS_GENERATE_EC_INPUT: Shape = Shape {
    def: "keys_generate_ec_input",
    members: &[req("crv", Kind::Enum(EC_CURVE_NAMES))],
    rules: &[],
};
/// The OKP curves of [`OKP_CURVES`], by their RFC 8037 §2 names.
const OKP_CURVE_NAMES: &[&str] = &["Ed25519", "X25519"];
const KEYS_GENERATE_OKP_INPUT: Shape = Shape {
    def: "keys_generate_okp_input",
    members: &[req("crv", Kind::Enum(OKP_CURVE_NAMES))],
    rules: &[],
};
/// What a key of `keys::generate` is, without its random material: as
/// [`KEYS_GENERATED_SHAPE`], without `alg` (such a key is bound to none).
const KEYS_GENERATED_KEY: Shape = Shape {
    def: "keys_generated_key",
    members: &[
        req("kty", Kind::Enum(&["EC", "OKP", "oct"])),
        opt("crv", Kind::String),
        opt("k_octets", Kind::Count),
    ],
    rules: &[],
};
/// A generated key's shape and its use round trip, both required.
const KEYS_GENERATE_OK: Shape = Shape {
    def: "keys_generate_ok",
    members: &[
        req("shape", Kind::Nested(&KEYS_GENERATED_KEY)),
        req("use_with", Kind::Nested(&KEYS_USE_WITH)),
    ],
    rules: &[],
};

// ---------------------------------------------------------------------------
// jwt.* shapes (RFC 7519; ADR 0027, ADR 0028, ADR 0029). Platform-neutral:
// every member is a JSON value each binding's own validate call takes as
// is, with no Rust type in it.
// ---------------------------------------------------------------------------

/// How `typ` is checked (RFC 7515 §4.1.9, RFC 8725 §3.11–§3.12;
/// ADR 0027 §5): `default` (absent or `JWT`), `exact` (`value` required),
/// or `any` (no check). `value` is allowed with `exact` only.
const JWT_TYP: Shape = Shape {
    def: "jwt_typ",
    members: &[
        req("mode", Kind::Enum(&["default", "exact", "any"])),
        opt("value", Kind::String),
    ],
    rules: &[Rule::OnlyWhen {
        member: "mode",
        value: "exact",
        dependent: "value",
    }],
};
/// The JWT validation policy (RFC 7519 §4.1, §7.2; RFC 8725 §3; ADR 0027
/// §3–§5, ADR 0029 §4). Every member is optional; an absent member keeps
/// the library default, which the runner never restates.
const JWT_POLICY: Shape = Shape {
    def: "jwt_policy",
    members: &[
        // RFC 7519 §4.1.1, RFC 8725 §3.8: one accepted issuer or a list.
        opt("issuer", Kind::StringOrList),
        // RFC 7519 §4.1.3, RFC 8725 §3.9.
        opt("audience", Kind::StringList),
        // RFC 7519 §4.1.2.
        opt("subject", Kind::String),
        // RFC 7519 §4.1.4-§4.1.5: whole seconds, at most 600 (ADR 0027 §3).
        opt("leeway", Kind::Count),
        // RFC 7519 §4.1.6: makes `iat` required (ADR 0027 §3).
        opt("max_age", Kind::Count),
        // RFC 7519 §4: required claim names (ADR 0027 §4).
        opt("require", Kind::StringList),
        // ADR 0007, ADR 0027 §3: the explicit opt-out of a required `exp`.
        opt("allow_missing_exp", Kind::Bool),
        // RFC 7519 §4.1.3, ADR 0027 §4: the explicit opt-out.
        opt("ignore_audience", Kind::Bool),
        opt("typ", Kind::Nested(&JWT_TYP)),
        // RFC 9068 §4 (ADR 0027 §5).
        opt("profile", Kind::Enum(&["access_token"])),
        // ADR 0029 §4.
        opt("max_key_candidates", Kind::Count),
    ],
    rules: &[],
};
/// The outer JWE layer of a nested JWT (RFC 7519 §5.2, §7.2 step 8;
/// RFC 8725 §3.3; ADR 0027 §7): the caller's decryption key and both
/// allow-lists, and the PBES2 bound (ADR 0023).
const JWT_DECRYPT: Shape = Shape {
    def: "jwt_decrypt",
    members: &[
        req("key", Kind::Object),
        req("allowed_algs", Kind::AlgList),
        req("allowed_enc", Kind::AlgList),
        opt("max_pbes2_count", Kind::Count),
    ],
    rules: &[],
};
// RFC 7519 §7.2 through `jwt::verify`, or `jwt::decrypt_nested` with
// `decrypt`: the time `now` as a FixedClock (ADR 0028 §4), the allow-list
// (RFC 8725 §3.1), and exactly one key source (ADR 0029 §1).
const JWT_VALIDATE_INPUT: Shape = Shape {
    def: "jwt_validate_input",
    members: &[
        req("token", Kind::String),
        req("now", Kind::Seconds),
        req("allowed_algs", Kind::AlgList),
        opt("key", Kind::Object),
        opt("jwks", Kind::Object),
        opt("policy", Kind::Nested(&JWT_POLICY)),
        opt("decrypt", Kind::Nested(&JWT_DECRYPT)),
    ],
    rules: &[Rule::ExactlyOne(&["key", "jwks"])],
};
/// The validated JWT: its Claims Set (compared as a JSON value: member
/// order ignored, numbers as doubles), the `alg` that verified, and, when
/// verified through `jwks`, the index of the member that did (ADR 0029
/// §4). `key_index` is present exactly when the input has `jwks`.
const JWT_VALIDATE_OK: Shape = Shape {
    def: "jwt_validate_ok",
    members: &[
        req("claims", Kind::Object),
        req("alg", Kind::String),
        opt("key_index", Kind::Count),
    ],
    rules: &[],
};
/// How a `jwt.issue` vector validates the token it issued: the members of
/// [`JWT_VALIDATE_INPUT`] other than `token`, with the same rules.
const JWT_ISSUE_VALIDATE: Shape = Shape {
    def: "jwt_issue_validate",
    members: &[
        req("now", Kind::Seconds),
        req("allowed_algs", Kind::AlgList),
        opt("key", Kind::Object),
        opt("jwks", Kind::Object),
        opt("policy", Kind::Nested(&JWT_POLICY)),
        opt("decrypt", Kind::Nested(&JWT_DECRYPT)),
    ],
    rules: &[Rule::ExactlyOne(&["key", "jwks"])],
};
/// The JWE layer of a nested JWT to issue (RFC 7519 §7.1 step 5, §11.2;
/// ADR 0027 §7): one recipient's key management `alg`, its JWK, and the
/// content encryption `enc`.
const JWT_ENCRYPT: Shape = Shape {
    def: "jwt_encrypt",
    members: &[
        req("alg", Kind::String),
        req("enc", Kind::String),
        req("key", Kind::Object),
    ],
    rules: &[],
};
// RFC 7519 §7.1 through `jwt::sign` (ADR 0027 §8), then, with `encrypt`,
// `jwt::encrypt_nested` (§7). `typ`: absent is the library default (JWT),
// a string sets it, null omits it (RFC 7519 §5.1).
const JWT_ISSUE_INPUT: Shape = Shape {
    def: "jwt_issue_input",
    members: &[
        req("claims", Kind::Object),
        req("alg", Kind::String),
        req("key", Kind::Object),
        opt("typ", Kind::StringOrNull),
        opt("encrypt", Kind::Nested(&JWT_ENCRYPT)),
        opt("validate", Kind::Nested(&JWT_ISSUE_VALIDATE)),
    ],
    rules: &[],
};
/// A deterministic signed JWT's exact token (HMAC, EdDSA; RFC 7515 §7.1),
/// compared as a string.
const JWT_ISSUE_EXACT: Shape = Shape {
    def: "jwt_issue_exact",
    members: &[req("token", Kind::String)],
    rules: &[],
};
/// A token the runner checks itself: its compact shape, and the round trip
/// through `validate` (see [`check_jwt_issue`] for when that is required).
const JWT_ISSUE_VALIDATED: Shape = Shape {
    def: "jwt_issue_validated",
    members: &[],
    rules: &[],
};

/// The operations this runner implements.
const SPECS: &[OpSpec] = &[
    OpSpec {
        name: "b64url.encode",
        input: &B64URL_ENCODE_INPUT,
        ok: &[&B64URL_ENCODE_OK],
        can_fail: false,
    },
    OpSpec {
        name: "b64url.decode",
        input: &B64URL_DECODE_INPUT,
        ok: &[&B64URL_DECODE_OK],
        can_fail: true,
    },
    OpSpec {
        name: "jwk.thumbprint",
        input: &JWK_THUMBPRINT_INPUT,
        ok: &[&JWK_THUMBPRINT_OK],
        can_fail: true,
    },
    OpSpec {
        name: "jwks.select",
        input: &JWKS_SELECT_INPUT,
        ok: &[&JWKS_SELECT_OK],
        can_fail: true,
    },
    OpSpec {
        name: "jws.sign",
        input: &JWS_SIGN_INPUT,
        ok: &[&JWS_SIGN_EXACT, &JWS_SIGN_ROUND_TRIP],
        can_fail: true,
    },
    OpSpec {
        name: "jws.verify",
        input: &JWS_VERIFY_INPUT,
        ok: &[&JWS_VERIFY_OK],
        can_fail: true,
    },
    OpSpec {
        name: "jwe.encrypt",
        input: &JWE_ENCRYPT_INPUT,
        ok: &[&JWE_ENCRYPT_EXACT, &JWE_ENCRYPT_ROUND_TRIP],
        can_fail: true,
    },
    OpSpec {
        name: "jwe.decrypt",
        input: &JWE_DECRYPT_INPUT,
        ok: &[&JWE_DECRYPT_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.import_pem",
        input: &KEYS_IMPORT_PEM_INPUT,
        ok: &[&KEYS_IMPORT_PEM_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.export_pem",
        input: &KEYS_EXPORT_PEM_INPUT,
        ok: &[&KEYS_EXPORT_PEM_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.import_der",
        input: &KEYS_IMPORT_DER_INPUT,
        ok: &[&KEYS_IMPORT_DER_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.export_der",
        input: &KEYS_EXPORT_DER_INPUT,
        ok: &[&KEYS_EXPORT_DER_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.generate_for",
        input: &KEYS_GENERATE_FOR_INPUT,
        ok: &[&KEYS_GENERATE_FOR_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.generate_oct",
        input: &KEYS_GENERATE_OCT_INPUT,
        ok: &[&KEYS_GENERATE_OK],
        can_fail: true,
    },
    OpSpec {
        name: "keys.generate_ec",
        input: &KEYS_GENERATE_EC_INPUT,
        ok: &[&KEYS_GENERATE_OK],
        can_fail: false,
    },
    OpSpec {
        name: "keys.generate_okp",
        input: &KEYS_GENERATE_OKP_INPUT,
        ok: &[&KEYS_GENERATE_OK],
        can_fail: false,
    },
    OpSpec {
        name: "jwt.validate",
        input: &JWT_VALIDATE_INPUT,
        ok: &[&JWT_VALIDATE_OK],
        can_fail: true,
    },
    OpSpec {
        name: "jwt.issue",
        input: &JWT_ISSUE_INPUT,
        ok: &[&JWT_ISSUE_EXACT, &JWT_ISSUE_VALIDATED],
        can_fail: true,
    },
];

fn spec(operation: &str) -> Option<&'static OpSpec> {
    SPECS.iter().find(|s| s.name == operation)
}

/// What a vector expects.
#[derive(Debug)]
enum Expect {
    /// Success with these output members (`ok` removed).
    Ok(Object),
    /// Failure with this stable error code.
    Err(String),
}

/// A schema-valid vector.
#[derive(Debug)]
struct Vector {
    operation: String,
    input: Object,
    expect: Expect,
    /// The cargo features it needs (top-level `features`), deduplicated.
    features: Vec<&'static str>,
    /// The cargo features it must run without (top-level
    /// `features_absent`, ADR 0056), deduplicated, none in `features`.
    features_absent: Vec<&'static str>,
}

/// A schema violation: the JSON pointer and what is wrong there.
fn violation(pointer: &str, problem: impl std::fmt::Display) -> String {
    format!("schema: {pointer}: {problem}")
}

fn is_text(s: &str) -> bool {
    !s.is_empty() && s.chars().any(|c| !c.is_whitespace())
}

fn is_hex(s: &str) -> bool {
    s.len().is_multiple_of(2) && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

fn is_base64url_alphabet(s: &str) -> bool {
    s.bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// `$defs/count`: `{"type": "integer", "minimum": 0, "maximum": COUNT_MAX}`.
fn is_count(value: &Value) -> bool {
    value.as_u64().is_some_and(|n| n <= COUNT_MAX)
}

/// `$defs/seconds`: `{"type": "integer", "minimum": -SECONDS_MAX,
/// "maximum": SECONDS_MAX}`.
fn is_seconds(value: &Value) -> bool {
    value.as_i64().is_some_and(|n| n.abs() <= SECONDS_MAX)
}

/// Checks that `object` has exactly the `allowed` members, all of which are
/// required.
fn exact_members(object: &Object, allowed: &[&str], pointer: &str) -> Result<(), String> {
    for (name, _) in object {
        if !allowed.contains(&name) {
            return Err(violation(
                &format!("{pointer}/{name}"),
                "unknown member (additionalProperties is false)",
            ));
        }
    }
    for name in allowed {
        if !object.contains(name) {
            return Err(violation(
                &format!("{pointer}/{name}"),
                "required member is missing",
            ));
        }
    }
    Ok(())
}

fn check_kind(value: &Value, kind: Kind, pointer: &str) -> Result<(), String> {
    match (kind, value) {
        (Kind::Nested(shape), Value::Object(object)) => {
            return check_shape(object, shape, false, pointer);
        }
        (Kind::List(shape), Value::Array(items)) if !items.is_empty() => {
            for (i, item) in items.iter().enumerate() {
                let at = format!("{pointer}/{i}");
                let object = item
                    .as_object()
                    .ok_or_else(|| violation(&at, "must be an object"))?;
                check_shape(object, shape, false, &at)?;
            }
            return Ok(());
        }
        _ => {}
    }
    let ok = match kind {
        Kind::Object => value.as_object().is_some(),
        Kind::String => value.as_str().is_some(),
        Kind::Hex => value.as_str().is_some_and(is_hex),
        Kind::Base64url => value.as_str().is_some_and(is_base64url_alphabet),
        Kind::Enum(values) => value.as_str().is_some_and(|s| values.contains(&s)),
        Kind::Count => is_count(value),
        Kind::Jws => value.as_str().is_some() || value.as_object().is_some(),
        Kind::AlgList | Kind::StringList => value
            .as_array()
            .is_some_and(|items| items.iter().all(|item| item.as_str().is_some())),
        Kind::Jwe => value.as_str().is_some() || value.as_object().is_some(),
        Kind::Bool => value.as_bool().is_some(),
        Kind::Seconds => is_seconds(value),
        Kind::StringOrList => {
            value.as_str().is_some()
                || value
                    .as_array()
                    .is_some_and(|items| items.iter().all(|item| item.as_str().is_some()))
        }
        Kind::StringOrNull => value.as_str().is_some() || value.is_null(),
        // Matched above when the value has the right type.
        Kind::Nested(_) | Kind::List(_) => false,
    };
    if ok {
        Ok(())
    } else {
        let wanted = match kind {
            Kind::Object => "an object".to_owned(),
            Kind::String => "a string".to_owned(),
            Kind::Hex => format!("a string matching {HEX_PATTERN}"),
            Kind::Base64url => format!("a string matching {BASE64URL_PATTERN}"),
            Kind::Enum(values) => format!("one of {values:?}"),
            Kind::Count => format!("an integer from 0 to {COUNT_MAX}"),
            Kind::Jws => "a string (compact) or an object (JSON serialization)".to_owned(),
            Kind::AlgList | Kind::StringList => "an array of strings".to_owned(),
            Kind::Jwe => "a string (compact) or an object (JSON serialization)".to_owned(),
            Kind::Bool => "a boolean".to_owned(),
            Kind::Seconds => format!("an integer from -{SECONDS_MAX} to {SECONDS_MAX}"),
            Kind::StringOrList => "a string or an array of strings".to_owned(),
            Kind::StringOrNull => "a string or null".to_owned(),
            Kind::Nested(shape) => format!("an object ({})", shape.def),
            Kind::List(shape) => format!("a non-empty array of objects ({})", shape.def),
        };
        Err(violation(pointer, format!("must be {wanted}")))
    }
}

/// Checks `object` against `shape`, plus `"ok"` when `ok` is set (a
/// success expectation, whose `ok` is already known to be `true`).
fn check_shape(object: &Object, shape: &Shape, ok: bool, pointer: &str) -> Result<(), String> {
    for (name, _) in object {
        let known = (ok && name == "ok") || shape.members.iter().any(|m| m.name == name);
        if !known {
            return Err(violation(
                &format!("{pointer}/{name}"),
                "unknown member (additionalProperties is false)",
            ));
        }
    }
    for member in shape.members {
        let at = format!("{pointer}/{}", member.name);
        match object.get(member.name) {
            Some(value) => check_kind(value, member.kind, &at)?,
            None if member.required => return Err(violation(&at, "required member is missing")),
            None => {}
        }
    }
    for rule in shape.rules {
        check_rule(object, rule, pointer)?;
    }
    Ok(())
}

/// Applies a [`Rule`] to an object whose members are valid.
fn check_rule(object: &Object, rule: &Rule, pointer: &str) -> Result<(), String> {
    match rule {
        Rule::Signers(rule) => check_signer_rule(object, rule, pointer),
        Rule::ExactlyOne(names) => {
            let present: Vec<&str> = names
                .iter()
                .copied()
                .filter(|n| object.contains(n))
                .collect();
            if present.len() == 1 {
                return Ok(());
            }
            let names = names
                .iter()
                .map(|n| format!("`{n}`"))
                .collect::<Vec<_>>()
                .join(", ");
            Err(violation(
                pointer,
                format!(
                    "needs exactly one of {names} (oneOf), has {}",
                    present.len()
                ),
            ))
        }
        Rule::OnlyWhen {
            member,
            value,
            dependent,
        } => {
            let selected = object.get(member).and_then(Value::as_str) == Some(*value);
            let at = format!("{pointer}/{dependent}");
            match (selected, object.contains(dependent)) {
                (true, false) => Err(violation(
                    &at,
                    format!("required when `{member}` is \"{value}\""),
                )),
                (false, true) => Err(violation(
                    &at,
                    format!("allowed only when `{member}` is \"{value}\""),
                )),
                _ => Ok(()),
            }
        }
    }
}

/// Applies a [`SignerRule`] to a `jws_sign_input` whose members are valid.
fn check_signer_rule(object: &Object, rule: &SignerRule, pointer: &str) -> Result<(), String> {
    if object.get("serialization").and_then(Value::as_str) != Some(rule.serialization) {
        return Ok(());
    }
    let signers = object
        .get("signers")
        .and_then(Value::as_array)
        .expect("checked as a member");
    let what = format!("a {} JWS", rule.serialization);
    if signers.len() > rule.max_signers {
        return Err(violation(
            &format!("{pointer}/signers"),
            format!("{what} has at most {} signer", rule.max_signers),
        ));
    }
    for (i, signer) in signers.iter().enumerate() {
        let signer = signer.as_object().expect("checked as a member");
        for name in rule.requires {
            if !signer.contains(name) {
                return Err(violation(
                    &format!("{pointer}/signers/{i}/{name}"),
                    format!("required for {what}"),
                ));
            }
        }
        for name in rule.forbids {
            if signer.contains(name) {
                return Err(violation(
                    &format!("{pointer}/signers/{i}/{name}"),
                    format!("not allowed in {what}"),
                ));
            }
        }
    }
    Ok(())
}

/// Checks a success expectation against the operation's success shapes:
/// it must match exactly one (schema `oneOf`).
fn check_ok(expect: &Object, spec: &OpSpec) -> Result<(), String> {
    if let [shape] = spec.ok {
        return check_shape(expect, shape, true, "/expect");
    }
    let results: Vec<(&str, Result<(), String>)> = spec
        .ok
        .iter()
        .map(|shape| (shape.def, check_shape(expect, shape, true, "/expect")))
        .collect();
    match results.iter().filter(|(_, r)| r.is_ok()).count() {
        1 => Ok(()),
        0 => Err(violation(
            "/expect",
            format!(
                "matches none of the success forms: {}",
                results
                    .iter()
                    .map(|(def, r)| format!("{def} ({})", r.as_ref().unwrap_err()))
                    .collect::<Vec<_>>()
                    .join("; ")
            ),
        )),
        _ => Err(violation(
            "/expect",
            "matches more than one success form (oneOf)",
        )),
    }
}

/// The vector's `source`, if it is usable, for failure messages.
fn usable_source(value: &Value) -> Option<String> {
    value
        .get("source")
        .and_then(Value::as_str)
        .filter(|s| is_text(s))
        .map(str::to_owned)
}

/// Checks one parsed vector file against the rules of `schema.json`.
fn validate(value: &Value) -> Result<Vector, String> {
    let root = value
        .as_object()
        .ok_or_else(|| violation("", "a vector file must hold one JSON object"))?;
    for (name, _) in root {
        if !TOP_LEVEL.contains(&name) && !TOP_LEVEL_OPTIONAL.contains(&name) {
            return Err(violation(
                &format!("/{name}"),
                "unknown member (additionalProperties is false)",
            ));
        }
    }
    for name in TOP_LEVEL {
        if !root.contains(name) {
            return Err(violation(&format!("/{name}"), "required member is missing"));
        }
    }
    let features = vector_features(root, "features")?;
    let features_absent = vector_features(root, "features_absent")?;
    if root.contains("features_absent") && features_absent.is_empty() {
        return Err(violation(
            "/features_absent",
            "must not be empty (minItems 1)",
        ));
    }
    // ADR 0056 §3: a name can't be both needed and forbidden.
    if let Some(both) = features.iter().find(|f| features_absent.contains(f)) {
        return Err(violation(
            "/features_absent",
            format!("\"{both}\" is listed in `features` too"),
        ));
    }
    for name in ["source", "description"] {
        let text = root.get(name).and_then(Value::as_str);
        if !text.is_some_and(is_text) {
            return Err(violation(
                &format!("/{name}"),
                "must be a string with a non-whitespace character",
            ));
        }
    }
    let operation = root
        .get("operation")
        .and_then(Value::as_str)
        .ok_or_else(|| violation("/operation", "must be a string"))?;
    if !OPERATIONS.contains(&operation) {
        return Err(violation(
            "/operation",
            format!("unknown operation `{operation}` (not in schema.json)"),
        ));
    }
    let input = root
        .get("input")
        .and_then(Value::as_object)
        .ok_or_else(|| violation("/input", "must be an object"))?;
    let expect = root
        .get("expect")
        .and_then(Value::as_object)
        .ok_or_else(|| violation("/expect", "must be an object"))?;
    let ok = expect
        .get("ok")
        .ok_or_else(|| violation("/expect/ok", "required member is missing"))?
        .as_bool()
        .ok_or_else(|| violation("/expect/ok", "must be a boolean"))?;

    let mut outputs = expect.clone();
    outputs.remove("ok");
    let expect = match spec(operation) {
        // Reserved operation: the schema constrains only `"ok"`, and
        // `execute` fails it, so the expectation is never compared.
        None if ok => Expect::Ok(outputs),
        None => Expect::Err(String::new()),
        Some(spec) => {
            check_shape(input, spec.input, false, "/input")?;
            if ok {
                check_ok(expect, spec)?;
                Expect::Ok(outputs)
            } else if !spec.can_fail {
                return Err(violation(
                    "/expect",
                    format!("`{operation}` cannot fail, so only {{\"ok\": true, ...}} is allowed"),
                ));
            } else {
                exact_members(expect, &["ok", "error"], "/expect")?;
                let code = expect
                    .get("error")
                    .and_then(Value::as_str)
                    .filter(|c| Error::CODES.contains(c))
                    .ok_or_else(|| violation("/expect/error", "must be one of Error::CODES"))?;
                Expect::Err(code.to_owned())
            }
        }
    };
    if operation == "jwe.encrypt" && spec(operation).is_some() {
        check_jwe_encrypt_features(input, &features, &features_absent)?;
    }
    if operation == "jwt.issue" {
        check_jwt_issue(input, &expect)?;
    }
    Ok(Vector {
        operation: operation.to_owned(),
        input: input.clone(),
        expect,
        features,
        features_absent,
    })
}

/// The top-level `features` or `features_absent` (`member`): an array of
/// [`FEATURES`] names, each at most once (schema: `uniqueItems`).
fn vector_features(root: &Object, member: &str) -> Result<Vec<&'static str>, String> {
    let Some(value) = root.get(member) else {
        return Ok(Vec::new());
    };
    let items = value
        .as_array()
        .ok_or_else(|| violation(&format!("/{member}"), "must be an array"))?;
    let mut features = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let feature = item
            .as_str()
            .and_then(|s| FEATURES.iter().map(|(name, _)| name).find(|f| **f == s))
            .ok_or_else(|| {
                violation(
                    &format!("/{member}/{i}"),
                    format!("must be one of {:?}", feature_names()),
                )
            })?;
        if features.contains(feature) {
            return Err(violation(
                &format!("/{member}/{i}"),
                "listed twice (uniqueItems)",
            ));
        }
        features.push(*feature);
    }
    Ok(features)
}

/// A `jwe.encrypt` vector declares the features its inputs need, so it is
/// SKIPPED, never failed or silently weakened, where they are off:
/// `rng_b64u` and `protected_b64u` need `fixed-rng` (cargo feature
/// `insecure-test-vectors`)
/// (`Encryptor::encrypt_reproducible`, ADR 0041 §3), `compress` needs
/// `deflate` (ADR 0017) listed in `features`, or in `features_absent` to
/// pin `UnsupportedAlgorithm` without it (ADR 0056 §4, ADR 0030 §4).
fn check_jwe_encrypt_features(
    input: &Object,
    features: &[&str],
    features_absent: &[&str],
) -> Result<(), String> {
    for (member, feature) in [("rng_b64u", "fixed-rng"), ("protected_b64u", "fixed-rng")] {
        if input.contains(member) && !features.contains(&feature) {
            return Err(violation(
                "/features",
                format!("`input/{member}` needs \"{feature}\" listed in `features`"),
            ));
        }
    }
    if input.contains("compress")
        && !features.contains(&"deflate")
        && !features_absent.contains(&"deflate")
    {
        return Err(violation(
            "/features",
            "`input/compress` needs \"deflate\" listed in `features` or `features_absent`",
        ));
    }
    Ok(())
}

/// The rules of a `jwt.issue` vector that tie its input to its
/// expectation (conformance/README.md), checked with the schema:
///
/// - with `encrypt` the token is randomized (the CEK, IV and any ephemeral
///   key come from the OS CSPRNG, RFC 7516 §5.1), so there is no exact
///   `token` to expect;
/// - `{"ok": true}` without `token` is checked by validating the issued
///   token with `validate`, which it therefore needs. Only with `encrypt`
///   may `validate` be left out, for a recipient whose private key the
///   vector does not hold; then only the token's compact shape is
///   checked;
/// - `validate` is used only on success, so a failure vector has none.
fn check_jwt_issue(input: &Object, expect: &Expect) -> Result<(), String> {
    let encrypt = input.contains("encrypt");
    let validate = input.contains("validate");
    match expect {
        Expect::Ok(want) if want.contains("token") && encrypt => Err(violation(
            "/expect/token",
            "an encrypted token is randomized (RFC 7516 §5.1), so with `encrypt` \
             expect {\"ok\": true} and give `validate`",
        )),
        Expect::Ok(want) if !want.contains("token") && !validate && !encrypt => Err(violation(
            "/input/validate",
            "required when the expectation has no `token`: the runner validates \
             the token it issued (only `encrypt` may go without)",
        )),
        Expect::Err(_) if validate => Err(violation(
            "/input/validate",
            "used only when the issue succeeds, so a failure vector has none",
        )),
        _ => Ok(()),
    }
}

fn hex_decode(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("validated hex"))
        .collect()
}

fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

fn input_str<'a>(input: &'a Object, name: &str) -> &'a str {
    input.get(name).and_then(Value::as_str).expect("validated")
}

fn input_object<'a>(object: &'a Object, name: &str) -> &'a Object {
    object
        .get(name)
        .and_then(Value::as_object)
        .expect("validated")
}

/// A `*_b64u` member's octets. The runner decodes them to hand them to the
/// library, so a value that does not decode is a broken vector, never an
/// outcome (the codec has its own `b64url.*` vectors).
fn input_bytes(object: &Object, name: &str) -> Result<Vec<u8>, String> {
    let text = object.get(name).and_then(Value::as_str).expect("validated");
    b64url_decode(text).map_err(|e| {
        format!(
            "`{name}` is not canonical base64url ({}); the runner must decode it",
            e.code()
        )
    })
}

/// An optional `$defs/count` member, as a `usize`.
fn input_count(object: &Object, name: &str) -> Option<usize> {
    object
        .get(name)
        .and_then(Value::as_u64)
        .map(|n| usize::try_from(n).expect("validated: at most u32::MAX"))
}

/// `allowed_algs`, mapped name by name: an unknown name becomes
/// `SigningAlg::Unknown`, which `VerifyOptions::new` refuses.
fn input_algs(object: &Object) -> Vec<SigningAlg> {
    object
        .get("allowed_algs")
        .and_then(Value::as_array)
        .expect("validated")
        .iter()
        .map(|alg| SigningAlg::from(alg.as_str().expect("validated")))
        .collect()
}

/// One signer's inputs, built from the vector.
struct SignerParts {
    key: Jwk,
    protected: Option<ProtectedHeader>,
    unprotected: Option<Header>,
}

/// Builds each signer, in order: import `key`, then decode and parse
/// `protected_b64u` (RFC 7515 §5.1 step 3, kept verbatim), then parse
/// `header` (§7.2.1). The first error is the outcome.
fn signer_parts(input: &Object) -> Result<Vec<SignerParts>, Error> {
    let signers = input
        .get("signers")
        .and_then(Value::as_array)
        .expect("validated");
    let mut parts = Vec::with_capacity(signers.len());
    for signer in signers {
        let signer = signer.as_object().expect("validated");
        let key = Jwk::from_object(input_object(signer, "key"))?;
        let protected = match signer.get("protected_b64u").and_then(Value::as_str) {
            Some(encoded) => Some(ProtectedHeader::from_encoded(encoded)?),
            None => None,
        };
        let unprotected = match signer.get("header") {
            Some(header) => Some(Header::from_json(header.to_json().as_bytes())?),
            None => None,
        };
        parts.push(SignerParts {
            key,
            protected,
            unprotected,
        });
    }
    Ok(parts)
}

/// `jws.sign` (RFC 7515 §5.1): build the signers (see [`signer_parts`]),
/// then sign in the requested serialization. An exact expectation gets the
/// output as `jws` (a string for compact; JSON output parsed, so it is
/// compared as a JSON value). A round-trip expectation is checked here
/// (see [`check_round_trip`]) and echoed back on success.
fn run_jws_sign(
    input: &Object,
    expect: &Expect,
    out: &mut Object,
) -> Result<Result<(), Error>, String> {
    let serialization = input_str(input, "serialization");
    let payload = input_bytes(input, "payload_b64u")?;
    let detached = input
        .get("detached")
        .and_then(Value::as_bool)
        .expect("validated");
    let parts = match signer_parts(input) {
        Ok(parts) => parts,
        Err(e) => return Ok(Err(e)),
    };
    let opts = SignOptions::new().detached(detached);
    let signed = if serialization == "compact" {
        // Schema: exactly one signer, with a protected header.
        let only = &parts[0];
        let protected = only.protected.as_ref().expect("validated");
        jws::sign_compact(protected, &payload, &only.key, &opts)
    } else {
        let signers: Vec<Signer<'_>> = parts
            .iter()
            .map(|part| {
                let mut signer = Signer::new(&part.key);
                if let Some(protected) = &part.protected {
                    signer = signer.protected(protected.clone());
                }
                if let Some(unprotected) = &part.unprotected {
                    signer = signer.unprotected(unprotected.clone());
                }
                signer
            })
            .collect();
        if serialization == "flattened" {
            jws::sign_flattened(&signers[0], &payload, &opts)
        } else {
            jws::sign_general(&signers, &payload, &opts)
        }
    };
    let text = match signed {
        Ok(text) => text,
        Err(e) => return Ok(Err(e)),
    };
    let jws = if serialization == "compact" {
        Value::from(text.as_str())
    } else {
        json::parse(text.as_bytes())
            .map_err(|e| format!("the signed JSON JWS does not parse: {}", e.code()))?
    };
    let verify_with = match expect {
        Expect::Ok(want) => want.get("verify_with").and_then(Value::as_object),
        Expect::Err(_) => None,
    };
    match verify_with {
        Some(verify_with) => {
            check_round_trip(
                serialization,
                &jws,
                &text,
                &payload,
                detached,
                parts.len(),
                verify_with,
            )?;
            out.insert("verify_with", verify_with.clone());
        }
        None => {
            out.insert("jws", jws);
        }
    }
    Ok(Ok(()))
}

/// Checks a randomized signature by round trip: the output has the shape
/// of the requested serialization (RFC 7515 §7.1, §7.2.1, §7.2.2), verifies
/// with `verify_with` (with the payload supplied separately when detached,
/// Appendix F), and yields the signed payload. Any failure is the vector's.
fn check_round_trip(
    serialization: &str,
    jws: &Value,
    text: &str,
    payload: &[u8],
    detached: bool,
    signers: usize,
    verify_with: &Object,
) -> Result<(), String> {
    let shape_ok = match serialization {
        "compact" => text.split('.').count() == 3,
        "flattened" => jws.get("signature").is_some() && jws.get("signatures").is_none(),
        _ => jws
            .get("signatures")
            .and_then(Value::as_array)
            .is_some_and(|all| all.len() == signers),
    };
    if !shape_ok {
        return Err(format!(
            "round trip: the output is not a {serialization} JWS with {signers} signature(s)"
        ));
    }
    let key = Jwk::from_object(input_object(verify_with, "key"))
        .map_err(|e| format!("round trip: verify_with.key does not import ({})", e.code()))?;
    let algs = input_algs(verify_with);
    let mut opts = VerifyOptions::new(&algs).map_err(|e| {
        format!(
            "round trip: verify_with.allowed_algs is refused ({})",
            e.code()
        )
    })?;
    if detached {
        opts = opts.detached_payload(payload);
    }
    let verified = match jws.as_str() {
        Some(compact) => jws::verify_compact(compact, &key, &opts),
        None => jws::verify_json(text, &key, &opts),
    }
    .map_err(|e| {
        format!(
            "round trip: the signed JWS does not verify with verify_with ({})",
            e.code()
        )
    })?;
    if *verified.payload != payload {
        return Err("round trip: the verified payload is not the signed one".to_owned());
    }
    Ok(())
}

/// `jws.verify` (RFC 7515 §5.2). The steps run in the order
/// conformance/README.md fixes for every runner, and the first error is
/// the outcome: import `key` (RFC 7517), build the options from
/// `allowed_algs` and the optional members, then verify. A string `jws`
/// goes to `verify_compact` (RFC 7515 §7.1); an object goes, as its JSON
/// text, to `verify_json` (§7.2).
fn run_jws_verify(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    let key = match Jwk::from_object(input_object(input, "key")) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    let algs = input_algs(input);
    let detached = match input.get("detached_payload_b64u") {
        Some(_) => Some(input_bytes(input, "detached_payload_b64u")?),
        None => None,
    };
    let mut opts = match VerifyOptions::new(&algs) {
        Ok(opts) => opts,
        Err(e) => return Ok(Err(e)),
    };
    if let Some(payload) = &detached {
        opts = opts.detached_payload(payload);
    }
    if let Some(n) = input_count(input, "max_input_len") {
        opts = opts.max_input_len(n);
    }
    if let Some(n) = input_count(input, "max_signatures") {
        opts = opts.max_signatures(n);
    }
    let jws = input.get("jws").expect("validated");
    let result = match jws.as_str() {
        Some(compact) => jws::verify_compact(compact, &key, &opts),
        None => jws::verify_json(&jws.to_json(), &key, &opts),
    };
    let verified = match result {
        Ok(verified) => verified,
        Err(e) => return Ok(Err(e)),
    };
    let index = u64::try_from(verified.signature_index).expect("an index fits u64");
    out.insert("payload_b64u", b64url_encode(&verified.payload));
    out.insert("alg", verified.alg.as_str());
    out.insert(
        "signature_index",
        Number::from_u64(index).expect("an index is a safe integer"),
    );
    Ok(Ok(()))
}

// ---------------------------------------------------------------------------
// jwe.* handlers (RFC 7516), kept apart from the jws.* ones.
// ---------------------------------------------------------------------------

/// A list member (`allowed_algs`, `allowed_enc`, `understood_crit`) as
/// strings, in order.
fn input_names<'a>(object: &'a Object, name: &str) -> Vec<&'a str> {
    object
        .get(name)
        .and_then(Value::as_array)
        .expect("validated")
        .iter()
        .map(|v| v.as_str().expect("validated"))
        .collect()
}

/// A `DecryptPolicy` from `allowed_algs` and `allowed_enc`, mapped name by
/// name (an unknown or unimplemented name is kept, and fails later as
/// `UnsupportedAlgorithm`), with the optional limits of `object`.
fn jwe_policy(object: &Object) -> Result<DecryptPolicy, Error> {
    let algs: Vec<KeyMgmtAlg> = input_names(object, "allowed_algs")
        .into_iter()
        .map(KeyMgmtAlg::from)
        .collect();
    let encs: Vec<ContentEncAlg> = input_names(object, "allowed_enc")
        .into_iter()
        .map(ContentEncAlg::from)
        .collect();
    let mut policy = DecryptPolicy::new(&algs, &encs)?;
    if object.contains("understood_crit") {
        policy = policy.understood_crit(&input_names(object, "understood_crit"));
    }
    if let Some(n) = input_count(object, "max_input_len") {
        policy = policy.max_input_len(n);
    }
    if let Some(n) = input_count(object, "max_recipients") {
        policy = policy.max_recipients(n);
    }
    if let Some(n) = input_count(object, "max_pbes2_count") {
        policy = policy.max_pbes2_count(u32::try_from(n).expect("validated: a u32"));
    }
    if let Some(n) = input_count(object, "max_decompressed_len") {
        policy = policy.max_decompressed_len(n);
    }
    Ok(policy)
}

/// Decrypts `jwe` (a compact string, or a JSON JWE object passed as its
/// text) with `key` under `policy`.
fn jwe_decrypt(jwe: &Value, key: &Jwk, policy: &DecryptPolicy) -> polyjose::Result<jwe::Decrypted> {
    match jwe.as_str() {
        Some(compact) => jwe::decrypt_compact(compact, key, policy),
        None => jwe::decrypt_json(&jwe.to_json(), key, policy),
    }
}

/// `encrypt_reproducible` with the vector's injected bytes. Every byte must
/// be drawn: a leftover means the draw order (`jwe::random`) differs from
/// the vector's.
#[cfg(feature = "insecure-test-vectors")]
fn jwe_encrypt_reproducible(
    encryptor: &Encryptor,
    plaintext: &[u8],
    form: jwe::Serialization,
    rng_bytes: Vec<u8>,
    protected_b64u: Option<&str>,
) -> Result<Result<String, Error>, String> {
    let mut rng = polyjose::insecure_test_vectors::FixedRng::new(rng_bytes);
    let result = encryptor.encrypt_reproducible(plaintext, form, &mut rng, protected_b64u);
    if result.is_ok() && rng.remaining() != 0 {
        return Err(format!(
            "`rng_b64u` has {} byte(s) the encryption did not draw",
            rng.remaining()
        ));
    }
    Ok(result)
}

/// Never reached: such a vector declares `insecure-test-vectors` and is
/// SKIPPED in this build.
#[cfg(not(feature = "insecure-test-vectors"))]
fn jwe_encrypt_reproducible(
    _encryptor: &Encryptor,
    _plaintext: &[u8],
    _form: jwe::Serialization,
    _rng_bytes: Vec<u8>,
    _protected_b64u: Option<&str>,
) -> Result<Result<String, Error>, String> {
    unreachable!(
        "a vector with rng_b64u or protected_b64u is skipped without insecure-test-vectors"
    )
}

/// `Encryptor::compress` (RFC 7516 §4.1.3). It exists in every build:
/// without `deflate` the encryption then fails with `UnsupportedAlgorithm`
/// (ADR 0017 §5, ADR 0030 §4), which a `features_absent: ["deflate"]`
/// vector pins (ADR 0056).
fn jwe_compress(encryptor: Encryptor) -> Encryptor {
    encryptor.compress()
}

/// The recipients of a `jwe.encrypt` vector, in order: for each, import
/// `key`, then parse `header`. The first error is the outcome.
fn jwe_recipients(input: &Object) -> Result<Result<Vec<Recipient>, Error>, String> {
    let items = input
        .get("recipients")
        .and_then(Value::as_array)
        .expect("validated");
    let mut recipients = Vec::with_capacity(items.len());
    for item in items {
        let item = item.as_object().expect("validated");
        let key = match Jwk::from_object(input_object(item, "key")) {
            Ok(key) => key,
            Err(e) => return Ok(Err(e)),
        };
        let mut recipient = Recipient::new(KeyMgmtAlg::from(input_str(item, "alg")), &key);
        if let Some(header) = item.get("header") {
            match Header::from_json(header.to_json().as_bytes()) {
                Ok(header) => recipient = recipient.header(header),
                Err(e) => return Ok(Err(e)),
            }
        }
        if item.contains("apu_b64u") {
            recipient = recipient.apu(input_bytes(item, "apu_b64u")?);
        }
        if item.contains("apv_b64u") {
            recipient = recipient.apv(input_bytes(item, "apv_b64u")?);
        }
        if let Some(n) = input_count(item, "p2c") {
            recipient = recipient.p2c(u32::try_from(n).expect("validated: a u32"));
        }
        if let Some(n) = input_count(item, "p2s_len") {
            recipient = recipient.p2s_len(n);
        }
        recipients.push(recipient);
    }
    Ok(Ok(recipients))
}

/// `jwe.encrypt` (RFC 7516 §5.1). The steps run in the order
/// conformance/README.md fixes: the recipients ([`jwe_recipients`]), then
/// `protected`, then `unprotected`, then the call; the first error is the
/// outcome. With `rng_b64u` or `protected_b64u` the call is
/// `encrypt_reproducible` (feature `insecure-test-vectors`); otherwise
/// `encrypt_compact` or `encrypt_json`, on the OS CSPRNG. An exact
/// expectation gets the output as `jwe` (a string for compact; JSON parsed,
/// so compared as a JSON value); a round trip is checked here
/// ([`check_jwe_round_trip`]) and echoed back on success.
fn run_jwe_encrypt(
    input: &Object,
    expect: &Expect,
    out: &mut Object,
) -> Result<Result<(), Error>, String> {
    let serialization = input_str(input, "serialization");
    let plaintext = input_bytes(input, "plaintext_b64u")?;
    let recipients = match jwe_recipients(input)? {
        Ok(recipients) => recipients,
        Err(e) => return Ok(Err(e)),
    };
    let count = recipients.len();
    let mut encryptor = Encryptor::new(ContentEncAlg::from(input_str(input, "enc")));
    for (member, shared) in [("protected", false), ("unprotected", true)] {
        let Some(header) = input.get(member) else {
            continue;
        };
        let header = match Header::from_json(header.to_json().as_bytes()) {
            Ok(header) => header,
            Err(e) => return Ok(Err(e)),
        };
        encryptor = if shared {
            encryptor.shared_unprotected_header(header)
        } else {
            encryptor.protected_header(header)
        };
    }
    if input.contains("aad_b64u") {
        encryptor = encryptor.aad(input_bytes(input, "aad_b64u")?);
    }
    if input.get("compress").and_then(Value::as_bool) == Some(true) {
        encryptor = jwe_compress(encryptor);
    }
    for recipient in recipients {
        encryptor = encryptor.recipient(recipient);
    }
    let form = match serialization {
        "compact" => jwe::Serialization::Compact,
        "flattened" => jwe::Serialization::Json(JsonForm::Flattened),
        _ => jwe::Serialization::Json(JsonForm::General),
    };
    let encrypted = if input.contains("rng_b64u") || input.contains("protected_b64u") {
        let rng_bytes = match input.get("rng_b64u") {
            Some(_) => input_bytes(input, "rng_b64u")?,
            None => Vec::new(),
        };
        let protected_b64u = input.get("protected_b64u").and_then(Value::as_str);
        jwe_encrypt_reproducible(&encryptor, &plaintext, form, rng_bytes, protected_b64u)?
    } else {
        match form {
            jwe::Serialization::Compact => encryptor.encrypt_compact(&plaintext),
            jwe::Serialization::Json(json_form) => encryptor.encrypt_json(&plaintext, json_form),
        }
    };
    let text = match encrypted {
        Ok(text) => text,
        Err(e) => return Ok(Err(e)),
    };
    let jwe = if serialization == "compact" {
        Value::from(text.as_str())
    } else {
        json::parse(text.as_bytes())
            .map_err(|e| format!("the encrypted JSON JWE does not parse: {}", e.code()))?
    };
    let decrypt_with = match expect {
        Expect::Ok(want) => want.get("decrypt_with").and_then(Value::as_object),
        Expect::Err(_) => None,
    };
    match decrypt_with {
        Some(decrypt_with) => {
            check_jwe_round_trip(serialization, &jwe, &plaintext, count, decrypt_with)?;
            out.insert("decrypt_with", decrypt_with.clone());
        }
        None => {
            out.insert("jwe", jwe);
        }
    }
    Ok(Ok(()))
}

/// Checks a randomized encryption by round trip: the output has the shape
/// of the requested serialization (five compact parts, RFC 7516 §7.1;
/// `ciphertext` without `recipients` for flattened, §7.2.2; one
/// `recipients` entry per recipient for general, §7.2.1), decrypts with
/// `decrypt_with`, and yields the plaintext. Any failure is the vector's.
fn check_jwe_round_trip(
    serialization: &str,
    jwe: &Value,
    plaintext: &[u8],
    recipients: usize,
    decrypt_with: &Object,
) -> Result<(), String> {
    let shape_ok = match serialization {
        "compact" => jwe.as_str().is_some_and(|t| t.split('.').count() == 5),
        "flattened" => jwe.get("ciphertext").is_some() && jwe.get("recipients").is_none(),
        _ => jwe
            .get("recipients")
            .and_then(Value::as_array)
            .is_some_and(|all| all.len() == recipients),
    };
    if !shape_ok {
        return Err(format!(
            "round trip: the output is not a {serialization} JWE with {recipients} recipient(s)"
        ));
    }
    let key = Jwk::from_object(input_object(decrypt_with, "key")).map_err(|e| {
        format!(
            "round trip: decrypt_with.key does not import ({})",
            e.code()
        )
    })?;
    let policy = jwe_policy(decrypt_with).map_err(|e| {
        format!(
            "round trip: decrypt_with's lists are refused ({})",
            e.code()
        )
    })?;
    let decrypted = jwe_decrypt(jwe, &key, &policy).map_err(|e| {
        format!(
            "round trip: the encrypted JWE does not decrypt with decrypt_with ({})",
            e.code()
        )
    })?;
    if decrypted.plaintext() != plaintext {
        return Err("round trip: the decrypted plaintext is not the encrypted one".to_owned());
    }
    Ok(())
}

/// `jwe.decrypt` (RFC 7516 §5.2). The steps run in the order
/// conformance/README.md fixes for every runner, and the first error is
/// the outcome: import `key` (RFC 7517), build the policy from
/// `allowed_algs`, `allowed_enc` and the optional members, then decrypt.
/// A string `jwe` goes to `decrypt_compact` (RFC 7516 §7.1); an object
/// goes, as its JSON text, to `decrypt_json` (§7.2).
fn run_jwe_decrypt(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    let key = match Jwk::from_object(input_object(input, "key")) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    let policy = match jwe_policy(input) {
        Ok(policy) => policy,
        Err(e) => return Ok(Err(e)),
    };
    let decrypted = match jwe_decrypt(input.get("jwe").expect("validated"), &key, &policy) {
        Ok(decrypted) => decrypted,
        Err(e) => return Ok(Err(e)),
    };
    let index = u64::try_from(decrypted.recipient()).expect("an index fits u64");
    out.insert("plaintext_b64u", b64url_encode(decrypted.plaintext()));
    out.insert(
        "recipient",
        Number::from_u64(index).expect("an index is a safe integer"),
    );
    Ok(Ok(()))
}

/// The library format a validated `format` member names.
fn input_format(input: &Object) -> KeyFormat {
    let name = input_str(input, "format");
    KEY_FORMATS
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, f)| *f)
        .expect("validated")
}

/// The outcome of a PEM or DER import: the JWK as an object. An `oct`
/// result fails the vector whatever it expects: PEM and DER never carry one
/// (RFC 8725 §2.1, ADR 0018 §3).
fn imported(result: Result<Jwk, Error>, out: &mut Object) -> Result<Result<(), Error>, String> {
    let key = match result {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    let jwk = key.to_object();
    if jwk.get("kty").and_then(Value::as_str) == Some("oct") {
        return Err("a PEM or DER import returned an oct key (RFC 8725 §2.1)".to_owned());
    }
    out.insert("jwk", Value::from(jwk));
    Ok(Ok(()))
}

/// `keys.import_pem`: `Jwk::from_pem`, and the JWK as an object.
fn run_keys_import_pem(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    imported(Jwk::from_pem(input_str(input, "pem")), out)
}

/// `keys.import_der`: decode `der_b64u` (a broken vector if it is not
/// canonical), then `Jwk::from_der` in `format`, and the JWK as an object.
fn run_keys_import_der(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    let der = input_bytes(input, "der_b64u")?;
    imported(Jwk::from_der(&der, input_format(input)), out)
}

/// `keys.export_pem`: the JWK import (`Jwk::from_object`), whose error is
/// the outcome, then `Jwk::to_pem` in `format`.
fn run_keys_export_pem(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    let format = input_format(input);
    let key = match Jwk::from_object(input_object(input, "jwk")) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    match key.to_pem(format) {
        Ok(pem) => {
            out.insert("pem", pem.as_str());
            Ok(Ok(()))
        }
        Err(e) => Ok(Err(e)),
    }
}

/// `keys.export_der`: the JWK import (`Jwk::from_object`), whose error is
/// the outcome, then `Jwk::to_der` in `format`, as canonical base64url.
fn run_keys_export_der(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    let format = input_format(input);
    let key = match Jwk::from_object(input_object(input, "jwk")) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    match key.to_der(format) {
        Ok(der) => {
            out.insert("der_b64u", b64url_encode(&der));
            Ok(Ok(()))
        }
        Err(e) => Ok(Err(e)),
    }
}

/// The identifier `name` registers. RFC 7518 §7.1 keeps JWS `alg`, JWE
/// `alg` and JWE `enc` values in one registry whose names are unique
/// (case-sensitive), so at most one of the three enums knows `name`. A name
/// none of them knows stays `SigningAlg::Unknown`, which generation refuses
/// with `UnsupportedAlgorithm`.
fn jose_alg(name: &str) -> JoseAlg {
    let signing = SigningAlg::from(name);
    if signing.is_known() {
        return signing.into();
    }
    let key_mgmt = KeyMgmtAlg::from(name);
    if key_mgmt.is_known() {
        return key_mgmt.into();
    }
    let enc = ContentEncAlg::from(name);
    if enc.is_known() {
        return enc.into();
    }
    signing.into()
}

/// The members a generated private key has: those RFC 7518 §6.2.1–§6.2.2
/// (EC), RFC 8037 §2 (OKP) or RFC 7518 §6.4.1 (oct) define, plus the `alg`
/// it is bound to (RFC 7517 §4.4). Sorted.
fn generated_members(kty: &str) -> Option<&'static [&'static str]> {
    match kty {
        "EC" => Some(&["alg", "crv", "d", "kty", "x", "y"]),
        "OKP" => Some(&["alg", "crv", "d", "kty", "x"]),
        "oct" => Some(&["alg", "k", "kty"]),
        _ => None,
    }
}

/// [`generated_members`] for a key bound to no algorithm (`keys::generate`):
/// the same members without `alg`. Sorted.
fn unbound_members(kty: &str) -> Option<&'static [&'static str]> {
    match kty {
        "EC" => Some(&["crv", "d", "kty", "x", "y"]),
        "OKP" => Some(&["crv", "d", "kty", "x"]),
        "oct" => Some(&["k", "kty"]),
        _ => None,
    }
}

/// The shape of a generated key, after checking what a shape cannot say:
/// the key is private, has exactly the members of
/// [`generated_members`], and imports back (`Jwk::from_object`) to the
/// same JWK. Any failure there fails the vector.
fn generated_shape(key: &Jwk) -> Result<Object, String> {
    shape_of(key, generated_members)
}

/// [`generated_shape`] with the member list `members` gives per `kty`.
fn shape_of(
    key: &Jwk,
    members: fn(&str) -> Option<&'static [&'static str]>,
) -> Result<Object, String> {
    if key.is_public() {
        return Err("generate_for returned a public key".to_owned());
    }
    let jwk = key.to_object();
    let kty = jwk.get("kty").and_then(Value::as_str).unwrap_or_default();
    let mut names: Vec<&str> = jwk.iter().map(|(name, _)| name).collect();
    names.sort_unstable();
    match members(kty) {
        Some(expected) if names == expected => {}
        _ => {
            return Err(format!(
                "generate_for returned a JWK with members {names:?}"
            ));
        }
    }
    let again = Jwk::from_object(&jwk)
        .map_err(|e| format!("the generated JWK does not import ({})", e.code()))?;
    if again.to_object() != jwk {
        return Err("the generated JWK imports as a different key".to_owned());
    }
    let mut shape = Object::new();
    for name in ["kty", "crv", "alg"] {
        if let Some(value) = jwk.get(name) {
            shape.insert(name, value.clone());
        }
    }
    if let Some(k) = jwk.get("k").and_then(Value::as_str) {
        let octets = b64url_decode(k).map_err(|e| format!("generated k: {}", e.code()))?;
        let octets = u64::try_from(octets.len()).expect("a length fits u64");
        shape.insert(
            "k_octets",
            Number::from_u64(octets).expect("a key length is a safe integer"),
        );
    }
    Ok(shape)
}

/// `keys.generate_for`: resolve `alg` (see [`jose_alg`]), generate, and
/// return the key's shape (see [`generated_shape`]), after its use round
/// trip when the vector has `use_with` (see [`check_use_with`]).
fn run_keys_generate_for(
    input: &Object,
    expect: &Expect,
    out: &mut Object,
) -> Result<Result<(), Error>, String> {
    let key = match generate_for(jose_alg(input_str(input, "alg"))) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    out.insert("shape", generated_shape(&key)?);
    echo_use_with(&key, expect, out)?;
    Ok(Ok(()))
}

/// The curve a validated `crv` names, from the curves the core generates.
fn input_spec(operation: &str, input: &Object) -> KeySpec {
    match operation {
        "keys.generate_oct" => KeySpec::Oct {
            bytes: input_count(input, "len_bytes").expect("validated"),
        },
        "keys.generate_ec" => {
            let crv = input_str(input, "crv");
            KeySpec::Ec(
                EC_CURVES
                    .into_iter()
                    .find(|c| c.as_str() == crv)
                    .expect("validated: one of EC_CURVE_NAMES"),
            )
        }
        _ => {
            let crv = input_str(input, "crv");
            KeySpec::Okp(
                OKP_CURVES
                    .into_iter()
                    .find(|c| c.as_str() == crv)
                    .expect("validated: one of OKP_CURVE_NAMES"),
            )
        }
    }
}

/// The EC curves `keys::generate` takes (RFC 7518 §6.2.1.1, RFC 8812 §3.1),
/// in [`EC_CURVE_NAMES`] order.
const EC_CURVES: [EcCurve; 4] = [
    EcCurve::P256,
    EcCurve::P384,
    EcCurve::P521,
    EcCurve::Secp256k1,
];
/// The OKP curves `keys::generate` takes (RFC 8037 §2), in
/// [`OKP_CURVE_NAMES`] order.
const OKP_CURVES: [OkpCurve; 2] = [OkpCurve::Ed25519, OkpCurve::X25519];

/// `keys.generate_oct`, `keys.generate_ec`, `keys.generate_okp` (ADR 0018
/// §5; ADR 0030 `jwk_generate_oct`/`_ec`/`_okp`): generate with
/// `keys::generate`, check the key (private, exactly the RFC members, no
/// `alg`, imports back), return its shape, and run its use round trip.
fn run_keys_generate(
    operation: &str,
    input: &Object,
    expect: &Expect,
    out: &mut Object,
) -> Result<Result<(), Error>, String> {
    let key = match generate(input_spec(operation, input)) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    out.insert("shape", shape_of(&key, unbound_members)?);
    echo_use_with(&key, expect, out)?;
    Ok(Ok(()))
}

/// Runs the expectation's `use_with` round trip on `key`, if it has one,
/// and echoes it back as an output, as `verify_with` is.
fn echo_use_with(key: &Jwk, expect: &Expect, out: &mut Object) -> Result<(), String> {
    if let Expect::Ok(want) = expect
        && let Some(use_with) = want.get("use_with").and_then(Value::as_object)
    {
        check_use_with(key, use_with)?;
        out.insert("use_with", use_with.clone());
    }
    Ok(())
}

/// The payload or plaintext of every `use_with` round trip: `polyjose`.
const USE_WITH_PAYLOAD: &[u8] = b"polyjose";

/// The `use_with` round trip of a generated key (ADR 0034 §6), any failure
/// failing the vector. The other side uses the key's public key, or the
/// key itself for `oct` (RFC 7518 §6.4).
///
/// - Without `enc`: a compact JWS (RFC 7515 §7.1) of [`USE_WITH_PAYLOAD`]
///   under the protected header `{"alg": alg}`, signed with `key` and
///   verified with allow-list `[alg]` (RFC 7515 §5.1–§5.2).
/// - With `enc`: a compact JWE (RFC 7516 §7.1) of it to one recipient with
///   `alg`, decrypted with `key` and allow-lists `[alg]` and `[enc]`
///   (RFC 7516 §5.1–§5.2).
fn check_use_with(key: &Jwk, use_with: &Object) -> Result<(), String> {
    let alg = input_str(use_with, "alg");
    let other = key.to_public().unwrap_or_else(|| key.clone());
    let fail = |what: &str, e: Error| format!("use_with: {what} ({})", e.code());
    match use_with.get("enc").and_then(Value::as_str) {
        None => {
            let header = format!(r#"{{"alg":{}}}"#, Value::from(alg).to_json());
            let protected = ProtectedHeader::from_encoded(&b64url_encode(header.as_bytes()))
                .map_err(|e| fail("the protected header is refused", e))?;
            let token = jws::sign_compact(&protected, USE_WITH_PAYLOAD, key, &SignOptions::new())
                .map_err(|e| fail("the key does not sign", e))?;
            let algs = [SigningAlg::from(alg)];
            let opts =
                VerifyOptions::new(&algs).map_err(|e| fail("the allow-list is refused", e))?;
            let verified = jws::verify_compact(&token, &other, &opts)
                .map_err(|e| fail("the signature does not verify", e))?;
            if verified.payload.as_slice() != USE_WITH_PAYLOAD {
                return Err("use_with: the verified payload is not the signed one".to_owned());
            }
        }
        Some(enc) => {
            let token = Encryptor::new(ContentEncAlg::from(enc))
                .recipient(Recipient::new(KeyMgmtAlg::from(alg), &other))
                .encrypt_compact(USE_WITH_PAYLOAD)
                .map_err(|e| fail("encryption to the key fails", e))?;
            let policy = DecryptPolicy::new(&[KeyMgmtAlg::from(alg)], &[ContentEncAlg::from(enc)])
                .map_err(|e| fail("the allow-lists are refused", e))?;
            let decrypted = jwe::decrypt_compact(&token, key, &policy)
                .map_err(|e| fail("the key does not decrypt", e))?;
            if decrypted.plaintext() != USE_WITH_PAYLOAD {
                return Err("use_with: the decrypted plaintext is not the encrypted one".to_owned());
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// jwt.* handlers (RFC 7519), kept apart from the jws.* and jwe.* ones.
// ---------------------------------------------------------------------------

/// The verification keys of a `jwt.*` vector: `key` (one JWK) or `jwks`
/// (a JWK Set, RFC 7517 §5; ADR 0029 §1). The schema allows exactly one.
enum JwtKeys {
    One(Box<Jwk>),
    Set(Box<JwkSet>),
}

impl JwtKeys {
    fn keys(&self) -> Keys<'_> {
        match self {
            JwtKeys::One(key) => Keys::One(key),
            JwtKeys::Set(set) => Keys::Set(set),
        }
    }
}

/// Everything a JWT validation takes except the token, built from a
/// `jwt.validate` input or a `jwt.issue` `validate` object.
struct JwtValidation {
    /// `now` (ADR 0028 §4): the only clock the runner ever builds, so
    /// every platform gives the same verdict on every day.
    clock: FixedClock,
    algs: Vec<SigningAlg>,
    keys: JwtKeys,
    /// `decrypt`: the outer JWE layer's key and policy (ADR 0027 §7).
    decrypt: Option<(Jwk, DecryptPolicy)>,
    policy: Option<Object>,
}

/// Builds a [`JwtValidation`] in the order conformance/README.md fixes,
/// the outer layer first: `decrypt.key` (RFC 7517), then `decrypt`'s
/// allow-lists and bound, then `key` or `jwks` (RFC 7517 §4, §5). The first
/// error is the vector's outcome, so a JWK or JWK Set import error is its
/// result (for example a multi-prime RSA key, `UnsupportedAlgorithm`,
/// ADR 0067 §3).
fn jwt_validation(object: &Object) -> Result<JwtValidation, Error> {
    let decrypt = match object.get("decrypt").and_then(Value::as_object) {
        Some(decrypt) => {
            let key = Jwk::from_object(input_object(decrypt, "key"))?;
            Some((key, jwe_policy(decrypt)?))
        }
        None => None,
    };
    let keys = match object.get("jwks").and_then(Value::as_object) {
        Some(set) => JwtKeys::Set(Box::new(JwkSet::from_object(set)?)),
        None => JwtKeys::One(Box::new(Jwk::from_object(input_object(object, "key"))?)),
    };
    let now = object
        .get("now")
        .and_then(Value::as_i64)
        .expect("validated");
    Ok(JwtValidation {
        clock: FixedClock(now),
        algs: input_algs(object),
        keys,
        decrypt,
        policy: object.get("policy").and_then(Value::as_object).cloned(),
    })
}

/// A `policy` member's strings: one string, or an array of them.
fn policy_names<'a>(policy: &'a Object, name: &str) -> Vec<&'a str> {
    match policy.get(name) {
        None => Vec::new(),
        Some(value) => match value.as_str() {
            Some(one) => vec![one],
            None => input_names(policy, name),
        },
    }
}

/// The JWT [`Policy`] for `clock`, `algs` and the vector's `policy`
/// (RFC 7519 §4.1, §7.2; RFC 8725 §3; ADR 0027 §3–§5, ADR 0029 §4). It
/// takes a [`FixedClock`] and nothing else, so the runner can never hand
/// the library a wall clock (ADR 0028 §4).
///
/// `profile: "access_token"` starts from `Policy::access_token` with the
/// `issuer` and `audience` lists (RFC 9068 §4); otherwise from
/// `Policy::new`, adding them. Each other member present calls its builder
/// method once; an absent member keeps the library default. The library's
/// refusals (an empty or `none` allow-list, a leeway over 600 s, an access
/// token policy without issuer or audience) are the vector's outcome.
///
/// A `typ` of mode `default` with `profile` is a broken vector (the outer
/// `Err`): the profile requires `at+jwt` (RFC 9068 §4), and no policy can
/// mean both.
fn jwt_policy<'a>(
    clock: &'a FixedClock,
    algs: &'a [SigningAlg],
    policy: Option<&Object>,
) -> Result<Result<Policy<'a>, Error>, String> {
    let empty = Object::new();
    let policy = policy.unwrap_or(&empty);
    let issuers = policy_names(policy, "issuer");
    let audiences = policy_names(policy, "audience");
    let typ = policy.get("typ").and_then(Value::as_object);
    let typ_mode = typ.map(|typ| input_str(typ, "mode"));
    let profile = policy.contains("profile");
    if profile && typ_mode == Some("default") {
        return Err(
            "`policy/typ/mode` \"default\" contradicts `policy/profile` \"access_token\", \
             which requires typ at+jwt (RFC 9068 §4)"
                .to_owned(),
        );
    }
    let built = if profile {
        Policy::access_token(clock, algs, &issuers, &audiences)
    } else {
        Policy::new(clock, algs).map(|p| p.issuers(&issuers).audiences(&audiences))
    };
    let mut built = match built {
        Ok(built) => built,
        Err(e) => return Ok(Err(e)),
    };
    if let Some(subject) = policy.get("subject").and_then(Value::as_str) {
        built = built.subject(subject);
    }
    if let Some(secs) = input_count(policy, "leeway") {
        match built.leeway(u32::try_from(secs).expect("validated: a u32")) {
            Ok(with) => built = with,
            Err(e) => return Ok(Err(e)),
        }
    }
    if let Some(secs) = input_count(policy, "max_age") {
        built = built.max_age(u32::try_from(secs).expect("validated: a u32"));
    }
    if policy.contains("require") {
        for claim in input_names(policy, "require") {
            built = built.require(claim);
        }
    }
    if policy.get("allow_missing_exp").and_then(Value::as_bool) == Some(true) {
        built = built.allow_missing_exp();
    }
    if policy.get("ignore_audience").and_then(Value::as_bool) == Some(true) {
        built = built.ignore_audience();
    }
    match typ_mode {
        Some("exact") => {
            built = built.expect_typ(input_str(typ.expect("present"), "value"));
        }
        Some("any") => built = built.any_typ(),
        // `default`, or absent: the library default (ADR 0027 §5).
        _ => {}
    }
    if let Some(n) = input_count(policy, "max_key_candidates") {
        built = built.max_key_candidates(n);
    }
    Ok(Ok(built))
}

/// Verifies `token` under `validation` and `policy`: `jwt::verify` for a
/// signed JWT, or `jwt::decrypt_nested` when the vector has `decrypt`
/// (RFC 7519 §7.2; ADR 0027 §7), whose inner JWT is the result.
fn jwt_verify(
    token: &str,
    validation: &JwtValidation,
    policy: &Policy<'_>,
) -> polyjose::Result<VerifiedJwt> {
    match &validation.decrypt {
        Some((key, decrypt_policy)) => {
            jwt::decrypt_nested(token, key, decrypt_policy, validation.keys.keys(), policy)
                .map(|nested| nested.inner)
        }
        None => jwt::verify(token, validation.keys.keys(), policy),
    }
}

/// The validated Claims Set as a JSON value (the library's own
/// serialization, ADR 0027 §1, read back), for comparison as JSON.
fn claims_value(verified: &VerifiedJwt) -> Result<Value, String> {
    json::parse(verified.claims.to_json().as_bytes()).map_err(|e| {
        format!(
            "the validated claims do not serialize as JSON: {}",
            e.code()
        )
    })
}

/// `jwt.validate` (RFC 7519 §7.2). The steps run in the order
/// conformance/README.md fixes for every runner, and the first error is
/// the outcome: build the inputs ([`jwt_validation`]), then the policy
/// ([`jwt_policy`]), then validate.
fn run_jwt_validate(input: &Object, out: &mut Object) -> Result<Result<(), Error>, String> {
    let validation = match jwt_validation(input) {
        Ok(validation) => validation,
        Err(e) => return Ok(Err(e)),
    };
    let policy = match jwt_policy(
        &validation.clock,
        &validation.algs,
        validation.policy.as_ref(),
    )? {
        Ok(policy) => policy,
        Err(e) => return Ok(Err(e)),
    };
    let verified = match jwt_verify(input_str(input, "token"), &validation, &policy) {
        Ok(verified) => verified,
        Err(e) => return Ok(Err(e)),
    };
    out.insert("claims", claims_value(&verified)?);
    out.insert("alg", verified.alg.as_str());
    if let Some(index) = verified.key_index {
        let index = u64::try_from(index).expect("an index fits u64");
        out.insert(
            "key_index",
            Number::from_u64(index).expect("an index is a safe integer"),
        );
    }
    Ok(Ok(()))
}

/// `jwt.issue` (RFC 7519 §7.1). The steps run in the order
/// conformance/README.md fixes, the first error being the outcome: import
/// `key` (RFC 7517), parse `claims` (RFC 7519 §4; ADR 0027 §1–§2), import
/// `encrypt.key`, sign with `alg` and `typ` (ADR 0027 §8), then encrypt
/// (ADR 0027 §7). The output must be a compact JWS (three parts, RFC 7515
/// §7.1) or, with `encrypt`, a compact JWE (five, RFC 7516 §7.1). An exact
/// expectation gets it as `token`; with `validate`, it is also validated
/// ([`check_jwt_issue_round_trip`]), any failure there failing the vector.
fn run_jwt_issue(
    input: &Object,
    expect: &Expect,
    out: &mut Object,
) -> Result<Result<(), Error>, String> {
    let key = match Jwk::from_object(input_object(input, "key")) {
        Ok(key) => key,
        Err(e) => return Ok(Err(e)),
    };
    let claims_in = input.get("claims").expect("validated");
    let claims = match Claims::from_json(claims_in.to_json().as_bytes()) {
        Ok(claims) => claims,
        Err(e) => return Ok(Err(e)),
    };
    let encryptor = match input.get("encrypt").and_then(Value::as_object) {
        Some(encrypt) => {
            let recipient_key = match Jwk::from_object(input_object(encrypt, "key")) {
                Ok(key) => key,
                Err(e) => return Ok(Err(e)),
            };
            let recipient =
                Recipient::new(KeyMgmtAlg::from(input_str(encrypt, "alg")), &recipient_key);
            Some(
                Encryptor::new(ContentEncAlg::from(input_str(encrypt, "enc"))).recipient(recipient),
            )
        }
        None => None,
    };
    let alg = input_str(input, "alg");
    let mut opts = IssueOptions::new(SigningAlg::from(alg));
    match input.get("typ") {
        Some(Value::Null) => opts = opts.no_typ(),
        Some(typ) => opts = opts.typ(typ.as_str().expect("validated")),
        None => {}
    }
    let signed = match jwt::sign(&claims, &opts, &key) {
        Ok(signed) => signed,
        Err(e) => return Ok(Err(e)),
    };
    let (token, parts) = match &encryptor {
        Some(encryptor) => match jwt::encrypt_nested(&signed, encryptor) {
            Ok(token) => (token, 5),
            Err(e) => return Ok(Err(e)),
        },
        None => (signed, 3),
    };
    if token.split('.').count() != parts {
        return Err(format!(
            "the issued token is not {parts} compact parts: {token}"
        ));
    }
    if let Some(validate) = input.get("validate").and_then(Value::as_object) {
        check_jwt_issue_round_trip(&token, alg, claims_in, validate)?;
    }
    if matches!(expect, Expect::Ok(want) if want.contains("token")) {
        out.insert("token", token);
    }
    Ok(Ok(()))
}

/// Validates an issued token with the vector's `validate` (RFC 7519 §7.2):
/// it must validate, with the `alg` it was signed with and the Claims Set
/// it was issued with (compared as JSON values). Any failure, including a
/// `validate` the library refuses, fails the vector.
fn check_jwt_issue_round_trip(
    token: &str,
    alg: &str,
    claims: &Value,
    validate: &Object,
) -> Result<(), String> {
    let validation = jwt_validation(validate)
        .map_err(|e| format!("round trip: `validate` does not import ({})", e.code()))?;
    let policy = jwt_policy(
        &validation.clock,
        &validation.algs,
        validation.policy.as_ref(),
    )?
    .map_err(|e| format!("round trip: `validate/policy` is refused ({})", e.code()))?;
    let verified = jwt_verify(token, &validation, &policy).map_err(|e| {
        format!(
            "round trip: the issued token does not validate with `validate` ({})",
            e.code()
        )
    })?;
    if verified.alg.as_str() != alg {
        return Err(format!(
            "round trip: validated with alg {}, issued with {alg}",
            verified.alg.as_str()
        ));
    }
    let validated = claims_value(&verified)?;
    if validated != *claims {
        return Err(format!(
            "round trip: validated claims {} are not the issued {}",
            validated.to_json(),
            claims.to_json()
        ));
    }
    Ok(())
}

/// `jwks.select` (ADR 0054 §1–§4; the binding `jwks_select` of ADR 0030
/// §4 as amended by ADR 0054 §9). The steps run in the order
/// conformance/README.md fixes, and the first error is the outcome, which
/// is the ADR 0054 §4 precedence:
///
/// 1. import `jwks` with [`JwkSet::from_object`] (RFC 7517 §5; ADR 0041 §2
///    skips; an RSA private member imports, ADR 0067 §4);
/// 2. build the selector from [`JwkSelector::new`] with `kid`, then `alg`
///    (`KeyAlg::from`), then `key_use` (`KeyUse::from`), each through its
///    setter, which validates it (ADR 0054 §1.1);
/// 3. [`JwkSet::select`]: one match, `NoMatchingKey` or
///    `MultipleMatchingKeys` (ADR 0054 §4).
///
/// The selected key is its core serialization ([`Jwk::to_object`]).
fn run_jwks_select(input: &Object, out: &mut Object) -> Result<(), Error> {
    let set = JwkSet::from_object(input_object(input, "jwks"))?;
    let selector = input_object(input, "selector");
    let mut built = JwkSelector::new();
    if selector.get("kid").is_some() {
        built = built.kid(input_str(selector, "kid"));
    }
    if selector.get("alg").is_some() {
        built = built.alg(KeyAlg::from(input_str(selector, "alg")))?;
    }
    if selector.get("key_use").is_some() {
        built = built.key_use(KeyUse::from(input_str(selector, "key_use")))?;
    }
    let (_, key) = set.select(&built)?;
    out.insert("jwk", key.to_object());
    Ok(())
}

/// Runs the operation through the public API: the success outputs, or the
/// library's error.
fn execute(vector: &Vector) -> Result<Result<Object, Error>, String> {
    let input = &vector.input;
    let mut out = Object::new();
    match vector.operation.as_str() {
        "b64url.encode" => {
            out.insert(
                "b64u",
                b64url_encode(&hex_decode(input_str(input, "bytes_hex"))),
            );
        }
        "b64url.decode" => match b64url_decode(input_str(input, "b64u")) {
            Ok(bytes) => {
                out.insert("bytes_hex", hex_encode(&bytes));
            }
            Err(e) => return Ok(Err(e)),
        },
        "jwk.thumbprint" => {
            // RFC 7638 §3 over the imported key, with the hash named by
            // `hash` (ADR 0054 §8.2) or, when absent, the core default,
            // SHA-256 (RFC 9278 §5). The URI carries the IANA hash name
            // whatever spelling was given (RFC 9278 §3, §4).
            let key = match Jwk::from_object(input_object(input, "jwk")) {
                Ok(key) => key,
                Err(e) => return Ok(Err(e)),
            };
            let hash = match input.get("hash").map(|_| input_str(input, "hash")) {
                None => ThumbprintHash::default(),
                Some(name) => match ThumbprintHash::from_name(name) {
                    Ok(hash) => hash,
                    Err(e) => return Ok(Err(e)),
                },
            };
            out.insert("thumbprint", key.thumbprint(hash));
            out.insert("thumbprint_uri", key.thumbprint_uri(hash));
        }
        "jwks.select" => {
            if let Err(e) = run_jwks_select(input, &mut out) {
                return Ok(Err(e));
            }
        }
        "jws.sign" => {
            if let Err(e) = run_jws_sign(input, &vector.expect, &mut out)? {
                return Ok(Err(e));
            }
        }
        "jws.verify" => {
            if let Err(e) = run_jws_verify(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "jwe.encrypt" => {
            if let Err(e) = run_jwe_encrypt(input, &vector.expect, &mut out)? {
                return Ok(Err(e));
            }
        }
        "jwe.decrypt" => {
            if let Err(e) = run_jwe_decrypt(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "keys.import_pem" => {
            if let Err(e) = run_keys_import_pem(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "keys.export_pem" => {
            if let Err(e) = run_keys_export_pem(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "keys.import_der" => {
            if let Err(e) = run_keys_import_der(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "keys.export_der" => {
            if let Err(e) = run_keys_export_der(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "keys.generate_for" => {
            if let Err(e) = run_keys_generate_for(input, &vector.expect, &mut out)? {
                return Ok(Err(e));
            }
        }
        "keys.generate_oct" | "keys.generate_ec" | "keys.generate_okp" => {
            if let Err(e) = run_keys_generate(&vector.operation, input, &vector.expect, &mut out)? {
                return Ok(Err(e));
            }
        }
        "jwt.validate" => {
            if let Err(e) = run_jwt_validate(input, &mut out)? {
                return Ok(Err(e));
            }
        }
        "jwt.issue" => {
            if let Err(e) = run_jwt_issue(input, &vector.expect, &mut out)? {
                return Ok(Err(e));
            }
        }
        other => {
            return Err(format!(
                "operation `{other}` is not implemented by the Rust runner; a vector is never skipped"
            ));
        }
    }
    Ok(Ok(out))
}

/// Compares the outcome with the expectation: on success the outputs must
/// be exactly the expected members (an optional output, such as
/// `jwt.validate`'s `key_index`, can't be left out unnoticed), each equal as
/// a JSON value (RFC 8259: object member order ignored, numbers compared
/// as doubles, RFC 7493 §2.2).
fn compare(expect: &Expect, outcome: &Result<Object, Error>) -> Result<(), String> {
    match (expect, outcome) {
        (Expect::Ok(want), Ok(got)) => {
            for (name, value) in want {
                let got_value = got.get(name);
                if got_value != Some(value) {
                    return Err(format!(
                        "`{name}`: expected {}, got {}",
                        value.to_json(),
                        got_value.map_or("nothing".to_owned(), Value::to_json)
                    ));
                }
            }
            for (name, value) in got {
                if !want.contains(name) {
                    return Err(format!(
                        "`{name}`: expected nothing, got {}",
                        value.to_json()
                    ));
                }
            }
            Ok(())
        }
        (Expect::Ok(_), Err(e)) => Err(format!("expected success, got error {}", e.code())),
        (Expect::Err(code), Ok(got)) => Err(format!(
            "expected error {code}, but the operation succeeded with {}",
            got.to_json()
        )),
        (Expect::Err(code), Err(e)) if e.code() == code => Ok(()),
        (Expect::Err(code), Err(e)) => {
            Err(format!("expected error {code}, got error {}", e.code()))
        }
    }
}

/// A vector that did not fail.
#[derive(Debug)]
enum Passed {
    /// It ran and met its expectation.
    Ran {
        operation: String,
        /// Whether it expects a failure (`"ok": false`).
        negative: bool,
    },
    /// It needs `missing`, which this build does not enable, or must run
    /// without `present`, which it enables (ADR 0056); it was validated but
    /// not run, and never counts as passing.
    Skipped {
        missing: Vec<&'static str>,
        present: Vec<&'static str>,
    },
}

impl Passed {
    /// A skip's results-file `reason` (ADR 0034 §3, ADR 0056 §2):
    /// `feature:`, the missing names in `features` order, then each
    /// enabled `features_absent` name as `!<name>` in its order.
    fn skip_reason(missing: &[&str], present: &[&str]) -> String {
        let names: Vec<String> = missing
            .iter()
            .map(|f| (*f).to_owned())
            .chain(present.iter().map(|f| format!("!{f}")))
            .collect();
        format!("feature:{}", names.join(","))
    }
}

/// Parses a vector file. Vector files are trusted test data, so they get a
/// 4 MiB input limit (conformance/README.md), room for a JWS just over the
/// library's 1 MiB default (ADR 0026 §7); every other JSON limit, and the
/// library under test, keep their defaults.
fn parse_vector_file(bytes: &[u8]) -> polyjose::Result<Value> {
    let mut limits = json::Limits::DEFAULT;
    limits.max_input_len = 4 * 1024 * 1024;
    json::parse_with_limits(bytes, &limits)
}

/// Checks one vector file: parse, validate, run, compare. Returns what
/// passed (or was skipped for a missing feature), or a failure message
/// naming the file and the `source`.
fn check_vector(name: &str, bytes: &[u8]) -> Result<Passed, String> {
    check_vector_with(name, bytes, &enabled_features())
}

/// [`check_vector`] with `enabled` as the build's features.
fn check_vector_with(name: &str, bytes: &[u8], enabled: &[&str]) -> Result<Passed, String> {
    check_vector_traced(name, bytes, enabled, &mut Trace::default())
}

/// What a results file records of one vector besides its status
/// (ADR 0034 §2). Filled in as [`check_vector_traced`] goes; recording
/// never changes how the vector is evaluated.
#[derive(Debug, Default)]
struct Trace {
    /// The vector's `source`, when usable (ADR 0034 §1: reported
    /// alongside the id).
    source: Option<String>,
    /// The vector's `operation`, when the file parses and names one.
    op: Option<String>,
    /// The operation's outcome, when it returned one: success, or the
    /// library's error code.
    actual: Option<Result<(), &'static str>>,
}

/// [`check_vector_with`], recording into `trace` the vector's `source`,
/// `operation` and, once the operation has run, its outcome.
fn check_vector_traced(
    name: &str,
    bytes: &[u8],
    enabled: &[&str],
    trace: &mut Trace,
) -> Result<Passed, String> {
    let value = parse_vector_file(bytes)
        .map_err(|e| format!("{name}: not a valid JSON text ({e}); see conformance/schema.json"))?;
    trace.source = usable_source(&value);
    trace.op = value
        .get("operation")
        .and_then(Value::as_str)
        .filter(|op| is_text(op))
        .map(str::to_owned);
    let source = usable_source(&value).unwrap_or_else(|| "<missing>".to_owned());
    let fail = |problem: String| format!("{name} (source: {source}): {problem}");
    let vector = validate(&value).map_err(fail)?;
    let missing: Vec<&'static str> = vector
        .features
        .iter()
        .copied()
        .filter(|f| !enabled.contains(f))
        .collect();
    let present: Vec<&'static str> = vector
        .features_absent
        .iter()
        .copied()
        .filter(|f| enabled.contains(f))
        .collect();
    if !missing.is_empty() || !present.is_empty() {
        return Ok(Passed::Skipped { missing, present });
    }
    let outcome = catch_unwind(AssertUnwindSafe(|| execute(&vector)))
        .map_err(|_| fail("panicked while running".to_owned()))?
        .map_err(fail)?;
    trace.actual = Some(outcome.as_ref().map(|_| ()).map_err(Error::code));
    compare(&vector.expect, &outcome).map_err(fail)?;
    Ok(Passed::Ran {
        negative: matches!(vector.expect, Expect::Err(_)),
        operation: vector.operation,
    })
}

/// Every check over a vectors directory.
#[derive(Debug, Default)]
struct Report {
    files: usize,
    /// Passing vectors per operation.
    passed: BTreeMap<String, usize>,
    /// Passing failure (`"ok": false`) vectors per operation.
    passed_negative: BTreeMap<String, usize>,
    /// `SKIPPED (needs feature ...)` lines, one per skipped vector file.
    skipped: Vec<String>,
    failures: Vec<String>,
    /// One results-file entry per vector file, in file order (ADR 0034
    /// §2; see [`result_entry`]).
    results: Vec<Object>,
    /// One [`digest_line`] per vector file whose bytes were read, in file
    /// order (ADR 0060 §2); [`Report::vectors_digest`] sorts them.
    digest_lines: Vec<Vec<u8>>,
    /// Whether every vector file was found: false when the walk itself
    /// failed (an unreadable directory, a symbolic link) or found nothing,
    /// so the results would not cover every vector.
    complete: bool,
}

impl Report {
    /// `vectors_digest` (ADR 0060 §3): the lowercase hex SHA-256 of the
    /// byte-sorted [`digest_line`]s. `None` when no vector file was read: an
    /// empty corpus is invalid, so such a run writes no results file.
    fn vectors_digest(&self) -> Option<String> {
        if self.digest_lines.is_empty() {
            return None;
        }
        let mut hasher = Sha256::new();
        for line in sorted_digest_lines(&self.digest_lines) {
            hasher.update(&line);
        }
        Some(hex_encode(&hasher.finalize()))
    }
}

/// One vector file's line of the vector-set digest (ADR 0060 §2): its id
/// (exactly the results entry's), a TAB, the lowercase hex SHA-256 of the
/// raw bytes the runner parsed (no line-ending, BOM or encoding change),
/// and an LF, as UTF-8.
fn digest_line(id: &str, bytes: &[u8]) -> Vec<u8> {
    format!("{id}\t{}\n", hex_encode(&Sha256::digest(bytes))).into_bytes()
}

/// `lines` in ascending order of their UTF-8 bytes (ADR 0060 §2), not of
/// paths by component: `jws-x/…` (0x2D) sorts before `jws/…` (0x2F).
fn sorted_digest_lines(lines: &[Vec<u8>]) -> Vec<Vec<u8>> {
    let mut sorted = lines.to_vec();
    sorted.sort();
    sorted
}

/// A vector's id (ADR 0034 §1 as amended by ADR 0045 §4): its path under
/// the vectors directory, `/`-separated on every platform, then `#0`, as
/// every file holds one vector.
fn vector_id(relative: &Path) -> String {
    format!("{}#0", slash_path(relative))
}

/// A path under the vectors directory as a vector name: its components
/// joined with `/` on every platform (`Path::display` gives `a\b.json` on
/// Windows), so names in reports and failures are the same everywhere.
fn slash_path(relative: &Path) -> String {
    let parts: Vec<String> = relative
        .components()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .collect();
    parts.join("/")
}

/// One results-file entry (`conformance/schema/results.schema.json`):
/// `id`, then `source` and `op` when known, `status`, `actual` for a vector
/// that ran, and `reason` for a skip (`feature:` and the missing feature
/// names, in the vector's order, ADR 0034 §3) or a failure (its message).
fn result_entry(id: String, trace: Trace, result: &Result<Passed, String>) -> Object {
    let mut entry = Object::new();
    entry.insert("id", id);
    if let Some(source) = trace.source {
        entry.insert("source", source);
    }
    if let Some(op) = trace.op {
        entry.insert("op", op);
    }
    let status = match result {
        Ok(Passed::Ran { .. }) => "pass",
        Ok(Passed::Skipped { .. }) => "skipped",
        Err(_) => "fail",
    };
    entry.insert("status", status);
    // A skipped vector never ran, so it has no outcome.
    if let Some(actual) = trace.actual {
        let mut outcome = Object::new();
        outcome.insert("ok", actual.is_ok());
        if let Err(code) = actual {
            outcome.insert("error", code);
        }
        entry.insert("actual", outcome);
    }
    match result {
        Ok(Passed::Ran { .. }) => {}
        Ok(Passed::Skipped { missing, present }) => {
            entry.insert("reason", Passed::skip_reason(missing, present));
        }
        Err(message) => {
            entry.insert("reason", message.as_str());
        }
    }
    entry
}

/// Every `*.json` file under `dir`, recursively, sorted. A symbolic link is
/// a failure: vectors must be regular files every platform reads the same.
fn collect(dir: &Path, files: &mut Vec<PathBuf>, failures: &mut Vec<String>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) => {
            failures.push(format!("{}: cannot read directory: {e}", dir.display()));
            return;
        }
    };
    for entry in entries {
        let (path, file_type) = match entry.and_then(|e| Ok((e.path(), e.file_type()?))) {
            Ok(pair) => pair,
            Err(e) => {
                failures.push(format!("{}: cannot read entry: {e}", dir.display()));
                continue;
            }
        };
        if file_type.is_symlink() {
            failures.push(format!(
                "{}: symbolic links are not allowed",
                path.display()
            ));
        } else if file_type.is_dir() {
            collect(&path, files, failures);
        } else if path.extension().is_some_and(|e| e == "json") {
            files.push(path);
        }
    }
}

fn run_dir(dir: &Path) -> Report {
    run_dir_with(dir, &enabled_features())
}

/// [`run_dir`] with `enabled` as the build's features.
fn run_dir_with(dir: &Path, enabled: &[&str]) -> Report {
    let mut report = Report::default();
    let mut files = Vec::new();
    collect(dir, &mut files, &mut report.failures);
    files.sort();
    report.files = files.len();
    if files.is_empty() {
        report
            .failures
            .push(format!("{}: no vector files (*.json) found", dir.display()));
    }
    report.complete = report.failures.is_empty();
    for path in files {
        let relative = path.strip_prefix(dir).unwrap_or(&path);
        let name = slash_path(relative);
        let id = vector_id(relative);
        let mut trace = Trace::default();
        // A file that cannot be read gets a `fail` and no digest line
        // (ADR 0060 §2); one that is read is hashed from the very bytes
        // parsed, whatever its result.
        let result = std::fs::read(&path)
            .map_err(|e| format!("{name}: cannot read: {e}"))
            .and_then(|bytes| {
                report.digest_lines.push(digest_line(&id, &bytes));
                check_vector_traced(&name, &bytes, enabled, &mut trace)
            });
        report.results.push(result_entry(id, trace, &result));
        match result {
            Ok(Passed::Ran {
                operation,
                negative,
            }) => {
                if negative {
                    *report.passed_negative.entry(operation.clone()).or_default() += 1;
                }
                *report.passed.entry(operation).or_default() += 1;
            }
            Ok(Passed::Skipped { missing, present }) => {
                let cargo = |names: &[&str]| {
                    names
                        .iter()
                        .map(|f| format!("`{}`", cargo_feature(f)))
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                let mut why = Vec::new();
                if !missing.is_empty() {
                    why.push(format!("needs feature {}", cargo(&missing)));
                }
                if !present.is_empty() {
                    why.push(format!("needs feature {} off", cargo(&present)));
                }
                report
                    .skipped
                    .push(format!("{name}: SKIPPED ({})", why.join("; ")));
            }
            Err(msg) => report.failures.push(msg),
        }
    }
    report
}

fn conformance_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../conformance")
}

/// Where every runner writes its results file (ADR 0034 §2):
/// `target/conformance/` at the repository root, whatever `CARGO_TARGET_DIR`
/// says, so `scripts/conformance-parity.sh` finds every runner's file in
/// one place.
fn results_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/conformance")
}

/// This build's results file name. Only the default-features build is the
/// reference run, `rust-core.json` (ADR 0034 §4); a build with features
/// writes `rust-core-<features>.json` (`rust-core-fixed-rng.json`,
/// `rust-core-deflate-fixed-rng.json`, ...), which the parity check
/// ignores.
fn results_file_name(enabled: &[&str]) -> String {
    if enabled.is_empty() {
        format!("{RUST_CORE}.json")
    } else {
        format!("{RUST_CORE}-{}.json", enabled.join("-"))
    }
}

/// The results file text (`conformance/schema/results.schema.json`): the
/// runner, the crate version, the `vectors_digest` of the files read
/// (ADR 0060 §1), the enabled `features`, `Error::CODES` (ADR 0034 §8) and
/// the results, one per line so a file can be searched by id.
fn results_document(enabled: &[&str], digest: &str, results: &[Object]) -> String {
    let strings = |items: &[&str]| -> Value {
        Value::from(items.iter().map(|s| Value::from(*s)).collect::<Vec<_>>())
    };
    let header: [(&str, Value); 5] = [
        ("runner", Value::from(RUST_CORE)),
        ("polyjose", Value::from(env!("CARGO_PKG_VERSION"))),
        ("vectors_digest", Value::from(digest)),
        ("features", strings(enabled)),
        ("error_codes", strings(Error::CODES)),
    ];
    let mut text = String::from("{\n");
    for (name, value) in &header {
        text.push_str(&format!(
            "  {}: {},\n",
            Value::from(*name).to_json(),
            value.to_json()
        ));
    }
    text.push_str("  \"results\": [");
    for (i, result) in results.iter().enumerate() {
        text.push_str(if i == 0 { "\n    " } else { ",\n    " });
        text.push_str(&result.to_json());
    }
    text.push_str(if results.is_empty() {
        "]\n}\n"
    } else {
        "\n  ]\n}\n"
    });
    text
}

/// Writes `report`'s results to `dir/file`, replacing any earlier file
/// atomically (a temporary file, then a rename), and returns its path. A
/// report whose walk was incomplete, or that read no vector file (no
/// digest, ADR 0060 §3), is not written: any earlier file is removed
/// instead, so a run that could not see every vector leaves no stale or
/// partial reference behind (the parity check then fails on the missing
/// file).
fn write_results(
    dir: &Path,
    file: &str,
    enabled: &[&str],
    report: &Report,
) -> Result<Option<PathBuf>, String> {
    let path = dir.join(file);
    let digest = match report.vectors_digest() {
        Some(digest) if report.complete => digest,
        _ => {
            return match std::fs::remove_file(&path) {
                Ok(()) => Ok(None),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
                Err(e) => Err(format!("{}: cannot remove: {e}", path.display())),
            };
        }
    };
    std::fs::create_dir_all(dir).map_err(|e| format!("{}: cannot create: {e}", dir.display()))?;
    let temporary = dir.join(format!(".{file}.{}.tmp", std::process::id()));
    std::fs::write(
        &temporary,
        results_document(enabled, &digest, &report.results),
    )
    .map_err(|e| format!("{}: cannot write: {e}", temporary.display()))?;
    std::fs::rename(&temporary, &path)
        .map_err(|e| format!("{}: cannot write: {e}", path.display()))?;
    Ok(Some(path))
}

/// The shared vectors: every file must be schema-valid and pass. The run
/// also writes this build's results file (ADR 0034 §2, §4; see
/// [`results_file_name`]), checked against `results.schema.json`, before
/// any assertion, so a failing run is recorded too.
#[test]
fn conformance_vectors() {
    let report = run_dir(&conformance_dir().join("vectors"));
    let enabled = enabled_features();
    let written = write_results(
        &results_dir(),
        &results_file_name(&enabled),
        &enabled,
        &report,
    )
    .unwrap_or_else(|e| panic!("results file: {e}"));
    if let Some(path) = written {
        let text = std::fs::read(&path).unwrap();
        if let Err(e) = check_results_text(&text) {
            panic!("{}: not valid per results.schema.json: {e}", path.display());
        }
    }
    assert!(
        report.failures.is_empty(),
        "{} of {} conformance vector file(s) failed:\n  {}",
        report.failures.len(),
        report.files,
        report.failures.join("\n  ")
    );
    let passed: usize = report.passed.values().sum();
    eprintln!(
        "conformance: {passed} of {} vectors passed {:?}; {} skipped",
        report.files,
        report.passed,
        report.skipped.len()
    );
    for line in &report.skipped {
        eprintln!("  {line}");
    }
    assert_eq!(
        passed + report.skipped.len(),
        report.files,
        "every vector file either passes or is skipped for a named feature"
    );
}

/// Every implemented operation has vectors, and every operation that can
/// fail has both success and failure vectors.
#[test]
fn every_implemented_operation_has_vectors() {
    let report = run_dir(&conformance_dir().join("vectors"));
    for spec in SPECS {
        let all = report.passed.get(spec.name).copied().unwrap_or(0);
        let negative = report.passed_negative.get(spec.name).copied().unwrap_or(0);
        assert!(all > negative, "{}: no passing success vectors", spec.name);
        assert!(
            !spec.can_fail || negative > 0,
            "{}: no passing failure vectors",
            spec.name
        );
    }
}

// ---------------------------------------------------------------------------
// schema.json and this runner must say the same thing.
// ---------------------------------------------------------------------------

fn schema() -> Value {
    let bytes = std::fs::read(conformance_dir().join("schema.json")).unwrap();
    json::parse(&bytes).expect("schema.json is I-JSON")
}

fn parse(json: &str) -> Value {
    json::parse(json.as_bytes()).unwrap()
}

fn at<'a>(value: &'a Value, path: &[&str]) -> &'a Value {
    path.iter().fold(value, |v, name| {
        v.get(name)
            .unwrap_or_else(|| panic!("schema.json: no member {path:?}"))
    })
}

fn strings(value: &Value) -> Vec<&str> {
    value
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect()
}

fn member_names(value: &Value) -> Vec<&str> {
    value.as_object().unwrap().iter().map(|(n, _)| n).collect()
}

/// The value without its `description` annotation.
fn annotated(value: &Value) -> Value {
    let mut object = value.as_object().unwrap().clone();
    object.remove("description");
    Value::from(object)
}

/// How `kind` is spelled in the schema.
fn schema_kind(kind: Kind) -> Value {
    if let Some(def) = kind.def() {
        return parse(&format!(r##"{{"$ref":"#/$defs/{def}"}}"##));
    }
    match kind {
        Kind::Hex
        | Kind::Base64url
        | Kind::Count
        | Kind::Jws
        | Kind::AlgList
        | Kind::Jwe
        | Kind::Nested(_)
        | Kind::Seconds => {
            unreachable!("a $ref kind")
        }
        Kind::StringList => parse(r#"{"type":"array","items":{"type":"string"}}"#),
        Kind::StringOrList => parse(r#"{"type":["string","array"],"items":{"type":"string"}}"#),
        Kind::StringOrNull => parse(r#"{"type":["string","null"]}"#),
        Kind::Bool => parse(r#"{"type":"boolean"}"#),
        Kind::List(shape) => parse(&format!(
            r##"{{"type":"array","minItems":1,"items":{{"$ref":"#/$defs/{}"}}}}"##,
            shape.def
        )),
        Kind::String => parse(r#"{"type":"string"}"#),
        Kind::Object => parse(r#"{"type":"object"}"#),
        Kind::Enum(values) => {
            let mut object = Object::new();
            object.insert(
                "enum",
                values.iter().map(|v| Value::from(*v)).collect::<Vec<_>>(),
            );
            Value::from(object)
        }
    }
}

/// How a [`Rule`] is spelled in the schema's `allOf`.
fn schema_rule(rule: &Rule) -> Value {
    match rule {
        Rule::Signers(rule) => schema_signer_rule(rule),
        Rule::ExactlyOne(names) => {
            let alternatives: Vec<String> = names
                .iter()
                .map(|n| format!(r#"{{"required":["{n}"]}}"#))
                .collect();
            parse(&format!(r#"{{"oneOf":[{}]}}"#, alternatives.join(",")))
        }
        Rule::OnlyWhen {
            member,
            value,
            dependent,
        } => parse(&format!(
            r#"{{"if":{{"properties":{{"{member}":{{"const":"{value}"}}}}}},"then":{{"required":["{dependent}"]}},"else":{{"properties":{{"{dependent}":false}}}}}}"#
        )),
    }
}

/// How a [`SignerRule`] is spelled in the schema's `allOf`.
fn schema_signer_rule(rule: &SignerRule) -> Value {
    let mut signers = format!(r#""maxItems":{}"#, rule.max_signers);
    if !rule.requires.is_empty() || !rule.forbids.is_empty() {
        let required: Vec<Value> = rule.requires.iter().map(|n| Value::from(*n)).collect();
        let forbidden: Vec<String> = rule
            .forbids
            .iter()
            .map(|n| format!(r#""{n}":false"#))
            .collect();
        signers.push_str(&format!(
            r#","items":{{"required":{},"properties":{{{}}}}}"#,
            Value::from(required).to_json(),
            forbidden.join(",")
        ));
    }
    parse(&format!(
        r#"{{"if":{{"properties":{{"serialization":{{"const":"{}"}}}}}},"then":{{"properties":{{"signers":{{{signers}}}}}}}}}"#,
        rule.serialization
    ))
}

/// `$ref` target name of `{"$ref": "#/$defs/<name>"}`.
fn def_ref<'a>(value: &'a Value, used: &mut Vec<String>) -> &'a str {
    let target = value.get("$ref").and_then(Value::as_str).unwrap();
    let name = target.strip_prefix("#/$defs/").unwrap();
    used.push(name.to_owned());
    name
}

/// A `$defs` object definition: exactly the keywords checked here, closed,
/// and its members (after `ok: {"const": true}` when `ok` is set) are
/// `shape`'s, in order, with the same kinds and the same `required` list.
fn check_def(defs: &Value, shape: &Shape, ok: bool, used: &mut Vec<String>) {
    let name = shape.def;
    used.push(name.to_owned());
    let def = at(defs, &[name]);
    let mut keywords = vec!["type", "required", "additionalProperties", "properties"];
    if !shape.rules.is_empty() {
        keywords.push("allOf");
        let rules: Vec<Value> = shape.rules.iter().map(schema_rule).collect();
        assert_eq!(*at(def, &["allOf"]), Value::from(rules), "{name}: allOf");
    }
    assert_eq!(member_names(&annotated(def)), keywords, "{name}: keywords");
    let mut names: Vec<&str> = shape.members.iter().map(|m| m.name).collect();
    let mut required: Vec<&str> = shape
        .members
        .iter()
        .filter(|m| m.required)
        .map(|m| m.name)
        .collect();
    if ok {
        names.insert(0, "ok");
        required.insert(0, "ok");
        assert_eq!(
            *at(def, &["properties", "ok"]),
            parse(r#"{"const":true}"#),
            "{name}"
        );
    }
    assert_eq!(at(def, &["type"]).as_str(), Some("object"), "{name}");
    assert_eq!(
        at(def, &["additionalProperties"]).as_bool(),
        Some(false),
        "{name}"
    );
    assert_eq!(strings(at(def, &["required"])), required, "{name}");
    assert_eq!(member_names(at(def, &["properties"])), names, "{name}");
    for member in shape.members {
        used.extend(member.kind.def().map(str::to_owned));
        if let Kind::Nested(inner) | Kind::List(inner) = member.kind {
            check_def(defs, inner, false, used);
        }
        let property = at(def, &["properties", member.name]);
        assert_eq!(
            annotated(property),
            schema_kind(member.kind),
            "{name}/{}",
            member.name
        );
    }
}

/// Drift guard: the hand-written validator implements exactly schema.json.
#[test]
fn schema_and_runner_agree() {
    let schema = schema();
    let defs = at(&schema, &["$defs"]);
    let mut used = Vec::new();

    assert_eq!(
        at(&schema, &["$schema"]).as_str(),
        Some("https://json-schema.org/draft/2020-12/schema")
    );
    // Root keywords: annotations plus exactly the constraints checked below.
    assert_eq!(
        member_names(&schema),
        [
            "$schema",
            "title",
            "description",
            "type",
            "required",
            "additionalProperties",
            "properties",
            "allOf",
            "$defs"
        ]
    );
    assert_eq!(at(&schema, &["type"]).as_str(), Some("object"));
    assert_eq!(
        at(&schema, &["additionalProperties"]).as_bool(),
        Some(false)
    );
    assert_eq!(strings(at(&schema, &["required"])), TOP_LEVEL);
    let mut properties = TOP_LEVEL.to_vec();
    properties.extend(TOP_LEVEL_OPTIONAL);
    assert_eq!(member_names(at(&schema, &["properties"])), properties);
    let mut features = Object::new();
    features.insert(
        "enum",
        feature_names()
            .into_iter()
            .map(Value::from)
            .collect::<Vec<_>>(),
    );
    let mut expected = parse(r#"{"type":"array","uniqueItems":true}"#)
        .into_object()
        .unwrap();
    expected.insert("items", features);
    assert_eq!(
        annotated(at(&schema, &["properties", "features"])),
        Value::from(expected.clone()),
        "features"
    );
    // ADR 0056: the same names, at least one.
    let mut absent = parse(r#"{"type":"array","minItems":1,"uniqueItems":true}"#)
        .into_object()
        .unwrap();
    absent.insert("items", expected.get("items").unwrap().clone());
    assert_eq!(
        annotated(at(&schema, &["properties", "features_absent"])),
        Value::from(absent),
        "features_absent"
    );
    for name in ["source", "description"] {
        let property = annotated(at(&schema, &["properties", name]));
        assert_eq!(property, parse(r##"{"$ref":"#/$defs/text"}"##));
        def_ref(&property, &mut used);
    }
    assert_eq!(
        *at(defs, &["text"]),
        parse(&format!(
            r#"{{"type":"string","minLength":1,"pattern":{}}}"#,
            Value::from(TEXT_PATTERN).to_json()
        ))
    );
    assert_eq!(
        member_names(at(&schema, &["properties", "operation"])),
        ["enum"]
    );
    assert_eq!(
        strings(at(&schema, &["properties", "operation", "enum"])),
        OPERATIONS
    );
    assert_eq!(
        *at(&schema, &["properties", "input"]),
        parse(r#"{"type":"object"}"#)
    );
    assert_eq!(
        *at(&schema, &["properties", "expect"]),
        parse(r#"{"type":"object","required":["ok"],"properties":{"ok":{"type":"boolean"}}}"#)
    );

    for (name, pattern) in [("hex", HEX_PATTERN), ("base64url", BASE64URL_PATTERN)] {
        assert_eq!(
            annotated(at(defs, &[name])),
            parse(&format!(
                r#"{{"type":"string","pattern":{}}}"#,
                Value::from(pattern).to_json()
            )),
            "{name}"
        );
    }
    assert_eq!(
        member_names(&annotated(at(defs, &["error_code"]))),
        ["enum"]
    );
    assert_eq!(strings(at(defs, &["error_code", "enum"])), Error::CODES);
    assert_eq!(
        annotated(at(defs, &["failure"])),
        parse(
            r##"{"type":"object","required":["ok","error"],"additionalProperties":false,
                "properties":{"ok":{"const":false},"error":{"$ref":"#/$defs/error_code"}}}"##
        )
    );
    used.extend(["error_code"].map(str::to_owned));
    assert_eq!(
        annotated(at(defs, &["count"])),
        parse(&format!(
            r#"{{"type":"integer","minimum":0,"maximum":{COUNT_MAX}}}"#
        ))
    );
    assert_eq!(
        annotated(at(defs, &["seconds"])),
        parse(&format!(
            r#"{{"type":"integer","minimum":-{SECONDS_MAX},"maximum":{SECONDS_MAX}}}"#
        ))
    );
    assert_eq!(
        annotated(at(defs, &["jws"])),
        parse(r#"{"type":["string","object"]}"#)
    );
    assert_eq!(
        annotated(at(defs, &["alg_list"])),
        parse(r#"{"type":"array","items":{"type":"string"}}"#)
    );
    assert_eq!(
        annotated(at(defs, &["jwe"])),
        parse(r#"{"type":["string","object"]}"#)
    );

    let rules = at(&schema, &["allOf"]).as_array().unwrap();
    assert_eq!(
        rules.len(),
        SPECS.len(),
        "one if/then rule per implemented operation"
    );
    for (rule, spec) in rules.iter().zip(SPECS) {
        assert_eq!(member_names(rule), ["if", "then"]);
        assert_eq!(
            *at(rule, &["if"]),
            parse(&format!(
                r#"{{"required":["operation"],"properties":{{"operation":{{"const":"{}"}}}}}}"#,
                spec.name
            ))
        );
        let then = at(rule, &["then"]);
        assert_eq!(member_names(then), ["properties"], "{}", spec.name);
        assert_eq!(member_names(at(then, &["properties"])), ["input", "expect"]);
        let input = def_ref(at(then, &["properties", "input"]), &mut used);
        assert_eq!(input, spec.input.def, "{}", spec.name);
        check_def(defs, spec.input, false, &mut used);

        // The success forms, then `failure` if the operation can fail: one
        // `$ref`, or a `oneOf` of them in that order.
        let mut alternatives: Vec<&str> = spec.ok.iter().map(|s| s.def).collect();
        if spec.can_fail {
            alternatives.push("failure");
        }
        let expect = at(then, &["properties", "expect"]);
        let refs: Vec<&str> = if alternatives.len() == 1 {
            assert_eq!(member_names(expect), ["$ref"], "{}", spec.name);
            vec![def_ref(expect, &mut used)]
        } else {
            assert_eq!(member_names(expect), ["oneOf"], "{}", spec.name);
            at(expect, &["oneOf"])
                .as_array()
                .unwrap()
                .iter()
                .map(|alternative| def_ref(alternative, &mut used))
                .collect()
        };
        assert_eq!(refs, alternatives, "{}", spec.name);
        for shape in spec.ok {
            check_def(defs, shape, true, &mut used);
        }
    }

    // No stale definitions.
    let mut defined: Vec<&str> = member_names(defs);
    defined.sort_unstable();
    used.sort();
    used.dedup();
    assert_eq!(defined, used, "every $defs entry is used");
}

/// The hand-written checks implement the schema's patterns.
#[test]
fn hand_written_checks_match_the_patterns() {
    // ^([0-9a-f]{2})*$
    for (s, ok) in [
        ("", true),
        ("00", true),
        ("0aff", true),
        ("0", false),
        ("0A", false),
        ("0g", false),
        ("00 ", false),
    ] {
        assert_eq!(is_hex(s), ok, "{s:?}");
    }
    // ^[A-Za-z0-9_-]*$
    for (s, ok) in [
        ("", true),
        ("AZaz09-_", true),
        ("Zg==", false),
        ("+/", false),
        ("a b", false),
        ("é", false),
    ] {
        assert_eq!(is_base64url_alphabet(s), ok, "{s:?}");
    }
    // minLength 1 and \S
    for (s, ok) in [
        ("", false),
        (" ", false),
        ("\t\r\n", false),
        ("x", true),
        (" RFC 4648 ", true),
    ] {
        assert_eq!(is_text(s), ok, "{s:?}");
    }
    // {"type": "integer", "minimum": 0, "maximum": 4294967295}
    for (json, ok) in [
        ("0", true),
        ("16", true),
        ("4294967295", true),
        ("1.0", true), // JSON Schema: an integer value is an integer
        ("4294967296", false),
        ("-1", false),
        ("1.5", false),
        ("\"1\"", false),
        ("null", false),
    ] {
        assert_eq!(is_count(&parse(json)), ok, "{json}");
    }
    // {"type": "integer", "minimum": -9007199254740991,
    //  "maximum": 9007199254740991}
    for (json, ok) in [
        ("0", true),
        ("-1", true),
        ("1300819380", true),
        ("9007199254740991", true),
        ("-9007199254740991", true),
        ("1.0", true),
        ("9007199254740992", false),
        ("-9007199254740992", false),
        ("1.5", false),
        ("\"1\"", false),
        ("null", false),
    ] {
        assert_eq!(is_seconds(&parse(json)), ok, "{json}");
    }
}

// ---------------------------------------------------------------------------
// Tests of the runner itself (criteria 1-3). Fixtures live in memory or in a
// temporary directory, never under conformance/vectors/.
// ---------------------------------------------------------------------------

const SOURCE: &str = "runner self-test 7f3a";

fn vector(operation: &str, input: &str, expect: &str) -> String {
    format!(
        r#"{{"source":"{SOURCE}","description":"self-test","operation":"{operation}","input":{input},"expect":{expect}}}"#
    )
}

fn fails_naming_source(name: &str, json: &str, needle: &str) {
    match check_vector(name, json.as_bytes()) {
        Ok(passed) => panic!("{name}: expected a failure, but it passed: {passed:?}: {json}"),
        Err(msg) => {
            assert!(msg.contains(name), "file name missing from {msg:?}");
            assert!(msg.contains(SOURCE), "source missing from {msg:?}");
            assert!(msg.contains(needle), "{needle:?} missing from {msg:?}");
        }
    }
}

#[test]
fn valid_vectors_pass() {
    let cases = [
        vector(
            "b64url.encode",
            r#"{"bytes_hex":"666f6f"}"#,
            r#"{"ok":true,"b64u":"Zm9v"}"#,
        ),
        vector(
            "b64url.decode",
            r#"{"b64u":"Zm9v"}"#,
            r#"{"ok":true,"bytes_hex":"666f6f"}"#,
        ),
        vector(
            "b64url.decode",
            r#"{"b64u":"Zg=="}"#,
            r#"{"ok":false,"error":"InvalidBase64"}"#,
        ),
        vector(
            "jwk.thumbprint",
            r#"{"hash":"sha-256","jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}}"#,
            r#"{"ok":true,"thumbprint":"kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k","thumbprint_uri":"urn:ietf:params:oauth:jwk-thumbprint:sha-256:kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"}"#,
        ),
        vector(
            "jwk.thumbprint",
            r#"{"hash":"sha-256","jwk":{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg=="}}"#,
            r#"{"ok":false,"error":"InvalidBase64"}"#,
        ),
        // ADR 0054 §8.2: `hash` is optional (the core default, SHA-256,
        // RFC 9278 §5), any of the nine names, and the URI always carries
        // the IANA name (RFC 9278 §4).
        vector(
            "jwk.thumbprint",
            r#"{"jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}}"#,
            r#"{"ok":true,"thumbprint":"kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k","thumbprint_uri":"urn:ietf:params:oauth:jwk-thumbprint:sha-256:kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"}"#,
        ),
        vector(
            "jwk.thumbprint",
            r#"{"hash":"sha384","jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}}"#,
            r#"{"ok":true,"thumbprint":"ePy6LSb6I7JWK2uWQyYJQ4DBrwGE4QoxPl6INUviCtqplTLCwzo6fD9Eaw69Wvtt","thumbprint_uri":"urn:ietf:params:oauth:jwk-thumbprint:sha-384:ePy6LSb6I7JWK2uWQyYJQ4DBrwGE4QoxPl6INUviCtqplTLCwzo6fD9Eaw69Wvtt"}"#,
        ),
        vector(
            "jwk.thumbprint",
            r#"{"hash":"SHA-512","jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}}"#,
            r#"{"ok":true,"thumbprint":"SfSqAgfmPYvpuNzfHCiQXi6Mr51GG78hHopngoabsV9xvLR0hcUfVCoJLfyzi08Dbnds6kmcAt23CpNV-8qLTg","thumbprint_uri":"urn:ietf:params:oauth:jwk-thumbprint:sha-512:SfSqAgfmPYvpuNzfHCiQXi6Mr51GG78hHopngoabsV9xvLR0hcUfVCoJLfyzi08Dbnds6kmcAt23CpNV-8qLTg"}"#,
        ),
        // ADR 0022: SHA-1 is a vector outcome now, not a schema error.
        vector(
            "jwk.thumbprint",
            r#"{"hash":"sha-1","jwk":{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"}}"#,
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
        ),
        // ADR 0054 §1.3: the empty selector on a one-key set returns that
        // key, compared as a JSON value (member order ignored).
        vector(
            "jwks.select",
            r#"{"jwks":{"keys":[{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]},"selector":{}}"#,
            r#"{"ok":true,"jwk":{"x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo","crv":"Ed25519","kty":"OKP"}}"#,
        ),
        // ADR 0054 §4: an empty set has no match.
        vector(
            "jwks.select",
            r#"{"jwks":{"keys":[]},"selector":{"kid":"a"}}"#,
            r#"{"ok":false,"error":"NoMatchingKey"}"#,
        ),
        // RFC 8410 §10.1; member order of the expected JWK does not matter.
        vector(
            "keys.import_pem",
            &format!(r#"{{"pem":{}}}"#, Value::from(RFC8410_10_1_PEM).to_json()),
            r#"{"ok":true,"jwk":{"x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE","crv":"Ed25519","kty":"OKP"}}"#,
        ),
        vector(
            "keys.import_pem",
            r#"{"pem":"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"}"#,
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
        ),
        vector(
            "keys.export_pem",
            r#"{"format":"spki","jwk":{"kty":"OKP","crv":"Ed25519","x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE"}}"#,
            &format!(
                r#"{{"ok":true,"pem":{}}}"#,
                Value::from(RFC8410_10_1_PEM).to_json()
            ),
        ),
        vector(
            "keys.export_pem",
            r#"{"format":"pkcs8","jwk":{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"}}"#,
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
        ),
        vector(
            "keys.import_der",
            &format!(r#"{{"format":"spki","der_b64u":"{RFC8410_10_1_DER}"}}"#),
            r#"{"ok":true,"jwk":{"x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE","crv":"Ed25519","kty":"OKP"}}"#,
        ),
        // RFC 5958 §2: an SPKI is not a OneAsymmetricKey.
        vector(
            "keys.import_der",
            &format!(r#"{{"format":"pkcs8","der_b64u":"{RFC8410_10_1_DER}"}}"#),
            r#"{"ok":false,"error":"InvalidKey"}"#,
        ),
        vector(
            "keys.export_der",
            r#"{"format":"spki","jwk":{"kty":"OKP","crv":"Ed25519","x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE"}}"#,
            &format!(r#"{{"ok":true,"der_b64u":"{RFC8410_10_1_DER}"}}"#),
        ),
        vector(
            "keys.export_der",
            r#"{"format":"spki","jwk":{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"}}"#,
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
        ),
        // RFC 7518 §3.4 and §3.2; generated keys are compared by shape.
        vector(
            "keys.generate_for",
            r#"{"alg":"ES256"}"#,
            r#"{"ok":true,"shape":{"alg":"ES256","crv":"P-256","kty":"EC"}}"#,
        ),
        vector(
            "keys.generate_for",
            r#"{"alg":"HS256"}"#,
            r#"{"ok":true,"shape":{"kty":"oct","alg":"HS256","k_octets":32}}"#,
        ),
        // A JWE `enc` name resolves too (RFC 7518 §7.1, one registry).
        vector(
            "keys.generate_for",
            r#"{"alg":"A128CBC-HS256"}"#,
            r#"{"ok":true,"shape":{"kty":"oct","alg":"A128CBC-HS256","k_octets":32}}"#,
        ),
        vector(
            "keys.generate_for",
            r#"{"alg":"RS256"}"#,
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
        ),
    ];
    for json in cases {
        assert!(
            check_vector("ok.json", json.as_bytes()).is_ok(),
            "{:?}",
            check_vector("ok.json", json.as_bytes())
        );
    }
}

/// RFC 8410 §10.1, the Ed25519 public key as SPKI.
const RFC8410_10_1_PEM: &str = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=\n-----END PUBLIC KEY-----\n";
/// The DER of [`RFC8410_10_1_PEM`], as canonical base64url.
const RFC8410_10_1_DER: &str = "MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE";

/// The keys.* vectors are checked like every other: a wrong expectation,
/// a format outside the enum and a missing member all fail the run.
#[test]
fn keys_vectors_fail_when_wrong_or_malformed() {
    let pem = Value::from(RFC8410_10_1_PEM).to_json();
    let jwk = r#"{"kty":"OKP","crv":"Ed25519","x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE"}"#;
    for (name, json, needle) in [
        (
            "import-wrong-jwk.json",
            vector(
                "keys.import_pem",
                &format!(r#"{{"pem":{pem}}}"#),
                r#"{"ok":true,"jwk":{"kty":"OKP","crv":"X25519","x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE"}}"#,
            ),
            "`jwk`",
        ),
        (
            "import-wrong-code.json",
            vector(
                "keys.import_pem",
                &format!(r#"{{"pem":{pem}}}"#),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "expected error InvalidKey",
        ),
        (
            "export-bad-format.json",
            vector(
                "keys.export_pem",
                &format!(r#"{{"jwk":{jwk},"format":"der"}}"#),
                r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
            ),
            "/input/format",
        ),
        (
            "export-no-format.json",
            vector(
                "keys.export_pem",
                &format!(r#"{{"jwk":{jwk}}}"#),
                r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
            ),
            "/input/format",
        ),
        (
            "export-wrong-pem.json",
            vector(
                "keys.export_pem",
                &format!(r#"{{"jwk":{jwk},"format":"spki"}}"#),
                r#"{"ok":true,"pem":"-----BEGIN PUBLIC KEY-----\n"}"#,
            ),
            "`pem`",
        ),
        (
            "import-der-wrong-jwk.json",
            vector(
                "keys.import_der",
                &format!(r#"{{"der_b64u":"{RFC8410_10_1_DER}","format":"spki"}}"#),
                r#"{"ok":true,"jwk":{"kty":"OKP","crv":"X25519","x":"Gb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE"}}"#,
            ),
            "`jwk`",
        ),
        (
            "import-der-padded.json",
            vector(
                "keys.import_der",
                &format!(r#"{{"der_b64u":"{RFC8410_10_1_DER}=","format":"spki"}}"#),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "/input/der_b64u",
        ),
        (
            // The last character carries non-zero pad bits (RFC 4648 §3.5):
            // the runner cannot decode it, so the vector is broken.
            "import-der-non-canonical.json",
            vector(
                "keys.import_der",
                &format!(
                    r#"{{"der_b64u":"{}F","format":"spki"}}"#,
                    &RFC8410_10_1_DER[..RFC8410_10_1_DER.len() - 1]
                ),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "not canonical base64url",
        ),
        (
            "import-der-no-format.json",
            vector(
                "keys.import_der",
                &format!(r#"{{"der_b64u":"{RFC8410_10_1_DER}"}}"#),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "/input/format",
        ),
        (
            "import-der-pem-member.json",
            vector(
                "keys.import_der",
                &format!(r#"{{"pem":{pem},"format":"spki"}}"#),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "/input/pem",
        ),
        (
            "export-der-wrong-der.json",
            vector(
                "keys.export_der",
                &format!(r#"{{"jwk":{jwk},"format":"spki"}}"#),
                r#"{"ok":true,"der_b64u":"MCowBQYDK2VwAyEA"}"#,
            ),
            "`der_b64u`",
        ),
        (
            "export-der-padded.json",
            vector(
                "keys.export_der",
                &format!(r#"{{"jwk":{jwk},"format":"spki"}}"#),
                &format!(r#"{{"ok":true,"der_b64u":"{RFC8410_10_1_DER}="}}"#),
            ),
            "/expect/der_b64u",
        ),
        (
            "export-der-pem-output.json",
            vector(
                "keys.export_der",
                &format!(r#"{{"jwk":{jwk},"format":"spki"}}"#),
                &format!(r#"{{"ok":true,"pem":{pem}}}"#),
            ),
            "/expect/pem",
        ),
        (
            "export-der-bad-format.json",
            vector(
                "keys.export_der",
                &format!(r#"{{"jwk":{jwk},"format":"pem"}}"#),
                r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
            ),
            "/input/format",
        ),
        (
            "import-extra-member.json",
            vector(
                "keys.import_pem",
                &format!(r#"{{"pem":{pem},"format":"spki"}}"#),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "/input/format",
        ),
    ] {
        fails_naming_source(name, &json, needle);
    }
}

/// `keys.generate_for` is compared by shape only, but exactly: a wrong or
/// missing shape member, an extra one and a malformed input all fail.
#[test]
fn generate_for_vectors_fail_when_wrong_or_malformed() {
    for (name, input, expect, needle) in [
        (
            "wrong-curve.json",
            r#"{"alg":"ES256"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-384","alg":"ES256"}}"#,
            "`shape`",
        ),
        (
            "no-curve.json",
            r#"{"alg":"ES256"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","alg":"ES256"}}"#,
            "`shape`",
        ),
        (
            "wrong-length.json",
            r#"{"alg":"A256GCM"}"#,
            r#"{"ok":true,"shape":{"kty":"oct","alg":"A256GCM","k_octets":16}}"#,
            "`shape`",
        ),
        (
            "key-material.json",
            r#"{"alg":"HS256"}"#,
            r#"{"ok":true,"shape":{"kty":"oct","alg":"HS256","k_octets":32,"k":"AA"}}"#,
            "/expect/shape/k",
        ),
        (
            "rsa-shape.json",
            r#"{"alg":"RS256"}"#,
            r#"{"ok":true,"shape":{"kty":"RSA","alg":"RS256"}}"#,
            "/expect/shape/kty",
        ),
        (
            "jwk-output.json",
            r#"{"alg":"HS256"}"#,
            r#"{"ok":true,"jwk":{"kty":"oct"}}"#,
            "/expect/jwk",
        ),
        (
            "no-alg.json",
            r#"{"enc":"A128GCM"}"#,
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
            "/input/enc",
        ),
        (
            "curve-required.json",
            r#"{"alg":"ECDH-ES"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256","alg":"ECDH-ES"}}"#,
            "expected success, got error InvalidKey",
        ),
    ] {
        let json = vector("keys.generate_for", input, expect);
        fails_naming_source(&format!("generate-{name}"), &json, needle);
    }
}

/// The generator operations (ADR 0030 `jwk_generate_oct`/`_ec`/`_okp`) and
/// `use_with`: each generated key has its RFC shape and survives its use
/// round trip (ADR 0034 §6); the core's length refusal is the outcome.
#[test]
fn generate_vectors_pass() {
    assert_passes(&[
        vector(
            "keys.generate_oct",
            r#"{"len_bytes":32}"#,
            r#"{"ok":true,"shape":{"kty":"oct","k_octets":32},"use_with":{"alg":"HS256"}}"#,
        ),
        vector(
            "keys.generate_oct",
            r#"{"len_bytes":16}"#,
            r#"{"ok":true,"shape":{"kty":"oct","k_octets":16},"use_with":{"alg":"A128KW","enc":"A128GCM"}}"#,
        ),
        vector(
            "keys.generate_oct",
            r#"{"len_bytes":15}"#,
            r#"{"ok":false,"error":"InvalidKey"}"#,
        ),
        vector(
            "keys.generate_ec",
            r#"{"crv":"P-256"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256"},"use_with":{"alg":"ES256"}}"#,
        ),
        vector(
            "keys.generate_ec",
            r#"{"crv":"P-384"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-384"},"use_with":{"alg":"ECDH-ES+A192KW","enc":"A192GCM"}}"#,
        ),
        vector(
            "keys.generate_okp",
            r#"{"crv":"Ed25519"}"#,
            r#"{"ok":true,"shape":{"kty":"OKP","crv":"Ed25519"},"use_with":{"alg":"EdDSA"}}"#,
        ),
        vector(
            "keys.generate_okp",
            r#"{"crv":"X25519"}"#,
            r#"{"ok":true,"shape":{"kty":"OKP","crv":"X25519"},"use_with":{"alg":"ECDH-ES","enc":"A128GCM"}}"#,
        ),
        vector(
            "keys.generate_for",
            r#"{"alg":"ES256"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256","alg":"ES256"},"use_with":{"alg":"ES256"}}"#,
        ),
        vector(
            "keys.generate_for",
            r#"{"alg":"A256GCM"}"#,
            r#"{"ok":true,"shape":{"kty":"oct","alg":"A256GCM","k_octets":32},"use_with":{"alg":"dir","enc":"A256GCM"}}"#,
        ),
    ]);
}

/// Generator vectors that are schema-invalid, or whose shape or use round
/// trip doesn't hold, fail naming their source.
#[test]
fn generate_vectors_fail_when_wrong_or_malformed() {
    let p256 = r#"{"crv":"P-256"}"#;
    for (name, operation, input, expect, needle) in [
        (
            "no-use-with.json",
            "keys.generate_ec",
            p256,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256"}}"#,
            "/expect/use_with",
        ),
        (
            "alg-in-shape.json",
            "keys.generate_ec",
            p256,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256","alg":"ES256"},"use_with":{"alg":"ES256"}}"#,
            "/expect/shape/alg",
        ),
        (
            "unknown-curve.json",
            "keys.generate_ec",
            r#"{"crv":"P-192"}"#,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-192"},"use_with":{"alg":"ES256"}}"#,
            "/input/crv",
        ),
        (
            "okp-curve-on-ec.json",
            "keys.generate_ec",
            r#"{"crv":"Ed25519"}"#,
            r#"{"ok":true,"shape":{"kty":"OKP","crv":"Ed25519"},"use_with":{"alg":"EdDSA"}}"#,
            "/input/crv",
        ),
        (
            "ec-cannot-fail.json",
            "keys.generate_ec",
            p256,
            r#"{"ok":false,"error":"InvalidKey"}"#,
            "cannot fail",
        ),
        (
            "use-with-member.json",
            "keys.generate_ec",
            p256,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256"},"use_with":{"alg":"ES256","kid":"1"}}"#,
            "/expect/use_with/kid",
        ),
        (
            "use-with-wrong-alg.json",
            "keys.generate_ec",
            p256,
            r#"{"ok":true,"shape":{"kty":"EC","crv":"P-256"},"use_with":{"alg":"ES384"}}"#,
            "use_with: the key does not sign",
        ),
        (
            "use-with-wrong-family.json",
            "keys.generate_okp",
            r#"{"crv":"X25519"}"#,
            r#"{"ok":true,"shape":{"kty":"OKP","crv":"X25519"},"use_with":{"alg":"EdDSA"}}"#,
            "use_with",
        ),
        (
            "wrong-length.json",
            "keys.generate_oct",
            r#"{"len_bytes":32}"#,
            r#"{"ok":true,"shape":{"kty":"oct","k_octets":16},"use_with":{"alg":"HS256"}}"#,
            "`shape`",
        ),
        (
            "length-not-a-count.json",
            "keys.generate_oct",
            r#"{"len_bytes":-1}"#,
            r#"{"ok":false,"error":"InvalidKey"}"#,
            "/input/len_bytes",
        ),
        (
            "for-use-with-wrong.json",
            "keys.generate_for",
            r#"{"alg":"HS256"}"#,
            r#"{"ok":true,"shape":{"kty":"oct","alg":"HS256","k_octets":32},"use_with":{"alg":"HS512"}}"#,
            "use_with",
        ),
    ] {
        fails_naming_source(
            &format!("generate-{name}"),
            &vector(operation, input, expect),
            needle,
        );
    }
}

/// The checks a shape cannot express catch a public key, a member RFC 7518
/// §6 does not define for a generated key (here `kid`) and a missing `alg`;
/// a well-formed private key yields its shape.
#[test]
fn generated_shape_checks_what_a_shape_cannot_say() {
    let jwk = |json: &str| Jwk::from_json(json.as_bytes()).unwrap();
    let public = jwk(A3_PUBLIC);
    assert!(generated_shape(&public).unwrap_err().contains("public key"));
    let with_kid = jwk(r#"{"kty":"oct","alg":"A128KW","kid":"1","k":"GawgguFyGrWKav7AX4VKUg"}"#);
    assert!(generated_shape(&with_kid).unwrap_err().contains("members"));
    let no_alg = jwk(A3_PRIVATE);
    assert!(generated_shape(&no_alg).unwrap_err().contains("members"));
    let bound = jwk(&A3_PRIVATE.replace(r#""kty":"EC""#, r#""kty":"EC","alg":"ES256""#));
    assert_eq!(
        Value::from(generated_shape(&bound).unwrap()),
        parse(r#"{"kty":"EC","crv":"P-256","alg":"ES256"}"#)
    );
    let oct = jwk(r#"{"kty":"oct","alg":"A128KW","k":"GawgguFyGrWKav7AX4VKUg"}"#);
    assert_eq!(
        Value::from(generated_shape(&oct).unwrap()),
        parse(r#"{"kty":"oct","alg":"A128KW","k_octets":16}"#)
    );
}

/// Criterion 1: an operation the schema does not know fails the run.
#[test]
fn unknown_operation_fails() {
    let json = vector("b64url.frobnicate", r#"{"b64u":""}"#, r#"{"ok":true}"#);
    fails_naming_source("unknown-op.json", &json, "unknown operation");
}

/// Criterion 1: an operation the schema reserves but this runner does not
/// implement fails the run too; it is never skipped.
#[test]
fn reserved_but_unimplemented_operations_fail() {
    // jwe.* were reserved until 0003 T09 implemented them, jwt.validate
    // until 0004 T10. With nothing reserved now, `validate` lets no such
    // vector through, so the runner's fallback is driven directly.
    let reserved = Vector {
        operation: "jwt.reserved".to_owned(),
        input: Object::new(),
        expect: Expect::Ok(Object::new()),
        features: Vec::new(),
        features_absent: Vec::new(),
    };
    let problem = execute(&reserved).unwrap_err();
    assert!(problem.contains("not implemented"), "{problem}");
    assert!(problem.contains("never skipped"), "{problem}");
}

/// Criterion 2: every way of breaking the schema fails the run, and the
/// message names the source whenever the vector has a usable one.
#[test]
fn schema_invalid_vectors_fail() {
    let encode_ok = r#"{"ok":true,"b64u":"Zm9v"}"#;
    let cases: &[(&str, String, &str)] = &[
        (
            "extra top-level member",
            vector("b64url.encode", r#"{"bytes_hex":"666f6f"}"#, encode_ok)
                .replace(r#""operation""#, r#""comment":"x","operation""#),
            "/comment: unknown member",
        ),
        (
            "blank description",
            vector("b64url.encode", r#"{"bytes_hex":"666f6f"}"#, encode_ok)
                .replace(r#""self-test""#, r#"" \t""#),
            "/description",
        ),
        (
            "description not a string",
            vector("b64url.encode", r#"{"bytes_hex":"666f6f"}"#, encode_ok)
                .replace(r#""self-test""#, "7"),
            "/description",
        ),
        (
            "missing input",
            vector("b64url.encode", r#"{"bytes_hex":"666f6f"}"#, encode_ok)
                .replace(r#""input":{"bytes_hex":"666f6f"},"#, ""),
            "/input: required member is missing",
        ),
        (
            "input not an object",
            vector("b64url.encode", r#""666f6f""#, encode_ok),
            "/input",
        ),
        (
            "unknown input member",
            vector(
                "b64url.encode",
                r#"{"bytes_hex":"666f6f","bytes":"foo"}"#,
                encode_ok,
            ),
            "/input/bytes: unknown member",
        ),
        (
            "missing input member",
            vector("b64url.encode", "{}", encode_ok),
            "/input/bytes_hex: required member is missing",
        ),
        (
            "uppercase hex",
            vector("b64url.encode", r#"{"bytes_hex":"666F6F"}"#, encode_ok),
            "/input/bytes_hex",
        ),
        (
            "odd-length hex",
            vector("b64url.encode", r#"{"bytes_hex":"666f6"}"#, encode_ok),
            "/input/bytes_hex",
        ),
        (
            "non-hex digit",
            vector("b64url.encode", r#"{"bytes_hex":"66zz"}"#, encode_ok),
            "/input/bytes_hex",
        ),
        (
            "base64url output with padding",
            vector(
                "b64url.encode",
                r#"{"bytes_hex":"66"}"#,
                r#"{"ok":true,"b64u":"Zg=="}"#,
            ),
            "/expect/b64u",
        ),
        (
            "missing ok",
            vector("b64url.encode", r#"{"bytes_hex":"66"}"#, r#"{"b64u":"Zg"}"#),
            "/expect/ok: required member is missing",
        ),
        (
            "ok not a boolean",
            vector(
                "b64url.encode",
                r#"{"bytes_hex":"66"}"#,
                r#"{"ok":"true","b64u":"Zg"}"#,
            ),
            "/expect/ok",
        ),
        (
            "encode cannot expect a failure",
            vector(
                "b64url.encode",
                r#"{"bytes_hex":"66"}"#,
                r#"{"ok":false,"error":"InvalidBase64"}"#,
            ),
            "cannot fail",
        ),
        (
            "success with an error member",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zg"}"#,
                r#"{"ok":true,"bytes_hex":"66","error":"InvalidBase64"}"#,
            ),
            "/expect/error: unknown member",
        ),
        (
            "failure with an output member",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zg"}"#,
                r#"{"ok":false,"error":"InvalidBase64","bytes_hex":"66"}"#,
            ),
            "/expect/bytes_hex: unknown member",
        ),
        (
            "failure without an error code",
            vector("b64url.decode", r#"{"b64u":"Zg=="}"#, r#"{"ok":false}"#),
            "/expect/error: required member is missing",
        ),
        (
            "unknown error code",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zg=="}"#,
                r#"{"ok":false,"error":"BadBase64"}"#,
            ),
            "/expect/error",
        ),
        (
            "decode input not a string",
            vector(
                "b64url.decode",
                r#"{"b64u":["Zg"]}"#,
                r#"{"ok":true,"bytes_hex":"66"}"#,
            ),
            "/input/b64u",
        ),
        (
            "thumbprint hash not a string",
            vector(
                "jwk.thumbprint",
                r#"{"hash":256,"jwk":{"kty":"oct","k":"AA"}}"#,
                r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
            ),
            "/input/hash",
        ),
        (
            "jwk not an object",
            vector(
                "jwk.thumbprint",
                r#"{"hash":"sha-256","jwk":"{\"kty\":\"oct\"}"}"#,
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "/input/jwk",
        ),
        (
            "thumbprint success missing the URI",
            vector(
                "jwk.thumbprint",
                r#"{"hash":"sha-256","jwk":{"kty":"oct","k":"AA"}}"#,
                r#"{"ok":true,"thumbprint":"AA"}"#,
            ),
            "/expect/thumbprint_uri: required member is missing",
        ),
        (
            "jwks.select without selector",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[]}}"#,
                r#"{"ok":false,"error":"NoMatchingKey"}"#,
            ),
            "/input/selector: required member is missing",
        ),
        (
            // The binding selector has no key_op (ADR 0054 §9).
            "jwks.select selector with key_op",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[]},"selector":{"key_op":"verify"}}"#,
                r#"{"ok":false,"error":"NoMatchingKey"}"#,
            ),
            "/input/selector/key_op: unknown member",
        ),
        (
            "jwks.select alg not a string",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[]},"selector":{"alg":["ES256"]}}"#,
                r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
            ),
            "/input/selector/alg",
        ),
        (
            "jwks.select jwks not an object",
            vector(
                "jwks.select",
                r#"{"jwks":"{\"keys\":[]}","selector":{}}"#,
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "/input/jwks",
        ),
        (
            "jwks.select success without jwk",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[]},"selector":{}}"#,
                r#"{"ok":true}"#,
            ),
            "/expect/jwk: required member is missing",
        ),
        (
            "jwks.select jwk not an object",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[]},"selector":{}}"#,
                r#"{"ok":true,"jwk":"{}"}"#,
            ),
            "/expect/jwk",
        ),
        (
            "operation not a string",
            vector("b64url.encode", r#"{"bytes_hex":"66"}"#, encode_ok)
                .replace(r#""b64url.encode""#, r#"["b64url.encode"]"#),
            "/operation",
        ),
    ];
    for (what, json, needle) in cases {
        let name = format!("invalid ({what}).json");
        fails_naming_source(&name, json, needle);
    }
}

/// A vector without a usable `source` is schema-invalid; the message still
/// names the file and says the source is missing.
#[test]
fn vectors_without_a_source_fail() {
    let valid = vector(
        "b64url.encode",
        r#"{"bytes_hex":"66"}"#,
        r#"{"ok":true,"b64u":"Zg"}"#,
    );
    let source_member = format!(r#""source":"{SOURCE}","#);
    let cases = [
        valid.replace(&source_member, ""),
        valid.replace(&source_member, r#""source":"","#),
        valid.replace(&source_member, r#""source":"   ","#),
        valid.replace(&source_member, r#""source":null,"#),
    ];
    for json in cases {
        let msg = check_vector("no-source.json", json.as_bytes()).unwrap_err();
        assert!(msg.contains("no-source.json"), "{msg}");
        assert!(msg.contains("/source"), "{msg}");
    }
}

/// Files that are not one JSON object fail, naming the file.
#[test]
fn unparseable_files_fail() {
    let duplicate = vector(
        "b64url.encode",
        r#"{"bytes_hex":"66"}"#,
        r#"{"ok":true,"b64u":"Zg"}"#,
    )
    .replace(r#""input""#, r#""source":"again","input""#);
    for json in ["", "[]", "{", "\"vector\"", duplicate.as_str()] {
        let msg = check_vector("broken.json", json.as_bytes()).unwrap_err();
        assert!(msg.contains("broken.json"), "{msg}");
    }
}

/// Criterion 3: a vector whose expectation the library does not meet fails,
/// and the message names the file and the source.
#[test]
fn failing_vectors_fail_naming_their_source() {
    let cases = [
        (
            "wrong encoding",
            vector(
                "b64url.encode",
                r#"{"bytes_hex":"666f6f"}"#,
                r#"{"ok":true,"b64u":"Zm9w"}"#,
            ),
            "Zm9w",
        ),
        (
            "wrong decoded bytes",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zm9v"}"#,
                r#"{"ok":true,"bytes_hex":"666f70"}"#,
            ),
            "666f70",
        ),
        (
            "expected success, got an error",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zg=="}"#,
                r#"{"ok":true,"bytes_hex":"66"}"#,
            ),
            "InvalidBase64",
        ),
        (
            "expected an error, got success",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zg"}"#,
                r#"{"ok":false,"error":"InvalidBase64"}"#,
            ),
            "succeeded",
        ),
        (
            "wrong error code",
            vector(
                "b64url.decode",
                r#"{"b64u":"Zg=="}"#,
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "InvalidKey",
        ),
        (
            "wrong thumbprint URI",
            vector(
                "jwk.thumbprint",
                r#"{"hash":"sha-256","jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}}"#,
                r#"{"ok":true,"thumbprint":"kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k","thumbprint_uri":"urn:ietf:params:oauth:jwk-thumbprint:sha-512:kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"}"#,
            ),
            "thumbprint_uri",
        ),
        (
            "SHA-384 vector expecting the SHA-256 thumbprint",
            vector(
                "jwk.thumbprint",
                r#"{"hash":"sha-384","jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}}"#,
                r#"{"ok":true,"thumbprint":"kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k","thumbprint_uri":"urn:ietf:params:oauth:jwk-thumbprint:sha-256:kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"}"#,
            ),
            "thumbprint",
        ),
        (
            "jwks.select expecting the other key",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"},{"kty":"oct","k":"AA"}]},"selector":{"alg":"EdDSA"}}"#,
                r#"{"ok":true,"jwk":{"kty":"oct","k":"AA"}}"#,
            ),
            "`jwk`",
        ),
        (
            "jwks.select expecting NoMatchingKey for two matches",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"},{"kty":"oct","k":"AA"}]},"selector":{}}"#,
                r#"{"ok":false,"error":"NoMatchingKey"}"#,
            ),
            "got error MultipleMatchingKeys",
        ),
        (
            "jwks.select expecting a key where none matches",
            vector(
                "jwks.select",
                r#"{"jwks":{"keys":[{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]},"selector":{"alg":"ES256"}}"#,
                &format!(
                    r#"{{"ok":true,"jwk":{}}}"#,
                    r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#
                ),
            ),
            "got error NoMatchingKey",
        ),
    ];
    for (what, json, needle) in cases {
        let name = format!("failing ({what}).json");
        fails_naming_source(&name, &json, needle);
    }
}

// ---------------------------------------------------------------------------
// jws.* self-tests, on RFC 7515 Appendix A values (the vector files under
// conformance/vectors/jws-rfc7515/ cite them).
// ---------------------------------------------------------------------------

/// RFC 7515 A.1 HMAC key.
const A1_KEY: &str = r#"{"kty":"oct","k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"}"#;
/// RFC 7515 A.1 protected header `{"typ":"JWT",\r\n "alg":"HS256"}`.
const A1_PROTECTED: &str = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
/// RFC 7515 A.1 payload (also A.2, A.3, A.5, A.6, A.7).
const PAYLOAD: &str = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
/// RFC 7515 A.1 HS256 signature.
const A1_SIGNATURE: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
/// RFC 7515 A.3 P-256 key, public and private.
const A3_PUBLIC: &str = r#"{"kty":"EC","crv":"P-256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"}"#;
/// RFC 7515 A.3 protected header `{"alg":"ES256"}` and signature.
const A3_PROTECTED: &str = "eyJhbGciOiJFUzI1NiJ9";
const A3_SIGNATURE: &str =
    "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q";
/// RFC 7515 A.5 unsecured JWS.
const A5_JWS: &str = "eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.";
/// A multi-prime RSA JWK (`oth`, RFC 7518 §6.3.2.7), which JWK import
/// refuses before reading anything else (ADR 0067 §3).
const RSA_MULTI_PRIME: &str = r#"{"kty":"RSA","n":"AQAB","e":"AQAB","d":"AQAB","oth":[]}"#;

fn a1_compact() -> String {
    format!("{A1_PROTECTED}.{PAYLOAD}.{A1_SIGNATURE}")
}

/// RFC 7515 A.7, the flattened JSON Serialization.
fn a7_flattened() -> String {
    format!(
        r#"{{"payload":"{PAYLOAD}","protected":"{A3_PROTECTED}","header":{{"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"}},"signature":"{A3_SIGNATURE}"}}"#
    )
}

/// A general JSON JWS whose signatures are A.1's (HS256) and A.3's (ES256).
fn general_hs256_es256() -> String {
    format!(
        r#"{{"payload":"{PAYLOAD}","signatures":[{{"protected":"{A1_PROTECTED}","signature":"{A1_SIGNATURE}"}},{{"protected":"{A3_PROTECTED}","signature":"{A3_SIGNATURE}"}}]}}"#
    )
}

fn verify_input(jws: &str, key: &str, algs: &str, extra: &str) -> String {
    format!(r#"{{"jws":{jws},"key":{key},"allowed_algs":{algs}{extra}}}"#)
}

fn verified(alg: &str, index: u32) -> String {
    format!(r#"{{"ok":true,"payload_b64u":"{PAYLOAD}","alg":"{alg}","signature_index":{index}}}"#)
}

fn quoted(s: &str) -> String {
    format!("\"{s}\"")
}

/// The RFC 8037 A.2 Ed25519 public key.
const ED25519_A2_PUBLIC: &str =
    r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#;

/// `jwks.select` runs its steps in the order conformance/README.md fixes,
/// which is the ADR 0054 §4 precedence: the set import, then the selector
/// (`kid`, `alg`, `key_use`), then selection. Each case breaks two steps
/// with different codes and expects the earlier one.
#[test]
fn jwks_select_runs_its_steps_in_order() {
    let two_keys = format!(r#"{{"keys":[{ED25519_A2_PUBLIC},{{"kty":"oct","k":"AA"}}]}}"#);
    let select = |jwks: &str, selector: &str| format!(r#"{{"jwks":{jwks},"selector":{selector}}}"#);
    let cases = [
        // The import (InvalidKey) before the alg (UnsupportedAlgorithm).
        vector(
            "jwks.select",
            &select(r#"{"keys":"x"}"#, r#"{"alg":"foo"}"#),
            &failure("InvalidKey"),
        ),
        // The import (InvalidKey) before the key_use (UnsupportedAlgorithm).
        vector(
            "jwks.select",
            &select(r#"{"keys":{}}"#, r#"{"key_use":"foo"}"#),
            &failure("InvalidKey"),
        ),
        // The alg (UnsupportedAlgorithm) before selection (NoMatchingKey).
        vector(
            "jwks.select",
            &select(r#"{"keys":[]}"#, r#"{"kid":"a","alg":"none"}"#),
            &failure("UnsupportedAlgorithm"),
        ),
        // The key_use (UnsupportedAlgorithm) before selection
        // (MultipleMatchingKeys).
        vector(
            "jwks.select",
            &select(&two_keys, r#"{"key_use":"foo"}"#),
            &failure("UnsupportedAlgorithm"),
        ),
        // Every part reaches the selector: alone, each of these leaves two
        // matches or none; together they pick the Ed25519 key.
        vector(
            "jwks.select",
            &select(&two_keys, "{}"),
            &failure("MultipleMatchingKeys"),
        ),
        vector(
            "jwks.select",
            &select(&two_keys, r#"{"kid":"a"}"#),
            &failure("NoMatchingKey"),
        ),
        vector(
            "jwks.select",
            &select(&two_keys, r#"{"key_use":"enc"}"#),
            &failure("MultipleMatchingKeys"),
        ),
        vector(
            "jwks.select",
            &select(&two_keys, r#"{"alg":"EdDSA","key_use":"sig"}"#),
            &format!(r#"{{"ok":true,"jwk":{ED25519_A2_PUBLIC}}}"#),
        ),
        vector(
            "jwks.select",
            &select(&two_keys, r#"{"alg":"EdDSA","key_use":"enc"}"#),
            &failure("NoMatchingKey"),
        ),
    ];
    assert_passes(&cases);
}

fn assert_passes(cases: &[String]) {
    for json in cases {
        let result = check_vector("ok.json", json.as_bytes());
        assert!(result.is_ok(), "{result:?}\n  for {json}");
    }
}

/// Every `jws.verify` input form runs: compact, flattened and general,
/// detached, limits, and errors from JWK import and the allow-list.
#[test]
fn jws_verify_vectors_pass() {
    let a1 = quoted(&a1_compact());
    let detached = quoted(&format!("{A1_PROTECTED}..{A1_SIGNATURE}"));
    let fails = |code: &str| format!(r#"{{"ok":false,"error":"{code}"}}"#);
    assert_passes(&[
        vector(
            "jws.verify",
            &verify_input(&a1, A1_KEY, r#"["HS256"]"#, ""),
            &verified("HS256", 0),
        ),
        vector(
            "jws.verify",
            &verify_input(&a7_flattened(), A3_PUBLIC, r#"["ES256"]"#, ""),
            &verified("ES256", 0),
        ),
        // The first signature that verifies with the key wins (ADR 0026 §3).
        vector(
            "jws.verify",
            &verify_input(
                &general_hs256_es256(),
                A3_PUBLIC,
                r#"["HS256","ES256"]"#,
                "",
            ),
            &verified("ES256", 1),
        ),
        vector(
            "jws.verify",
            &verify_input(
                &detached,
                A1_KEY,
                r#"["HS256"]"#,
                &format!(r#","detached_payload_b64u":"{PAYLOAD}""#),
            ),
            &verified("HS256", 0),
        ),
        vector(
            "jws.verify",
            &verify_input(&quoted(A5_JWS), A1_KEY, r#"["HS256"]"#, ""),
            &fails("AlgorithmNotAllowed"),
        ),
        // The allow-list is refused before anything is verified.
        vector(
            "jws.verify",
            &verify_input(&a1, A1_KEY, "[]", ""),
            &fails("AlgorithmNotAllowed"),
        ),
        vector(
            "jws.verify",
            &verify_input(&a1, A1_KEY, r#"["none"]"#, ""),
            &fails("AlgorithmNotAllowed"),
        ),
        // A JWK import error is the vector's outcome.
        vector(
            "jws.verify",
            &verify_input(&a1, RSA_MULTI_PRIME, r#"["RS256"]"#, ""),
            &fails("UnsupportedAlgorithm"),
        ),
        vector(
            "jws.verify",
            &verify_input(&a1, A1_KEY, r#"["HS256"]"#, r#","max_input_len":10"#),
            &fails("InvalidFormat"),
        ),
        vector(
            "jws.verify",
            &verify_input(
                &general_hs256_es256(),
                A3_PUBLIC,
                r#"["HS256","ES256"]"#,
                r#","max_signatures":1"#,
            ),
            &fails("InvalidFormat"),
        ),
        vector(
            "jws.verify",
            &verify_input(
                &general_hs256_es256(),
                A3_PUBLIC,
                r#"["HS256","ES256"]"#,
                r#","max_signatures":2,"max_input_len":4294967295"#,
            ),
            &verified("ES256", 1),
        ),
    ]);
}

/// A `jws.verify` vector that breaks the schema fails the run.
#[test]
fn jws_verify_schema_violations_fail() {
    let a1 = quoted(&a1_compact());
    let input = |extra: &str| verify_input(&a1, A1_KEY, r#"["HS256"]"#, extra);
    let ok = verified("HS256", 0);
    let cases: Vec<(&str, String, &str)> = vec![
        (
            "misspelled member",
            vector(
                "jws.verify",
                &format!(r#"{{"jws":{a1},"key":{A1_KEY},"allowed_alg":["HS256"]}}"#),
                &ok,
            ),
            "/input/allowed_alg: unknown member",
        ),
        (
            "missing allowed_algs",
            vector(
                "jws.verify",
                &format!(r#"{{"jws":{a1},"key":{A1_KEY}}}"#),
                &ok,
            ),
            "/input/allowed_algs: required member is missing",
        ),
        (
            "jws a number",
            vector(
                "jws.verify",
                &verify_input("7", A1_KEY, r#"["HS256"]"#, ""),
                &ok,
            ),
            "/input/jws",
        ),
        (
            "jws an array",
            vector(
                "jws.verify",
                &verify_input(&format!("[{a1}]"), A1_KEY, r#"["HS256"]"#, ""),
                &ok,
            ),
            "/input/jws",
        ),
        (
            "key a string",
            vector(
                "jws.verify",
                &verify_input(&a1, &quoted("k"), r#"["HS256"]"#, ""),
                &ok,
            ),
            "/input/key",
        ),
        (
            "allowed_algs a string",
            vector(
                "jws.verify",
                &verify_input(&a1, A1_KEY, r#""HS256""#, ""),
                &ok,
            ),
            "/input/allowed_algs",
        ),
        (
            "allowed_algs with a number",
            vector(
                "jws.verify",
                &verify_input(&a1, A1_KEY, r#"["HS256",256]"#, ""),
                &ok,
            ),
            "/input/allowed_algs",
        ),
        (
            "negative max_signatures",
            vector("jws.verify", &input(r#","max_signatures":-1"#), &ok),
            "/input/max_signatures",
        ),
        (
            "fractional max_signatures",
            vector("jws.verify", &input(r#","max_signatures":1.5"#), &ok),
            "/input/max_signatures",
        ),
        (
            "max_input_len above u32",
            vector("jws.verify", &input(r#","max_input_len":4294967296"#), &ok),
            "/input/max_input_len",
        ),
        (
            "max_input_len a string",
            vector("jws.verify", &input(r#","max_input_len":"10""#), &ok),
            "/input/max_input_len",
        ),
        (
            "padded detached payload",
            vector(
                "jws.verify",
                &input(r#","detached_payload_b64u":"Zg==""#),
                &ok,
            ),
            "/input/detached_payload_b64u",
        ),
        (
            "success without signature_index",
            vector(
                "jws.verify",
                &input(""),
                &format!(r#"{{"ok":true,"payload_b64u":"{PAYLOAD}","alg":"HS256"}}"#),
            ),
            "/expect/signature_index: required member is missing",
        ),
        (
            "signature_index a string",
            vector(
                "jws.verify",
                &input(""),
                &ok.replace(r#""signature_index":0"#, r#""signature_index":"0""#),
            ),
            "/expect/signature_index",
        ),
        (
            "success with a sign output",
            vector(
                "jws.verify",
                &input(""),
                &ok.replace(r#""ok":true"#, &format!(r#""ok":true,"jws":{a1}"#)),
            ),
            "/expect/jws: unknown member",
        ),
        (
            "failure with an output member",
            vector(
                "jws.verify",
                &input(""),
                r#"{"ok":false,"error":"InvalidSignature","alg":"HS256"}"#,
            ),
            "/expect/alg: unknown member",
        ),
    ];
    for (what, json, needle) in cases {
        fails_naming_source(&format!("invalid ({what}).json"), &json, needle);
    }
}

/// A `jws.verify` vector the library does not meet fails, naming the file
/// and the source.
#[test]
fn jws_verify_mismatches_fail() {
    let a1 = quoted(&a1_compact());
    let input = verify_input(&a1, A1_KEY, r#"["HS256"]"#, "");
    let cases = [
        (
            "wrong signature_index",
            vector("jws.verify", &input, &verified("HS256", 1)),
            "signature_index",
        ),
        (
            "wrong alg",
            vector("jws.verify", &input, &verified("HS384", 0)),
            "HS384",
        ),
        (
            "wrong payload",
            vector(
                "jws.verify",
                &input,
                &verified("HS256", 0).replace(PAYLOAD, "UGF5bG9hZA"),
            ),
            "payload_b64u",
        ),
        (
            "tampered signature",
            vector(
                "jws.verify",
                &input.replace(A1_SIGNATURE, &A1_SIGNATURE.replace('d', "e")),
                &verified("HS256", 0),
            ),
            "InvalidSignature",
        ),
        (
            "expected an error, got success",
            vector(
                "jws.verify",
                &input,
                r#"{"ok":false,"error":"InvalidSignature"}"#,
            ),
            "succeeded",
        ),
        // The runner decodes bytes it passes to the library; a value that
        // does not decode is the vector's fault, never an outcome.
        (
            "detached payload that does not decode",
            vector(
                "jws.verify",
                &verify_input(
                    &quoted(&format!("{A1_PROTECTED}..{A1_SIGNATURE}")),
                    A1_KEY,
                    r#"["HS256"]"#,
                    r#","detached_payload_b64u":"Zh""#,
                ),
                r#"{"ok":false,"error":"InvalidBase64"}"#,
            ),
            "detached_payload_b64u",
        ),
    ];
    for (what, json, needle) in cases {
        fails_naming_source(&format!("failing ({what}).json"), &json, needle);
    }
}

/// RFC 7515 A.3 P-256 private key.
const A3_PRIVATE: &str = r#"{"kty":"EC","crv":"P-256","x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0","d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI"}"#;
/// Another P-256 public key (RFC 7517 A.1), which verifies nothing A.3 signs.
const OTHER_P256: &str = r#"{"kty":"EC","crv":"P-256","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}"#;

fn sign_input(serialization: &str, detached: bool, signers: &[String]) -> String {
    format!(
        r#"{{"serialization":"{serialization}","payload_b64u":"{PAYLOAD}","detached":{detached},"signers":[{}]}}"#,
        signers.join(",")
    )
}

fn signer(protected: Option<&str>, header: Option<&str>, key: &str) -> String {
    let mut members = Vec::new();
    if let Some(protected) = protected {
        members.push(format!(r#""protected_b64u":"{protected}""#));
    }
    if let Some(header) = header {
        members.push(format!(r#""header":{header}"#));
    }
    members.push(format!(r#""key":{key}"#));
    format!("{{{}}}", members.join(","))
}

fn signed(jws: &str) -> String {
    format!(r#"{{"ok":true,"jws":{jws}}}"#)
}

fn round_trip(key: &str, algs: &str) -> String {
    format!(r#"{{"ok":true,"verify_with":{{"key":{key},"allowed_algs":{algs}}}}}"#)
}

/// Every `jws.sign` form runs: exact and round-trip expectations, all three
/// serializations, several signers, unprotected headers, detached output,
/// and errors from JWK import and header parsing.
#[test]
fn jws_sign_vectors_pass() {
    let hs256 = signer(Some(A1_PROTECTED), None, A1_KEY);
    let es256 = signer(Some(A3_PROTECTED), None, A3_PRIVATE);
    let fails = |code: &str| format!(r#"{{"ok":false,"error":"{code}"}}"#);
    assert_passes(&[
        vector(
            "jws.sign",
            &sign_input("compact", false, std::slice::from_ref(&hs256)),
            &signed(&quoted(&a1_compact())),
        ),
        // Appendix F: the payload part is empty.
        vector(
            "jws.sign",
            &sign_input("compact", true, std::slice::from_ref(&hs256)),
            &signed(&quoted(&format!("{A1_PROTECTED}..{A1_SIGNATURE}"))),
        ),
        // JSON output is compared as JSON: member order does not matter.
        vector(
            "jws.sign",
            &sign_input("flattened", false, std::slice::from_ref(&hs256)),
            &signed(&format!(
                r#"{{"signature":"{A1_SIGNATURE}","protected":"{A1_PROTECTED}","payload":"{PAYLOAD}"}}"#
            )),
        ),
        // Two signers; the unprotected header is not signed, so both MACs
        // are A.1's.
        vector(
            "jws.sign",
            &sign_input(
                "general",
                false,
                &[
                    hs256.clone(),
                    signer(Some(A1_PROTECTED), Some(r#"{"kid":"k2"}"#), A1_KEY),
                ],
            ),
            &signed(&format!(
                r#"{{"payload":"{PAYLOAD}","signatures":[{{"protected":"{A1_PROTECTED}","signature":"{A1_SIGNATURE}"}},{{"protected":"{A1_PROTECTED}","header":{{"kid":"k2"}},"signature":"{A1_SIGNATURE}"}}]}}"#
            )),
        ),
        vector(
            "jws.sign",
            &sign_input("compact", false, std::slice::from_ref(&es256)),
            &round_trip(A3_PUBLIC, r#"["ES256"]"#),
        ),
        vector(
            "jws.sign",
            &sign_input("flattened", true, std::slice::from_ref(&es256)),
            &round_trip(A3_PUBLIC, r#"["ES256"]"#),
        ),
        // A multi-signer round trip verifies the signature the key fits.
        vector(
            "jws.sign",
            &sign_input("general", false, &[hs256.clone(), es256.clone()]),
            &round_trip(A3_PUBLIC, r#"["ES256"]"#),
        ),
        // No protected header (RFC 7515 §7.2.1; RFC 7520 §4.7).
        vector(
            "jws.sign",
            &sign_input(
                "flattened",
                false,
                &[signer(None, Some(r#"{"alg":"HS256"}"#), A1_KEY)],
            ),
            &round_trip(A1_KEY, r#"["HS256"]"#),
        ),
        // A JWK import error is the vector's outcome (ADR 0067 §3).
        vector(
            "jws.sign",
            &sign_input(
                "compact",
                false,
                &[signer(Some(A1_PROTECTED), None, RSA_MULTI_PRIME)],
            ),
            &fails("UnsupportedAlgorithm"),
        ),
        // So are header errors: "foo" is not a JSON object, and kid must be
        // a string (RFC 7515 §4.1.4).
        vector(
            "jws.sign",
            &sign_input("compact", false, &[signer(Some("Zm9v"), None, A1_KEY)]),
            &fails("InvalidJson"),
        ),
        vector(
            "jws.sign",
            &sign_input(
                "flattened",
                false,
                &[signer(Some(A1_PROTECTED), Some(r#"{"kid":5}"#), A1_KEY)],
            ),
            &fails("InvalidHeader"),
        ),
        // Without a protected header, alg is missing.
        vector(
            "jws.sign",
            &sign_input("general", false, &[signer(None, None, A1_KEY)]),
            &fails("InvalidHeader"),
        ),
    ]);
}

/// A `jws.sign` vector that breaks the schema, including its
/// per-serialization rules, fails the run.
#[test]
fn jws_sign_schema_violations_fail() {
    let hs256 = signer(Some(A1_PROTECTED), None, A1_KEY);
    let one = |serialization: &str| sign_input(serialization, false, std::slice::from_ref(&hs256));
    let ok = signed(&quoted(&a1_compact()));
    let cases: Vec<(&str, String, &str)> = vec![
        (
            "compact with two signers",
            vector(
                "jws.sign",
                &sign_input("compact", false, &[hs256.clone(), hs256.clone()]),
                &ok,
            ),
            "/input/signers: a compact JWS has at most 1 signer",
        ),
        (
            "flattened with two signers",
            vector(
                "jws.sign",
                &sign_input("flattened", false, &[hs256.clone(), hs256.clone()]),
                &ok,
            ),
            "/input/signers: a flattened JWS has at most 1 signer",
        ),
        (
            "compact with only a key",
            vector(
                "jws.sign",
                &sign_input("compact", false, &[signer(None, None, A1_KEY)]),
                &ok,
            ),
            "/input/signers/0/protected_b64u: required for a compact JWS",
        ),
        (
            "compact with an unprotected header",
            vector(
                "jws.sign",
                &sign_input(
                    "compact",
                    false,
                    &[signer(Some(A1_PROTECTED), Some("{}"), A1_KEY)],
                ),
                &ok,
            ),
            "/input/signers/0/header: not allowed in a compact JWS",
        ),
        (
            "no signers",
            vector("jws.sign", &sign_input("general", false, &[]), &ok),
            "/input/signers",
        ),
        (
            "signers not an array",
            vector(
                "jws.sign",
                &one("general").replace(&format!("[{hs256}]"), &hs256),
                &ok,
            ),
            "/input/signers",
        ),
        (
            "signer not an object",
            vector(
                "jws.sign",
                &sign_input("general", false, &[quoted(A1_PROTECTED)]),
                &ok,
            ),
            "/input/signers/0",
        ),
        (
            "misspelled signer member",
            vector(
                "jws.sign",
                &one("compact").replace("protected_b64u", "protected"),
                &ok,
            ),
            "/input/signers/0/protected: unknown member",
        ),
        (
            "signer without a key",
            vector(
                "jws.sign",
                &one("compact").replace(&format!(r#","key":{A1_KEY}"#), ""),
                &ok,
            ),
            "/input/signers/0/key: required member is missing",
        ),
        (
            "padded protected header",
            vector(
                "jws.sign",
                &one("compact").replace(A1_PROTECTED, "eyJhbGciOiJIUzI1NiJ9=="),
                &ok,
            ),
            "/input/signers/0/protected_b64u",
        ),
        (
            "unknown serialization",
            vector("jws.sign", &one("json"), &ok),
            "/input/serialization",
        ),
        (
            "detached a string",
            vector(
                "jws.sign",
                &one("compact").replace(r#""detached":false"#, r#""detached":"false""#),
                &ok,
            ),
            "/input/detached",
        ),
        (
            "detached missing",
            vector(
                "jws.sign",
                &one("compact").replace(r#""detached":false,"#, ""),
                &ok,
            ),
            "/input/detached: required member is missing",
        ),
        (
            "misspelled input member",
            vector(
                "jws.sign",
                &one("compact").replace("payload_b64u", "payload"),
                &ok,
            ),
            "/input/payload: unknown member",
        ),
        (
            "both success forms",
            vector(
                "jws.sign",
                &one("compact"),
                &round_trip(A1_KEY, r#"["HS256"]"#).replace(
                    r#""ok":true"#,
                    &format!(r#""ok":true,"jws":"{}""#, a1_compact()),
                ),
            ),
            "matches none of the success forms",
        ),
        (
            "neither success form",
            vector("jws.sign", &one("compact"), r#"{"ok":true}"#),
            "matches none of the success forms",
        ),
        (
            "misspelled verify_with member",
            vector(
                "jws.sign",
                &one("compact"),
                &round_trip(A1_KEY, r#"["HS256"]"#).replace("allowed_algs", "allowed_alg"),
            ),
            "/expect/verify_with/allowed_alg: unknown member",
        ),
        (
            "verify_with without allowed_algs",
            vector(
                "jws.sign",
                &one("compact"),
                &format!(r#"{{"ok":true,"verify_with":{{"key":{A1_KEY}}}}}"#),
            ),
            "/expect/verify_with/allowed_algs: required member is missing",
        ),
        (
            "jws a number",
            vector("jws.sign", &one("compact"), &signed("7")),
            "/expect/jws",
        ),
        (
            "failure with an output",
            vector(
                "jws.sign",
                &one("compact"),
                &format!(
                    r#"{{"ok":false,"error":"InvalidKey","jws":"{}"}}"#,
                    a1_compact()
                ),
            ),
            "/expect/jws: unknown member",
        ),
    ];
    for (what, json, needle) in cases {
        fails_naming_source(&format!("invalid ({what}).json"), &json, needle);
    }
}

/// A `jws.sign` vector the library does not meet fails, naming the file and
/// the source; so does a round trip whose verification fails.
#[test]
fn jws_sign_mismatches_fail() {
    let hs256 = sign_input(
        "compact",
        false,
        &[signer(Some(A1_PROTECTED), None, A1_KEY)],
    );
    let es256 = sign_input(
        "compact",
        false,
        &[signer(Some(A3_PROTECTED), None, A3_PRIVATE)],
    );
    let cases = [
        (
            "wrong signature",
            vector(
                "jws.sign",
                &hs256,
                &signed(&quoted(&a1_compact().replace('d', "e"))),
            ),
            "`jws`",
        ),
        (
            "flattened output expected for compact",
            vector(
                "jws.sign",
                &hs256,
                &signed(&format!(
                    r#"{{"payload":"{PAYLOAD}","protected":"{A1_PROTECTED}","signature":"{A1_SIGNATURE}"}}"#
                )),
            ),
            "`jws`",
        ),
        (
            "round trip with another key",
            vector("jws.sign", &es256, &round_trip(OTHER_P256, r#"["ES256"]"#)),
            "round trip",
        ),
        (
            "round trip with another algorithm",
            vector("jws.sign", &es256, &round_trip(A3_PUBLIC, r#"["ES384"]"#)),
            "AlgorithmNotAllowed",
        ),
        (
            "round trip with a key that does not import",
            vector(
                "jws.sign",
                &es256,
                &round_trip(RSA_MULTI_PRIME, r#"["ES256"]"#),
            ),
            "verify_with",
        ),
        (
            "expected an error, got success",
            vector("jws.sign", &hs256, r#"{"ok":false,"error":"InvalidKey"}"#),
            "succeeded",
        ),
        (
            "payload that does not decode",
            vector(
                "jws.sign",
                &hs256.replace(PAYLOAD, "Zh"),
                &signed(&quoted(&a1_compact())),
            ),
            "payload_b64u",
        ),
    ];
    for (what, json, needle) in cases {
        fails_naming_source(&format!("failing ({what}).json"), &json, needle);
    }
}

// ---------------------------------------------------------------------------
// Binding readiness: the WASM, Node, Kotlin and Swift runners (features
// 0006-0009) must read the jws.* vectors with their platform JSON parsers,
// unchanged (ADR 0034).
// ---------------------------------------------------------------------------

/// The number tokens of a JSON text, as written (outside strings).
fn number_tokens(text: &str) -> Vec<&str> {
    let mut tokens = Vec::new();
    let (mut in_string, mut escaped, mut start) = (false, false, None);
    for (i, c) in text.char_indices() {
        if in_string {
            match (escaped, c) {
                (true, _) => escaped = false,
                (false, '\\') => escaped = true,
                (false, '"') => in_string = false,
                _ => {}
            }
            continue;
        }
        // A number starts with '-' or a digit (RFC 8259 §6); `true` and
        // `false` hold an `e` but never start one.
        let begins = c.is_ascii_digit() || c == '-';
        let continues = begins || matches!(c, '+' | '.' | 'e' | 'E');
        match (start, begins, continues) {
            (None, true, _) => start = Some(i),
            (Some(s), _, false) => {
                tokens.push(&text[s..i]);
                start = None;
            }
            _ => {}
        }
        in_string = c == '"';
    }
    if let Some(s) = start {
        tokens.push(&text[s..]);
    }
    tokens
}

/// Every member of `value`, at any depth, with its JSON pointer.
fn members_deep<'a>(
    value: &'a Value,
    pointer: String,
    out: &mut Vec<(String, &'a str, &'a Value)>,
) {
    if let Some(object) = value.as_object() {
        for (name, member) in object {
            let at = format!("{pointer}/{name}");
            out.push((at.clone(), name, member));
            members_deep(member, at, out);
        }
    } else if let Some(items) = value.as_array() {
        for (i, item) in items.iter().enumerate() {
            members_deep(item, format!("{pointer}/{i}"), out);
        }
    }
}

/// Whether a vector file uses only what every binding's JSON parser reads
/// exactly:
///
/// - every number is written as a plain integer (no fraction or exponent,
///   which JavaScript, Kotlin and Swift parsers may read as a double) of
///   magnitude at most 2^32 - 1, so no binding needs a 64-bit-only type
///   (ADR 0030 `u32`);
/// - octets are base64url text (`*_b64u`), never raw bytes or `*_hex`, and
///   every one the runner decodes is canonical (`protected_b64u` is passed
///   to the library as text, so it may be anything the schema allows);
/// - in a `keys.*` vector, every base64url JWK member (`x`, `y`, `d`, `n`,
///   `e`, `k`; RFC 7518 §6, RFC 8037 §2) of a `jwk` object is canonical, so
///   a binding's base64url decoder reads the key the vector means.
fn binding_ready(text: &str) -> Result<(), String> {
    binding_ready_with(text, Numbers::Count)
}

/// Which numbers a binding-ready vector may contain.
#[derive(Debug, Clone, Copy)]
enum Numbers {
    /// `jws.*`, `jwe.*`, `keys.*`: plain integers of magnitude at most
    /// 2^32 − 1 (ADR 0030 `u32`).
    Count,
    /// `jwt.*`: plain integers within ±(2^53 − 1), the NumericDate and
    /// clock range (RFC 7493 §2.2; ADR 0027 §2, ADR 0028 §1), and
    /// non-integral decimals (`1300819380.5`, a fractional NumericDate,
    /// RFC 7519 §2) of magnitude within it. Every binding's JSON reads
    /// these exactly: JavaScript's numbers are doubles, which hold every
    /// integer of that range. An integral value is written as a plain
    /// integer (never `1.0` or `1e3`), so a binding reads `now` and every
    /// other integer member as an integer.
    Safe,
}

/// Whether the number token `token` (as written) is one `numbers` allows.
fn allowed_number(token: &str, numbers: Numbers) -> bool {
    let unsigned = token.strip_prefix('-').unwrap_or(token);
    let (int, frac) = match unsigned.split_once('.') {
        Some((int, frac)) => (int, Some(frac)),
        None => (unsigned, None),
    };
    let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
    if !digits(int) || frac.is_some_and(|f| !digits(f)) {
        return false; // an exponent, or not a number at all
    }
    match (numbers, frac) {
        (Numbers::Count, None) => token
            .parse::<i64>()
            .is_ok_and(|n| n.unsigned_abs() <= COUNT_MAX),
        (Numbers::Count, Some(_)) => false,
        (Numbers::Safe, None) => token
            .parse::<i64>()
            .is_ok_and(|n| n.unsigned_abs() <= SECONDS_MAX.unsigned_abs()),
        // Compared as the double every binding reads: within range, and
        // not integral (an integral value is written as an integer).
        (Numbers::Safe, Some(_)) => token
            .parse::<f64>()
            .is_ok_and(|v| v.is_finite() && v.abs() <= SECONDS_MAX as f64 && v.fract() != 0.0),
    }
}

/// [`binding_ready`] with the number rule `numbers`.
fn binding_ready_with(text: &str, numbers: Numbers) -> Result<(), String> {
    for token in number_tokens(text) {
        if !allowed_number(token, numbers) {
            return Err(match numbers {
                Numbers::Count => format!(
                    "number {token} is not a plain integer of magnitude at most {COUNT_MAX}"
                ),
                Numbers::Safe => format!(
                    "number {token} is not a plain integer, or a non-integral decimal, \
                     of magnitude at most {SECONDS_MAX}"
                ),
            });
        }
    }
    let value =
        parse_vector_file(text.as_bytes()).map_err(|e| format!("not JSON ({})", e.code()))?;
    let keys_vector = value
        .get("operation")
        .and_then(Value::as_str)
        .is_some_and(|op| op.starts_with("keys."));
    let mut members = Vec::new();
    members_deep(&value, String::new(), &mut members);
    for (pointer, name, member) in members {
        let jwk_member = pointer
            .rsplit_once('/')
            .is_some_and(|(parent, _)| parent.ends_with("/jwk"));
        if keys_vector && jwk_member && JWK_B64U_MEMBERS.contains(&name) {
            let canonical = member
                .as_str()
                .is_some_and(|s| b64url_decode(s).is_ok_and(|b| b64url_encode(&b) == s));
            if !canonical {
                return Err(format!("{pointer}: not canonical base64url"));
            }
        }
        if name.ends_with("_hex") {
            return Err(format!(
                "{pointer}: raw bytes; jws.* vectors write octets as *_b64u"
            ));
        }
        if name.ends_with("_b64u") && name != "protected_b64u" {
            let canonical = member
                .as_str()
                .is_some_and(|s| b64url_decode(s).is_ok_and(|b| b64url_encode(&b) == s));
            if !canonical {
                return Err(format!("{pointer}: not canonical base64url"));
            }
        }
    }
    Ok(())
}

/// The base64url members of a JWK (RFC 7518 §6.2–§6.4, RFC 8037 §2).
const JWK_B64U_MEMBERS: &[&str] = &["x", "y", "d", "n", "e", "k"];

/// The vectors the binding-readiness rule covers: everything under a
/// `jws-*` directory, a `third_party/**/jws/` directory or `keys/`, and any
/// jws.* or keys.* vector elsewhere.
fn needs_binding_readiness(relative: &Path, text: &str) -> bool {
    let parts: Vec<String> = relative
        .components()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .collect();
    let jws_dir = parts
        .first()
        .is_some_and(|first| first.starts_with("jws-") || first == "keys");
    let third_party_jws = parts.first().is_some_and(|first| first == "third_party")
        && parts[..parts.len() - 1].iter().any(|part| part == "jws");
    let jws_operation = parse_vector_file(text.as_bytes()).is_ok_and(|v| {
        v.get("operation")
            .and_then(Value::as_str)
            .is_some_and(|op| op.starts_with("jws.") || op.starts_with("keys."))
    });
    jws_dir || third_party_jws || jws_operation
}

/// Every JWS and keys vector is binding-ready (see [`binding_ready`]).
#[test]
fn jws_and_keys_vectors_are_binding_ready() {
    let dir = conformance_dir().join("vectors");
    let (mut files, mut failures) = (Vec::new(), Vec::new());
    collect(&dir, &mut files, &mut failures);
    let mut checked = 0;
    for path in files {
        let relative = path.strip_prefix(&dir).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        if !needs_binding_readiness(relative, &text) {
            continue;
        }
        checked += 1;
        if let Err(problem) = binding_ready(&text) {
            failures.push(format!("{}: {problem}", slash_path(relative)));
        }
    }
    assert!(
        failures.is_empty(),
        "not binding-ready:\n  {}",
        failures.join("\n  ")
    );
    assert!(
        checked >= 19,
        "only {checked} JWS and keys vector files found"
    );
}

/// The readiness check rejects what a binding could misread, and nothing
/// else; the vector selection matches the documented directories.
#[test]
fn binding_readiness_check_works() {
    for ok in [
        r#"{"a":0,"b":16,"c":-1,"d":4294967295,"e":[1,2]}"#,
        r#"{"s":"1.5e3 inside a string","t":"a\"1.0\\","n":7}"#,
        r#"{"payload_b64u":"Zm9v","protected_b64u":"Zh","x":{"detached_payload_b64u":""}}"#,
        r#"{"detached":false,"ok":true,"v":null,"n":12}"#,
        r#"{"operation":"keys.export_pem","input":{"jwk":{"kty":"oct","k":"Zm9v"}}}"#,
        // Outside keys.*, a `jwk` object's members are not checked here.
        r#"{"operation":"jws.verify","x":{"jwk":{"k":"Zh"}}}"#,
    ] {
        assert_eq!(binding_ready(ok), Ok(()), "{ok}");
    }
    for (bad, needle) in [
        (r#"{"n":1.0}"#, "1.0"),
        (r#"{"n":1e3}"#, "1e3"),
        (r#"{"n":0.5}"#, "0.5"),
        (r#"{"n":-0.0}"#, "-0.0"),
        (r#"{"n":4294967296}"#, "4294967296"),
        (r#"{"n":-4294967296}"#, "-4294967296"),
        (r#"{"a":[{"n":9007199254740993}]}"#, "9007199254740993"),
        (r#"{"input":{"bytes_hex":"00"}}"#, "/input/bytes_hex"),
        (r#"{"payload_b64u":"Zh"}"#, "/payload_b64u"),
        (
            r#"{"x":[{"detached_payload_b64u":"Zg=="}]}"#,
            "/x/0/detached_payload_b64u",
        ),
        (
            r#"{"operation":"keys.export_pem","input":{"jwk":{"kty":"oct","k":"Zh"}}}"#,
            "/input/jwk/k",
        ),
        (
            r#"{"operation":"keys.import_pem","expect":{"jwk":{"x":"Zg=="}}}"#,
            "/expect/jwk/x",
        ),
    ] {
        let problem = binding_ready(bad).unwrap_err();
        assert!(problem.contains(needle), "{bad}: {problem}");
    }
    let verify = r#"{"operation":"jws.verify"}"#;
    let import = r#"{"operation":"keys.import_pem"}"#;
    let other = r#"{"operation":"b64url.encode"}"#;
    for (path, text, covered) in [
        ("jws-rfc7515/a.json", other, true),
        ("jws-negative/deep/a.json", other, true),
        ("third_party/rfc7520/jws/a.json", other, true),
        ("third_party/rfc7520/jwe/a.json", other, false),
        ("third_party/jws.json", other, false),
        ("b64url/a.json", other, false),
        ("binding-surface/a.json", verify, true),
        ("keys/a.json", other, true),
        ("keys-extra/a.json", other, false),
        ("elsewhere/a.json", import, true),
    ] {
        assert_eq!(
            needs_binding_readiness(Path::new(path), text),
            covered,
            "{path}"
        );
    }
}

/// A temporary directory, removed on drop.
struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> TempDir {
        let path =
            std::env::temp_dir().join(format!("polyjose-conformance-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).unwrap();
        TempDir(path)
    }

    fn write(&self, relative: &str, contents: &str) {
        let path = self.0.join(relative);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// The directory walk finds nested files, ignores non-JSON files, and
/// collects every failure before reporting instead of stopping at the first.
#[test]
fn run_dir_collects_every_failure() {
    let dir = TempDir::new("collect");
    let ok = vector(
        "b64url.encode",
        r#"{"bytes_hex":"66"}"#,
        r#"{"ok":true,"b64u":"Zg"}"#,
    );
    dir.write("a/ok.json", &ok);
    dir.write("third_party/deep/ok.json", &ok);
    dir.write("third_party/LICENSE", "not a vector");
    dir.write(
        "a/unknown-op.json",
        &vector("jws.frobnicate", "{}", r#"{"ok":true}"#),
    );
    dir.write("b/invalid.json", &ok.replace(r#""66""#, r#""6""#));
    dir.write(
        "b/failing.json",
        &ok.replace(r#""b64u":"Zg""#, r#""b64u":"Zh""#),
    );
    let report = run_dir(&dir.0);
    assert_eq!(report.files, 5, "{report:?}");
    assert_eq!(report.failures.len(), 3, "{report:?}");
    for file in ["unknown-op.json", "invalid.json", "failing.json"] {
        assert!(
            report
                .failures
                .iter()
                .any(|f| f.contains(file) && f.contains(SOURCE)),
            "{file} not reported with its source: {report:?}"
        );
    }
}

/// An empty or missing directory fails, so a broken path cannot pass
/// vacuously.
#[test]
fn run_dir_fails_when_there_is_nothing_to_run() {
    let empty = TempDir::new("empty");
    empty.write("README.md", "no vectors here");
    let report = run_dir(&empty.0);
    assert_eq!(report.files, 0);
    assert!(
        report
            .failures
            .iter()
            .any(|f| f.contains("no vector files")),
        "{report:?}"
    );

    let missing = empty.0.join("does-not-exist");
    let report = run_dir(&missing);
    assert!(!report.failures.is_empty(), "{report:?}");
}

// ---------------------------------------------------------------------------
// jwe.* self-tests and the `features` member (0003 T09), on RFC 7516 A.3
// (the vector files under conformance/vectors/jwe/ cite it).
// ---------------------------------------------------------------------------

/// RFC 7516 A.3.3 key and A.3.7 compact JWE.
const JWE_A3_KEY: &str = r#"{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"}"#;
const JWE_A3: &str = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.U0m_YmjN04DJvceFICbCVQ";
/// "Live long and prosper." (RFC 7516 A.3).
const JWE_A3_PLAINTEXT_B64U: &str = "TGl2ZSBsb25nIGFuZCBwcm9zcGVyLg";
const JWE_A3_POLICY: &str = r#""allowed_algs":["A128KW"],"allowed_enc":["A128CBC-HS256"]"#;

fn jwe_decrypt_input(jwe: &str, key: &str, extra: &str) -> String {
    format!(r#"{{"jwe":"{jwe}","key":{key},{JWE_A3_POLICY}{extra}}}"#)
}

fn jwe_encrypt_input(serialization: &str, recipients: &str, extra: &str) -> String {
    format!(
        r#"{{"serialization":"{serialization}","enc":"A128CBC-HS256","plaintext_b64u":"{JWE_A3_PLAINTEXT_B64U}","recipients":{recipients}{extra}}}"#
    )
}

fn jwe_a3_recipient() -> String {
    format!(r#"[{{"alg":"A128KW","key":{JWE_A3_KEY}}}]"#)
}

fn jwe_decrypt_with() -> String {
    format!(r#"{{"ok":true,"decrypt_with":{{"key":{JWE_A3_KEY},{JWE_A3_POLICY}}}}}"#)
}

fn with_features(vector: &str, features: &str) -> String {
    vector.replacen(
        r#""operation""#,
        &format!(r#""features":{features},"operation""#),
        1,
    )
}

/// Every `jwe.*` input form runs: decrypt success and failure (from the
/// key import, the policy and the library), and encrypt round trips and
/// refusals.
#[test]
fn jwe_vectors_pass() {
    let decrypted =
        format!(r#"{{"ok":true,"plaintext_b64u":"{JWE_A3_PLAINTEXT_B64U}","recipient":0}}"#);
    let cases = [
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, ""),
            &decrypted,
        ),
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(
                JWE_A3,
                JWE_A3_KEY,
                r#","understood_crit":["x"],"max_input_len":1000,"max_recipients":1,"max_pbes2_count":1000,"max_decompressed_len":0"#,
            ),
            &decrypted,
        ),
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, r#","max_input_len":10"#),
            r#"{"ok":false,"error":"InvalidFormat"}"#,
        ),
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, r#"{"kty":"oct","k":"Zg=="}"#, ""),
            r#"{"ok":false,"error":"InvalidBase64"}"#,
        ),
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, "").replace(r#"["A128KW"]"#, "[]"),
            r#"{"ok":false,"error":"AlgorithmNotAllowed"}"#,
        ),
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, "").replace(r#""jwe":"eyJ"#, r#""jwe":"x.eyJ"#),
            r#"{"ok":false,"error":"InvalidFormat"}"#,
        ),
        vector(
            "jwe.encrypt",
            &jwe_encrypt_input("compact", &jwe_a3_recipient(), ""),
            &jwe_decrypt_with(),
        ),
        vector(
            "jwe.encrypt",
            &jwe_encrypt_input("compact", &jwe_a3_recipient(), r#","aad_b64u":"YQ""#),
            r#"{"ok":false,"error":"InvalidFormat"}"#,
        ),
        vector(
            "jwe.encrypt",
            &jwe_encrypt_input(
                "compact",
                r#"[{"alg":"A128KW","key":{"kty":"oct","k":"Zg=="}}]"#,
                "",
            ),
            r#"{"ok":false,"error":"InvalidBase64"}"#,
        ),
        vector(
            "jwe.encrypt",
            &jwe_encrypt_input("compact", &jwe_a3_recipient(), r#","protected":{"kid":7}"#),
            r#"{"ok":false,"error":"InvalidHeader"}"#,
        ),
    ];
    assert_passes(&cases);
}

/// A `jwe.*` vector that breaks the schema fails the run.
#[test]
fn jwe_schema_violations_fail() {
    let ok = r#"{"ok":true,"plaintext_b64u":"","recipient":0}"#;
    let input = jwe_decrypt_input(JWE_A3, JWE_A3_KEY, "");
    let encrypt = jwe_encrypt_input("compact", &jwe_a3_recipient(), "");
    let cases: Vec<(&str, String, &str)> = vec![
        (
            "decrypt without allowed_enc",
            vector(
                "jwe.decrypt",
                &input.replace(r#","allowed_enc":["A128CBC-HS256"]"#, ""),
                ok,
            ),
            "/input/allowed_enc: required member is missing",
        ),
        (
            "decrypt with an unknown member",
            vector(
                "jwe.decrypt",
                &input.replace(r#""jwe""#, r#""token":1,"jwe""#),
                ok,
            ),
            "/input/token: unknown member",
        ),
        (
            "decrypt jwe of the wrong type",
            vector(
                "jwe.decrypt",
                &input.replace(&format!(r#""{JWE_A3}""#), "7"),
                ok,
            ),
            "/input/jwe: must be a string (compact) or an object",
        ),
        (
            "decrypt understood_crit not strings",
            vector(
                "jwe.decrypt",
                &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, r#","understood_crit":[1]"#),
                ok,
            ),
            "/input/understood_crit: must be an array of strings",
        ),
        (
            "decrypt ok without recipient",
            vector("jwe.decrypt", &input, r#"{"ok":true,"plaintext_b64u":""}"#),
            "/expect/recipient: required member is missing",
        ),
        (
            "encrypt recipient with an unknown member",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input(
                    "compact",
                    &format!(r#"[{{"alg":"A128KW","key":{JWE_A3_KEY},"kid":"a"}}]"#),
                    "",
                ),
                &jwe_decrypt_with(),
            ),
            "/input/recipients/0/kid: unknown member",
        ),
        (
            "encrypt with no recipients",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("compact", "[]", ""),
                &jwe_decrypt_with(),
            ),
            "/input/recipients: must be a non-empty array",
        ),
        (
            "encrypt with an unknown serialization",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("json", &jwe_a3_recipient(), ""),
                &jwe_decrypt_with(),
            ),
            "/input/serialization: must be one of",
        ),
        (
            "encrypt expecting both forms",
            vector(
                "jwe.encrypt",
                &encrypt,
                &format!(
                    r#"{{"ok":true,"jwe":"a","decrypt_with":{{"key":{JWE_A3_KEY},{JWE_A3_POLICY}}}}}"#
                ),
            ),
            "matches none of the success forms",
        ),
        (
            "rng_b64u without its feature",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("compact", &jwe_a3_recipient(), r#","rng_b64u":"AA""#),
                r#"{"ok":true,"jwe":"x"}"#,
            ),
            "needs \"fixed-rng\" listed in `features`",
        ),
        (
            "protected_b64u with only another feature",
            with_features(
                &vector(
                    "jwe.encrypt",
                    &jwe_encrypt_input(
                        "compact",
                        &jwe_a3_recipient(),
                        r#","protected_b64u":"e30""#,
                    ),
                    r#"{"ok":true,"jwe":"x"}"#,
                ),
                r#"["deflate"]"#,
            ),
            "needs \"fixed-rng\"",
        ),
        (
            "compress without its feature",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("compact", &jwe_a3_recipient(), r#","compress":true"#),
                &jwe_decrypt_with(),
            ),
            "needs \"deflate\" listed in `features`",
        ),
        (
            "an unknown feature",
            with_features(&vector("jwe.decrypt", &input, ok), r#"["sha1"]"#),
            "/features/0: must be one of",
        ),
        (
            "a feature listed twice",
            with_features(
                &vector("jwe.decrypt", &input, ok),
                r#"["deflate","deflate"]"#,
            ),
            "/features/1: listed twice",
        ),
        (
            "features not an array",
            with_features(&vector("jwe.decrypt", &input, ok), r#""deflate""#),
            "/features: must be an array",
        ),
    ];
    for (what, json, needle) in &cases {
        fails_naming_source(&format!("schema ({what}).json"), json, needle);
    }
}

/// A `jwe.*` vector the library does not meet fails, naming the file and
/// the source; so does a round trip whose decryption fails.
#[test]
fn jwe_mismatches_fail() {
    let other_key = r#"{"kty":"oct","k":"BwcHBwcHBwcHBwcHBwcHBw"}"#;
    let cases = [
        (
            "wrong plaintext",
            vector(
                "jwe.decrypt",
                &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, ""),
                r#"{"ok":true,"plaintext_b64u":"AA","recipient":0}"#,
            ),
            "`plaintext_b64u`: expected",
        ),
        (
            "wrong error",
            vector(
                "jwe.decrypt",
                &jwe_decrypt_input(JWE_A3, other_key, ""),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            "expected error InvalidKey, got error DecryptionFailed",
        ),
        (
            "round trip with the wrong key",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("compact", &jwe_a3_recipient(), ""),
                &format!(r#"{{"ok":true,"decrypt_with":{{"key":{other_key},{JWE_A3_POLICY}}}}}"#),
            ),
            "does not decrypt with decrypt_with (DecryptionFailed)",
        ),
        (
            "round trip with a key that does not import",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("compact", &jwe_a3_recipient(), ""),
                &format!(
                    r#"{{"ok":true,"decrypt_with":{{"key":{{"kty":"oct"}},{JWE_A3_POLICY}}}}}"#
                ),
            ),
            "decrypt_with.key does not import",
        ),
        (
            "an exact expectation of a randomized encryption",
            vector(
                "jwe.encrypt",
                &jwe_encrypt_input("compact", &jwe_a3_recipient(), ""),
                &format!(r#"{{"ok":true,"jwe":"{JWE_A3}"}}"#),
            ),
            "`jwe`: expected",
        ),
    ];
    for (what, json, needle) in &cases {
        fails_naming_source(&format!("failing ({what}).json"), json, needle);
    }
}

/// The reproducible path (feature `insecure-test-vectors`): the A.3 output
/// exactly, and every injected byte must be drawn, so a vector pins the
/// draw order (CEK, recipients, IV).
#[cfg(feature = "insecure-test-vectors")]
#[test]
fn jwe_reproducible_vectors_pin_the_draw_order() {
    // A.3.2 CEK then A.3.4 IV.
    let rng = "BNMfxVSd_P4LZJ36P6pqzmt81C1vawnbyLEA8I-cLM8DFjwMK0NoaWxsaWNvdGhl";
    let protected = JWE_A3.split('.').next().unwrap();
    let exact = format!(r#"{{"ok":true,"jwe":"{JWE_A3}"}}"#);
    let input = |rng: &str| {
        jwe_encrypt_input(
            "compact",
            &jwe_a3_recipient(),
            &format!(r#","protected_b64u":"{protected}","rng_b64u":"{rng}""#),
        )
    };
    let features = r#"["fixed-rng"]"#;
    assert_passes(&[with_features(
        &vector("jwe.encrypt", &input(rng), &exact),
        features,
    )]);
    fails_naming_source(
        "leftover.json",
        &with_features(
            &vector("jwe.encrypt", &input(&format!("{rng}AAAA")), &exact),
            features,
        ),
        "byte(s) the encryption did not draw",
    );
    // IV before CEK: another output.
    let swapped = "AxY8DCtDaGlsbGljb3RoZQTTH8VUnfz-C2Sd-j-qas5rfNQtb2sJ28ixAPCPnCzP";
    fails_naming_source(
        "swapped.json",
        &with_features(&vector("jwe.encrypt", &input(swapped), &exact), features),
        "`jwe`: expected",
    );
}

/// A vector needing a feature the build lacks is reported SKIPPED with the
/// feature's name, is never counted as passing, and is still validated.
#[test]
fn vectors_needing_a_disabled_feature_are_skipped_by_name() {
    let needs = with_features(
        &vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, ""),
            r#"{"ok":false,"error":"InvalidKey"}"#,
        ),
        r#"["deflate","fixed-rng"]"#,
    );
    // Its expectation is wrong, but with the features off it does not run.
    match check_vector_with("needs.json", needs.as_bytes(), &[]) {
        Ok(Passed::Skipped { missing, present }) => {
            assert_eq!(missing, ["deflate", "fixed-rng"]);
            assert!(present.is_empty());
        }
        other => panic!("expected SKIPPED, got {other:?}"),
    }
    match check_vector_with("needs.json", needs.as_bytes(), &["fixed-rng"]) {
        Ok(Passed::Skipped { missing, .. }) => assert_eq!(missing, ["deflate"]),
        other => panic!("expected SKIPPED, got {other:?}"),
    }
    // With the features on, it runs, and fails.
    assert!(check_vector_with("needs.json", needs.as_bytes(), &feature_names()).is_err());
    // A schema-invalid vector fails even when it would be skipped.
    let invalid = needs.replace(r#""allowed_enc""#, r#""allowed_encs""#);
    assert!(check_vector_with("invalid.json", invalid.as_bytes(), &[]).is_err());

    let dir = TempDir::new("skip");
    dir.write("a/needs.json", &needs);
    dir.write(
        "a/runs.json",
        &vector(
            "b64url.encode",
            r#"{"bytes_hex":"66"}"#,
            r#"{"ok":true,"b64u":"Zg"}"#,
        ),
    );
    let report = run_dir_with(&dir.0, &[]);
    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(report.files, 2);
    assert_eq!(report.passed.values().sum::<usize>(), 1, "{report:?}");
    assert_eq!(report.passed.get("jwe.decrypt"), None, "{report:?}");
    assert_eq!(
        report.skipped,
        ["a/needs.json: SKIPPED (needs feature `deflate`, `insecure-test-vectors`)"]
    );
    assert_eq!(
        enabled_features().len(),
        usize::from(cfg!(feature = "deflate"))
            + usize::from(cfg!(feature = "insecure-test-vectors"))
    );
}

/// `features_absent` (ADR 0056): a vector that must run without a feature
/// the build enables is SKIPPED with `feature:!<name>`, after the missing
/// `features` names; it is never counted as passing, and it is still
/// validated.
#[test]
fn vectors_forbidding_an_enabled_feature_are_skipped_by_name() {
    let forbids = |absent: &str| {
        vector(
            "jwe.decrypt",
            &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, ""),
            r#"{"ok":false,"error":"InvalidKey"}"#,
        )
        .replacen(
            r#""operation""#,
            &format!(r#""features_absent":{absent},"operation""#),
            1,
        )
    };
    let both = forbids(r#"["deflate","fixed-rng"]"#);
    // Its expectation is wrong, but with the features on it does not run.
    match check_vector_with("forbids.json", both.as_bytes(), &feature_names()) {
        Ok(Passed::Skipped { missing, present }) => {
            assert!(missing.is_empty());
            assert_eq!(present, ["deflate", "fixed-rng"]);
        }
        other => panic!("expected SKIPPED, got {other:?}"),
    }
    match check_vector_with("forbids.json", both.as_bytes(), &["fixed-rng"]) {
        Ok(Passed::Skipped { present, .. }) => assert_eq!(present, ["fixed-rng"]),
        other => panic!("expected SKIPPED, got {other:?}"),
    }
    // With the features off, it runs, and fails.
    assert!(check_vector_with("forbids.json", both.as_bytes(), &[]).is_err());
    // A schema-invalid vector fails even when it would be skipped.
    let invalid = both.replace(r#""allowed_enc""#, r#""allowed_encs""#);
    assert!(check_vector_with("invalid.json", invalid.as_bytes(), &feature_names()).is_err());

    // Needed and forbidden at once: the missing names first (ADR 0056 §2).
    let mixed = with_features(&forbids(r#"["deflate"]"#), r#"["fixed-rng"]"#);
    let dir = TempDir::new("skip-absent");
    dir.write("a/forbids.json", &forbids(r#"["deflate","fixed-rng"]"#));
    dir.write("a/mixed.json", &mixed);
    dir.write(
        "a/runs.json",
        &vector(
            "b64url.encode",
            r#"{"bytes_hex":"66"}"#,
            r#"{"ok":true,"b64u":"Zg"}"#,
        ),
    );
    let report = run_dir_with(&dir.0, &["deflate"]);
    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(report.passed.values().sum::<usize>(), 1, "{report:?}");
    assert_eq!(
        report.skipped,
        [
            "a/forbids.json: SKIPPED (needs feature `deflate` off)",
            "a/mixed.json: SKIPPED (needs feature `insecure-test-vectors`; needs feature `deflate` off)",
        ]
    );
    let reasons: Vec<Option<&str>> = report
        .results
        .iter()
        .map(|entry| entry.get("reason").and_then(Value::as_str))
        .collect();
    assert_eq!(
        reasons,
        [
            Some("feature:!deflate"),
            Some("feature:fixed-rng,!deflate"),
            None
        ]
    );
    for entry in &report.results[..2] {
        assert_eq!(entry.get("status").and_then(Value::as_str), Some("skipped"));
        assert!(entry.get("actual").is_none(), "{entry:?}");
    }
}

/// The schema rules of `features_absent` (ADR 0056 §1, §3, §4): known
/// names, each once, at least one, none also in `features`; and a
/// `compress` vector may list `deflate` in either.
#[test]
fn features_absent_is_strict() {
    let input = jwe_decrypt_input(JWE_A3, JWE_A3_KEY, "");
    let ok = &format!(r#"{{"ok":true,"plaintext_b64u":"{JWE_A3_PLAINTEXT_B64U}","recipient":0}}"#);
    let absent = |vector: &str, list: &str| {
        vector.replacen(
            r#""operation""#,
            &format!(r#""features_absent":{list},"operation""#),
            1,
        )
    };
    let decrypt = vector("jwe.decrypt", &input, ok);
    for (what, json, needle) in [
        (
            "an unknown name",
            absent(&decrypt, r#"["sha1"]"#),
            "/features_absent/0: must be one of",
        ),
        (
            "a name listed twice",
            absent(&decrypt, r#"["deflate","deflate"]"#),
            "/features_absent/1: listed twice",
        ),
        (
            "an empty list",
            absent(&decrypt, "[]"),
            "/features_absent: must not be empty",
        ),
        (
            "not an array",
            absent(&decrypt, r#""deflate""#),
            "/features_absent: must be an array",
        ),
        (
            "a name in both lists",
            absent(&with_features(&decrypt, r#"["deflate"]"#), r#"["deflate"]"#),
            "/features_absent: \"deflate\" is listed in `features` too",
        ),
        (
            "a misspelled member",
            decrypt.replacen(
                r#""operation""#,
                r#""feature_absent":["deflate"],"operation""#,
                1,
            ),
            "/feature_absent: unknown member",
        ),
        (
            "compress with only fixed-rng absent",
            absent(
                &vector(
                    "jwe.encrypt",
                    &jwe_encrypt_input("compact", &jwe_a3_recipient(), r#","compress":true"#),
                    r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
                ),
                r#"["fixed-rng"]"#,
            ),
            "needs \"deflate\" listed in `features` or `features_absent`",
        ),
    ] {
        fails_naming_source(&format!("schema ({what}).json"), &json, needle);
    }
    // `compress` with `deflate` absent: UnsupportedAlgorithm without the
    // codec (ADR 0017 §5, ADR 0030 §4), skipped where it is built in.
    let compress = absent(
        &vector(
            "jwe.encrypt",
            &jwe_encrypt_input("compact", &jwe_a3_recipient(), r#","compress":true"#),
            r#"{"ok":false,"error":"UnsupportedAlgorithm"}"#,
        ),
        r#"["deflate"]"#,
    );
    match (
        check_vector("compress.json", compress.as_bytes()),
        cfg!(feature = "deflate"),
    ) {
        (Ok(Passed::Skipped { present, .. }), true) => assert_eq!(present, ["deflate"]),
        (Ok(Passed::Ran { negative: true, .. }), false) => {}
        (other, deflate) => panic!("with deflate {deflate}: {other:?}"),
    }
}

/// Every JWE vector is binding-ready (see [`binding_ready`]): the bindings
/// run the `jwe.*` vectors too (features 0006-0009), except those needing
/// `insecure-test-vectors`, which no binding enables (ADR 0005).
#[test]
fn jwe_vectors_are_binding_ready() {
    let dir = conformance_dir().join("vectors");
    let (mut files, mut failures) = (Vec::new(), Vec::new());
    collect(&dir, &mut files, &mut failures);
    let mut checked = 0;
    for path in files {
        let relative = path.strip_prefix(&dir).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        let is_jwe = relative
            .components()
            .next()
            .is_some_and(|c| c.as_os_str() == "jwe")
            || json::parse(text.as_bytes()).is_ok_and(|v| {
                v.get("operation")
                    .and_then(Value::as_str)
                    .is_some_and(|op| op.starts_with("jwe."))
            });
        if !is_jwe {
            continue;
        }
        checked += 1;
        if let Err(problem) = binding_ready(&text) {
            failures.push(format!("{}: {problem}", slash_path(relative)));
        }
    }
    assert!(
        failures.is_empty(),
        "not binding-ready:\n  {}",
        failures.join("\n  ")
    );
    assert!(checked >= 60, "only {checked} JWE vector files found");
}

// ---------------------------------------------------------------------------
// jwt.* self-tests (0004 T10), on the RFC 7519 §3.1 JWT (= RFC 7515 A.1) and
// the RFC 7515 A.3 ES256 JWS over the same claims. The vector files under
// conformance/vectors/jwt/ cite them.
// ---------------------------------------------------------------------------

/// The RFC 7519 §3.1 Claims Set, as the library returns it.
const JWT_CLAIMS: &str = r#"{"iss":"joe","exp":1300819380,"http://example.com/is_root":true}"#;
/// RFC 7519 §3.1's `iat`-free example is valid 60 s before its `exp`.
const JWT_NOW: &str = "1300819320";

/// RFC 7515 A.3, an ES256 JWS (no `typ`) over the §3.1 claims.
fn a3_compact() -> String {
    format!("{A3_PROTECTED}.{PAYLOAD}.{A3_SIGNATURE}")
}

/// A `jwt.validate` input: `token`, `now` [`JWT_NOW`], `allowed_algs`, the
/// key source `keys` (`"key":{...}` or `"jwks":{...}`) and `extra` members
/// (each with a leading comma).
fn jwt_validate_input(token: &str, algs: &str, keys: &str, extra: &str) -> String {
    format!(
        r#"{{"token":{},"now":{JWT_NOW},"allowed_algs":{algs},{keys}{extra}}}"#,
        quoted(token)
    )
}

/// The §3.1 JWT with its HS256 key and `extra` input members.
fn jwt_hs256(extra: &str) -> String {
    jwt_validate_input(
        &a1_compact(),
        r#"["HS256"]"#,
        &format!(r#""key":{A1_KEY}"#),
        extra,
    )
}

/// A `jwt.validate` success with the §3.1 claims, `alg` and `extra`
/// expectation members.
fn jwt_validated(alg: &str, extra: &str) -> String {
    format!(r#"{{"ok":true,"claims":{JWT_CLAIMS},"alg":"{alg}"{extra}}}"#)
}

fn failure(code: &str) -> String {
    format!(r#"{{"ok":false,"error":"{code}"}}"#)
}

/// Every `jwt.validate` input form runs, through `key` and `jwks`, and
/// every policy member reaches the library: each case below differs from
/// the passing §3.1 one by that member alone, so its outcome proves it.
#[test]
fn jwt_validate_vectors_pass() {
    let ok = jwt_validated("HS256", "");
    let jwks = format!(r#""jwks":{{"keys":[{OTHER_P256},{A3_PUBLIC}]}}"#);
    let cases = [
        vector("jwt.validate", &jwt_hs256(""), &ok),
        // Claims compare as JSON: member order and number spelling aside.
        vector(
            "jwt.validate",
            &jwt_hs256(""),
            r#"{"ok":true,"alg":"HS256","claims":{"http://example.com/is_root":true,"exp":1300819380.0,"iss":"joe"}}"#,
        ),
        // `now` is the only clock: at the expiry instant with no leeway the
        // token is expired, and before it, it is not.
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"leeway":0}"#).replace(JWT_NOW, "1300819380"),
            &failure("TokenExpired"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"leeway":0}"#).replace(JWT_NOW, "1300819379"),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256("").replace(JWT_NOW, "-9007199254740991"),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256("").replace(r#"["HS256"]"#, r#"["HS384"]"#),
            &failure("AlgorithmNotAllowed"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256("").replace(r#"["HS256"]"#, "[]"),
            &failure("AlgorithmNotAllowed"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256("").replace(r#"["HS256"]"#, r#"["none"]"#),
            &failure("AlgorithmNotAllowed"),
        ),
        // issuer: a string or a list (RFC 7519 §4.1.1).
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"issuer":"joe"}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"issuer":["bob","joe"]}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"issuer":"bob"}"#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"issuer":[]}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"audience":["joe"]}"#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"subject":"joe"}"#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"leeway":601}"#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"max_age":300}"#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"require":["iss","jti"]}"#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"require":[]}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"allow_missing_exp":true,"ignore_audience":true}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"allow_missing_exp":false,"ignore_audience":false}"#),
            &ok,
        ),
        // typ: the §3.1 header says JWT (RFC 7519 §5.1).
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"typ":{"mode":"default"}}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"typ":{"mode":"exact","value":"application/JWT"}}"#),
            &ok,
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"typ":{"mode":"exact","value":"at+jwt"}}"#),
            &failure("InvalidHeader"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"typ":{"mode":"any"}}"#),
            &ok,
        ),
        // RFC 9068 §4: typ JWT is not at+jwt, checked before any claim.
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"profile":"access_token","issuer":"joe","audience":["api"]}"#),
            &failure("InvalidHeader"),
        ),
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"profile":"access_token","audience":["api"]}"#),
            &failure("InvalidClaim"),
        ),
        // profile, then a typ mode that overrides its at+jwt.
        vector(
            "jwt.validate",
            &jwt_hs256(
                r#","policy":{"profile":"access_token","issuer":"joe","audience":["api"],"typ":{"mode":"any"}}"#,
            ),
            &failure("InvalidClaim"),
        ),
        // jwks (ADR 0029): the kid-less A.3 token tries member 0, then
        // verifies with member 1.
        vector(
            "jwt.validate",
            &jwt_validate_input(&a3_compact(), r#"["ES256"]"#, &jwks, ""),
            &jwt_validated("ES256", r#","key_index":1"#),
        ),
        vector(
            "jwt.validate",
            &jwt_validate_input(
                &a3_compact(),
                r#"["ES256"]"#,
                &jwks,
                r#","policy":{"max_key_candidates":1}"#,
            ),
            &failure("NoMatchingKey"),
        ),
        // A JWK or JWK Set import error is the outcome.
        vector(
            "jwt.validate",
            &jwt_validate_input(
                &a1_compact(),
                r#"["HS256"]"#,
                r#""key":{"kty":"oct","k":"Zg=="}"#,
                "",
            ),
            &failure("InvalidBase64"),
        ),
        vector(
            "jwt.validate",
            &jwt_validate_input(&a1_compact(), r#"["HS256"]"#, r#""jwks":{"keys":"x"}"#, ""),
            &failure("InvalidKey"),
        ),
        // An invalid member is skipped at import (RFC 7517 §5), so the set
        // has no candidate left: NoMatchingKey (ADR 0029 §4).
        vector(
            "jwt.validate",
            &jwt_validate_input(
                &a1_compact(),
                r#"["HS256"]"#,
                r#""jwks":{"keys":[{"kty":"oct","k":"Zg=="}]}"#,
                "",
            ),
            &failure("NoMatchingKey"),
        ),
    ];
    assert_passes(&cases);
}

/// The step order of conformance/README.md: `decrypt.key`, then
/// `decrypt`'s lists, then `key` or `jwks`, then the policy, the first
/// error being the outcome. Each case breaks two steps with different
/// codes and expects the earlier one, so none depends on the library's own
/// JWE or JWT processing order.
#[test]
fn jwt_validate_runs_its_steps_in_order() {
    let broken_set = r#""jwks":{"keys":"x"}"#; // InvalidKey
    let decrypt = |key: &str, enc: &str| {
        format!(r#","decrypt":{{"key":{key},"allowed_algs":["A128KW"],"allowed_enc":{enc}}}"#)
    };
    let cases = [
        // decrypt.key (InvalidBase64) before jwks (InvalidKey).
        vector(
            "jwt.validate",
            &jwt_validate_input(
                &a1_compact(),
                r#"["HS256"]"#,
                broken_set,
                &decrypt(r#"{"kty":"oct","k":"Zg=="}"#, r#"["A128GCM"]"#),
            ),
            &failure("InvalidBase64"),
        ),
        // decrypt.key (InvalidBase64) before decrypt's lists
        // (AlgorithmNotAllowed).
        vector(
            "jwt.validate",
            &jwt_hs256(&decrypt(r#"{"kty":"oct","k":"Zg=="}"#, "[]")),
            &failure("InvalidBase64"),
        ),
        // decrypt's lists (AlgorithmNotAllowed) before jwks (InvalidKey).
        vector(
            "jwt.validate",
            &jwt_validate_input(
                &a1_compact(),
                r#"["HS256"]"#,
                broken_set,
                &decrypt(JWE_A3_KEY, "[]"),
            ),
            &failure("AlgorithmNotAllowed"),
        ),
        // jwks (InvalidKey) before the policy (InvalidClaim, leeway).
        vector(
            "jwt.validate",
            &jwt_validate_input(
                &a1_compact(),
                r#"["HS256"]"#,
                broken_set,
                r#","policy":{"leeway":601}"#,
            ),
            &failure("InvalidKey"),
        ),
        // The allow-list (AlgorithmNotAllowed) before the leeway
        // (InvalidClaim): both are the policy's, built in that order.
        vector(
            "jwt.validate",
            &jwt_hs256(r#","policy":{"leeway":601}"#).replace(r#"["HS256"]"#, "[]"),
            &failure("AlgorithmNotAllowed"),
        ),
    ];
    assert_passes(&cases);
}

/// The runner's strictness (criterion 2): a misspelled member, a missing
/// `now`, both `key` and `jwks`, and every other way of breaking the
/// `jwt.validate` schema fail the run, naming the member.
#[test]
fn jwt_validate_schema_violations_fail() {
    let ok = jwt_validated("HS256", "");
    let with_policy = |policy: &str| jwt_hs256(&format!(r#","policy":{policy}"#));
    let decrypt = r#","decrypt":{"key":{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"},"allowed_algs":["A128KW"],"allowed_enc":["A128GCM"]}"#;
    let cases: &[(&str, String, &str)] = &[
        (
            "misspelled allowed_algs",
            jwt_hs256("").replace(r#""allowed_algs""#, r#""allowed_alg""#),
            "/input/allowed_alg: unknown member",
        ),
        (
            "missing now",
            jwt_hs256("").replace(&format!(r#""now":{JWT_NOW},"#), ""),
            "/input/now: required member is missing",
        ),
        (
            "missing token",
            jwt_hs256("").replace(&format!(r#""token":"{}","#, a1_compact()), ""),
            "/input/token: required member is missing",
        ),
        (
            "missing allowed_algs",
            jwt_hs256("").replace(r#""allowed_algs":["HS256"],"#, ""),
            "/input/allowed_algs: required member is missing",
        ),
        (
            "both key and jwks",
            jwt_hs256(&format!(r#","jwks":{{"keys":[{A1_KEY}]}}"#)),
            "/input: needs exactly one of `key`, `jwks` (oneOf), has 2",
        ),
        (
            "neither key nor jwks",
            jwt_validate_input(&a1_compact(), r#"["HS256"]"#, r#""policy":{}"#, ""),
            "/input: needs exactly one of `key`, `jwks` (oneOf), has 0",
        ),
        (
            "now as a string",
            jwt_hs256("").replace(JWT_NOW, &quoted(JWT_NOW)),
            "/input/now",
        ),
        (
            "fractional now",
            jwt_hs256("").replace(JWT_NOW, "1300819320.5"),
            "/input/now",
        ),
        (
            "now above 2^53 - 1",
            jwt_hs256("").replace(JWT_NOW, "9007199254740992"),
            "/input/now",
        ),
        (
            "now below -(2^53 - 1)",
            jwt_hs256("").replace(JWT_NOW, "-9007199254740992"),
            "/input/now",
        ),
        (
            "token not a string",
            jwt_hs256("").replace(&quoted(&a1_compact()), "[]"),
            "/input/token",
        ),
        (
            "key not an object",
            jwt_hs256("").replace(A1_KEY, &quoted("k")),
            "/input/key",
        ),
        (
            "jwks not an object",
            jwt_validate_input(&a1_compact(), r#"["HS256"]"#, r#""jwks":[]"#, ""),
            "/input/jwks",
        ),
        (
            "misspelled policy member",
            with_policy(r#"{"audiences":["joe"]}"#),
            "/input/policy/audiences: unknown member",
        ),
        ("policy not an object", with_policy("[]"), "/input/policy"),
        (
            "issuer a number",
            with_policy(r#"{"issuer":7}"#),
            "/input/policy/issuer",
        ),
        (
            "issuer list with a number",
            with_policy(r#"{"issuer":["joe",7]}"#),
            "/input/policy/issuer",
        ),
        (
            "audience a string",
            with_policy(r#"{"audience":"joe"}"#),
            "/input/policy/audience",
        ),
        (
            "negative leeway",
            with_policy(r#"{"leeway":-1}"#),
            "/input/policy/leeway",
        ),
        (
            "max_age a string",
            with_policy(r#"{"max_age":"300"}"#),
            "/input/policy/max_age",
        ),
        (
            "require a string",
            with_policy(r#"{"require":"jti"}"#),
            "/input/policy/require",
        ),
        (
            "allow_missing_exp a string",
            with_policy(r#"{"allow_missing_exp":"true"}"#),
            "/input/policy/allow_missing_exp",
        ),
        (
            "unknown profile",
            with_policy(r#"{"profile":"id_token"}"#),
            "/input/policy/profile",
        ),
        (
            "typ a string",
            with_policy(r#"{"typ":"JWT"}"#),
            "/input/policy/typ",
        ),
        (
            "unknown typ mode",
            with_policy(r#"{"typ":{"mode":"strict"}}"#),
            "/input/policy/typ/mode",
        ),
        (
            "typ without a mode",
            with_policy(r#"{"typ":{"value":"JWT"}}"#),
            "/input/policy/typ/mode: required member is missing",
        ),
        (
            "exact typ without a value",
            with_policy(r#"{"typ":{"mode":"exact"}}"#),
            "/input/policy/typ/value: required when `mode` is \"exact\"",
        ),
        (
            "a value with typ mode any",
            with_policy(r#"{"typ":{"mode":"any","value":"JWT"}}"#),
            "/input/policy/typ/value: allowed only when `mode` is \"exact\"",
        ),
        (
            "unknown typ member",
            with_policy(r#"{"typ":{"mode":"any","strict":true}}"#),
            "/input/policy/typ/strict: unknown member",
        ),
        (
            "max_key_candidates negative",
            with_policy(r#"{"max_key_candidates":-1}"#),
            "/input/policy/max_key_candidates",
        ),
        (
            "decrypt without allowed_enc",
            jwt_hs256(&decrypt.replace(r#","allowed_enc":["A128GCM"]"#, "")),
            "/input/decrypt/allowed_enc: required member is missing",
        ),
        (
            "misspelled decrypt member",
            jwt_hs256(&decrypt.replace(r#"["A128GCM"]}"#, r#"["A128GCM"],"max_p2c":1}"#)),
            "/input/decrypt/max_p2c: unknown member",
        ),
        (
            "decrypt key not an object",
            jwt_hs256(&decrypt.replace(r#"{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"}"#, "\"k\"")),
            "/input/decrypt/key",
        ),
    ];
    for (what, input, needle) in cases {
        let json = vector("jwt.validate", input, &ok);
        fails_naming_source(&format!("invalid ({what}).json"), &json, needle);
    }
    let input = jwt_hs256("");
    let expectations: &[(&str, String, &str)] = &[
        (
            "success without claims",
            r#"{"ok":true,"alg":"HS256"}"#.to_owned(),
            "/expect/claims: required member is missing",
        ),
        (
            "success without alg",
            format!(r#"{{"ok":true,"claims":{JWT_CLAIMS}}}"#),
            "/expect/alg: required member is missing",
        ),
        (
            "claims not an object",
            r#"{"ok":true,"claims":[],"alg":"HS256"}"#.to_owned(),
            "/expect/claims",
        ),
        (
            "key_index a string",
            jwt_validated("HS256", r#","key_index":"0""#),
            "/expect/key_index",
        ),
        (
            "unknown success member",
            jwt_validated("HS256", r#","kid":"a""#),
            "/expect/kid: unknown member",
        ),
        (
            "failure with claims",
            format!(r#"{{"ok":false,"error":"TokenExpired","claims":{JWT_CLAIMS}}}"#),
            "/expect/claims: unknown member",
        ),
        ("unknown error code", failure("Expired"), "/expect/error"),
    ];
    for (what, expect, needle) in expectations {
        let json = vector("jwt.validate", &input, expect);
        fails_naming_source(&format!("invalid ({what}).json"), &json, needle);
    }
}

/// A `jwt.validate` vector whose expectation the library does not meet
/// fails, naming what differs; `key_index` is compared both ways.
#[test]
fn jwt_validate_mismatches_fail() {
    let jwks = format!(r#""jwks":{{"keys":[{OTHER_P256},{A3_PUBLIC}]}}"#);
    let via_set = jwt_validate_input(&a3_compact(), r#"["ES256"]"#, &jwks, "");
    let cases = [
        (
            "wrong claims",
            vector(
                "jwt.validate",
                &jwt_hs256(""),
                &jwt_validated("HS256", "").replace("1300819380", "1300819381"),
            ),
            "`claims`: expected",
        ),
        (
            "an extra claim",
            vector(
                "jwt.validate",
                &jwt_hs256(""),
                &jwt_validated("HS256", "").replace(r#""iss":"joe""#, r#""iss":"joe","sub":"x""#),
            ),
            "`claims`: expected",
        ),
        (
            "wrong alg",
            vector("jwt.validate", &jwt_hs256(""), &jwt_validated("HS384", "")),
            "`alg`: expected \"HS384\"",
        ),
        (
            "key_index left out for a jwks",
            vector("jwt.validate", &via_set, &jwt_validated("ES256", "")),
            "`key_index`: expected nothing, got 1",
        ),
        (
            "wrong key_index",
            vector(
                "jwt.validate",
                &via_set,
                &jwt_validated("ES256", r#","key_index":0"#),
            ),
            "`key_index`: expected 0, got 1",
        ),
        (
            "key_index for a single key",
            vector(
                "jwt.validate",
                &jwt_hs256(""),
                &jwt_validated("HS256", r#","key_index":0"#),
            ),
            "`key_index`: expected 0, got nothing",
        ),
        (
            "expected success, but expired",
            vector(
                "jwt.validate",
                &jwt_hs256("").replace(JWT_NOW, "1300819440"),
                &jwt_validated("HS256", ""),
            ),
            "expected success, got error TokenExpired",
        ),
        (
            "wrong error code",
            vector(
                "jwt.validate",
                &jwt_hs256("").replace(JWT_NOW, "1300819440"),
                &failure("InvalidClaim"),
            ),
            "expected error InvalidClaim, got error TokenExpired",
        ),
        (
            "expected an error, but valid",
            vector("jwt.validate", &jwt_hs256(""), &failure("TokenExpired")),
            "succeeded",
        ),
        (
            "profile with typ mode default",
            vector(
                "jwt.validate",
                &jwt_hs256(
                    r#","policy":{"profile":"access_token","issuer":"joe","audience":["a"],"typ":{"mode":"default"}}"#,
                ),
                &failure("InvalidHeader"),
            ),
            "contradicts `policy/profile`",
        ),
    ];
    for (what, json, needle) in cases {
        fails_naming_source(&format!("failing ({what}).json"), &json, needle);
    }
}

/// The §3.1 claims issued with HS256 and `extra` input members.
fn jwt_issue_input(alg: &str, key: &str, extra: &str) -> String {
    format!(r#"{{"claims":{JWT_CLAIMS},"alg":"{alg}","key":{key}{extra}}}"#)
}

/// A `validate` member checking the issued token with `key`.
fn jwt_issue_validate(algs: &str, key: &str, extra: &str) -> String {
    format!(r#","validate":{{"now":{JWT_NOW},"allowed_algs":{algs},"key":{key}{extra}}}"#)
}

/// The exact HS256 token of the §3.1 claims with `{"alg":"HS256",
/// "typ":"JWT"}`, as conformance/vectors/jwt/rfc7519/3-1-hs256-issue-exact.json
/// derives it independently.
const JWT_ISSUED_HS256: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.d6nMDXnJZfNNj-1o1e75s6d0six0lkLp5hSrGaz4o9A";

/// Every `jwt.issue` input and expectation form runs: exact, validated
/// round trips (with `typ` set, defaulted and omitted, ES256 randomized),
/// and the import, claims and signing errors.
#[test]
fn jwt_issue_vectors_pass() {
    let hs = |extra: &str| jwt_issue_input("HS256", A1_KEY, extra);
    let hs_validate = |extra: &str| jwt_issue_validate(r#"["HS256"]"#, A1_KEY, extra);
    let exact = format!(r#"{{"ok":true,"token":"{JWT_ISSUED_HS256}"}}"#);
    let validated = r#"{"ok":true}"#;
    let cases = [
        vector("jwt.issue", &hs(""), &exact),
        // An exact token with `validate` is also validated.
        vector("jwt.issue", &hs(&hs_validate("")), &exact),
        vector("jwt.issue", &hs(&hs_validate("")), validated),
        // typ null omits it (RFC 7519 §5.1), and the default mode accepts
        // that; an explicit typ needs the matching mode (RFC 8725 §3.11).
        vector(
            "jwt.issue",
            &hs(&format!(r#","typ":null{}"#, hs_validate(""))),
            validated,
        ),
        vector(
            "jwt.issue",
            &hs(&format!(
                r#","typ":"secevent+jwt"{}"#,
                hs_validate(r#","policy":{"typ":{"mode":"exact","value":"secevent+jwt"}}"#)
            )),
            validated,
        ),
        // ECDSA is randomized: only a round trip can check it.
        vector(
            "jwt.issue",
            &jwt_issue_input(
                "ES256",
                A3_PRIVATE,
                &jwt_issue_validate(r#"["ES256"]"#, A3_PUBLIC, ""),
            ),
            validated,
        ),
        // Validation through a JWK Set.
        vector(
            "jwt.issue",
            &jwt_issue_input(
                "ES256",
                A3_PRIVATE,
                &format!(
                    r#","validate":{{"now":{JWT_NOW},"allowed_algs":["ES256"],"jwks":{{"keys":[{OTHER_P256},{A3_PUBLIC}]}}}}"#
                ),
            ),
            validated,
        ),
        // Errors, in step order: key import, claims, signing.
        vector(
            "jwt.issue",
            &jwt_issue_input("HS256", r#"{"kty":"oct","k":"Zg=="}"#, ""),
            &failure("InvalidBase64"),
        ),
        vector(
            "jwt.issue",
            &hs("").replace(r#""exp":1300819380"#, r#""exp":"1300819380""#),
            &failure("InvalidClaim"),
        ),
        vector(
            "jwt.issue",
            &jwt_issue_input("none", A1_KEY, ""),
            &failure("AlgorithmNotAllowed"),
        ),
        vector(
            "jwt.issue",
            &jwt_issue_input("HS257", A1_KEY, ""),
            &failure("UnsupportedAlgorithm"),
        ),
        vector(
            "jwt.issue",
            &jwt_issue_input("ES384", A3_PRIVATE, ""),
            &failure("KeyAlgorithmMismatch"),
        ),
        // An `encrypt.key` import error is the outcome, before signing.
        vector(
            "jwt.issue",
            &jwt_issue_input(
                "none",
                A1_KEY,
                r#","encrypt":{"alg":"A128KW","enc":"A128GCM","key":{"kty":"oct","k":"Zg=="}}"#,
            ),
            &failure("InvalidBase64"),
        ),
    ];
    assert_passes(&cases);
}

/// The `jwt.issue` schema and its cross-member rules fail the run, naming
/// the member.
#[test]
fn jwt_issue_schema_violations_fail() {
    let exact = format!(r#"{{"ok":true,"token":"{JWT_ISSUED_HS256}"}}"#);
    let validated = r#"{"ok":true}"#.to_owned();
    let validate = jwt_issue_validate(r#"["HS256"]"#, A1_KEY, "");
    let encrypt = r#","encrypt":{"alg":"A128KW","enc":"A128GCM","key":{"kty":"oct","k":"GawgguFyGrWKav7AX4VKUg"}}"#;
    let hs = |extra: &str| jwt_issue_input("HS256", A1_KEY, extra);
    let cases: &[(&str, String, String, &str)] = &[
        (
            "misspelled member",
            hs("").replace(r#""claims""#, r#""claim""#),
            exact.clone(),
            "/input/claim: unknown member",
        ),
        (
            "missing alg",
            hs("").replace(r#""alg":"HS256","#, ""),
            exact.clone(),
            "/input/alg: required member is missing",
        ),
        (
            "claims not an object",
            hs("").replace(JWT_CLAIMS, "[]"),
            exact.clone(),
            "/input/claims",
        ),
        (
            "typ a number",
            hs(r#","typ":1"#),
            exact.clone(),
            "/input/typ",
        ),
        (
            "encrypt without enc",
            hs(&encrypt.replace(r#""enc":"A128GCM","#, "")),
            validated.clone(),
            "/input/encrypt/enc: required member is missing",
        ),
        (
            "validate with a token",
            hs(&validate.replace(r#""now""#, r#""token":"a.b.c","now""#)),
            validated.clone(),
            "/input/validate/token: unknown member",
        ),
        (
            "validate without now",
            hs(&validate.replace(&format!(r#""now":{JWT_NOW},"#), "")),
            validated.clone(),
            "/input/validate/now: required member is missing",
        ),
        (
            "validate with both key and jwks",
            hs(&validate.replace(r#""key""#, r#""jwks":{"keys":[]},"key""#)),
            validated.clone(),
            "/input/validate: needs exactly one of `key`, `jwks` (oneOf), has 2",
        ),
        (
            "validate with a misspelled policy member",
            hs(&jwt_issue_validate(
                r#"["HS256"]"#,
                A1_KEY,
                r#","policy":{"leway":0}"#,
            )),
            validated.clone(),
            "/input/validate/policy/leway: unknown member",
        ),
        (
            "an exact token with encrypt",
            hs(encrypt),
            exact.clone(),
            "/expect/token: an encrypted token is randomized",
        ),
        (
            "validated without validate or encrypt",
            hs(""),
            validated.clone(),
            "/input/validate: required when the expectation has no `token`",
        ),
        (
            "a failure with validate",
            hs(&validate),
            failure("AlgorithmNotAllowed"),
            "/input/validate: used only when the issue succeeds",
        ),
        (
            "token not a string",
            hs(""),
            r#"{"ok":true,"token":7}"#.to_owned(),
            "/expect",
        ),
        (
            "an unknown success member",
            hs(""),
            format!(r#"{{"ok":true,"token":"{JWT_ISSUED_HS256}","kid":"a"}}"#),
            "/expect",
        ),
    ];
    for (what, input, expect, needle) in cases {
        let json = vector("jwt.issue", input, expect);
        fails_naming_source(&format!("invalid ({what}).json"), &json, needle);
    }
}

/// A `jwt.issue` vector whose expectation the library does not meet fails:
/// a wrong exact token, and every way a round trip can fail.
#[test]
fn jwt_issue_mismatches_fail() {
    let hs = |extra: &str| jwt_issue_input("HS256", A1_KEY, extra);
    let validated = r#"{"ok":true}"#;
    let cases = [
        (
            "wrong exact token",
            vector(
                "jwt.issue",
                &hs(""),
                &format!(r#"{{"ok":true,"token":"{}"}}"#, a1_compact()),
            ),
            "`token`: expected",
        ),
        (
            "round trip with the wrong key",
            vector(
                "jwt.issue",
                // RFC 7515 A.1's key with its first octets changed.
                &hs(&jwt_issue_validate(
                    r#"["HS256"]"#,
                    &A1_KEY.replace("AyM1", "ByM1"),
                    "",
                )),
                validated,
            ),
            "round trip: the issued token does not validate with `validate` (InvalidSignature)",
        ),
        (
            "round trip after expiry",
            vector(
                "jwt.issue",
                &hs(&jwt_issue_validate(r#"["HS256"]"#, A1_KEY, "").replace(JWT_NOW, "1300819440")),
                validated,
            ),
            "(TokenExpired)",
        ),
        (
            "round trip with a refused policy",
            vector(
                "jwt.issue",
                &hs(&jwt_issue_validate(
                    r#"["HS256"]"#,
                    A1_KEY,
                    r#","policy":{"leeway":601}"#,
                )),
                validated,
            ),
            "round trip: `validate/policy` is refused (InvalidClaim)",
        ),
        (
            "round trip with a key that does not import",
            vector(
                "jwt.issue",
                &hs(&jwt_issue_validate(
                    r#"["HS256"]"#,
                    r#"{"kty":"oct","k":"Zg=="}"#,
                    "",
                )),
                validated,
            ),
            "round trip: `validate` does not import (InvalidBase64)",
        ),
        (
            "round trip with typ omitted but exact typ required",
            vector(
                "jwt.issue",
                &hs(&format!(
                    r#","typ":null{}"#,
                    jwt_issue_validate(
                        r#"["HS256"]"#,
                        A1_KEY,
                        r#","policy":{"typ":{"mode":"exact","value":"JWT"}}"#
                    )
                )),
                validated,
            ),
            "(InvalidHeader)",
        ),
        (
            "expected an error, but issued",
            vector("jwt.issue", &hs(""), &failure("UnsupportedAlgorithm")),
            "succeeded",
        ),
    ];
    for (what, json, needle) in cases {
        fails_naming_source(&format!("failing ({what}).json"), &json, needle);
    }
}

/// The JWT vectors the binding-readiness rule covers: everything under
/// `jwt/`, and any `jwt.*` vector elsewhere.
fn needs_jwt_binding_readiness(relative: &Path, text: &str) -> bool {
    let jwt_dir = relative
        .components()
        .next()
        .is_some_and(|c| c.as_os_str() == "jwt");
    let jwt_operation = parse_vector_file(text.as_bytes()).is_ok_and(|v| {
        v.get("operation")
            .and_then(Value::as_str)
            .is_some_and(|op| op.starts_with("jwt."))
    });
    jwt_dir || jwt_operation
}

/// Criterion 4: every JWT vector is binding-ready (see
/// [`binding_ready_with`] and [`Numbers::Safe`]): no integer outside
/// ±(2^53 − 1) in the vector JSON itself. Out-of-range values under test
/// live inside base64url token payloads, never in the JSON.
#[test]
fn jwt_vectors_are_binding_ready() {
    let dir = conformance_dir().join("vectors");
    let (mut files, mut failures) = (Vec::new(), Vec::new());
    collect(&dir, &mut files, &mut failures);
    let mut checked = 0;
    for path in files {
        let relative = path.strip_prefix(&dir).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        if !needs_jwt_binding_readiness(relative, &text) {
            continue;
        }
        checked += 1;
        if let Err(problem) = binding_ready_with(&text, Numbers::Safe) {
            failures.push(format!("{}: {problem}", slash_path(relative)));
        }
    }
    assert!(
        failures.is_empty(),
        "not binding-ready:\n  {}",
        failures.join("\n  ")
    );
    assert!(checked >= 12, "only {checked} JWT vector files found");
}

/// The JWT readiness rule accepts every number a binding reads exactly,
/// and nothing else; the vector selection is `jwt/` and `jwt.*`.
#[test]
fn jwt_binding_readiness_check_works() {
    for ok in [
        r#"{"now":1300819320,"exp":-100,"n":0}"#,
        r#"{"now":9007199254740991,"then":-9007199254740991}"#,
        // A fractional NumericDate (RFC 7519 §2) in expected claims.
        r#"{"claims":{"exp":1300819380.5,"nbf":-0.25}}"#,
        r#"{"typ":null,"ok":true,"s":"9007199254740993 inside a string"}"#,
    ] {
        assert_eq!(binding_ready_with(ok, Numbers::Safe), Ok(()), "{ok}");
    }
    for (bad, needle) in [
        (r#"{"now":9007199254740992}"#, "9007199254740992"),
        (r#"{"now":-9007199254740992}"#, "-9007199254740992"),
        (
            r#"{"a":[{"exp":18446744073709551616}]}"#,
            "18446744073709551616",
        ),
        // An integral value is written as a plain integer.
        (r#"{"now":1300819320.0}"#, "1300819320.0"),
        (r#"{"exp":1e3}"#, "1e3"),
        (r#"{"exp":1.5e3}"#, "1.5e3"),
        (r#"{"exp":9007199254740991.5}"#, "9007199254740991.5"),
        (r#"{"input":{"bytes_hex":"00"}}"#, "/input/bytes_hex"),
        (r#"{"payload_b64u":"Zh"}"#, "/payload_b64u"),
    ] {
        let problem = binding_ready_with(bad, Numbers::Safe).unwrap_err();
        assert!(problem.contains(needle), "{bad}: {problem}");
    }
    // The jws/keys rule stays as strict as before.
    assert!(binding_ready_with(r#"{"now":1300819320}"#, Numbers::Count).is_ok());
    assert!(binding_ready_with(r#"{"now":4294967296}"#, Numbers::Count).is_err());
    assert!(binding_ready_with(r#"{"exp":0.5}"#, Numbers::Count).is_err());
    let validate = r#"{"operation":"jwt.validate"}"#;
    let other = r#"{"operation":"b64url.encode"}"#;
    for (path, text, covered) in [
        ("jwt/rfc7519/a.json", other, true),
        ("jwt/a.json", other, true),
        ("elsewhere/a.json", validate, true),
        ("jwt-extra/a.json", other, false),
        ("jws-rfc7515/jwt/a.json", other, false),
    ] {
        assert_eq!(
            needs_jwt_binding_readiness(Path::new(path), text),
            covered,
            "{path}"
        );
    }
}

/// Criterion 2 (ADR 0028 §4): the runner's only clock is the `FixedClock`
/// it builds from `now`. `jwt_policy` takes a `&FixedClock`, so the types
/// already keep any other clock out of the library call; this scan of the
/// runner's own source keeps a later edit from reading the wall clock
/// another way. The names are assembled at run time so this test does not
/// match itself.
#[test]
fn jwt_runner_never_reads_the_wall_clock() {
    let source = include_str!("conformance.rs");
    let forbidden = [
        ["System", "Clock"].concat(),
        ["System", "Time"].concat(),
        ["Instant", "::"].concat(),
        ["UNIX", "_EPOCH"].concat(),
    ];
    for name in &forbidden {
        assert!(!source.contains(name.as_str()), "the runner names {name}");
    }
    let fixed = ["FixedClock", "(now)"].concat();
    assert_eq!(
        source.matches(fixed.as_str()).count(),
        1,
        "one clock, from `now`"
    );
    // And `now` decides: the RFC 7519 §3.1 JWT expired in 2011, so it is
    // valid only because the runner's clock is `now`.
    let valid = vector("jwt.validate", &jwt_hs256(""), &jwt_validated("HS256", ""));
    assert!(check_vector("clock.json", valid.as_bytes()).is_ok());
}

// ---------------------------------------------------------------------------
// Results files (ADR 0034 §2): conformance/schema/results.schema.json and a
// validator for it.
// ---------------------------------------------------------------------------

/// `conformance/schema/results.schema.json`, parsed by `serde_json`, the
/// dev-only JSON oracle (ADR 0016 §5), so a results file is checked by a
/// parser independent of the writer's.
fn results_schema() -> serde_json::Value {
    let bytes = std::fs::read(conformance_dir().join("schema/results.schema.json")).unwrap();
    serde_json::from_slice(&bytes).expect("results.schema.json is JSON")
}

/// The JSON Schema keywords [`check_against`] implements. A schema node
/// with any other keyword fails [`results_schema_keywords`], so the
/// validator can never skip a rule the schema states.
const RESULTS_SCHEMA_KEYWORDS: &[&str] = &[
    "$schema",
    "title",
    "description",
    "$defs",
    "$ref",
    "type",
    "required",
    "additionalProperties",
    "properties",
    "items",
    "enum",
    "const",
    "minLength",
    "minItems",
    "uniqueItems",
    "pattern",
    "oneOf",
];

/// `$defs/id/pattern`: a path under `conformance/vectors/` (no leading `/`,
/// no `\`, no `#`) of a `.json` file, then `#0` (ADR 0045 §4).
const RESULT_ID_PATTERN: &str = "^[^#/\\\\][^#\\\\]*\\.json#0$";

/// `$defs/skipped/properties/reason/pattern`: `feature:` and the missing
/// feature names, comma-separated (ADR 0034 §3).
const SKIP_REASON_PATTERN: &str = "^feature:!?[a-z0-9-]+(,!?[a-z0-9-]+)*$";

/// `properties/vectors_digest/pattern`: a SHA-256 digest as exactly 64
/// lowercase hex characters, no prefix or separator (ADR 0060 §1).
const VECTORS_DIGEST_PATTERN: &str = "^[0-9a-f]{64}$";

/// [`VECTORS_DIGEST_PATTERN`], by hand (no regex crate, ADR 0016).
fn is_vectors_digest(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// [`RESULT_ID_PATTERN`], by hand (no regex crate, ADR 0016).
fn is_result_id(s: &str) -> bool {
    let Some(path) = s.strip_suffix("#0") else {
        return false;
    };
    let first_ok = path
        .chars()
        .next()
        .is_some_and(|c| !matches!(c, '#' | '/' | '\\'));
    first_ok
        && !path.contains(['#', '\\'])
        && path
            .strip_suffix(".json")
            .is_some_and(|stem| !stem.is_empty())
}

/// [`SKIP_REASON_PATTERN`], by hand: each name may carry a `!` (a
/// `features_absent` name the build enables, ADR 0056 §2).
fn is_skip_reason(s: &str) -> bool {
    s.strip_prefix("feature:").is_some_and(|names| {
        names.split(',').all(|name| {
            let name = name.strip_prefix('!').unwrap_or(name);
            !name.is_empty()
                && name
                    .bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        })
    })
}

/// The predicate of a `pattern` the results schema uses; `None` for any
/// other, which [`check_against`] refuses rather than ignores.
fn results_pattern(pattern: &str) -> Option<fn(&str) -> bool> {
    match pattern {
        RESULT_ID_PATTERN => Some(is_result_id),
        SKIP_REASON_PATTERN => Some(is_skip_reason),
        VECTORS_DIGEST_PATTERN => Some(is_vectors_digest),
        _ => None,
    }
}

/// Every keyword of every schema node in `schema` is one
/// [`RESULTS_SCHEMA_KEYWORDS`] names, and every `pattern` one
/// [`results_pattern`] knows. `enum` and `const` hold values, not schemas.
fn results_schema_keywords(schema: &serde_json::Value, pointer: &str) -> Result<(), String> {
    let node = schema
        .as_object()
        .ok_or_else(|| format!("{pointer}: a schema node must be an object"))?;
    for (keyword, value) in node {
        if !RESULTS_SCHEMA_KEYWORDS.contains(&keyword.as_str()) {
            return Err(format!("{pointer}: unsupported keyword `{keyword}`"));
        }
        let here = format!("{pointer}/{keyword}");
        match keyword.as_str() {
            "properties" | "$defs" => {
                for (name, sub) in value.as_object().ok_or(format!("{here}: not an object"))? {
                    results_schema_keywords(sub, &format!("{here}/{name}"))?;
                }
            }
            "items" => results_schema_keywords(value, &here)?,
            "oneOf" => {
                for (i, sub) in value
                    .as_array()
                    .ok_or(format!("{here}: not an array"))?
                    .iter()
                    .enumerate()
                {
                    results_schema_keywords(sub, &format!("{here}/{i}"))?;
                }
            }
            "additionalProperties" if value != &serde_json::Value::Bool(false) => {
                return Err(format!("{here}: only `false` is supported"));
            }
            "pattern" => {
                let pattern = value.as_str().ok_or(format!("{here}: not a string"))?;
                if results_pattern(pattern).is_none() {
                    return Err(format!("{here}: no hand-written check for {pattern:?}"));
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// The JSON Schema type name of `value` (`integer` for a whole number).
fn json_type(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => "integer",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

/// Validates `value` against the schema node `schema` of the schema
/// document `root` (JSON Schema 2020-12, restricted to
/// [`RESULTS_SCHEMA_KEYWORDS`]). The error names the JSON pointer of the
/// first violation.
fn check_against(
    root: &serde_json::Value,
    schema: &serde_json::Value,
    value: &serde_json::Value,
    pointer: &str,
) -> Result<(), String> {
    let at = |problem: String| Err(format!("{pointer}: {problem}"));
    if let Some(reference) = schema.get("$ref").and_then(serde_json::Value::as_str) {
        let name = reference
            .strip_prefix("#/$defs/")
            .ok_or(format!("{pointer}: unsupported $ref {reference}"))?;
        let target = root
            .get("$defs")
            .and_then(|defs| defs.get(name))
            .ok_or(format!("{pointer}: no $defs/{name}"))?;
        check_against(root, target, value, pointer)?;
    }
    if let Some(kind) = schema.get("type").and_then(serde_json::Value::as_str) {
        let actual = json_type(value);
        if actual != kind && !(kind == "number" && actual == "integer") {
            return at(format!("must be of type {kind}, is {actual}"));
        }
    }
    if let Some(allowed) = schema.get("enum").and_then(serde_json::Value::as_array)
        && !allowed.contains(value)
    {
        return at(format!(
            "must be one of {}",
            serde_json::Value::from(allowed.clone())
        ));
    }
    if let Some(constant) = schema.get("const")
        && value != constant
    {
        return at(format!("must be {constant}"));
    }
    if let (Some(min), Some(s)) = (
        schema.get("minLength").and_then(serde_json::Value::as_u64),
        value.as_str(),
    ) && (s.chars().count() as u64) < min
    {
        return at(format!("must have at least {min} character(s)"));
    }
    if let (Some(pattern), Some(s)) = (
        schema.get("pattern").and_then(serde_json::Value::as_str),
        value.as_str(),
    ) {
        let matches = results_pattern(pattern).ok_or(format!("{pointer}: pattern {pattern:?}"))?;
        if !matches(s) {
            return at(format!("{s:?} must match {pattern}"));
        }
    }
    if let Some(items) = value.as_array() {
        if let Some(min) = schema.get("minItems").and_then(serde_json::Value::as_u64)
            && (items.len() as u64) < min
        {
            return at(format!("must have at least {min} item(s)"));
        }
        if schema.get("uniqueItems") == Some(&serde_json::Value::Bool(true)) {
            for (i, item) in items.iter().enumerate() {
                if items[..i].contains(item) {
                    return at(format!("item {i} repeats an earlier one (uniqueItems)"));
                }
            }
        }
        if let Some(item_schema) = schema.get("items") {
            for (i, item) in items.iter().enumerate() {
                check_against(root, item_schema, item, &format!("{pointer}/{i}"))?;
            }
        }
    }
    if let Some(object) = value.as_object() {
        if let Some(required) = schema.get("required").and_then(serde_json::Value::as_array) {
            for name in required.iter().filter_map(serde_json::Value::as_str) {
                if !object.contains_key(name) {
                    return at(format!("missing required member `{name}`"));
                }
            }
        }
        let properties = schema
            .get("properties")
            .and_then(serde_json::Value::as_object);
        for (name, member) in object {
            match properties.and_then(|p| p.get(name)) {
                Some(member_schema) => {
                    check_against(root, member_schema, member, &format!("{pointer}/{name}"))?;
                }
                None if schema.get("additionalProperties")
                    == Some(&serde_json::Value::Bool(false)) =>
                {
                    return at(format!("unknown member `{name}`"));
                }
                None => {}
            }
        }
    }
    if let Some(branches) = schema.get("oneOf").and_then(serde_json::Value::as_array) {
        let errors: Vec<String> = branches
            .iter()
            .filter_map(|branch| check_against(root, branch, value, pointer).err())
            .collect();
        let matched = branches.len() - errors.len();
        if matched != 1 {
            return at(format!(
                "must match exactly one oneOf branch, matches {matched} ({})",
                errors.join("; ")
            ));
        }
    }
    Ok(())
}

/// Validates a results file's text against `results.schema.json`, parsing
/// it with `serde_json`.
fn check_results_text(text: &[u8]) -> Result<(), String> {
    let value: serde_json::Value =
        serde_json::from_slice(text).map_err(|e| format!("not JSON: {e}"))?;
    let schema = results_schema();
    check_against(&schema, &schema, &value, "")
}

/// The schema uses only what the validator implements, so no rule of it is
/// silently ignored; and the two hand-written patterns accept and refuse
/// what their regular expressions do.
#[test]
fn results_schema_uses_only_supported_keywords() {
    results_schema_keywords(&results_schema(), "").unwrap();
    for (id, ok) in [
        ("jws-rfc7515/a1.json#0", true),
        ("a.json#0", true),
        ("third_party/rfc7520/jws/4-1.json#0", true),
        ("a.json#1", false),
        ("a.json", false),
        (".json#0", false),
        ("/a.json#0", false),
        ("a\\b.json#0", false),
        ("a#b.json#0", false),
        ("a.jsonx#0", false),
        ("", false),
    ] {
        assert_eq!(is_result_id(id), ok, "{id:?}");
    }
    for (reason, ok) in [
        ("feature:deflate", true),
        ("feature:deflate,fixed-rng", true),
        ("feature:!deflate", true),
        ("feature:fixed-rng,!deflate", true),
        ("feature:!deflate,!fixed-rng", true),
        ("feature:!", false),
        ("feature:!!deflate", false),
        ("feature:deflate!", false),
        ("feature:", false),
        ("feature:deflate,", false),
        ("feature:Deflate", false),
        ("feature: deflate", false),
        ("deflate", false),
    ] {
        assert_eq!(is_skip_reason(reason), ok, "{reason:?}");
    }
    let hex64 = "9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1";
    for (digest, ok) in [
        (hex64.to_owned(), true),
        ("0".repeat(64), true),
        (hex64.to_uppercase(), false),
        (hex64[..63].to_owned(), false),
        (format!("{hex64}0"), false),
        (format!("sha256:{}", &hex64[7..]), false),
        (hex64.replacen('9', "g", 1), false),
        (format!(" {}", &hex64[1..]), false),
        (String::new(), false),
    ] {
        assert_eq!(is_vectors_digest(&digest), ok, "{digest:?}");
    }
    // An unknown keyword or pattern is refused, not ignored.
    let unknown: serde_json::Value =
        serde_json::from_str(r#"{"type":"string","maxLength":3}"#).unwrap();
    assert!(results_schema_keywords(&unknown, "").is_err());
    let pattern: serde_json::Value =
        serde_json::from_str(r#"{"type":"string","pattern":"^a$"}"#).unwrap();
    assert!(results_schema_keywords(&pattern, "").is_err());
}

/// The schema's `features` enum is the runner's [`FEATURES`] table, in
/// schema order, and its `runner` enum names the reference run first
/// (ADR 0034 §2, §4).
#[test]
fn results_schema_agrees_with_the_runner() {
    let schema = results_schema();
    let features: Vec<&str> = schema["properties"]["features"]["items"]["enum"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert_eq!(features, feature_names());
    let runners = schema["properties"]["runner"]["enum"].as_array().unwrap();
    assert_eq!(runners.first().and_then(|r| r.as_str()), Some(RUST_CORE));
}

/// The runner name of this file's results (ADR 0034 §2).
const RUST_CORE: &str = "rust-core";

/// A minimal results file with one result of each status.
const RESULTS_EXAMPLE: &str = r#"{"runner":"node","polyjose":"0.1.0","vectors_digest":"9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1","features":[],"error_codes":["InvalidBase64","InvalidKey"],"results":[{"id":"a/b.json#0","source":"RFC 4648 §10","op":"b64url.decode","status":"pass","actual":{"ok":false,"error":"InvalidBase64"}},{"id":"a/c.json#0","op":"jwe.encrypt","status":"skipped","reason":"feature:fixed-rng"},{"id":"a/d.json#0","status":"fail","reason":"not JSON"},{"id":"a/e.json#0","op":"jws.verify","status":"fail","actual":{"ok":true},"reason":"expected error InvalidKey"}]}"#;

/// The validator accepts a valid results file and refuses each way one can
/// break the schema (so the check of the reference file is not vacuous).
#[test]
fn results_validator_refuses_invalid_files() {
    check_results_text(RESULTS_EXAMPLE.as_bytes()).unwrap();
    check_results_text(br#"{"runner":"rust-core","polyjose":"0.1.0","vectors_digest":"9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1","features":["deflate","fixed-rng"],"error_codes":["X"],"results":[]}"#).unwrap();
    for (old, new, problem) in [
        (
            r#""runner":"node","#,
            "",
            "missing required member `runner`",
        ),
        (r#""runner":"node""#, r#""runner":"node-x86_64""#, "/runner"),
        (r#""features":[]"#, r#""features":["zlib"]"#, "/features/0"),
        (
            r#""features":[]"#,
            r#""features":["deflate","deflate"]"#,
            "uniqueItems",
        ),
        (
            r#""error_codes":["InvalidBase64","InvalidKey"]"#,
            r#""error_codes":[]"#,
            "at least 1 item",
        ),
        (r#""InvalidKey"]"#, r#""InvalidBase64"]"#, "uniqueItems"),
        (r#""polyjose":"0.1.0""#, r#""polyjose":"""#, "/polyjose"),
        (
            r#""vectors_digest":"9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1","#,
            "",
            "missing required member `vectors_digest`",
        ),
        (
            r#""9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1""#,
            r#""9A06F1EFDD269176088CB0E6BFC6A7E4D4F74AA3D1B1B8FC6C879FDBB82AC7D1""#,
            "/vectors_digest",
        ),
        (
            r#""9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1""#,
            r#""9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d10""#,
            "/vectors_digest",
        ),
        (
            r#""9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1""#,
            r#"7"#,
            "/vectors_digest",
        ),
        (
            r#""results":["#,
            r#""extra":1,"results":["#,
            "unknown member `extra`",
        ),
        (r#""a/b.json#0""#, r#""a/b.json""#, "/results/0"),
        (r#""a/b.json#0""#, r#""a/b.json#1""#, "/results/0"),
        (r#""status":"pass""#, r#""status":"passed""#, "/results/0"),
        (
            r#","actual":{"ok":false,"error":"InvalidBase64"}}"#,
            "}",
            "/results/0",
        ),
        (
            r#""actual":{"ok":false,"error":"InvalidBase64"}"#,
            r#""actual":{"ok":false}"#,
            "/results/0",
        ),
        (
            r#""actual":{"ok":false,"error":"InvalidBase64"}"#,
            r#""actual":{"ok":true,"error":"InvalidBase64"}"#,
            "/results/0",
        ),
        (
            r#""actual":{"ok":false,"error":"InvalidBase64"}"#,
            r#""actual":{"ok":false,"error":"InvalidBase64"},"reason":"x""#,
            "/results/0",
        ),
        (
            r#""reason":"feature:fixed-rng""#,
            r#""reason":"fixed-rng""#,
            "/results/1",
        ),
        (
            r#""reason":"feature:fixed-rng""#,
            r#""reason":"feature:fixed-rng","actual":{"ok":true}"#,
            "/results/1",
        ),
        (r#""op":"jwe.encrypt","#, "", "/results/1"),
        (
            r#""status":"fail","reason":"not JSON""#,
            r#""status":"fail""#,
            "/results/2",
        ),
    ] {
        assert_eq!(RESULTS_EXAMPLE.matches(old).count(), 1, "{old}");
        let broken = RESULTS_EXAMPLE.replacen(old, new, 1);
        let err = check_results_text(broken.as_bytes()).expect_err(&broken);
        assert!(err.contains(problem), "{old} -> {new}: {err}");
    }
}

/// `run_dir` records one result per vector file (ADR 0034 §2): the id is
/// the path under the directory plus `#0` (ADR 0045 §4); a vector that ran
/// records its outcome as `actual`, passing or not; a skip names the
/// missing features in the vector's order; a broken file fails with a
/// reason, and with `op` when it names one.
#[test]
fn run_dir_records_one_result_per_vector() {
    let dir = TempDir::new("results");
    let encode = vector(
        "b64url.encode",
        r#"{"bytes_hex":"66"}"#,
        r#"{"ok":true,"b64u":"Zg"}"#,
    );
    dir.write("a/ok.json", &encode);
    dir.write(
        "a/negative.json",
        &vector(
            "b64url.decode",
            r#"{"b64u":"Zg="}"#,
            r#"{"ok":false,"error":"InvalidBase64"}"#,
        ),
    );
    dir.write(
        "b/wrong.json",
        &vector(
            "b64url.decode",
            r#"{"b64u":"Zg="}"#,
            r#"{"ok":false,"error":"InvalidKey"}"#,
        ),
    );
    dir.write(
        "b/needs.json",
        &with_features(
            &vector(
                "jwe.decrypt",
                &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, ""),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            r#"["fixed-rng","deflate"]"#,
        ),
    );
    dir.write("c/invalid.json", &encode.replace(r#""66""#, r#""6""#));
    dir.write(
        "c/unknown.json",
        &vector("jws.frobnicate", "{}", r#"{"ok":true}"#),
    );
    dir.write("c/broken.json", "{");
    dir.write("c/LICENSE", "not a vector");
    let report = run_dir_with(&dir.0, &[]);
    assert!(report.complete, "{report:?}");
    let got: Vec<String> = report.results.iter().map(Object::to_json).collect();
    let expected = [
        format!(
            r#"{{"id":"a/negative.json#0","source":"{SOURCE}","op":"b64url.decode","status":"pass","actual":{{"ok":false,"error":"InvalidBase64"}}}}"#
        ),
        format!(
            r#"{{"id":"a/ok.json#0","source":"{SOURCE}","op":"b64url.encode","status":"pass","actual":{{"ok":true}}}}"#
        ),
        format!(
            r#"{{"id":"b/needs.json#0","source":"{SOURCE}","op":"jwe.decrypt","status":"skipped","reason":"feature:fixed-rng,deflate"}}"#
        ),
    ];
    assert_eq!(got.len(), 7, "{got:#?}");
    assert_eq!(got[..3], expected, "{got:#?}");
    let fails: Vec<&Object> = report.results[3..].iter().collect();
    let ids: Vec<&str> = fails
        .iter()
        .map(|r| r.get("id").and_then(Value::as_str).unwrap())
        .collect();
    assert_eq!(
        ids,
        [
            "b/wrong.json#0",
            "c/broken.json#0",
            "c/invalid.json#0",
            "c/unknown.json#0"
        ]
    );
    for result in &fails {
        assert_eq!(result.get("status").and_then(Value::as_str), Some("fail"));
        let reason = result.get("reason").and_then(Value::as_str).unwrap();
        assert!(report.failures.iter().any(|f| f == reason), "{reason}");
    }
    // The wrong expectation ran: its outcome is recorded.
    assert_eq!(
        fails[0].get("actual").map(Value::to_json).as_deref(),
        Some(r#"{"ok":false,"error":"InvalidBase64"}"#)
    );
    // The unparseable file names no op; the others name theirs. None of the
    // three ran, so none has an outcome.
    let ops: Vec<Option<&str>> = fails[1..]
        .iter()
        .map(|r| r.get("op").and_then(Value::as_str))
        .collect();
    assert_eq!(ops, [None, Some("b64url.encode"), Some("jws.frobnicate")]);
    assert!(fails[1..].iter().all(|r| !r.contains("actual")));
    // Each entry is schema-valid.
    let document = format!(
        r#"{{"runner":"rust-core","polyjose":"0.1.0","vectors_digest":"{}","features":[],"error_codes":["X"],"results":[{}]}}"#,
        report.vectors_digest().unwrap(),
        got.join(",")
    );
    check_results_text(document.as_bytes()).unwrap();

    // A walk that finds nothing is incomplete, so no results file is
    // written from it.
    let empty = TempDir::new("results-empty");
    let report = run_dir_with(&empty.0, &[]);
    assert!(!report.complete && report.results.is_empty(), "{report:?}");
}

/// Tester edge corpus for ADR 0060 §2: non-ASCII ids sorted by UTF-8 bytes (U+FF61 is
/// EF BD A1, U+1F600 is F0 9F 98 80, so U+FF61 first), bytes that are not UTF-8 hashed
/// as read, a `jws-x/` before `jws/` pair, and a symbolic link that gets no line. The
/// expected digest is from an independent Python `hashlib` walk and the POSIX shell
/// reference of the ADR.
#[test]
fn vectors_digest_edge_corpus_matches_the_independent_oracle() {
    let dir = TempDir::new("digest-edge");
    let files: [(&str, &[u8]); 7] = [
        ("a.json", b"{}"),
        ("jws/b.json", b"{}\n"),
        ("jws-x/c.json", b"\xef\xbb\xbf{}"),
        ("\u{e9}/d.json", b"{}"),
        ("\u{ff61}.json", b"1"),
        ("\u{1f600}.json", b"2"),
        ("bad.json", b"\xff\xfe{}"),
    ];
    for (relative, bytes) in files {
        let path = dir.0.join(relative);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, bytes).unwrap();
    }
    std::fs::write(dir.0.join("README.md"), "notes").unwrap();
    #[cfg(unix)]
    std::os::unix::fs::symlink("a.json", dir.0.join("link.json")).unwrap();
    let report = run_dir_with(&dir.0, &[]);
    // The link is a walk failure (the run is incomplete, so no results file), not a digest line.
    #[cfg(unix)]
    assert!(
        report
            .failures
            .iter()
            .any(|f| f.contains("link.json: symbolic links are not allowed")),
        "{:?}",
        report.failures
    );
    #[cfg(unix)]
    assert!(!report.complete);
    // Without the link, nothing else in the corpus fails the walk.
    #[cfg(not(unix))]
    assert!(report.complete, "{:?}", report.failures);
    assert_eq!(report.digest_lines.len(), 7);
    assert_eq!(
        report.vectors_digest().as_deref(),
        Some("c743cb52d786b61176972303ee0cfa56b8940d655723a9a3debfe691760ead93")
    );
}

/// The worked example of ADR 0060 §4: one line per `*.json` file read
/// (`README.md` is not a vector), `<id>` TAB `<sha256 of the raw bytes>` LF,
/// sorted by bytes (`jws-x/` before `jws/`, unlike `Path` order), whatever
/// the vector's own result (none of these is a valid vector); then the
/// SHA-256 of the lines. The bytes are hashed as read: the BOM and the LF
/// stay.
#[test]
fn vectors_digest_follows_the_adr_0060_worked_example() {
    let dir = TempDir::new("digest-example");
    dir.write("a.json", "{}");
    dir.write("jws/b.json", "{}\n");
    dir.write("jws-x/c.json", "\u{feff}{}");
    dir.write("README.md", "notes");
    let report = run_dir_with(&dir.0, &[]);
    assert!(report.complete, "{report:?}");
    assert_eq!(report.results.len(), 3);
    let lines: Vec<String> = sorted_digest_lines(&report.digest_lines)
        .into_iter()
        .map(|line| String::from_utf8(line).unwrap())
        .collect();
    assert_eq!(
        lines,
        [
            "a.json#0\t44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a\n",
            "jws-x/c.json#0\taa25e978046d680ef8740d837e6de5bc1e2a2dc6089dbda1012544b538d53f65\n",
            "jws/b.json#0\tca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356\n",
        ]
    );
    assert_eq!(
        report.vectors_digest().as_deref(),
        Some("9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1")
    );
    // The lines are sorted for the digest, so the order files were read in
    // does not matter.
    let mut reversed = report.digest_lines.clone();
    reversed.reverse();
    assert_eq!(
        sorted_digest_lines(&reversed),
        sorted_digest_lines(&report.digest_lines)
    );

    // The digest is written into the results file.
    let out = TempDir::new("digest-example-out");
    let path = write_results(&out.0, "rust-core.json", &[], &report)
        .unwrap()
        .unwrap();
    let text = std::fs::read_to_string(&path).unwrap();
    check_results_text(text.as_bytes()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&text).unwrap();
    assert_eq!(
        value["vectors_digest"],
        "9a06f1efdd269176088cb0e6bfc6a7e4d4f74aa3d1b1b8fc6c879fdbb82ac7d1"
    );
}

/// An empty corpus is invalid (ADR 0060 §3): a run that read no vector
/// file has no digest and writes no results file, removing an earlier one,
/// even when its walk was complete.
#[test]
fn a_run_that_read_no_vector_file_writes_no_results() {
    let nothing = Report {
        complete: true,
        ..Report::default()
    };
    assert_eq!(nothing.vectors_digest(), None);
    let out = TempDir::new("digest-empty-out");
    out.write("rust-core.json", "stale");
    assert_eq!(
        write_results(&out.0, "rust-core.json", &[], &nothing).unwrap(),
        None
    );
    assert!(!out.0.join("rust-core.json").exists());
}

/// The writer names the file by the build's features (ADR 0034 §4: only
/// the default build is the `rust-core` reference), writes a file that
/// validates against `results.schema.json`, one result per line, and
/// removes an earlier file instead of writing when the walk was incomplete.
#[test]
fn results_writer_writes_the_reference_file() {
    assert_eq!(results_file_name(&[]), "rust-core.json");
    assert_eq!(
        results_file_name(&["fixed-rng"]),
        "rust-core-fixed-rng.json"
    );
    assert_eq!(
        results_file_name(&["deflate", "fixed-rng"]),
        "rust-core-deflate-fixed-rng.json"
    );

    let vectors = TempDir::new("writer-vectors");
    vectors.write(
        "x/ok.json",
        &vector(
            "b64url.encode",
            r#"{"bytes_hex":"66"}"#,
            r#"{"ok":true,"b64u":"Zg"}"#,
        ),
    );
    vectors.write(
        "x/needs.json",
        &with_features(
            &vector(
                "jwe.decrypt",
                &jwe_decrypt_input(JWE_A3, JWE_A3_KEY, ""),
                r#"{"ok":false,"error":"InvalidKey"}"#,
            ),
            r#"["deflate"]"#,
        ),
    );
    let out = TempDir::new("writer-out");
    let target = out.0.join("conformance");
    let report = run_dir_with(&vectors.0, &[]);
    let path = write_results(&target, "rust-core.json", &[], &report)
        .unwrap()
        .expect("a complete report is written");
    let text = std::fs::read_to_string(&path).unwrap();
    check_results_text(text.as_bytes()).unwrap();
    let value: serde_json::Value = serde_json::from_str(&text).unwrap();
    assert_eq!(value["runner"], "rust-core");
    assert_eq!(value["polyjose"], env!("CARGO_PKG_VERSION"));
    assert_eq!(value["features"], serde_json::json!([]));
    assert_eq!(value["error_codes"], serde_json::json!(Error::CODES));
    assert_eq!(value["results"].as_array().unwrap().len(), 2);
    // Files are sorted by path, so x/needs.json comes first.
    assert_eq!(value["results"][0]["reason"], "feature:deflate");
    assert_eq!(value["results"][1]["id"], "x/ok.json#0");
    assert_eq!(
        text.lines().filter(|l| l.contains(r#""id":"#)).count(),
        2,
        "one result per line: {text}"
    );
    assert!(
        std::fs::read_dir(&target).unwrap().count() == 1,
        "no temporary file left"
    );

    // With features, the features are recorded.
    let path = write_results(&target, "rust-core-deflate.json", &["deflate"], &report)
        .unwrap()
        .unwrap();
    let text = std::fs::read_to_string(&path).unwrap();
    check_results_text(text.as_bytes()).unwrap();
    assert!(text.contains(r#""features": ["deflate"]"#), "{text}");

    // An incomplete walk removes the earlier file and writes nothing.
    let incomplete = run_dir_with(&out.0.join("missing"), &[]);
    assert_eq!(
        write_results(&target, "rust-core.json", &[], &incomplete).unwrap(),
        None
    );
    assert!(!target.join("rust-core.json").exists());
    assert_eq!(
        write_results(&target, "rust-core.json", &[], &incomplete).unwrap(),
        None,
        "nothing to remove is fine"
    );
}