jose-rs 0.14.0

Pure-Rust JOSE library (JWS, JWE, JWK, JWT) with software and HSM key support
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
//! Shared, crate-private JWE processing.
//!
//! Every JWE serialization (compact, flattened JSON, general JSON) must apply
//! the *same* header policy, key-management rules, content-encryption limits
//! and algorithm allow-list semantics. Duplicating that logic per serializer
//! is how an algorithm-substitution or header-confusion gap reappears in one
//! path while another path stays correct, so the shared pieces live here and
//! the serialization modules only translate between a wire shape and this
//! model.
//!
//! Two invariants hold throughout:
//!
//! 1. **Parsed is not authenticated.** [`ParsedEnvelope`] is the result of
//!    structure and policy checks only. No plaintext and no CEK leaves this
//!    module until `content_decrypt` has verified the tag over the *original*
//!    serialized bytes.
//! 2. **Key material stays inside zeroizing owners.** CEKs move as
//!    `Zeroizing<Vec<u8>>` and a raw CEK is never part of a public API.
//!
//! This module is the ADR 0011 extraction of the code that previously lived in
//! `jwe/compact.rs`; behaviour, error variants and messages are unchanged.

use zeroize::Zeroizing;

use crate::algorithm::{JweAlgorithm, JweEncryption};
use crate::base64url;
use crate::error::{JoseError, Result};
use crate::header::JoseHeader;
use crate::jwe::content;

// ---------------------------------------------------------------------------
// Size limits
// ---------------------------------------------------------------------------

/// Reject a serialized token larger than [`crate::MAX_TOKEN_BYTES`].
pub(crate) fn ensure_token_size(token: &str) -> Result<()> {
    if token.len() > crate::MAX_TOKEN_BYTES {
        return Err(JoseError::InvalidToken(format!(
            "token size {} exceeds MAX_TOKEN_BYTES ({})",
            token.len(),
            crate::MAX_TOKEN_BYTES
        )));
    }
    Ok(())
}

/// Lower bound on the plaintext length implied by an encoded ciphertext,
/// computed *before* base64url decoding so oversized content is refused
/// before any key operation runs.
///
/// - AES-GCM: plaintext length equals ciphertext length.
/// - AES-CBC-HS: PKCS#7 padding occupies 1..=16 bytes, so the plaintext is at
///   least `ciphertext_len - 16`.
///
/// For a valid unpadded base64url input, `encoded_len * 3 / 4` is the exact
/// decoded length; invalid encodings fail in the decode step afterwards.
pub(crate) fn minimum_plaintext_len(encoded_ciphertext_len: usize, enc: JweEncryption) -> usize {
    let ciphertext_len = encoded_ciphertext_len * 3 / 4;
    match enc {
        JweEncryption::A128GCM | JweEncryption::A192GCM | JweEncryption::A256GCM => ciphertext_len,
        JweEncryption::A128CbcHs256 | JweEncryption::A192CbcHs384 | JweEncryption::A256CbcHs512 => {
            ciphertext_len.saturating_sub(16)
        }
    }
}

// ---------------------------------------------------------------------------
// Emit-side header policy
// ---------------------------------------------------------------------------

/// Options controlling JWE encryption with a caller-supplied protected
/// header.
///
/// [`Default`] / [`JweEncryptOptions::new`] is the strict policy used by the
/// plain `encrypt_with_header*` entry points.
///
/// The struct is `#[non_exhaustive]` so new policy switches can be added
/// without breaking callers: start from [`JweEncryptOptions::new`] and use
/// the `with_*` builders.
///
/// ```
/// use jose_rs::jwe::JweEncryptOptions;
///
/// let opts = JweEncryptOptions::new().with_key_reference_headers(true);
/// assert!(opts.allow_key_reference_headers);
/// ```
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct JweEncryptOptions {
    /// Permit the key-reference members `jku`, `jwk`, `x5u` and `x5c`
    /// ([`crate::header::KEY_REFERENCE_MEMBERS`]) in the protected header.
    /// Defaults to `false`.
    ///
    /// RFC 7516 §4.1.4-4.1.7 uses these to identify the recipient's key.
    /// This crate never reads them, but a peer may dereference or trust
    /// them, so they are refused unless the caller opts in.
    pub allow_key_reference_headers: bool,
    /// External additional authenticated data, carried by the JSON `aad`
    /// member (RFC 7516 §2 / §7.2.1). Never `pub`: the value must reach
    /// [`aad_input`](self::aad_input) unaltered, so only this crate's
    /// serializers may position it.
    external_aad: Option<Vec<u8>>,
    /// Private header parameters the caller has implemented, which may
    /// therefore be listed in `crit`. See
    /// [`JweEncryptOptions::with_understood_crit`].
    understood_crit: Vec<String>,
    /// PBKDF2 iteration count to publish as `p2c` for a PBES2 algorithm.
    /// `None` means [`PBES2_DEFAULT_ITERATIONS`](super::password::PBES2_DEFAULT_ITERATIONS).
    pbes2_iterations: Option<u32>,
}

impl JweEncryptOptions {
    /// Strict defaults: no key-reference header members, no external AAD.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set [`allow_key_reference_headers`](Self::allow_key_reference_headers).
    #[must_use]
    pub fn with_key_reference_headers(mut self, allow: bool) -> Self {
        self.allow_key_reference_headers = allow;
        self
    }

    /// Encrypt with external additional authenticated data.
    ///
    /// The bytes are placed in the message's `aad` member and are covered by
    /// the content authentication tag through the RFC's AAD input construction
    /// (`ASCII(protected || '.' || BASE64URL(aad))`, RFC 7516 §5.1 step 14);
    /// they are *not* encrypted, so they must
    /// not be confidential, and the recipient has to know them out of band.
    /// Only the JSON serializations can carry them — the compact form has no
    /// `aad` member, so the compact APIs refuse this option rather than
    /// dropping it. An empty value is refused at use time, because RFC 7516
    /// §7.2.1 requires the member to be absent when the value is empty and an
    /// empty AAD is therefore indistinguishable from no AAD at all.
    ///
    /// ```
    /// use jose_rs::jwe::JweEncryptOptions;
    /// let opts = JweEncryptOptions::new().with_external_aad(b"invoice-42");
    /// assert!(opts.external_aad().is_some());
    /// ```
    #[must_use]
    pub fn with_external_aad(mut self, aad: impl AsRef<[u8]>) -> Self {
        self.external_aad = Some(aad.as_ref().to_vec());
        self
    }

    /// The configured external additional authenticated data, if any.
    #[must_use]
    pub fn external_aad(&self) -> Option<&[u8]> {
        self.external_aad.as_deref()
    }

    /// Choose the PBES2 iteration count (`p2c`, RFC 7518 §4.8.1.2) to publish.
    ///
    /// The default is
    /// [`PBES2_DEFAULT_ITERATIONS`](super::password::PBES2_DEFAULT_ITERATIONS), and
    /// this is not a knob to turn casually: **the count you choose is CPU the recipient
    /// spends before it learns whether the password was right**, so raising it spends
    /// someone else's time, and lowering it weakens the only thing separating two
    /// messages under one password. Anything below
    /// [`PBES2_MIN_ITERATIONS`](super::password::PBES2_MIN_ITERATIONS) is refused when
    /// the message is produced, not here, so the check also covers a header built by
    /// hand.
    ///
    /// ```
    /// use jose_rs::jwe::JweEncryptOptions;
    /// let opts = JweEncryptOptions::new().with_pbes2_iterations(250_000);
    /// assert_eq!(opts.pbes2_iterations(), Some(250_000));
    /// ```
    #[must_use]
    pub fn with_pbes2_iterations(mut self, iterations: u32) -> Self {
        self.pbes2_iterations = Some(iterations);
        self
    }

    /// The PBES2 iteration count the caller chose, or `None` for the default.
    #[must_use]
    pub fn pbes2_iterations(&self) -> Option<u32> {
        self.pbes2_iterations
    }

    /// Declare that the caller implements the private header parameters in
    /// `names`, so they may be listed in the protected header's `crit` member.
    ///
    /// This crate implements **no** JWE critical extensions of its own. The
    /// list is the caller's: a `crit` entry outside it is refused, on both the
    /// emit and the receive side, which is what keeps an unread extension from
    /// being silently ignored (RFC 7516 §4.1.13 / RFC 7515 §4.1.11).
    ///
    /// ```
    /// use jose_rs::jwe::JweEncryptOptions;
    /// let opts = JweEncryptOptions::new().with_understood_crit(["etsiU"]);
    /// assert_eq!(opts.understood_crit(), ["etsiU"]);
    /// ```
    #[must_use]
    pub fn with_understood_crit<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.understood_crit = names.into_iter().map(Into::into).collect();
        self
    }

    /// The header parameters the caller declared it understands.
    #[must_use]
    pub fn understood_crit(&self) -> &[String] {
        &self.understood_crit
    }
}

/// Registered header members this crate does not implement for JWE compact
/// encryption, and so must not emit (RFC 7516 / RFC 7518 registry):
///
/// - `zip`: content compression (RFC 7516 §4.1.3); not implemented, and
///   RFC 8725 §3.6 advises against compressing before encryption;
/// - `b64`: RFC 7797 unencoded payload, a JWS-only member;
/// - `epk`: ECDH key agreement's ephemeral key (RFC 7518 §4.6.1);
/// - `p2s`, `p2c`: PBES2's salt input and iteration count (RFC 7518 §4.8.1);
/// - `iv`, `tag`: the AES-GCM key wrap's IV and authentication tag (RFC 7518
///   §4.7.1).
///
/// Emitting any of these would describe processing that did not happen, so a
/// peer that implements them would read the token differently. Which members
/// those are depends on the key-management algorithm: `apu`/`apv` feed the
/// Concat KDF, so they are emittable exactly when the algorithm runs it.
///
/// `epk`, `p2s`, `p2c`, `iv` and `tag` stay on the list for **every** algorithm,
/// including the ones that use them, and that is deliberate rather than
/// unfinished. They are the members this crate generates itself — an ephemeral
/// key, a nonce, a work budget, an AEAD nonce and its tag — and a caller that
/// could supply them would be choosing values whose reuse or fabrication breaks
/// the key operation (RFC 7518 §4.6: "A new ephemeral public key value MUST be
/// generated for each key agreement operation"). Each is inserted after this
/// check, by the code that generates it, in the key-management paths that
/// actually run (ADRs 0018, 0020, 0021).
pub(crate) const UNIMPLEMENTED_JWE_MEMBERS: &[&str] =
    &["zip", "b64", "epk", "apu", "apv", "p2s", "p2c", "iv", "tag"];

/// The members `alg` cannot legitimately accompany in a header this crate emits.
pub(crate) fn unimplemented_jwe_members(alg: JweAlgorithm) -> &'static [&'static str] {
    if alg_is_agreement(alg) {
        // `apu`/`apv` are Concat KDF inputs and are honoured by the derivation.
        &["zip", "b64", "epk", "p2s", "p2c", "iv", "tag"]
    } else {
        UNIMPLEMENTED_JWE_MEMBERS
    }
}

/// The refusal shared by every path that would put a direct-agreement algorithm
/// in front of a general JWE.
///
/// The reason is structural, not a missing feature: in direct mode the agreed
/// key **is** the CEK, so a second recipient would need a second CEK, and one
/// ciphertext cannot be encrypted under two keys. RFC 7518 §4.6 offers key
/// agreement *with key wrapping* as the multi-recipient form.
pub(crate) fn direct_agreement_not_multi(alg: JweAlgorithm) -> JoseError {
    JoseError::UnsupportedAlgorithm(format!(
        "{} agrees the content encryption key with one recipient, so it cannot address a general \
         JWE; use the flattened or compact serialization for one recipient, or ECDH-ES+A128KW/\
         +A192KW/+A256KW to wrap a shared CEK for several",
        alg.as_str()
    ))
}

/// Whether `alg` derives its key by agreement rather than transporting or
/// wrapping one.
///
/// Agreement modes differ structurally, not just cryptographically: their key
/// material is a JWK rather than bytes, the peer key arrives inside the message
/// (`epk`), and the CEK is *agreed* rather than carried — so `encrypted_key` is
/// empty in direct mode and one recipient is all direct mode can address.
pub(crate) fn alg_is_agreement(alg: JweAlgorithm) -> bool {
    matches!(
        alg,
        JweAlgorithm::EcdhEs
            | JweAlgorithm::EcdhEsA128kw
            | JweAlgorithm::EcdhEsA192kw
            | JweAlgorithm::EcdhEsA256kw
    )
}

/// Header parameters defined by RFC 7516 or RFC 7518 for use with JWE.
///
/// RFC 7515 §4.1.11 forbids a producer from listing these in `crit`: they are
/// not extensions, so declaring them critical says nothing a recipient does not
/// already have to do, and an implementation that "checked" the marker would be
/// agreeing to a constraint it had to satisfy anyway.
pub(crate) const REGISTERED_JWE_MEMBERS: &[&str] = &[
    "alg", "enc", "zip", "crit", "b64", "kid", "cty", "typ", "jku", "jwk", "x5u", "x5c", "x5t",
    "x5t#S256", "epk", "apu", "apv", "p2s", "p2c", "iv", "tag",
];

/// Whether `param` is a header parameter this message actually carries.
///
/// RFC 7515 §4.1.11: a producer "MUST NOT ... [list] names that do not occur as
/// Header Parameter names within the JOSE Header". Registered names live in
/// typed fields; everything a caller may legitimately list is a private member
/// in [`JoseHeader::extra`].
fn header_has_param(header: &JoseHeader, param: &str) -> bool {
    match param {
        "alg" => !header.alg.is_empty(),
        "enc" => header.enc.is_some(),
        "kid" => header.kid.is_some(),
        "typ" => header.typ.is_some(),
        "cty" => header.cty.is_some(),
        "jku" => header.jku.is_some(),
        "jwk" => header.jwk.is_some(),
        "x5u" => header.x5u.is_some(),
        "x5c" => header.x5c.is_some(),
        "x5t" => header.x5t.is_some(),
        "x5t#S256" => header.x5t_s256.is_some(),
        "crit" => header.crit.is_some(),
        _ => header.extra.contains_key(param),
    }
}

/// Apply the `crit` rules of RFC 7516 §4.1.13 (which adopts RFC 7515 §4.1.11)
/// to a **protected** header.
///
/// Identical on the emit and the receive side on purpose: a message this crate
/// is willing to write is always one it is willing to read, and the two checks
/// drifting apart is how implementations end up producing tokens they cannot
/// themselves decrypt. `understood` is the caller's list — this crate
/// implements no critical extensions of its own.
///
/// Rules:
/// 1. `crit` must not be empty;
/// 2. no duplicate names;
/// 3. no registered JWE/JWA name (those are not extensions);
/// 4. every name must be in `understood` — this is the rule that makes an
///    unread extension fail loudly instead of being ignored;
/// 5. every name must actually occur in the header.
///
/// The check runs against the protected header only, which is also where RFC
/// 7515 §4.1.11 requires `crit` to be: on the JSON serializations an extension
/// could in principle be carried unprotected, and this crate refuses that — a
/// parameter whose criticality is asserted by bytes nobody authenticates is not
/// critical (ADR 0015).
pub(crate) fn validate_crit(header: &JoseHeader, understood: &[String]) -> Result<()> {
    let Some(crit) = header.crit.as_ref() else {
        return Ok(());
    };
    if crit.is_empty() {
        return Err(JoseError::InvalidHeader(
            "crit header must not be empty (RFC 7515 §4.1.11)".into(),
        ));
    }
    for (index, param) in crit.iter().enumerate() {
        if crit[..index].contains(param) {
            return Err(JoseError::InvalidHeader(format!(
                "crit lists {param} more than once (RFC 7515 §4.1.11)"
            )));
        }
        if REGISTERED_JWE_MEMBERS.contains(&param.as_str()) {
            return Err(JoseError::InvalidHeader(format!(
                "crit must not name the registered header parameter {param}; it is not an \
                 extension (RFC 7515 §4.1.11)"
            )));
        }
        if !understood.iter().any(|known| known == param) {
            return Err(JoseError::InvalidHeader(format!(
                "unsupported crit extension: {param}"
            )));
        }
        if !header_has_param(header, param) {
            return Err(JoseError::InvalidHeader(format!(
                "crit names {param} but it is absent from the protected header \
                 (RFC 7515 §4.1.11)"
            )));
        }
    }
    Ok(())
}

/// Validate the JWE-specific content of a caller-supplied protected header
/// before it is serialized and used as additional authenticated data.
///
/// Callers must already have checked that `header.alg` / `header.enc` match
/// the algorithms actually used. The shared rules (duplicate members,
/// key-reference members, size) are applied afterwards by
/// [`JoseHeader::to_protected_b64`]. Rules enforced here:
///
/// 1. `extra` must not contain an [`UNIMPLEMENTED_JWE_MEMBERS`] entry; for
///    `zip` the check and message match the decrypt path, so a token this
///    crate emits is always one it can decrypt.
/// 2. `crit` passes [`validate_crit`] against the caller's understood-extension
///    list. This crate implements no critical extensions itself, so with an
///    empty list — the default — `crit` must be absent.
///
/// # Errors
///
/// Returns [`JoseError::InvalidHeader`] naming the first rule violated.
pub(crate) fn validate_encrypt_header(
    header: &JoseHeader,
    alg: JweAlgorithm,
    understood: &[String],
) -> Result<()> {
    // Rule 1. `extra["crit"]` is not handled here: it duplicates a typed
    // field, which `to_protected_b64` rejects before anything is emitted.
    if header.extra.contains_key("zip") {
        return Err(JoseError::InvalidHeader(
            "unsupported zip header: content compression is not supported".into(),
        ));
    }
    if let Some(name) = unimplemented_jwe_members(alg)
        .iter()
        .find(|name| header.extra.contains_key(**name))
    {
        // `epk` is refused even for the agreement algorithms, for a different
        // reason than the rest: the member is implemented, but the key in it is
        // not ours to choose. Accepting one would make ephemeral-key reuse —
        // which leaks the agreed key — expressible as a function argument.
        if *name == "epk" && alg_is_agreement(alg) {
            return Err(JoseError::InvalidHeader(
                "epk is generated by this crate for each encryption (RFC 7518 §4.6 requires a new ephemeral key per key agreement operation); do not supply one"
                    .into(),
            ));
        }
        return Err(JoseError::InvalidHeader(format!(
            "unsupported JWE header member {name}: not implemented for JWE encryption"
        )));
    }

    // Rule 2: the caller's list is the only thing that can license a `crit`
    // entry, and it licenses nothing that this crate does not itself process.
    validate_crit(header, understood)
}

// ---------------------------------------------------------------------------
// Algorithm policy (decrypt side)
// ---------------------------------------------------------------------------

/// Algorithm policy and plaintext-size limit for JWE decryption.
///
/// Use [`JweDecryptOptions::new`] to pin an explicit allow-list of key
/// management algorithms and content encryption algorithms. Tokens whose
/// header advertises anything outside the allow-list are rejected before
/// any cryptographic operation — the canonical defence against
/// algorithm-substitution attacks when one key is reused across configs.
#[derive(Debug, Clone, Default)]
pub struct JweDecryptOptions {
    allowed_alg: Vec<JweAlgorithm>,
    allowed_enc: Vec<JweEncryption>,
    allow_all: bool,
    max_plaintext: Option<usize>,
    /// External additional authenticated data expected from the message's
    /// `aad` member (RFC 7516 §2). See
    /// [`JweDecryptOptions::with_external_aad`].
    external_aad: Option<Vec<u8>>,
    /// Private header parameters the caller has implemented, and so may accept
    /// when a message lists them in `crit`. See
    /// [`JweDecryptOptions::with_understood_crit`].
    understood_crit: Vec<String>,
    /// Ceiling on the PBKDF2 work a message may ask for. `None` means
    /// [`PBES2_DEFAULT_MAX_ITERATIONS`](super::password::PBES2_DEFAULT_MAX_ITERATIONS).
    pbes2_max_iterations: Option<u32>,
}

impl JweDecryptOptions {
    /// Construct options pinning an explicit allow-list.
    pub fn new(allowed_alg: Vec<JweAlgorithm>, allowed_enc: Vec<JweEncryption>) -> Self {
        Self {
            allowed_alg,
            allowed_enc,
            allow_all: false,
            max_plaintext: None,
            external_aad: None,
            understood_crit: Vec::new(),
            pbes2_max_iterations: None,
        }
    }

    /// Options pinned to a JWK's own `alg`, accepting every content algorithm
    /// the library supports.
    ///
    /// This is what the JWK decryption APIs use: the algorithm comes from the
    /// *key*, never from token header data, which is what makes comparing the
    /// token's claim against it meaningful (ADR 0013). Callers who also need
    /// external AAD or caller-understood `crit` extensions build on the result.
    ///
    /// # Errors
    ///
    /// [`JoseError::Key`] when `jwk.alg` is unset, and
    /// [`JoseError::UnsupportedAlgorithm`] when it names something this crate
    /// does not implement for JWE.
    pub fn pinned_to_jwk(jwk: &crate::jwk::Jwk) -> Result<Self> {
        let alg = jwk
            .alg
            .as_deref()
            .ok_or_else(|| JoseError::Key("JWK alg must be set for the JWE JWK APIs".into()))?;
        let alg = JweAlgorithm::from_str(alg)?;
        Ok(Self::new(
            vec![alg],
            crate::jwe::internal::all_enc_algorithms(),
        ))
    }

    /// Permit every algorithm the library supports. Used internally by
    /// [`crate::jwe::decrypt`] for backwards compatibility — new code should
    /// prefer [`JweDecryptOptions::new`].
    pub fn permissive() -> Self {
        Self {
            allowed_alg: Vec::new(),
            allowed_enc: Vec::new(),
            allow_all: true,
            max_plaintext: None,
            external_aad: None,
            understood_crit: Vec::new(),
            pbes2_max_iterations: None,
        }
    }

    /// Limit returned plaintext to at most `bytes` bytes (inclusive).
    ///
    /// Zero permits only empty plaintext. By default there is no additional
    /// plaintext limit; [`crate::MAX_TOKEN_BYTES`] still bounds the token.
    /// This does not enable compression or change the algorithm policy.
    /// Oversized ciphertext is rejected before decoding or key operations
    /// when its length proves the plaintext cannot fit. CBC padding requires
    /// up to one extra 16-byte block and an exact post-authentication check.
    /// This bounds plaintext, not total process memory or key-operation cost.
    ///
    /// ```
    /// use jose_rs::{jwe::{self, JweDecryptOptions}, JweAlgorithm, JweEncryption};
    /// let options = JweDecryptOptions::new(
    ///     vec![JweAlgorithm::Dir], vec![JweEncryption::A256GCM],
    /// ).with_max_plaintext(1024);
    /// let key = [7_u8; 32]; // Example only; generate a secret key in production.
    /// let token = jwe::encrypt(&key, b"message", JweAlgorithm::Dir, JweEncryption::A256GCM)?;
    /// assert_eq!(jwe::decrypt_with_options(&key, &token, &options)?, b"message");
    /// # Ok::<(), jose_rs::JoseError>(())
    /// ```
    #[must_use]
    pub fn with_max_plaintext(mut self, bytes: usize) -> Self {
        self.max_plaintext = Some(bytes);
        self
    }

    /// Supply the external additional authenticated data for a message that
    /// carries an `aad` member.
    ///
    /// RFC 7516 keeps this data out of the ciphertext but *inside* the content
    /// authentication tag's reach: it is authenticated, not confidential, and
    /// a recipient must already know it. If the message has no `aad` member,
    /// or the bytes differ from it, decryption is refused with an explanatory
    /// error instead of a bare authentication failure — the member's presence
    /// and encoding are not secret, and a caller who forgot to pass the AAD
    /// deserves better than `Crypto("decryption failed")`.
    ///
    /// ```
    /// use jose_rs::{jwe::JweDecryptOptions, JweAlgorithm, JweEncryption};
    /// let options = JweDecryptOptions::new(
    ///     vec![JweAlgorithm::Dir], vec![JweEncryption::A256GCM],
    /// ).with_external_aad(b"invoice-42");
    /// assert_eq!(options.external_aad(), Some(&b"invoice-42"[..]));
    /// ```
    #[must_use]
    pub fn with_external_aad(mut self, aad: impl AsRef<[u8]>) -> Self {
        self.external_aad = Some(aad.as_ref().to_vec());
        self
    }

    /// The configured external additional authenticated data, if any.
    #[must_use]
    pub fn external_aad(&self) -> Option<&[u8]> {
        self.external_aad.as_deref()
    }

    /// Cap the PBKDF2 work a message may require of this recipient.
    ///
    /// `p2c` is chosen by the sender and paid by the recipient, so an accepted
    /// message can otherwise name any iteration count up to the backend's 100 million
    /// and make this process compute for minutes before the wrapped key's integrity
    /// check says the password was wrong. The default is
    /// [`PBES2_DEFAULT_MAX_ITERATIONS`](super::password::PBES2_DEFAULT_MAX_ITERATIONS)
    /// (about a second on the measured machine); a message naming more is refused
    /// **before** any derivation, so refusal is free.
    ///
    /// Raising it is a decision about how much CPU a stranger may bill to this
    /// process. Lowering it is usually what a latency-sensitive verifier wants. A
    /// caller that tries several passwords in a loop pays the budget per attempt —
    /// one PBES2 recipient element per message is all this crate reads, so the loop is
    /// the caller's to bound.
    ///
    /// ```
    /// use jose_rs::algorithm::{JweAlgorithm, JweEncryption};
    /// use jose_rs::jwe::JweDecryptOptions;
    ///
    /// let opts = JweDecryptOptions::new(vec![JweAlgorithm::Pbes2Hs256A128kw], vec![JweEncryption::A128GCM])
    ///     .with_pbes2_max_iterations(20_000);
    /// assert_eq!(opts.pbes2_max_iterations(), 20_000);
    /// ```
    #[must_use]
    pub fn with_pbes2_max_iterations(mut self, iterations: u32) -> Self {
        self.pbes2_max_iterations = Some(iterations);
        self
    }

    /// The effective PBKDF2 iteration ceiling for this recipient.
    #[must_use]
    pub fn pbes2_max_iterations(&self) -> u32 {
        self.pbes2_max_iterations
            .unwrap_or(super::password::PBES2_DEFAULT_MAX_ITERATIONS)
    }

    /// Accept a `crit` member listing the private header parameters in `names`.
    ///
    /// A message listing anything outside this list is refused, and with the
    /// default (empty) list a message carrying `crit` at all is refused — the
    /// behaviour this crate has always had, now expressible as an explicit
    /// opt-in rather than a hard denial (RFC 7516 §4.1.13, RFC 7515 §4.1.11,
    /// ADR 0015). Declaring an extension "understood" is a claim about *code the
    /// caller wrote*: jose-rs reads the member, checks that it is present and
    /// integrity protected, and hands it over in
    /// [`JoseHeader::extra`](crate::JoseHeader::extra). It does not act on it.
    ///
    /// ```
    /// use jose_rs::jwe::JweDecryptOptions;
    /// use jose_rs::JweAlgorithm;
    /// use jose_rs::JweEncryption;
    /// let opts = JweDecryptOptions::new(vec![JweAlgorithm::A128KW], vec![JweEncryption::A128GCM])
    ///     .with_understood_crit(["etsiU"]);
    /// assert_eq!(opts.understood_crit(), ["etsiU"]);
    /// ```
    #[must_use]
    pub fn with_understood_crit<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.understood_crit = names.into_iter().map(Into::into).collect();
        self
    }

    /// The header parameters the caller declared it understands.
    #[must_use]
    pub fn understood_crit(&self) -> &[String] {
        &self.understood_crit
    }

    /// Fill in "every supported content algorithm" when the caller did not
    /// constrain one (crate-internal: the JWK APIs take the key-management
    /// algorithm from the key and must not force the caller to enumerate `enc`).
    pub(crate) fn allow_any_enc_when_unset(self) -> Self {
        if self.allowed_enc.is_empty() {
            Self {
                allowed_enc: all_enc_algorithms(),
                ..self
            }
        } else {
            self
        }
    }

    /// Resolve a message's `aad` member against the caller's expectation.
    ///
    /// Returns the **encoded** form to feed [`aad_input`][self::aad_input], or
    /// `None` when neither side has external AAD. Every disagreement between
    /// "the message says there is external AAD" and "the caller supplied some"
    /// is refused here, before key derivation, because all four combinations
    /// are distinguishable without any secret and each is a plausible
    /// integration mistake.
    pub(crate) fn resolve_external_aad(&self, aad_b64: Option<&str>) -> Result<Option<String>> {
        let supplied = self.external_aad.as_deref();
        match (aad_b64, supplied) {
            (None, None) => Ok(None),
            (Some(member), None) => Err(JoseError::InvalidToken(format!(
                "message carries external additional authenticated data ({member}); supply \
                 the same bytes with JweDecryptOptions::with_external_aad"
            ))),
            (None, Some(_)) => Err(JoseError::InvalidToken(
                "decrypt options carry external additional authenticated data but the message \
                 has no \"aad\" member"
                    .into(),
            )),
            (Some(member), Some(bytes)) => {
                // The tag covers the base64url *text*, so the caller's bytes
                // must re-encode to the member exactly. Checking it here turns
                // "wrong external AAD" into a named error rather than a
                // generic authentication failure.
                if base64url::encode(bytes) != member {
                    return Err(JoseError::InvalidToken(
                        "external additional authenticated data does not match the message's \
                         \"aad\" member"
                            .into(),
                    ));
                }
                Ok(Some(member.to_string()))
            }
        }
    }

    pub(crate) fn check_plaintext_size(&self, bytes: usize) -> Result<()> {
        if self.max_plaintext.is_some_and(|limit| bytes > limit) {
            return Err(JoseError::InvalidToken(
                "plaintext exceeds configured maximum size".into(),
            ));
        }
        Ok(())
    }

    pub(crate) fn check(&self, alg: JweAlgorithm, enc: JweEncryption) -> Result<()> {
        if self.allow_all {
            return Ok(());
        }
        if !self.allowed_alg.contains(&alg) {
            return Err(JoseError::UnsupportedAlgorithm(format!(
                "JWE alg {} is not in the caller's allow-list",
                alg.as_str()
            )));
        }
        if !self.allowed_enc.contains(&enc) {
            return Err(JoseError::UnsupportedAlgorithm(format!(
                "JWE enc {} is not in the caller's allow-list",
                enc.as_str()
            )));
        }
        Ok(())
    }
}

/// Every content-encryption algorithm the library supports. Used by the
/// JWK-first decrypt path, which pins `alg` to the JWK but leaves `enc`
/// flexible (the CEK length is bound to `enc` and re-validated downstream).
pub(crate) fn all_enc_algorithms() -> Vec<JweEncryption> {
    vec![
        JweEncryption::A128CbcHs256,
        JweEncryption::A192CbcHs384,
        JweEncryption::A256CbcHs512,
        JweEncryption::A128GCM,
        JweEncryption::A192GCM,
        JweEncryption::A256GCM,
    ]
}

// ---------------------------------------------------------------------------
// Parsed (unauthenticated) envelope
// ---------------------------------------------------------------------------

/// A JWE envelope after structural and policy checks, before authentication.
///
/// `header_b64` keeps the *original* encoded protected-header bytes verbatim:
/// they are the first component of the AEAD/MAC input, and re-serializing the
/// parsed header would produce different bytes (member order, escaping), which
/// would both break authentication and let a re-encode hide a header change.
/// The parsed [`JoseHeader`] is returned separately by [`parse_envelope`]: it
/// is caller-facing data (which headers were authenticated), while this struct
/// is the encrypted content the crypto layer consumes.
#[derive(Debug)]
pub(crate) struct ParsedEnvelope<'a> {
    /// Verbatim base64url protected header (AAD input, never re-encoded).
    pub header_b64: &'a str,
    /// Key-management algorithm, already allow-listed by the caller.
    pub alg: JweAlgorithm,
    /// Whether `alg` came from the integrity-protected header.
    ///
    /// RFC 7516 §7.2.1 allows `alg` to sit in an unprotected member of the JSON
    /// serialization. Nothing in this crate *trusts* an unauthenticated
    /// algorithm: when this is `false` the caller must have independently
    /// pinned the algorithm to the key it holds (see the JWK decrypt paths),
    /// so the header value is being *checked*, not believed.
    pub alg_authenticated: bool,
    /// Content-encryption algorithm, already allow-listed by the caller.
    pub enc: JweEncryption,
    /// Wrapped key (empty for `dir`).
    pub encrypted_key: Vec<u8>,
    /// Content IV.
    pub iv: Vec<u8>,
    /// Content ciphertext.
    pub ciphertext: Vec<u8>,
    /// Content authentication tag.
    pub tag: Vec<u8>,
}

/// Protected-header decisions made before any ciphertext field is decoded.
pub(crate) struct InspectedEnvelope {
    /// Key-management algorithm and whether its source was authenticated.
    pub alg: JweAlgorithm,
    pub alg_authenticated: bool,
    /// Protected content-encryption algorithm.
    pub enc: JweEncryption,
    /// Parsed protected header used by key management after policy passes.
    pub protected: JoseHeader,
}

/// Decode and policy-check one envelope's fields.
///
/// `unprotected_alg` is the `alg` value conveyed outside the protected header,
/// if any (JSON serialization only; the compact path passes `None`).
///
/// Rejects `zip` (compression is not implemented, so returning the still
/// compressed bytes as "plaintext" would be a silent integrity failure) and
/// any `crit` member (no JWE critical extension is implemented), then resolves
/// the typed algorithms. The caller enforces its own algorithm allow-list with
/// [`JweDecryptOptions::check`] once `alg` / `enc` are known.
///
/// # Errors
///
/// [`JoseError::InvalidHeader`] for a policy violation or a missing/unknown
/// `enc`; [`JoseError::UnsupportedAlgorithm`] for an unknown `alg`;
/// [`JoseError::Base64`] / [`JoseError::Json`] for malformed field data.
///
/// Returns the envelope content together with the parsed protected header.
pub(crate) fn parse_envelope<'a>(
    header_b64: &'a str,
    unprotected_alg: Option<&str>,
    encrypted_key_b64: &str,
    iv_b64: &str,
    ciphertext_b64: &str,
    tag_b64: &str,
    options: &JweDecryptOptions,
) -> Result<(ParsedEnvelope<'a>, JoseHeader)> {
    let inspected = inspect_envelope(header_b64, unprotected_alg, options.understood_crit())?;
    preflight_envelope_fields(
        encrypted_key_b64,
        iv_b64,
        ciphertext_b64,
        tag_b64,
        &inspected,
        options,
    )?;
    decode_envelope_fields(
        header_b64,
        encrypted_key_b64,
        iv_b64,
        ciphertext_b64,
        tag_b64,
        inspected,
    )
}

/// Parse and validate only the protected header, without decoding encrypted bodies.
pub(crate) fn inspect_envelope(
    header_b64: &str,
    unprotected_alg: Option<&str>,
    understood_crit: &[String],
) -> Result<InspectedEnvelope> {
    ensure_token_size(header_b64)?;
    let header_json = base64url::decode(header_b64)?;
    let header: JoseHeader = serde_json::from_slice(&header_json)?;

    // RFC 7516 §4.1.3: the library does not implement content compression.
    // Reject tokens declaring a `zip` member instead of silently returning
    // the still-compressed bytes as plaintext.
    if header.extra.contains_key("zip") {
        return Err(JoseError::InvalidHeader(
            "unsupported zip header: content compression is not supported".into(),
        ));
    }

    // RFC 7516 §4.1.13 / RFC 7515 §4.1.11: `crit` may name only extensions the
    // *caller* has declared it implements. With the default (empty) list, any
    // `crit` is refused — which is the pre-existing behaviour, kept as the
    // default rather than re-litigated (ADR 0015).
    validate_crit(&header, understood_crit)?;

    // `alg` normally lives in the protected header. The JSON serialization may
    // instead convey it in an unprotected member (`unprotected_alg`), which is
    // legal (RFC 7516 §7.2.1) but unauthenticated: the flag records where it
    // came from so callers can demand a key-pinned algorithm before accepting
    // it. The compact serialization always passes `None`, so an absent `alg`
    // there keeps its original "unknown algorithm" error.
    let (alg, alg_authenticated) = match (header.alg.as_str(), unprotected_alg) {
        ("", Some(outer)) => (JweAlgorithm::from_str(outer)?, false),
        (protected, _) => (JweAlgorithm::from_str(protected)?, !protected.is_empty()),
    };
    let enc_str = header
        .enc
        .as_deref()
        .ok_or_else(|| JoseError::InvalidHeader("missing enc field".into()))?;
    let enc = JweEncryption::from_str(enc_str)?;

    Ok(InspectedEnvelope {
        alg,
        alg_authenticated,
        enc,
        protected: header,
    })
}

/// Enforce algorithm, allocation, and plaintext budgets before decoding body fields.
pub(crate) fn preflight_envelope_fields(
    encrypted_key_b64: &str,
    iv_b64: &str,
    ciphertext_b64: &str,
    tag_b64: &str,
    inspected: &InspectedEnvelope,
    options: &JweDecryptOptions,
) -> Result<()> {
    for field in [encrypted_key_b64, iv_b64, ciphertext_b64, tag_b64] {
        ensure_token_size(field)?;
    }
    options.check(inspected.alg, inspected.enc)?;
    options.check_plaintext_size(minimum_plaintext_len(ciphertext_b64.len(), inspected.enc))?;
    Ok(())
}

/// Decode encrypted fields after the caller has completed all cheap policy checks.
pub(crate) fn decode_envelope_fields<'a>(
    header_b64: &'a str,
    encrypted_key_b64: &str,
    iv_b64: &str,
    ciphertext_b64: &str,
    tag_b64: &str,
    inspected: InspectedEnvelope,
) -> Result<(ParsedEnvelope<'a>, JoseHeader)> {
    let envelope = ParsedEnvelope {
        header_b64,
        alg: inspected.alg,
        alg_authenticated: inspected.alg_authenticated,
        enc: inspected.enc,
        encrypted_key: base64url::decode(encrypted_key_b64)?,
        iv: base64url::decode(iv_b64)?,
        ciphertext: base64url::decode(ciphertext_b64)?,
        tag: base64url::decode(tag_b64)?,
    };
    Ok((envelope, inspected.protected))
}

/// Content-decrypt an envelope and enforce the plaintext-size limit. The
/// caller has already run the algorithm allow-list check and recovered the CEK.
///
/// The exact AES-CBC plaintext length is known only after authenticated
/// padding removal; on a size rejection the authenticated plaintext is wiped
/// instead of returned.
pub(crate) fn finish_decrypt(
    envelope: &ParsedEnvelope<'_>,
    cek: &[u8],
    aad: &[u8],
    options: &JweDecryptOptions,
) -> Result<Vec<u8>> {
    let mut plaintext = Zeroizing::new(content::content_decrypt(
        envelope.enc,
        cek,
        &envelope.iv,
        &envelope.ciphertext,
        &envelope.tag,
        aad,
    )?);
    options.check_plaintext_size(plaintext.len())?;
    Ok(std::mem::take(&mut *plaintext))
}

// ---------------------------------------------------------------------------
// Key management: produce CEK (encrypt side)
// ---------------------------------------------------------------------------

/// Returns `(cek, encrypted_key)`. For `dir`, `encrypted_key` is empty.
///
/// The CEK is returned wrapped in `Zeroizing` so its heap buffer is
/// wiped when it goes out of scope — key material never lingers in
/// the allocator after the encryption completes.
pub(crate) fn produce_cek(
    key: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
    // Direct key agreement: the key *is* the CEK, so there is nothing to wrap
    // and no `encrypted_key` member to emit.
    if alg == JweAlgorithm::Dir {
        check_dir_key(key, enc)?;
        return Ok((Zeroizing::new(key.to_vec()), Vec::new()));
    }
    let cek = Zeroizing::new(content::random_bytes(enc.cek_size()));
    let wrapped = wrap_cek(&cek, key, alg, enc)?;
    Ok((cek, wrapped))
}

/// Wrap an existing CEK for one recipient.
///
/// Split out of [`produce_cek`] because the General JWE Serialization
/// (RFC 7516 §7.2.1) encrypts the *same* CEK once per recipient: content
/// encryption happens a single time and only the key-management step repeats.
///
/// # Errors
///
/// [`JoseError::UnsupportedAlgorithm`] for `dir` (which conveys no key) or
/// unimplemented key management, [`JoseError::Key`] for a wrong-length KEK,
/// [`JoseError::Crypto`] for a wrap failure.
pub(crate) fn wrap_cek(
    cek: &[u8],
    key: &[u8],
    alg: JweAlgorithm,
    _enc: JweEncryption,
) -> Result<Vec<u8>> {
    match alg {
        // `dir` has no per-recipient key: the shared key is the CEK itself.
        // Asking to "wrap it for another recipient" is asking for a second copy
        // of the CEK, which is not what direct key agreement means.
        JweAlgorithm::Dir => Err(JoseError::UnsupportedAlgorithm(
            "dir conveys no encrypted key, so a general JWE cannot address a second recipient; \
             use a key-wrapping or key-transport algorithm to reach several recipients"
                .into(),
        )),

        // AES Key Wrap.
        JweAlgorithm::A128KW | JweAlgorithm::A192KW | JweAlgorithm::A256KW => {
            check_kek_size(alg, key)?;
            let kw_alg = jwe_alg_to_keywrap(alg)?;
            kryptering::keywrap::wrap(kw_alg, key, cek).map_err(JoseError::Crypto)
        }

        // AES-GCM key management for a *second* recipient would need its own `iv`
        // and `tag` per recipient, which has no authenticated home (ADR 0020). The
        // single-recipient path never reaches this function.
        other if aes_gcm_kw_key_len(other).is_some() => {
            Err(per_recipient_member_unsupported(alg, "iv and tag"))
        }

        // RSA-OAEP.
        JweAlgorithm::RsaOaep256 => {
            let pub_key = parse_rsa_public_key(key)?;
            let kt_alg = jwe_alg_to_keytransport(alg)?;
            kryptering::keytransport::kt_encrypt(kt_alg, &pub_key, cek, None)
                .map_err(JoseError::Crypto)
        }

        #[cfg(feature = "rsa-oaep")]
        JweAlgorithm::RsaOaep => {
            let pub_key = parse_rsa_public_key(key)?;
            let kt_alg = jwe_alg_to_keytransport(alg)?;
            kryptering::keytransport::kt_encrypt(kt_alg, &pub_key, cek, None)
                .map_err(JoseError::Crypto)
        }

        _ => Err(JoseError::UnsupportedAlgorithm(format!(
            "key management algorithm {} not yet implemented",
            alg.as_str()
        ))),
    }
}

/// RFC 7518 §4.6.2's `OtherInfo`, split the way the backend's parameters want
/// it: AlgorithmID, PartyUInfo, and PartyVInfo with **SuppPubInfo on its tail**.
///
/// The backend defines OtherInfo as `AlgID || PartyUInfo || PartyVInfo`; JOSE
/// appends SuppPubInfo (the key length in bits, big-endian). Appending it to the
/// last field makes the concatenation byte-identical to the RFC's, which the
/// unit test below pins against the byte array printed in Appendix C.
struct OtherInfo {
    algorithm_id: Vec<u8>,
    party_u: Vec<u8>,
    party_v: Vec<u8>,
}

impl OtherInfo {
    /// The whole structure as one buffer.
    ///
    /// The backend takes the three fields separately, so production code never
    /// needs this; it exists so the tests can assert the *concatenation* — which
    /// is what the backend hashes — against the octet array RFC 7518 Appendix C
    /// prints.
    #[cfg(test)]
    fn as_bytes(&self) -> Vec<u8> {
        let mut out =
            Vec::with_capacity(self.algorithm_id.len() + self.party_u.len() + self.party_v.len());
        out.extend_from_slice(&self.algorithm_id);
        out.extend_from_slice(&self.party_u);
        out.extend_from_slice(&self.party_v);
        out
    }
}

/// Build [`OtherInfo`] from already-decoded party values.
///
/// Each field is `Datalen || Data` with a big-endian 32-bit length. An absent
/// `apu`/`apv` contributes the empty octet sequence — **four zero octets**, not
/// nothing, which is the single easiest way to derive a key nobody else
/// derives.
fn other_info(alg_id: &str, apu: Option<&[u8]>, apv: Option<&[u8]>, key_len: usize) -> OtherInfo {
    fn length_prefixed(data: Option<&[u8]>) -> Vec<u8> {
        let data = data.unwrap_or(&[]);
        let mut out = Vec::with_capacity(4 + data.len());
        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
        out.extend_from_slice(data);
        out
    }

    let mut party_v = length_prefixed(apv);
    party_v.extend_from_slice(&((key_len as u32) * 8).to_be_bytes());
    OtherInfo {
        algorithm_id: length_prefixed(Some(alg_id.as_bytes())),
        party_u: length_prefixed(apu),
        party_v,
    }
}

/// JOSE's Concat KDF, RFC 7518 §4.6.2 (NIST SP 800-56A §5.8.1 single step).
///
/// Derives the agreed key from the ECDH shared secret `Z`. Three properties are
/// worth stating because they are the ones an implementation gets wrong:
///
/// * **the digest is always SHA-256** — RFC 7518 §4.6.2 fixes it ("where the
///   Digest Method is SHA-256") rather than tying it to the key size, so a
///   derivation that picked SHA-512 for a 256-bit CEK would agree with nobody,
///   including the RFC's own Appendix C vector (which this crate's tests assert);
/// * **`OtherInfo` is length-prefixed**: each of AlgorithmID, PartyUInfo and
///   PartyVInfo is `Datalen || Data` with a big-endian 32-bit `Datalen`, and
///   SuppPubInfo is the key length *in bits* as a 32-bit big-endian value.
///   Skipping a prefix, or using a zero length for an absent `apu` instead of
///   the four zero octets, changes the derived key with no error anywhere;
/// * **`apu` and `apv` must differ** when both are used (RFC 7518 §4.6.2), so
///   that the two party values actually identify two parties.
///
/// `alg_id` is the ASCII `enc` value for direct key agreement and the ASCII
/// `alg` value for key agreement with key wrapping (RFC 7518 §4.6.2). `apu` and
/// `apv` are the base64url *encoded* header values, decoded here.
///
/// # Errors
///
/// [`JoseError::InvalidHeader`] for a non-canonical `apu`/`apv`, or for equal
/// ones; [`JoseError::Crypto`] if the backend rejects the derivation.
pub(crate) fn concat_kdf(
    z: &[u8],
    key_len: usize,
    alg_id: &str,
    apu: Option<&str>,
    apv: Option<&str>,
) -> Result<Zeroizing<Vec<u8>>> {
    let apu = apu.map(crate::base64url::decode).transpose()?;
    let apv = apv.map(crate::base64url::decode).transpose()?;
    if let (Some(apu), Some(apv)) = (&apu, &apv) {
        if apu == apv {
            return Err(JoseError::InvalidHeader(
                "apu and apv must be distinct when both are present (RFC 7518 §4.6.2)".into(),
            ));
        }
    }

    let info = other_info(alg_id, apu.as_deref(), apv.as_deref(), key_len);
    // kryptering's OtherInfo is the concatenation of these three fields in
    // order, so the bytes it hashes are RFC 7518 §4.6.2's OtherInfo exactly.
    let params = kryptering::kdf::ConcatKdfParams {
        hash: kryptering::HashAlgorithm::Sha256,
        algorithm_id: Some(info.algorithm_id),
        party_u_info: Some(info.party_u),
        party_v_info: Some(info.party_v),
    };
    let derived = kryptering::kdf::concat_kdf(z, key_len, &params).map_err(JoseError::Crypto)?;
    if derived.len() != key_len {
        return Err(JoseError::Key(format!(
            "Concat KDF derived {} bytes, expected {key_len}",
            derived.len()
        )));
    }
    Ok(Zeroizing::new(derived))
}

/// Read an `apu`/`apv` header member as the base64url string it must be.
///
/// These members are not typed fields, so they arrive through the untyped
/// member map and can hold any JSON value. A non-string is refused rather than
/// stringified: `"apu": 5` and `"apu": "5"` would otherwise derive the same key
/// while looking nothing alike.
fn agreement_member(header: &JoseHeader, name: &str) -> Result<Option<String>> {
    match header.extra.get(name) {
        None => Ok(None),
        Some(value) => match value.as_str() {
            Some(text) => Ok(Some(text.to_string())),
            None => Err(JoseError::InvalidHeader(format!(
                "{name} must be a base64url string (RFC 7518 §4.6.1)"
            ))),
        },
    }
}

/// The key-encryption key length an agreement-with-wrapping algorithm names.
///
/// `None` for every other algorithm, including `ECDH-ES` itself: in direct mode
/// there is no KEK, the KDF output *is* the CEK. This is also the predicate this
/// crate uses to ask "is this an agreement algorithm that wraps?".
///
/// The length comes from the **algorithm**, never from `enc`: `keydatalen` is the
/// KEK's bit length in this mode (RFC 7518 §4.6.2), while the CEK it wraps is
/// sized by `enc` — an `ECDH-ES+A128KW` + `A256GCM` message derives a 128-bit KEK
/// for a 256-bit CEK.
pub(crate) fn agreement_kek_len(alg: JweAlgorithm) -> Option<usize> {
    match alg {
        JweAlgorithm::EcdhEsA128kw => Some(16),
        JweAlgorithm::EcdhEsA192kw => Some(24),
        JweAlgorithm::EcdhEsA256kw => Some(32),
        _ => None,
    }
}

/// The refusal when a key-agreement algorithm is asked to address a general JWE.
///
/// In wrapping modes the cryptography scales to several recipients on its own —
/// one CEK, one agreement per recipient — but each recipient needs its *own*
/// ephemeral value, and RFC 7516 gives a recipient element no protected header of
/// its own to carry it in. Publishing it in the element's unprotected `header` is
/// what RFC 7520 §5.13 and other implementations do, and this crate does not read
/// or write an unauthenticated key contribution until that trade-off is decided
/// (ADR 0018, which records the argument and the alternatives).
pub(crate) fn per_recipient_epk_unsupported(alg: JweAlgorithm) -> JoseError {
    per_recipient_member_unsupported(alg, "epk")
}

/// The key length an AES-GCM key-management algorithm names.
///
/// `None` for every other algorithm. As with [`agreement_kek_len`], this answers
/// "how long is the key that wraps the CEK", and the answer comes from `alg` —
/// `A128GCMKW` uses a 128-bit key whatever `enc` needs the CEK to be.
pub(crate) fn aes_gcm_kw_key_len(alg: JweAlgorithm) -> Option<usize> {
    match alg {
        JweAlgorithm::A128Gcmkw => Some(16),
        JweAlgorithm::A192Gcmkw => Some(24),
        JweAlgorithm::A256Gcmkw => Some(32),
        _ => None,
    }
}

/// What a PBES2 algorithm fixes: the derived key length and the HMAC PRF.
///
/// RFC 7518 §4.8 pairs each `alg` with one hash and one AES-KW key size —
/// `PBES2-HS256+A128KW` is HMAC-SHA-256 producing a 128-bit key for `A128KW`, and so
/// on. The name says all of it, which is why nothing here reads a length from
/// anywhere else: the derived key is the key-encryption key, so its length is the
/// wrapping algorithm's key length, and `enc` has no claim on it (the CEK it protects
/// is a different length entirely, and the two get compared only by accident).
pub(crate) fn pbes2_params(alg: JweAlgorithm) -> Option<(usize, kryptering::HashAlgorithm)> {
    use kryptering::HashAlgorithm;
    match alg {
        JweAlgorithm::Pbes2Hs256A128kw => Some((16, HashAlgorithm::Sha256)),
        JweAlgorithm::Pbes2Hs384A192kw => Some((24, HashAlgorithm::Sha384)),
        JweAlgorithm::Pbes2Hs512A256kw => Some((32, HashAlgorithm::Sha512)),
        _ => None,
    }
}

/// Whether `alg` derives its key-encryption key from a password.
///
/// Separate from [`pbes2_params`] because the receive path needs to refuse a
/// password-shaped input for a non-PBES2 algorithm *by name*, before it can say
/// anything about parameters.
pub(crate) fn alg_is_pbes2(alg: JweAlgorithm) -> bool {
    pbes2_params(alg).is_some()
}

/// The PBKDF2 salt for a PBES2 operation: `UTF8(Alg) || 0x00 || Salt Input`.
///
/// The algorithm identifier is inside the salt (RFC 7518 §4.8.1.1), so the same
/// password and the same salt input derive *different* keys under the three PBES2
/// algorithms. That is what makes the `alg` pin load-bearing here rather than
/// cosmetic: a message that claims `PBES2-HS256+A128KW` while intending
/// `PBES2-HS512+A256KW` derives a different KEK and fails the wrap's integrity check,
/// instead of happening to work.
pub(crate) fn pbes2_salt(alg: JweAlgorithm, salt_input: &[u8]) -> Vec<u8> {
    let mut salt = Vec::with_capacity(alg.as_str().len() + 1 + salt_input.len());
    salt.extend_from_slice(alg.as_str().as_bytes());
    salt.push(0x00);
    salt.extend_from_slice(salt_input);
    salt
}

/// Derive a PBES2 key-encryption key, within the caller's work budget.
///
/// The budget is the point of routing PBKDF2 through here rather than calling the
/// backend directly: `p2c` arrives in the message, chosen by whoever sent it, and it
/// names how much CPU the *recipient* spends. `max_iterations` is that recipient's
/// limit, applied before any work happens — a rejected count costs nothing, whereas
/// deriving and then discovering the count was absurd is exactly the bill this
/// prevents. The floors and ceilings are documented on the constants in
/// [`crate::jwe::password`].
///
/// The result is `Zeroizing`: of everything in this flow, the derived key is what an
/// attacker with memory access wants, and it is derived in milliseconds from
/// something a human typed.
pub(crate) fn pbes2_derive(
    alg: JweAlgorithm,
    password: &super::password::Password,
    salt_input: &[u8],
    iterations: u32,
    max_iterations: u32,
) -> Result<Zeroizing<Vec<u8>>> {
    let (key_len, hash) = pbes2_params(alg).ok_or_else(|| {
        JoseError::UnsupportedAlgorithm(format!("{} is not a PBES2 algorithm", alg.as_str()))
    })?;
    if iterations < super::password::PBES2_MIN_ITERATIONS {
        return Err(JoseError::InvalidHeader(format!(
            "p2c of {iterations} is below the {min} iteration floor this crate accepts \
             (RFC 7518 §4.8.1.2 recommends a minimum of 1000)",
            min = super::password::PBES2_MIN_ITERATIONS
        )));
    }
    if iterations > max_iterations {
        return Err(JoseError::InvalidHeader(format!(
            "p2c of {iterations} exceeds this recipient's PBES2 work budget of \
             {max_iterations} iterations; the sender chooses that count and the recipient \
             pays it, so it is refused rather than computed"
        )));
    }
    let params = kryptering::kdf::Pbkdf2Params {
        hash,
        salt: pbes2_salt(alg, salt_input),
        iteration_count: iterations,
        key_length: key_len,
    };
    Ok(Zeroizing::new(kryptering::kdf::pbkdf2_derive(
        password.as_bytes(),
        &params,
    )?))
}

/// Generate a PBES2 salt input: fresh, random, and longer than the RFC's minimum.
///
/// RFC 7518 §4.8.1.1 requires "8 or more octets" and a new value for *every*
/// encryption operation. Sixteen is used because the salt is the only thing
/// separating two messages protected by the same password — with a repeated salt,
/// two messages under one password are two AES-KW ciphertexts of the same CEK under
/// the same derived key, which is the shape an offline attack wants — and because
/// that is the length both interop peers emit.
pub(crate) fn pbes2_salt_input() -> Vec<u8> {
    content::random_bytes(16)
}

/// Publish PBES2's `p2s` and `p2c` in the protected header.
///
/// Both are mandatory (RFC 7518 §4.8.1) and both are **this crate's to generate**:
/// `p2s` is a nonce whose reuse collapses the salt's purpose, and `p2c` is a work
/// budget the recipient pays. They join `epk` and the AES-GCM wrap's `iv`/`tag` as
/// members the library produces, refused from a caller for every algorithm — and, as
/// there, the check lives here too, because this is the function that would otherwise
/// overwrite a supplied value in silence.
///
/// `p2c` is written as a JSON integer, as §4.8.1.2 requires; a quoted number would be
/// read as a string by a conformant peer and refused.
fn with_pbes2_members(
    header: &JoseHeader,
    salt_input: &[u8],
    iterations: u32,
    alg: JweAlgorithm,
) -> Result<JoseHeader> {
    let mut header = header.clone();
    for member in ["p2s", "p2c"] {
        if header.extra.contains_key(member) {
            return Err(JoseError::InvalidHeader(format!(
                "{}: `{member}` is generated by this crate for PBES2 (RFC 7518 \u{a7}4.8.1) and \
                 cannot be supplied by the caller",
                alg.as_str()
            )));
        }
    }
    header.extra.insert(
        "p2s".into(),
        serde_json::json!(crate::base64url::encode(salt_input)),
    );
    header
        .extra
        .insert("p2c".into(), serde_json::json!(iterations));
    Ok(header)
}

/// Read a PBES2 message's salt input and iteration count from the protected header.
///
/// Both members are mandatory, and both are read **only** from the integrity-protected
/// header: an unprotected `p2s`/`p2c` was refused at parse time (ADR 0013). That is
/// load-bearing in a way it is not for most members. These two values are the KDF's
/// inputs, and a peer that can edit them without detection can pick a salt of its
/// choosing — which turns "derive a key from the password" into "derive a key from the
/// password and a value I control", the primitive behind every offline dictionary
/// attack that beats a precomputed table.
///
/// The salt must be at least 8 octets (§4.8.1.1's own minimum) and the count must be a
/// JSON integer, positive, and within the caller's budget.
fn pbes2_message_params(header: &JoseHeader, alg: JweAlgorithm) -> Result<(Vec<u8>, u32)> {
    let salt_member = header.extra.get("p2s").ok_or_else(|| {
        JoseError::InvalidHeader(format!(
            "{} requires a p2s header member (RFC 7518 \u{a7}4.8.1.1), which is absent",
            alg.as_str()
        ))
    })?;
    let text = salt_member.as_str().ok_or_else(|| {
        JoseError::InvalidHeader("p2s must be a base64url string (RFC 7518 \u{a7}4.8.1.1)".into())
    })?;
    let salt_input = crate::base64url::decode(text)?;
    if salt_input.len() < 8 {
        return Err(JoseError::InvalidHeader(format!(
            "p2s must encode 8 or more octets (RFC 7518 \u{a7}4.8.1.1), got {}",
            salt_input.len()
        )));
    }

    let count_member = header.extra.get("p2c").ok_or_else(|| {
        JoseError::InvalidHeader(format!(
            "{} requires a p2c header member (RFC 7518 \u{a7}4.8.1.2), which is absent",
            alg.as_str()
        ))
    })?;
    // `as_u64` accepts only a JSON integer: a float, a quoted number, a bool and a
    // negative all fail here, which is the §4.8.1.2 definition of "positive JSON
    // integer" rather than a best-effort coercion.
    let iterations = count_member.as_u64().ok_or_else(|| {
        JoseError::InvalidHeader(
            "p2c must be a positive JSON integer (RFC 7518 \u{a7}4.8.1.2)".into(),
        )
    })?;
    let iterations = u32::try_from(iterations).map_err(|_| {
        JoseError::InvalidHeader(format!(
            "p2c of {iterations} is larger than this implementation can run"
        ))
    })?;
    Ok((salt_input, iterations))
}

/// Recover the CEK from a PBES2 message.
///
/// A wrong password fails here, at the AES-KW integrity check on the wrapped key, and
/// says so — unlike RSA-OAEP there is no implicit rejection to preserve, because RFC
/// 3394's wrap authenticates and a wrong derived key cannot produce a CEK at all. That
/// also means this path is a password oracle for anyone who can send a message and
/// observe the failure: which is inherent to password-based crypto, and the reason the
/// iteration count (rather than the failure mode) is what limits an offline attack.
fn pbes2_recover_cek(
    header: &JoseHeader,
    password: &super::password::Password,
    alg: JweAlgorithm,
    enc: JweEncryption,
    encrypted_key: &[u8],
    max_iterations: u32,
) -> Result<Zeroizing<Vec<u8>>> {
    if encrypted_key.is_empty() {
        return Err(JoseError::InvalidToken(format!(
            "{} must convey the wrapped content key",
            alg.as_str()
        )));
    }
    let (salt_input, iterations) = pbes2_message_params(header, alg)?;
    let kek = pbes2_derive(alg, password, &salt_input, iterations, max_iterations)?;
    let cek = Zeroizing::new(
        kryptering::keywrap::unwrap(jwe_alg_to_keywrap(alg)?, &kek, encrypted_key)
            .map_err(|e| {
                // Named as a password failure rather than a generic crypto error: this
                // is the one key-management path where "unwrap failed" almost always
                // means "wrong password", and that distinction is the whole diagnostic.
                JoseError::Key(format!(
                    "{}: the wrapped key did not authenticate; wrong password, or the                      p2s/p2c parameters do not match the sender's ({e})",
                    alg.as_str()
                ))
            })?,
    );
    if cek.len() != enc.cek_size() {
        return Err(JoseError::Key(format!(
            "{}: unwrapped CEK length {} does not match the {} bytes {} requires",
            alg.as_str(),
            cek.len(),
            enc.cek_size(),
            enc.as_str()
        )));
    }
    Ok(cek)
}

/// The refusal when a key-management algorithm's per-message values would have to
/// be published once per recipient.
///
/// `epk` (agreement) and `iv`/`tag` (AES-GCM key management) both describe *one*
/// recipient's key operation, and RFC 7516 §7.2.1 gives a recipient element exactly
/// two members — `header` (unprotected) and `encrypted_key`. There is no
/// per-recipient protected header, so the values can only be published
/// unauthenticated; this crate refuses rather than doing that, on emit and on
/// receive alike (ADR 0018, ADR 0020).
pub(crate) fn per_recipient_member_unsupported(alg: JweAlgorithm, members: &str) -> JoseError {
    JoseError::UnsupportedAlgorithm(format!(
        "{} needs one {members} value per recipient, and RFC 7516 gives a recipient element no \
         protected header of its own to carry it in, so only the single-recipient (flattened and \
         compact) forms are supported for this algorithm",
        alg.as_str()
    ))
}

/// Publish `ephemeral`'s public half as the message's `epk` member.
///
/// Public half only: the ephemeral private scalar must never travel in the
/// message (RFC 7518 §4.6.1.1).
fn with_epk(header: &JoseHeader, ephemeral: &crate::jwk::Jwk) -> Result<JoseHeader> {
    let mut with_epk = header.clone();
    with_epk.extra.insert(
        "epk".into(),
        serde_json::to_value(own_public_jwk(ephemeral))?,
    );
    Ok(with_epk)
}

/// Read the sender's ephemeral public key from a received agreement message.
///
/// The **authenticated protected header only**: the JSON serializations already
/// refuse `epk` in an unprotected position (ADR 0013), so a recipient never
/// derives a key from a value the sender did not integrity protect.
fn epk_from_header(header: &JoseHeader) -> Result<crate::jwk::Jwk> {
    let epk_value = header
        .extra
        .get("epk")
        .ok_or_else(|| JoseError::InvalidHeader(
            "key agreement requires an epk (ephemeral public key) member in the protected header (RFC 7518 §4.6.1.1)"
                .into(),
        ))?;
    serde_json::from_value(epk_value.clone())
        .map_err(|e| JoseError::InvalidHeader(format!("epk is not a well-formed JWK: {e}")))
}

/// The sender's half of a key agreement, with the ephemeral key already published.
///
/// Holds the agreement handles rather than a derived key, and is consumed by
/// either mode: direct agreement derives the CEK, wrapping modes derive a KEK and
/// wrap. Nothing here hands out `Z` (ADR 0016).
struct AgreementSender {
    own: crate::jwk::agreement::AgreementKey,
    peer: crate::jwk::agreement::PeerKey,
    /// The caller's header plus the `epk` member naming [`Self::own`].
    header: JoseHeader,
}

/// Generate this operation's ephemeral key and pair it with `recipient`.
///
/// The curve is the **recipient's** (`peer_key` refuses an off-curve or
/// private-bearing peer): agreement is only defined within one curve, and this
/// way a P-521 recipient cannot be talked into a P-521→P-256 downgrade through a
/// caller-chosen ephemeral key. `epk` is not an input anywhere in this crate,
/// which is how RFC 7518 §4.6's "MUST generate a new ephemeral key ... for each
/// key agreement operation" stays true.
fn agreement_sender(header: &JoseHeader, recipient: &crate::jwk::Jwk) -> Result<AgreementSender> {
    use crate::jwk::agreement::{agreement_key, peer_key};
    // Senders legitimately hold the recipient's *private* JWK (the RFC's own
    // examples do), so `d` is dropped rather than refused — but only the public
    // half is ever used, and only the public half is ever published.
    let peer = peer_key(&recipient.to_public_jwk())?;
    let ephemeral = crate::jwk::agreement::generate_ephemeral(peer.curve())?;
    let own = agreement_key(&ephemeral)?;
    Ok(AgreementSender {
        own,
        peer,
        header: with_epk(header, &ephemeral)?,
    })
}

impl AgreementSender {
    /// Concat KDF over this agreement, with the header's `apu`/`apv` as inputs.
    ///
    /// `alg_id` and `key_len` are decided by the caller because the two
    /// agreement modes disagree about both — see [`Self::derive_cek`] and
    /// [`Self::wrap`].
    fn derive(
        &self,
        alg_id: &str,
        apu: Option<&str>,
        apv: Option<&str>,
        key_len: usize,
    ) -> Result<Zeroizing<Vec<u8>>> {
        self.own.derive_key(&self.peer, alg_id, apu, apv, key_len)
    }

    /// Direct agreement: the KDF output **is** the CEK, so AlgorithmID is the
    /// ASCII `enc` value and keydatalen the CEK length (`enc.cek_size()`).
    fn derive_cek(&self, enc: JweEncryption) -> Result<Zeroizing<Vec<u8>>> {
        let apu = agreement_member(&self.header, "apu")?;
        let apv = agreement_member(&self.header, "apv")?;
        self.derive(enc.as_str(), apu.as_deref(), apv.as_deref(), enc.cek_size())
    }

    /// Agreement with key wrapping: AlgorithmID is the ASCII **`alg`** value and
    /// keydatalen the KEK length the algorithm names (§4.6.2) — so the same two
    /// keys derive a different KEK here than the CEK they derive under `ECDH-ES`,
    /// which is what stops a message from being read under the wrong mode.
    fn wrap(&self, alg: JweAlgorithm, cek: &[u8]) -> Result<Vec<u8>> {
        let kek_len = agreement_kek_len(alg).ok_or_else(|| {
            JoseError::UnsupportedAlgorithm(format!(
                "{} does not wrap a key with an agreed key-encryption key",
                alg.as_str()
            ))
        })?;
        let apu = agreement_member(&self.header, "apu")?;
        let apv = agreement_member(&self.header, "apv")?;
        let kek = self.derive(alg.as_str(), apu.as_deref(), apv.as_deref(), kek_len)?;
        kryptering::keywrap::wrap(jwe_alg_to_keywrap(alg)?, &kek, cek).map_err(JoseError::Crypto)
    }
}

/// Direct key agreement (`ECDH-ES`): agree the CEK and return the header that
/// carries the ephemeral public key.
///
/// The sender's half is generated here and nowhere else. RFC 7518 §4.6 requires
/// a new ephemeral key per operation, so the value is not an input: accepting
/// one would let a caller reuse an ephemeral key across two messages to two
/// recipients, which reveals the agreed keys to anyone who sees both. The public
/// half is published as `epk` in the protected header, which is also the AAD
/// input — so an attacker who swaps `epk` for a key they control breaks the tag
/// rather than receiving the plaintext (though they can make a recipient derive
/// a key the attacker chose; see the module docs and ADR 0016/0017).
///
/// Returns the header with `epk` inserted, plus the agreed CEK.
fn agree_direct(
    header: &JoseHeader,
    recipient: &crate::jwk::Jwk,
    enc: JweEncryption,
) -> Result<(JoseHeader, Zeroizing<Vec<u8>>)> {
    // The sender's half, the recipient's half and the header carrying `epk` are
    // built by one function shared with the wrapping modes, so "where does the
    // ephemeral key come from" has exactly one answer in this crate.
    let sender = agreement_sender(header, recipient)?;
    let cek = sender.derive_cek(enc)?;
    Ok((sender.header, cek))
}

/// The public-only JWK to publish as `epk`: the freshly generated key with its
/// private component removed.
fn own_public_jwk(ephemeral: &crate::jwk::Jwk) -> crate::jwk::Jwk {
    ephemeral.to_public_jwk()
}

/// Recover the CEK by direct key agreement, from the recipient's private JWK and
/// the `epk` the message carries.
///
/// `epk` is read from the **authenticated protected header only** (the JSON
/// serializations already refuse it in an unprotected position, ADR 0013), and
/// `peer_key` refuses private material in it and validates the point. A curve
/// mismatch against the recipient's own key is refused before any derivation.
fn agree_direct_recover(
    header: &JoseHeader,
    recipient: &crate::jwk::Jwk,
    enc: JweEncryption,
    encrypted_key: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    use crate::jwk::agreement::{agreement_key, peer_key};

    // RFC 7518 §4.6: in Direct Key Agreement mode "the empty octet sequence is
    // used as the JWE Encrypted Key value". A message that conveys one as well
    // is describing two key-management schemes at once, and the CEK it decrypts
    // under would depend on which one a recipient happened to look at first.
    if !encrypted_key.is_empty() {
        return Err(JoseError::InvalidToken(
            "ECDH-ES: encrypted key must be empty (direct key agreement conveys no key)".into(),
        ));
    }

    let epk = epk_from_header(header)?;
    let peer = peer_key(&epk)?;
    let own = agreement_key(recipient)?;

    let apu = agreement_member(header, "apu")?;
    let apv = agreement_member(header, "apv")?;
    own.derive_key(
        &peer,
        enc.as_str(),
        apu.as_deref(),
        apv.as_deref(),
        enc.cek_size(),
    )
}

/// Recover the CEK from a message that agreed a key-encryption key and wrapped it.
///
/// Mirror of [`AgreementSender::wrap`]: AlgorithmID `alg`, keydatalen the KEK
/// length, then AES-KW. Unlike direct mode this mode **must** convey an encrypted
/// key — a message that omits it has no CEK to recover, and reading it as though
/// the agreement supplied the CEK directly would mix two key-management schemes
/// (that is the substitution this check exists to block).
fn agree_wrap_recover(
    header: &JoseHeader,
    recipient: &crate::jwk::Jwk,
    alg: JweAlgorithm,
    enc: JweEncryption,
    encrypted_key: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    use crate::jwk::agreement::{agreement_key, peer_key};

    let kek_len = agreement_kek_len(alg).ok_or_else(|| {
        JoseError::UnsupportedAlgorithm(format!(
            "{} does not wrap a key with an agreed key-encryption key",
            alg.as_str()
        ))
    })?;
    if encrypted_key.is_empty() {
        return Err(JoseError::InvalidToken(format!(
            "{}: an encrypted key is required (the CEK is wrapped under the agreed key)",
            alg.as_str()
        )));
    }

    let epk = epk_from_header(header)?;
    let peer = peer_key(&epk)?;
    let own = agreement_key(recipient)?;
    let apu = agreement_member(header, "apu")?;
    let apv = agreement_member(header, "apv")?;
    let kek = own.derive_key(&peer, alg.as_str(), apu.as_deref(), apv.as_deref(), kek_len)?;

    let cek = kryptering::keywrap::unwrap(jwe_alg_to_keywrap(alg)?, &kek, encrypted_key)
        .map_err(JoseError::Crypto)?;
    if cek.len() != enc.cek_size() {
        return Err(JoseError::Key(format!(
            "{}: unwrapped CEK length {} does not match the {} bytes {} requires",
            alg.as_str(),
            cek.len(),
            enc.cek_size(),
            enc.as_str()
        )));
    }
    Ok(Zeroizing::new(cek))
}

/// What AES-GCM key management produces: the wrapped CEK, plus the two values the
/// protected header must carry.
struct GcmKeyWrap {
    /// `JWE Encrypted Key` — the AES-GCM ciphertext (RFC 7518 §4.7).
    encrypted_key: Vec<u8>,
    /// The 96-bit IV, published as the `iv` header member.
    iv: Vec<u8>,
    /// The 128-bit authentication tag, published as the `tag` header member.
    tag: Vec<u8>,
}

/// Run AES-GCM at the key-wrap sizes, with the parameters RFC 7518 §4.7 fixes.
///
/// One macro for both directions because the only per-direction difference is
/// which of the tag/iv values is input and which is output; the three key sizes,
/// the empty AAD and the 96-bit nonce are identical, and having them spelled once
/// is what keeps the wrap and the unwrap from disagreeing about the AAD — the
/// single way to get this algorithm wrong without the tag catching it.
///
/// The sizes are checked before the primitive is called rather than left to
/// `Nonce::from_slice`/`Tag::from_slice`, which **panic** on a wrong length. The
/// message path cannot reach that (both members are read through
/// `required_header_bytes`, which enforces 12 and 16), but a length check belongs
/// in the function that has the lengths, so the panic is not reachable at all and a
/// future caller cannot introduce it.
macro_rules! gcm_kw_aead {
    (encrypt $kek:expr, $iv:expr, $buffer:expr) => {{
        use aes_gcm::aead::{AeadInOut, KeyInit, Nonce};
        let gcm_err = |e: aes_gcm::Error| {
            JoseError::Crypto(kryptering::Error::Crypto(format!("AES-GCM: {e}")))
        };
        let key_err = |e| JoseError::Key(format!("AES-GCM key init: {e}"));
        let (kek, iv, buffer) = ($kek, $iv, $buffer);
        if iv.len() != 12 {
            return Err(JoseError::Key(format!(
                "internal error: AES-GCM key wrap called with a {}-octet IV, not 12",
                iv.len()
            )));
        }
        match kek.len() {
            16 => {
                type Cipher = aes_gcm::Aes128Gcm;
                let cipher = Cipher::new_from_slice(kek).map_err(key_err)?;
                cipher
                    .encrypt_inout_detached(
                        &Nonce::<Cipher>::try_from(iv.as_slice()).expect("IV length checked above"),
                        b"",
                        (&mut buffer[..]).into(),
                    )
                    .map_err(gcm_err)?
            }
            24 => {
                use aes_gcm::aead::consts::U12;
                type Cipher = aes_gcm::AesGcm<aes::Aes192, U12>;
                let cipher = Cipher::new_from_slice(kek).map_err(key_err)?;
                cipher
                    .encrypt_inout_detached(
                        &Nonce::<Cipher>::try_from(iv.as_slice()).expect("IV length checked above"),
                        b"",
                        (&mut buffer[..]).into(),
                    )
                    .map_err(gcm_err)?
            }
            32 => {
                type Cipher = aes_gcm::Aes256Gcm;
                let cipher = Cipher::new_from_slice(kek).map_err(key_err)?;
                cipher
                    .encrypt_inout_detached(
                        &Nonce::<Cipher>::try_from(iv.as_slice()).expect("IV length checked above"),
                        b"",
                        (&mut buffer[..]).into(),
                    )
                    .map_err(gcm_err)?
            }
            other => {
                // `check_kek_size` has already refused this; getting here means a
                // call site skipped it, which is an internal error, not bad input.
                return Err(JoseError::Key(format!(
                    "internal error: AES-GCM key wrap called with a {other}-byte key"
                )));
            }
        }
    }};
    (decrypt $kek:expr, $iv:expr, $buffer:expr, $tag:expr) => {{
        use aes_gcm::aead::{AeadInOut, KeyInit, Nonce, Tag};
        let gcm_err = |e: aes_gcm::Error| {
            JoseError::Crypto(kryptering::Error::Crypto(format!("AES-GCM: {e}")))
        };
        let key_err = |e| JoseError::Key(format!("AES-GCM key init: {e}"));
        let (kek, iv, buffer, tag) = ($kek, $iv, $buffer, $tag);
        // Same reason as on the encrypt side: the primitive's constructors assert
        // rather than report, and a message-supplied length must never reach one.
        if iv.len() != 12 {
            return Err(JoseError::Key(format!(
                "AES-GCM key unwrap: `iv` must be 12 octets, got {}",
                iv.len()
            )));
        }
        if tag.len() != 16 {
            return Err(JoseError::Key(format!(
                "AES-GCM key unwrap: `tag` must be 16 octets, got {}",
                tag.len()
            )));
        }
        match kek.len() {
            16 => {
                type Cipher = aes_gcm::Aes128Gcm;
                Cipher::new_from_slice(kek)
                    .map_err(key_err)?
                    .decrypt_inout_detached(
                        &Nonce::<Cipher>::try_from(iv).expect("IV length checked above"),
                        b"",
                        (&mut buffer[..]).into(),
                        &Tag::<Cipher>::try_from(tag).expect("tag length checked above"),
                    )
                    .map_err(gcm_err)?
            }
            24 => {
                use aes_gcm::aead::consts::U12;
                type Cipher = aes_gcm::AesGcm<aes::Aes192, U12>;
                Cipher::new_from_slice(kek)
                    .map_err(key_err)?
                    .decrypt_inout_detached(
                        &Nonce::<Cipher>::try_from(iv).expect("IV length checked above"),
                        b"",
                        (&mut buffer[..]).into(),
                        &Tag::<Cipher>::try_from(tag).expect("tag length checked above"),
                    )
                    .map_err(gcm_err)?
            }
            32 => {
                type Cipher = aes_gcm::Aes256Gcm;
                Cipher::new_from_slice(kek)
                    .map_err(key_err)?
                    .decrypt_inout_detached(
                        &Nonce::<Cipher>::try_from(iv).expect("IV length checked above"),
                        b"",
                        (&mut buffer[..]).into(),
                        &Tag::<Cipher>::try_from(tag).expect("tag length checked above"),
                    )
                    .map_err(gcm_err)?
            }
            other => {
                return Err(JoseError::Key(format!(
                    "internal error: AES-GCM key unwrap called with a {other}-byte key"
                )))
            }
        }
    }};
}

/// Encrypt the CEK with AES-GCM (RFC 7518 §4.7).
///
/// The RFC fixes every parameter that an implementation might otherwise be
/// tempted to choose: a 96-bit IV (which is also what makes a random IV safe for
/// GCM), a 128-bit tag regardless of key size, and the **empty octet string** as
/// additional authenticated data. That last point is why the wrap is what it is:
/// the header values that carry the IV and tag are authenticated by the *content*
/// tag as AAD, not by anything the key wrap authenticates itself.
fn gcm_kw_wrap(kek: &[u8], cek: &[u8]) -> Result<GcmKeyWrap> {
    let mut iv = [0u8; 12];
    getrandom::fill(&mut iv).map_err(|e| {
        JoseError::Crypto(kryptering::Error::Crypto(format!(
            "operating-system randomness failed: {e}"
        )))
    })?;
    let mut buffer = cek.to_vec();
    let tag = gcm_kw_aead!(encrypt kek, &iv, &mut buffer);
    Ok(GcmKeyWrap {
        encrypted_key: buffer,
        iv: iv.to_vec(),
        tag: tag.to_vec(),
    })
}

/// Recover the CEK from an AES-GCM wrapped key.
///
/// A failed authentication is reported as a `JoseError::Crypto` rather than
/// silently substituting a random CEK (contrast RSA-OAEP's implicit rejection):
/// here the recipient's key only unwraps a key the message carries, and the
/// content tag would fail regardless, so the extra indirection would hide nothing.
fn gcm_kw_unwrap(kek: &[u8], iv: &[u8], tag: &[u8], encrypted_key: &[u8]) -> Result<Vec<u8>> {
    let mut buffer = encrypted_key.to_vec();
    gcm_kw_aead!(decrypt kek, iv, &mut buffer, tag);
    Ok(buffer)
}

/// Publish AES-GCM key management's `iv` and `tag` in the protected header.
///
/// Both members are mandatory for these algorithms (RFC 7518 §4.7.1) and they are
/// **this crate's to generate**: a caller that supplied them would be choosing the
/// IV of a key wrap, so `validate_encrypt_header` refuses them from a caller for
/// every algorithm and they are inserted here instead — before serialization, so
/// they are authenticated as part of the AAD rather than merely present.
fn with_gcm_members(
    header: &JoseHeader,
    wrap: &GcmKeyWrap,
    alg: JweAlgorithm,
) -> Result<JoseHeader> {
    let mut header = header.clone();
    // Checked here as well as in `validate_encrypt_header`, because this is the
    // function that publishes the members: inserting over a caller's value would
    // silently discard a supplied IV, which is the thing the rule exists to prevent.
    for member in ["iv", "tag"] {
        if header.extra.contains_key(member) {
            return Err(JoseError::InvalidHeader(format!(
                "{}: `{member}` is generated by this crate for AES-GCM key management \
                 (RFC 7518 §4.7.1) and cannot be supplied by the caller",
                alg.as_str()
            )));
        }
    }
    header.extra.insert(
        "iv".into(),
        serde_json::json!(crate::base64url::encode(&wrap.iv)),
    );
    header.extra.insert(
        "tag".into(),
        serde_json::json!(crate::base64url::encode(&wrap.tag)),
    );
    Ok(header)
}

/// A mandatory base64url header member of a fixed length, read from the
/// authenticated protected header.
///
/// `iv` and `tag` for AES-GCM key management are the same values as the header
/// members of those names — and they are *not* the envelope's own
/// `iv`/`tag` members, which belong to the content encryption (RFC 7516 §7.2). A
/// message that puts them in an unprotected position is refused at parse time
/// (ADR 0013), so by the time a key-management step runs they are authenticated.
fn required_header_bytes(
    header: &JoseHeader,
    name: &str,
    len: usize,
    alg: JweAlgorithm,
) -> Result<Vec<u8>> {
    let value = header.extra.get(name).ok_or_else(|| {
        JoseError::InvalidHeader(format!(
            "{alg} requires a {name} header member (RFC 7518 §4.7.1), which is absent",
            alg = alg.as_str()
        ))
    })?;
    let text = value.as_str().ok_or_else(|| {
        JoseError::InvalidHeader(format!(
            "{name} must be a base64url string (RFC 7518 §4.7.1)"
        ))
    })?;
    let bytes = crate::base64url::decode(text)?;
    if bytes.len() != len {
        return Err(JoseError::InvalidHeader(format!(
            "{name} must be {len} octets for {}, got {}",
            alg.as_str(),
            bytes.len()
        )));
    }
    Ok(bytes)
}

/// Check a `dir` key against the CEK size the content algorithm requires.
fn check_dir_key(key: &[u8], enc: JweEncryption) -> Result<()> {
    let cek_len = enc.cek_size();
    if key.len() != cek_len {
        return Err(JoseError::Key(format!(
            "dir: key length {} does not match required CEK size {}",
            key.len(),
            cek_len
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Key management: recover CEK (decrypt side)
// ---------------------------------------------------------------------------

pub(crate) fn recover_cek(
    key: &KeyMaterial,
    alg: JweAlgorithm,
    enc: JweEncryption,
    encrypted_key: &[u8],
    header: &JoseHeader,
    pbes2_max_iterations: u32,
) -> Result<Zeroizing<Vec<u8>>> {
    let cek_len = enc.cek_size();

    // Key agreement first, and separately: it needs the JWK and the message's
    // `epk`, so it never reaches the byte-oriented match below. Handling it
    // before that match is also what makes the raw-key refusal reach a caller
    // who passed bytes with an agreement algorithm — `(Bytes, _)` would
    // otherwise swallow it into "not yet implemented".
    if alg_is_agreement(alg) {
        return match (key, alg) {
            (KeyMaterial::Jwk(recipient), JweAlgorithm::EcdhEs) => {
                agree_direct_recover(header, recipient, enc, encrypted_key)
            }
            (KeyMaterial::Jwk(recipient), other) if agreement_kek_len(other).is_some() => {
                agree_wrap_recover(header, recipient, other, enc, encrypted_key)
            }
            (KeyMaterial::Jwk(_), other) => Err(JoseError::UnsupportedAlgorithm(format!(
                "{} is not implemented by this crate",
                other.as_str()
            ))),
            (KeyMaterial::Bytes(_), other) => Err(JoseError::Key(format!(
                "{} requires a JWK: key agreement needs the curve and coordinates of a key, and the peer key is read from the message's epk header member, so the raw-key API cannot express it",
                other.as_str()
            ))),
            // A password cannot do agreement either, and saying so keeps it out of the
            // "pass bytes" advice below, which would be nonsense for a password.
            (KeyMaterial::Password(_), other) => Err(JoseError::Key(format!(
                "{} requires a key pair, not a password",
                other.as_str()
            ))),
        };
    }

    // PBES2 next, and separately for the same reason agreement is: its key material is
    // a password rather than bytes, and the derivation's inputs (`p2s`, `p2c`) come out
    // of the authenticated header. Handing a key here is refused by name rather than
    // quietly treated as a password — a key handed to a password algorithm would be
    // *usable* (its bytes are bytes), which is precisely why it must not be.
    if alg_is_pbes2(alg) {
        return match key {
            KeyMaterial::Password(password) => {
                pbes2_recover_cek(header, password, alg, enc, encrypted_key, pbes2_max_iterations)
            }
            KeyMaterial::Bytes(_) | KeyMaterial::Jwk(_) => Err(JoseError::Key(format!(
                "{} derives its key from a password with the message's p2s and p2c, so it needs                  one: use the password API. Key bytes are not accepted here because a key and a                  password have different security arguments and one secret must not serve both                  (RFC 7518 {}4.8)",
                alg.as_str(),
                "\u{a7}"
            ))),
        };
    }
    let key = match key {
        KeyMaterial::Bytes(bytes) => bytes.as_slice(),
        // Unreachable: agreement and PBES2 both returned above, so only the algorithms
        // that consume key bytes get here.
        KeyMaterial::Jwk(_) => {
            return Err(JoseError::Key(
                "internal error: JWK key material reached a byte-oriented recovery path".into(),
            ))
        }
        KeyMaterial::Password(_) => {
            return Err(JoseError::Key(
                "internal error: password key material reached a byte-oriented recovery path"
                    .into(),
            ))
        }
    };

    match alg {
        JweAlgorithm::Dir => {
            if !encrypted_key.is_empty() {
                return Err(JoseError::InvalidToken(
                    "dir: encrypted key must be empty".into(),
                ));
            }
            if key.len() != cek_len {
                return Err(JoseError::Key(format!(
                    "dir: key length {} does not match required CEK size {}",
                    key.len(),
                    cek_len
                )));
            }
            Ok(Zeroizing::new(key.to_vec()))
        }

        JweAlgorithm::A128KW | JweAlgorithm::A192KW | JweAlgorithm::A256KW => {
            check_kek_size(alg, key)?;
            let kw_alg = jwe_alg_to_keywrap(alg)?;
            let cek = Zeroizing::new(
                kryptering::keywrap::unwrap(kw_alg, key, encrypted_key)
                    .map_err(JoseError::Crypto)?,
            );
            if cek.len() != cek_len {
                return Err(JoseError::Key(format!(
                    "unwrapped CEK length {} does not match expected {}",
                    cek.len(),
                    cek_len
                )));
            }
            Ok(cek)
        }

        // AES-GCM key management (RFC 7518 §4.7): the CEK is carried, encrypted
        // under the algorithm's key, with the IV and authentication tag as header
        // members rather than envelope members. They are read from the protected
        // header — an unprotected `iv`/`tag` was already refused at parse time
        // (ADR 0013) — and they are the *key wrap's*, not the content encryption's,
        // which is why the envelope's own `iv`/`tag` never come through here.
        other if aes_gcm_kw_key_len(other).is_some() => {
            check_kek_size(alg, key)?;
            let iv = required_header_bytes(header, "iv", 12, alg)?;
            let tag = required_header_bytes(header, "tag", 16, alg)?;
            let cek = Zeroizing::new(gcm_kw_unwrap(key, &iv, &tag, encrypted_key)?);
            if cek.len() != cek_len {
                return Err(JoseError::Key(format!(
                    "{}: unwrapped CEK length {} does not match the {} bytes {} requires",
                    alg.as_str(),
                    cek.len(),
                    cek_len,
                    enc.as_str()
                )));
            }
            Ok(cek)
        }

        JweAlgorithm::RsaOaep256 => rsa_oaep_recover_cek(key, alg, encrypted_key, cek_len),

        #[cfg(feature = "rsa-oaep")]
        JweAlgorithm::RsaOaep => rsa_oaep_recover_cek(key, alg, encrypted_key, cek_len),

        _ => Err(JoseError::UnsupportedAlgorithm(format!(
            "key management algorithm {} not yet implemented",
            alg.as_str()
        ))),
    }
}

/// Shared RSA-OAEP CEK recovery (used by both RSA-OAEP-256 and the deprecated
/// SHA-1 RSA-OAEP variant).
///
/// A random fallback CEK is generated before attempting the unwrap. Invalid
/// OAEP ciphertexts and incorrectly sized results use that fallback so they
/// continue through content authentication instead of returning early. This
/// implicit-rejection pattern prevents callers from distinguishing an OAEP
/// failure from a valid unwrap followed by failed content authentication.
/// Trusted-key parsing and algorithm-configuration errors remain explicit.
fn rsa_oaep_recover_cek(
    key: &[u8],
    alg: JweAlgorithm,
    encrypted_key: &[u8],
    cek_len: usize,
) -> Result<Zeroizing<Vec<u8>>> {
    let priv_key = parse_rsa_private_key(key)?;
    let kt_alg = jwe_alg_to_keytransport(alg)?;

    // Generate this unconditionally so successful and failed unwraps perform
    // the same random-number generation work. It is zeroized if unused.
    let fallback_cek = Zeroizing::new(content::random_bytes(cek_len));
    let recovered = kryptering::keytransport::kt_decrypt(kt_alg, &priv_key, encrypted_key, None)
        .map(Zeroizing::new);

    match recovered {
        Ok(cek) if cek.len() == cek_len => Ok(cek),
        // `cek`, when present with the wrong length, and the fallback are both
        // `Zeroizing`, so neither recovered nor dummy key material lingers.
        Ok(_) | Err(_) => Ok(fallback_cek),
    }
}

// ---------------------------------------------------------------------------
// Algorithm mapping helpers
// ---------------------------------------------------------------------------

/// Verify that the supplied Key Encryption Key is exactly the size
/// demanded by the declared AES Key Wrap algorithm.
///
/// Prevents silent acceptance of a 32-byte key for `A128KW` (or similar
/// mis-sized KEKs) if the underlying crypto backend does not validate
/// strictly.
pub(crate) fn check_kek_size(alg: JweAlgorithm, key: &[u8]) -> Result<()> {
    let expected = match alg {
        JweAlgorithm::A128KW => 16,
        JweAlgorithm::A192KW => 24,
        JweAlgorithm::A256KW => 32,
        JweAlgorithm::A128Gcmkw => 16,
        JweAlgorithm::A192Gcmkw => 24,
        JweAlgorithm::A256Gcmkw => 32,
        _ => return Ok(()),
    };
    if key.len() != expected {
        return Err(JoseError::Key(format!(
            "{}: KEK must be {} bytes, got {}",
            alg.as_str(),
            expected,
            key.len()
        )));
    }
    Ok(())
}

/// The AES key wrapping a key-management algorithm performs.
///
/// The `A*KW` algorithms and the ECDH-agreement-with-wrapping algorithms share
/// this mapping on purpose: they run *the same* RFC 3394 wrap, and differ only in
/// where the key-encryption key came from — held by both parties already, or
/// derived from the agreement. Accepting both here keeps a third spelling of
/// "128-bit AES-KW" out of the codebase; it does **not** make the raw-byte path
/// reachable for agreement, which is dispatched away long before this is called
/// ([`recover_cek`], [`encrypt_core_multi`]).
pub(crate) fn jwe_alg_to_keywrap(alg: JweAlgorithm) -> Result<kryptering::KeyWrapAlgorithm> {
    use kryptering::{AesKeySize, KeyWrapAlgorithm};
    match alg {
        // PBES2's derived key *is* the AES-KW key, at the length the algorithm's own
        // name states, so it shares this mapping rather than owning a copy.
        JweAlgorithm::A128KW | JweAlgorithm::EcdhEsA128kw | JweAlgorithm::Pbes2Hs256A128kw => {
            Ok(KeyWrapAlgorithm::AesKw(AesKeySize::Aes128))
        }
        JweAlgorithm::A192KW | JweAlgorithm::EcdhEsA192kw | JweAlgorithm::Pbes2Hs384A192kw => {
            Ok(KeyWrapAlgorithm::AesKw(AesKeySize::Aes192))
        }
        JweAlgorithm::A256KW | JweAlgorithm::EcdhEsA256kw | JweAlgorithm::Pbes2Hs512A256kw => {
            Ok(KeyWrapAlgorithm::AesKw(AesKeySize::Aes256))
        }
        _ => Err(JoseError::UnsupportedAlgorithm(format!(
            "{} is not a key wrap algorithm",
            alg.as_str()
        ))),
    }
}

pub(crate) fn jwe_alg_to_keytransport(
    alg: JweAlgorithm,
) -> Result<kryptering::KeyTransportAlgorithm> {
    use kryptering::{HashAlgorithm, KeyTransportAlgorithm, OaepConfig};
    match alg {
        #[cfg(feature = "rsa-oaep")]
        JweAlgorithm::RsaOaep => Ok(KeyTransportAlgorithm::RsaOaep(OaepConfig {
            digest: HashAlgorithm::Sha1,
            mgf_digest: HashAlgorithm::Sha1,
        })),
        JweAlgorithm::RsaOaep256 => Ok(KeyTransportAlgorithm::RsaOaep(OaepConfig {
            digest: HashAlgorithm::Sha256,
            mgf_digest: HashAlgorithm::Sha256,
        })),
        _ => Err(JoseError::UnsupportedAlgorithm(format!(
            "{} is not a key transport algorithm",
            alg.as_str()
        ))),
    }
}

// ---------------------------------------------------------------------------
// RSA key parsing
// ---------------------------------------------------------------------------

pub(crate) fn parse_rsa_public_key(der: &[u8]) -> Result<kryptering::SoftwareKey> {
    use rsa::pkcs8::DecodePublicKey;
    use rsa::traits::PublicKeyParts;
    crate::ensure_key_der_size(der.len())?;
    let key = rsa::PublicKey::from_public_key_der(der)
        .map_err(|e| JoseError::Key(format!("failed to parse RSA public key DER: {e}")))?;
    crate::ensure_rsa_bits(key.n().bit_width() as usize)?;
    kryptering::SoftwareKey::from_spki_der(kryptering::KeyAlgorithm::Rsa, der).map_err(Into::into)
}

pub(crate) fn parse_rsa_private_key(der: &[u8]) -> Result<kryptering::SoftwareKey> {
    use pkcs8::der::Decode;
    use rsa::pkcs8::DecodePrivateKey;
    use rsa::traits::PublicKeyParts;
    crate::ensure_key_der_size(der.len())?;
    let info = pkcs8::PrivateKeyInfoRef::from_der(der)
        .map_err(|e| JoseError::Key(format!("failed to parse RSA private key PKCS#8 DER: {e}")))?;
    let raw = rsa::pkcs1::RsaPrivateKeyRef::from_der(info.private_key.as_bytes())
        .map_err(|e| JoseError::Key(format!("failed to parse RSA private key PKCS#8 DER: {e}")))?;
    crate::ensure_rsa_modulus_bytes(raw.modulus.as_bytes())?;
    let key = rsa::PrivateKey::from_pkcs8_der(der)
        .map_err(|e| JoseError::Key(format!("failed to parse RSA private key PKCS#8 DER: {e}")))?;
    crate::ensure_rsa_bits(key.n().bit_width() as usize)?;
    kryptering::SoftwareKey::from_pkcs8_der(kryptering::KeyAlgorithm::Rsa, der).map_err(Into::into)
}

// ---------------------------------------------------------------------------
// JWK-aware key material (shared by the raw-key one-shot APIs and the
// JSON serialization APIs)
// ---------------------------------------------------------------------------

/// Determine which `JwkOp` governs a JWE alg on the encrypt side.
///
/// `Dir` uses the key directly for content encryption (`Encrypt`);
/// key-transport (`A*KW`, `RSA-OAEP*`) wraps a CEK (`WrapKey`).
pub(crate) fn jwe_alg_encrypt_op(alg: JweAlgorithm) -> crate::jwk::JwkOp {
    match alg {
        JweAlgorithm::Dir => crate::jwk::JwkOp::Encrypt,
        // Agreement is neither encryption nor wrapping: the recipient's key is
        // used to *derive*, and RFC 7517 §4.3 spells that `deriveKey`. A key
        // pinned to `wrapKey` therefore cannot be an ECDH-ES recipient key.
        a if alg_is_agreement(a) => crate::jwk::JwkOp::DeriveKey,
        _ => crate::jwk::JwkOp::WrapKey,
    }
}

/// Determine which `JwkOp` governs a JWE alg on the decrypt side.
pub(crate) fn jwe_alg_decrypt_op(alg: JweAlgorithm) -> crate::jwk::JwkOp {
    match alg {
        JweAlgorithm::Dir => crate::jwk::JwkOp::Decrypt,
        a if alg_is_agreement(a) => crate::jwk::JwkOp::DeriveKey,
        _ => crate::jwk::JwkOp::UnwrapKey,
    }
}

/// The key material one key-management step operates on.
///
/// Two shapes, because the algorithms consume two different things:
///
/// * [`KeyMaterial::Bytes`] — a shared CEK (`dir`), an AES key-wrap KEK, or RSA
///   DER. The algorithm consumes the bytes and nothing else.
/// * [`KeyMaterial::Jwk`] — the ECDH key-agreement family. Agreement cannot work
///   from bytes: it needs the curve and coordinates, whether private material is
///   present, and the key's own `use`/`key_ops`/`alg` statements (ADR 0016). On
///   the producing side it also has to publish a freshly generated public key,
///   which raw bytes could not express.
///
/// Raw-key public APIs therefore hand out [`KeyMaterial::Bytes`] and cannot
/// reach an agreement algorithm at all: there is no way to name a curve, and no
/// `epk` to agree with, in a `&[u8]`.
pub(crate) enum KeyMaterial {
    Bytes(Zeroizing<Vec<u8>>),
    /// Boxed so the byte variant stays small: a `Jwk` is well over half a
    /// kilobyte, and this enum is passed around by value on every encrypt.
    Jwk(Box<crate::jwk::Jwk>),
    /// A password, accepted only by the PBES2 algorithms.
    ///
    /// A third variant rather than `Bytes` with a flag, because the distinction is the
    /// point: `Bytes` means "use these octets as the key", and `Password` means "these
    /// octets are the *input* to a key derivation with parameters from the message". A
    /// password that reached a `Bytes` path would be used as a KEK directly — one secret
    /// serving two incompatible security arguments, which is a confusion waiting to be
    /// exploited rather than a bug to be found.
    Password(super::password::Password),
}

impl KeyMaterial {
    /// Key bytes, for the transport and wrapping algorithms.
    ///
    /// A password is refused here by name, and not with the "internal error" wording
    /// used for the JWK case: reaching this function with a password is reachable from
    /// the public API (a password handed to a non-PBES2 algorithm), and the caller
    /// deserves to be told that a password is not a key.
    fn bytes(&self) -> Result<&[u8]> {
        match self {
            Self::Bytes(bytes) => Ok(bytes),
            Self::Jwk(_) => Err(JoseError::Key(
                "internal error: JWK key material reached a byte-oriented key-management path"
                    .into(),
            )),
            Self::Password(_) => Err(JoseError::Key(
                "a password is not a key: PBES2 derives a key-encryption key from it using \
                 the message's p2s and p2c, so its bytes are never key material directly \
                 (RFC 7518 \u{a7}4.8). Use the password API with a PBES2 algorithm, and a \
                 key with any other"
                    .into(),
            )),
        }
    }
}

/// Route a password into key material, for the PBES2 family only.
///
/// The refusal matters as much as the acceptance. Accepting a password for `A128KW` or
/// `dir` — which is what an untyped `&[u8]` entry point would do — uses its bytes
/// straight as a key, and a password has none of the entropy those algorithms assume.
/// Refusing by name is what keeps the two families from sharing an entry point.
pub(crate) fn password_key(
    password: &super::password::Password,
    alg: JweAlgorithm,
) -> Result<KeyMaterial> {
    if alg_is_pbes2(alg) {
        Ok(KeyMaterial::Password(password.clone()))
    } else {
        Err(JoseError::Key(format!(
            "{} does not use a password; PBES2-HS256+A128KW, PBES2-HS384+A192KW and \
             PBES2-HS512+A256KW are the password-based key management algorithms, and this \
             one would use the password's bytes directly as a key (RFC 7518 \u{a7}4.8)",
            alg.as_str()
        )))
    }
}

/// Route a JWK into the form `alg` consumes.
pub(crate) fn recipient_key(
    jwk: &crate::jwk::Jwk,
    alg: JweAlgorithm,
    for_decrypt: bool,
) -> Result<KeyMaterial> {
    if alg_is_agreement(alg) {
        Ok(KeyMaterial::Jwk(Box::new(jwk.clone())))
    } else {
        Ok(KeyMaterial::Bytes(jwk_to_jwe_key_bytes(
            jwk,
            alg,
            for_decrypt,
        )?))
    }
}

/// Convert a JWK to the raw key-material form that the raw-key encrypt and
/// decrypt paths expect for the given JWE algorithm.
///
/// - For `dir`, `A*KW`: returns the `k` bytes of an `oct` JWK.
/// - For `RSA-OAEP*` on the encrypt side: returns SPKI DER of the public key.
/// - For `RSA-OAEP*` on the decrypt side: returns PKCS#8 DER of the private key.
pub(crate) fn jwk_to_jwe_key_bytes(
    jwk: &crate::jwk::Jwk,
    alg: JweAlgorithm,
    for_decrypt: bool,
) -> Result<Zeroizing<Vec<u8>>> {
    match alg {
        JweAlgorithm::Dir
        | JweAlgorithm::A128KW
        | JweAlgorithm::A192KW
        | JweAlgorithm::A256KW
        | JweAlgorithm::A128Gcmkw
        | JweAlgorithm::A192Gcmkw
        | JweAlgorithm::A256Gcmkw => {
            if jwk.kty.as_str() != "oct" {
                return Err(JoseError::Key(format!(
                    "JWE alg {} requires kty oct, got {}",
                    alg.as_str(),
                    jwk.kty.as_str()
                )));
            }
            let k = jwk
                .k
                .as_deref()
                .ok_or_else(|| JoseError::Key("JWK is missing `k`".into()))?;
            Ok(Zeroizing::new(base64url::decode(k)?))
        }
        JweAlgorithm::RsaOaep256 => rsa_jwk_to_der(jwk, for_decrypt),
        #[cfg(feature = "rsa-oaep")]
        JweAlgorithm::RsaOaep => rsa_jwk_to_der(jwk, for_decrypt),
        // Named rather than left to the catch-all below, because this is the exact
        // confusion the password type exists to prevent: an `oct` JWK whose `k` holds a
        // passphrase looks usable here, and the same JWK would be accepted by `A128KW` —
        // one secret, two incompatible security arguments.
        other if alg_is_pbes2(other) => Err(JoseError::Key(format!(
            "{} derives its key from a password, not from a JWK: an `oct` key's bytes are              high-entropy key material and a passphrase is not, so the same JWK would be              acceptable to A128KW as well. Use the password API (RFC 7518 \u{a7}4.8)",
            other.as_str()
        ))),
        _ => Err(JoseError::UnsupportedAlgorithm(format!(
            "JWE alg {} not supported via JWK one-shot API",
            alg.as_str()
        ))),
    }
}

fn rsa_jwk_to_der(jwk: &crate::jwk::Jwk, for_decrypt: bool) -> Result<Zeroizing<Vec<u8>>> {
    let sw = crate::jwk::jwk_to_software_key(jwk)?;
    if sw.algorithm() != kryptering::KeyAlgorithm::Rsa {
        return Err(JoseError::Key("RSA JWK expected".into()));
    }
    if for_decrypt {
        if !sw.has_private_key() {
            return Err(JoseError::Key("JWK lacks RSA private components".into()));
        }
        sw.export_private().map_err(Into::into)
    } else {
        Ok(Zeroizing::new(sw.export_spki_der()?))
    }
}

// ---------------------------------------------------------------------------
// Shared encryption core (compact and JSON serializations)
// ---------------------------------------------------------------------------

/// Key management plus content encryption, before any serialization.
///
/// `header_b64` is the exact string that was used as the additional
/// authenticated data, so a serializer that emits it verbatim produces a
/// message the recipient can authenticate.
pub(crate) struct EncryptedCore {
    /// `BASE64URL(UTF8(JWE Protected Header))`, also the AAD input.
    pub header_b64: String,
    /// Wrapped key (empty for `dir`).
    pub encrypted_key: Vec<u8>,
    /// Content IV.
    pub iv: Vec<u8>,
    /// Content ciphertext.
    pub ciphertext: Vec<u8>,
    /// Content authentication tag.
    pub tag: Vec<u8>,
}

/// Key management that had to happen **before** the protected header was serialized.
///
/// Three of the four shapes exist because a mode's key-material output is also
/// header content: the ephemeral public key (`epk`) and the AES-GCM wrap's `iv`/
/// `tag` have to be inside the protected header, and that serialized header *is*
/// the AEAD's additional authenticated data. Doing the key work afterwards would
/// either leave those members unauthenticated or produce a header whose bytes no
/// longer match what was authenticated — so the enum records not just what the CEK
/// is, but what the header now says.
enum Prepared {
    /// Direct agreement: the CEK **is** the agreed key, and nothing is conveyed as
    /// the encrypted key (RFC 7518 §4.6).
    Agreed { cek: Zeroizing<Vec<u8>> },
    /// Agreement with key wrapping: the ephemeral key is already published; the
    /// CEK is generated normally and wrapped with the agreed KEK. Boxed because
    /// the sender holds both halves of the pair and a whole header, which would
    /// otherwise size up every other variant of this enum.
    AgreementWrap { sender: Box<AgreementSender> },
    /// AES-GCM key management: already wrapped, because the IV and tag it produced
    /// are in the header.
    GcmWrapped {
        cek: Zeroizing<Vec<u8>>,
        encrypted_key: Vec<u8>,
    },
    /// PBES2: already wrapped, because the salt input and iteration count it consumed
    /// are in the header — and because the key-encryption key those parameters produce
    /// exists only for this one operation.
    Pbes2Wrapped {
        cek: Zeroizing<Vec<u8>>,
        encrypted_key: Vec<u8>,
    },
    /// `dir`, RFC 3394 AES-KW and RSA-OAEP: key bytes in, wrapped after the header
    /// is serialized, since none of them publishes anything in the header.
    ByteKey,
}

/// Build the content-authentication input (RFC 7516 §5.1 step 14).
///
/// `ASCII(Encoded Protected Header)`, or — when a JWE AAD value is present,
/// which only the JSON serialization can carry —
/// `ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD))`.
///
/// `external_aad_b64` must be the *encoded* form: the RFC authenticates the
/// base64url text, not the raw additional-authenticated-data octets, so the
/// same bytes under two different encodings are different messages.
/// Refuse an external AAD that encodes to nothing.
///
/// RFC 7516 §7.2.1 requires the `aad` member to be absent when the value is
/// empty, and the AAD *input* differs between "no member" and `""` (the
/// separator), so accepting an empty value would let a sender and a recipient
/// disagree about which message they hold.
pub(crate) fn ensure_external_aad_present(bytes: &[u8]) -> Result<()> {
    if bytes.is_empty() {
        return Err(JoseError::InvalidHeader(
            "external additional authenticated data must not be empty; an empty JWE AAD is indistinguishable from no AAD (RFC 7516 §7.2.1)"
                .into(),
        ));
    }
    Ok(())
}

pub(crate) fn aad_input(header_b64: &str, external_aad_b64: Option<&str>) -> Vec<u8> {
    match external_aad_b64 {
        None => header_b64.as_bytes().to_vec(),
        Some(aad_b64) => format!("{header_b64}.{aad_b64}").into_bytes(),
    }
}

/// Encrypt once, for any serialization.
///
/// Applies the whole emit-side policy in one place, so a new serializer
/// cannot skip a rule:
///
/// 1. `header.alg` / `header.enc` must agree with the algorithms actually
///    used (RFC 8725 §3.1);
/// 2. [`validate_encrypt_header`] (unimplemented members, `crit`);
/// 3. [`JoseHeader::to_protected_b64`] (duplicate members, key-reference
///    members, header size);
/// 4. a size pre-flight so a token this crate could not decode is never
///    produced;
/// 5. key management and content encryption over
///    [`aad_input`](self::aad_input).
///
/// `aad_b64` is the encoded external AAD (`None` for compact and for JSON
/// without an `aad` member).
pub(crate) fn encrypt_core(
    header: &JoseHeader,
    key: KeyMaterial,
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
    opts: &JweEncryptOptions,
    aad_b64: Option<&str>,
) -> Result<EncryptedCore> {
    if header.alg != alg.as_str() {
        return Err(JoseError::InvalidHeader(format!(
            "protected header alg {} does not match JWE algorithm {}",
            header.alg,
            alg.as_str()
        )));
    }
    if header.enc.as_deref() != Some(enc.as_str()) {
        return Err(JoseError::InvalidHeader(format!(
            "protected header enc {:?} does not match JWE encryption {}",
            header.enc,
            enc.as_str()
        )));
    }
    // alg/enc agree; now the JWE-specific member rules, then the shared
    // duplicate / key-reference / size rules while serializing.
    validate_encrypt_header(header, alg, opts.understood_crit())?;
    let header_b64 = header.to_protected_b64(opts.allow_key_reference_headers)?;

    // The ciphertext is at least as long as the plaintext, so refuse before
    // any key wrapping or encryption when the token cannot possibly fit. The
    // external AAD (plus its `.` separator) is part of the serialized
    // message, so it counts against the limit too.
    let aad_len = aad_b64.map_or(0, |aad| aad.len() + 1);
    crate::ensure_emit_size(
        header_b64.len() + aad_len + content::base64url_len(plaintext.len()) + 4,
    )?;

    let (core, wrapped) = encrypt_core_multi(header, &[key], plaintext, alg, enc, opts, aad_b64)?;
    Ok(EncryptedCore {
        encrypted_key: wrapped.into_iter().next().unwrap_or_default(),
        ..core
    })
}

/// Shared body of a general-serialization encryption.
///
/// The whole emit-side policy runs **once** — the protected header, the AAD
/// input and the content encryption are shared by every recipient — and only
/// key management repeats, which is what RFC 7516 §7.2.1 requires: one
/// ciphertext, one encrypted CEK per recipient.
///
/// All recipients share the key-management algorithm. Per-recipient algorithms
/// would put `alg` in the element's unprotected header, where it is not
/// integrity protected, and this crate will not *emit* an algorithm a recipient
/// cannot authenticate (ADR 0013).
///
/// Returns the shared envelope plus `keys[i]`'s wrapped CEK, positionally.
pub(crate) fn encrypt_core_multi(
    header: &JoseHeader,
    keys: &[KeyMaterial],
    plaintext: &[u8],
    alg: JweAlgorithm,
    enc: JweEncryption,
    opts: &JweEncryptOptions,
    aad_b64: Option<&str>,
) -> Result<(EncryptedCore, Vec<Vec<u8>>)> {
    let Some((first, rest)) = keys.split_first() else {
        return Err(JoseError::InvalidHeader(
            "a JWE must name at least one recipient key".into(),
        ));
    };

    if header.alg != alg.as_str() {
        return Err(JoseError::InvalidHeader(format!(
            "protected header alg {} does not match JWE algorithm {}",
            header.alg,
            alg.as_str()
        )));
    }
    if header.enc.as_deref() != Some(enc.as_str()) {
        return Err(JoseError::InvalidHeader(format!(
            "protected header enc {:?} does not match JWE encryption {}",
            header.enc,
            enc.as_str()
        )));
    }
    validate_encrypt_header(header, alg, opts.understood_crit())?;

    // Direct key agreement has to happen before the header is serialized,
    // because publishing the ephemeral public key *changes* the protected header
    // that is then used as the AAD input. `Cow` so that every other algorithm
    // keeps borrowing the caller's header.
    let (header, prepared): (std::borrow::Cow<'_, JoseHeader>, Prepared) = match (first, alg) {
        (KeyMaterial::Jwk(recipient), JweAlgorithm::EcdhEs) => {
            if !rest.is_empty() {
                // The agreed key *is* the CEK, and it is agreed with exactly
                // one recipient. Two recipients would need two different
                // CEKs, and one ciphertext cannot be encrypted under two.
                return Err(direct_agreement_not_multi(alg));
            }
            let (header, cek) = agree_direct(header, recipient, enc)?;
            (std::borrow::Cow::Owned(header), Prepared::Agreed { cek })
        }
        // Agreement with key wrapping: the CEK is generated normally and wrapped
        // per recipient, so all this mode needs up front is the ephemeral key to
        // publish (which changes the protected header, hence "before serialize").
        (KeyMaterial::Jwk(recipient), other) if agreement_kek_len(other).is_some() => {
            if !rest.is_empty() {
                return Err(per_recipient_epk_unsupported(other));
            }
            let sender = agreement_sender(header, recipient)?;
            (
                std::borrow::Cow::Owned(sender.header.clone()),
                Prepared::AgreementWrap {
                    sender: Box::new(sender),
                },
            )
        }
        // AES-GCM key management: the wrap happens here rather than below because
        // its IV and authentication tag are *header members* (RFC 7518 §4.7.1), so
        // they have to exist before the header is serialized — and being in the
        // header, they are then authenticated as AAD.
        (KeyMaterial::Bytes(kek), other) if aes_gcm_kw_key_len(other).is_some() => {
            if !rest.is_empty() {
                return Err(per_recipient_member_unsupported(other, "iv and tag"));
            }
            check_kek_size(alg, kek)?;
            let cek = Zeroizing::new(content::random_bytes(enc.cek_size()));
            let wrapped = gcm_kw_wrap(kek, &cek)?;
            let header = with_gcm_members(header, &wrapped, alg)?;
            (
                std::borrow::Cow::Owned(header),
                Prepared::GcmWrapped {
                    cek,
                    encrypted_key: wrapped.encrypted_key,
                },
            )
        }
        // PBES2 (RFC 7518 §4.8): the salt input and iteration count are header
        // members, so — as with agreement's `epk` and the AES-GCM wrap's `iv`/`tag` —
        // the key work has to happen before the header is serialized, because that
        // serialized header is what authenticates them.
        (KeyMaterial::Password(password), other) if alg_is_pbes2(other) => {
            if !rest.is_empty() {
                // Each recipient's password derives a different KEK, so each needs its
                // own `p2s`/`p2c` — and a recipient element has no protected header to
                // carry them in. The same structural refusal as `epk` and `iv`/`tag`.
                return Err(per_recipient_member_unsupported(other, "p2s and p2c"));
            }
            // Refused on the emit side only: an unset secret and an empty one look
            // identical here. A peer's message is never refused for the shape of its
            // secret when reading — the wrap's integrity check decides that.
            if password.is_empty() {
                return Err(JoseError::Key(
                    "PBES2 with an empty password is refused: an unset secret and an empty \
                     one are indistinguishable here, and no salt fixes a zero-length \
                     password (RFC 7518 \u{a7}4.8)"
                        .into(),
                ));
            }
            let iterations = opts
                .pbes2_iterations()
                .unwrap_or(super::password::PBES2_DEFAULT_ITERATIONS);
            if iterations < super::password::PBES2_MIN_ITERATIONS {
                return Err(JoseError::InvalidHeader(format!(
                    "a p2c of {iterations} would be refused by every conformant reader: RFC \
                     7518 \u{a7}4.8.1.2 recommends a minimum of 1000, and this crate does not \
                     emit what it refuses to read"
                )));
            }
            let salt_input = pbes2_salt_input();
            let cek = Zeroizing::new(content::random_bytes(enc.cek_size()));
            // The sender's only ceiling is the backend's: the count was chosen
            // knowingly, and it is the *recipient's* budget that limits a received one.
            let kek = pbes2_derive(
                other,
                password,
                &salt_input,
                iterations,
                kryptering::kdf::PBKDF2_MAX_ITERATIONS,
            )?;
            let encrypted_key = kryptering::keywrap::wrap(jwe_alg_to_keywrap(other)?, &kek, &cek)
                .map_err(JoseError::Crypto)?;
            let header = with_pbes2_members(header, &salt_input, iterations, other)?;
            (
                std::borrow::Cow::Owned(header),
                Prepared::Pbes2Wrapped { cek, encrypted_key },
            )
        }
        (KeyMaterial::Password(_), other) => {
            return Err(JoseError::Key(format!(
                "{} does not use a password; see PBES2-HS256+A128KW / +HS384+A192KW /                  +HS512+A256KW",
                other.as_str()
            )))
        }
        (KeyMaterial::Jwk(_), other) => {
            return Err(JoseError::UnsupportedAlgorithm(format!(
                "{} is not implemented by this crate",
                other.as_str()
            )))
        }
        (KeyMaterial::Bytes(_), other) if alg_is_agreement(other) => {
            return Err(JoseError::Key(format!(
                "{} requires a JWK; the raw-key API cannot name a curve or carry the peer key",
                other.as_str()
            )))
        }
        _ => (std::borrow::Cow::Borrowed(header), Prepared::ByteKey),
    };
    let header_b64 = header.to_protected_b64(opts.allow_key_reference_headers)?;

    // The ciphertext is at least as long as the plaintext, so refuse before any
    // key wrapping or encryption when the token cannot possibly fit. The
    // external AAD (plus its `.` separator) is part of the serialized message,
    // so it counts against the limit too, as does each additional recipient's
    // encrypted key.
    let aad_len = aad_b64.map_or(0, |aad| aad.len() + 1);
    let extra_keys_len = content::base64url_len(plaintext.len()).saturating_mul(rest.len());
    crate::ensure_emit_size(
        header_b64.len() + aad_len + content::base64url_len(plaintext.len()) + 4 + extra_keys_len,
    )?;

    // 1. Generate or use the CEK, wrap it for the first recipient. Direct key
    // agreement has already agreed it, and conveys nothing; agreement with
    // wrapping and AES-GCM key management both generated the CEK normally, the
    // latter already having wrapped it so its header members could be published.
    let (cek, first_wrapped) = match prepared {
        Prepared::Agreed { cek } => (cek, Vec::new()),
        Prepared::GcmWrapped { cek, encrypted_key }
        | Prepared::Pbes2Wrapped { cek, encrypted_key } => (cek, encrypted_key),
        Prepared::AgreementWrap { sender } => {
            let cek = Zeroizing::new(content::random_bytes(enc.cek_size()));
            let wrapped = sender.wrap(alg, &cek)?;
            (cek, wrapped)
        }
        Prepared::ByteKey => produce_cek(first.bytes()?, alg, enc)?,
    };

    // 2. Content encryption — once, over the shared AAD input.
    let aad = aad_input(&header_b64, aad_b64);
    let (iv, ciphertext, tag) = content::content_encrypt(enc, &cek, plaintext, &aad)?;

    // 3. Same CEK, wrapped for each remaining recipient.
    let mut wrapped = Vec::with_capacity(keys.len());
    wrapped.push(first_wrapped);
    for key in rest {
        wrapped.push(wrap_cek(&cek, key.bytes()?, alg, enc)?);
    }

    Ok((
        EncryptedCore {
            header_b64,
            encrypted_key: Vec::new(),
            iv,
            ciphertext,
            tag,
        },
        wrapped,
    ))
}

#[cfg(test)]
mod tests {
    use super::{
        aes_gcm_kw_key_len, agreement_kek_len, alg_is_pbes2, gcm_kw_unwrap, gcm_kw_wrap,
        jwe_alg_to_keywrap, other_info, password_key, pbes2_derive, pbes2_message_params,
        pbes2_params, pbes2_salt, per_recipient_member_unsupported, required_header_bytes,
        with_gcm_members, with_pbes2_members, GcmKeyWrap, KeyMaterial,
    };
    use crate::algorithm::{JweAlgorithm, JweEncryption};
    use crate::header::JoseHeader;

    /// A header for a key-management mode that publishes wrap members, so the
    /// member-reading rules can be tested without a whole message.
    fn gcm_header(alg: JweAlgorithm) -> JoseHeader {
        JoseHeader::for_jwe(alg, JweEncryption::A128GCM)
    }

    #[test]
    fn the_gcm_key_management_algorithms_name_their_key_length() {
        // `alg` fixes the key-encryption key, `enc` the content key. Nothing else
        // decides these, and reading either off the wrong field would still decrypt
        // in the single case where the two lengths coincide (A128GCMKW + A128GCM),
        // which is exactly why the pairing is asserted separately.
        assert_eq!(aes_gcm_kw_key_len(JweAlgorithm::A128Gcmkw), Some(16));
        assert_eq!(aes_gcm_kw_key_len(JweAlgorithm::A192Gcmkw), Some(24));
        assert_eq!(aes_gcm_kw_key_len(JweAlgorithm::A256Gcmkw), Some(32));
        // Not key-management modes at all, so no length to report.
        for alg in [
            JweAlgorithm::Dir,
            JweAlgorithm::A128KW,
            JweAlgorithm::EcdhEs,
            JweAlgorithm::EcdhEsA128kw,
            JweAlgorithm::RsaOaep256,
            JweAlgorithm::Pbes2Hs256A128kw,
        ] {
            assert_eq!(aes_gcm_kw_key_len(alg), None, "{alg:?}");
        }
    }

    #[test]
    fn the_rfc_3394_and_agreement_algorithms_share_one_key_wrap_mapping() {
        // There is one spelling of "wrap with AES-KW" in this crate, so agreement
        // modes cannot acquire a second, incompatible one. `ECDH-ES` itself is
        // refused: its agreed key is the content key, and wrapping it would be a
        // different key-management mode wearing the same name.
        for alg in [
            JweAlgorithm::A128KW,
            JweAlgorithm::A192KW,
            JweAlgorithm::A256KW,
            JweAlgorithm::EcdhEsA128kw,
            JweAlgorithm::EcdhEsA192kw,
            JweAlgorithm::EcdhEsA256kw,
        ] {
            assert!(jwe_alg_to_keywrap(alg).is_ok(), "{alg:?}");
        }
        assert!(jwe_alg_to_keywrap(JweAlgorithm::EcdhEs).is_err());
        assert!(jwe_alg_to_keywrap(JweAlgorithm::Dir).is_err());

        // And the wrapping agreement modes are recognised as such, by the length
        // of the key they agree — not by the content algorithm.
        assert_eq!(agreement_kek_len(JweAlgorithm::EcdhEsA128kw), Some(16));
        assert_eq!(agreement_kek_len(JweAlgorithm::EcdhEsA192kw), Some(24));
        assert_eq!(agreement_kek_len(JweAlgorithm::EcdhEsA256kw), Some(32));
        assert_eq!(agreement_kek_len(JweAlgorithm::EcdhEs), None);
        assert_eq!(agreement_kek_len(JweAlgorithm::A128Gcmkw), None);
    }

    #[test]
    fn a_gcm_wrap_round_trips_and_refuses_every_edit() {
        for key_len in [16, 24, 32] {
            let kek = vec![0x42u8; key_len];
            // Any bytes will do as a stand-in CEK; only the framing matters here.
            let cek = (0u8..40).collect::<Vec<u8>>();
            let wrapped = gcm_kw_wrap(&kek, &cek).unwrap();
            assert_eq!(
                wrapped.encrypted_key.len(),
                cek.len(),
                "GCM does not expand"
            );
            assert_eq!(wrapped.iv.len(), 12, "RFC 7518 §4.7 requires a 96-bit IV");
            assert_eq!(
                wrapped.tag.len(),
                16,
                "RFC 7518 §4.7 requires a 128-bit tag"
            );
            assert_eq!(
                gcm_kw_unwrap(&kek, &wrapped.iv, &wrapped.tag, &wrapped.encrypted_key).unwrap(),
                cek
            );

            // Two wraps of the same CEK share no prefix, because the IV is fresh.
            let again = gcm_kw_wrap(&kek, &cek).unwrap();
            assert_ne!(again.iv, wrapped.iv);
            assert_ne!(again.encrypted_key, wrapped.encrypted_key);

            // Each of the three parts is load-bearing.
            let mut bad_key = kek.clone();
            bad_key[0] ^= 1;
            assert!(
                gcm_kw_unwrap(&bad_key, &wrapped.iv, &wrapped.tag, &wrapped.encrypted_key).is_err()
            );
            let mut bad_iv = wrapped.iv.clone();
            bad_iv[0] ^= 1;
            assert!(gcm_kw_unwrap(&kek, &bad_iv, &wrapped.tag, &wrapped.encrypted_key).is_err());
            let mut bad_tag = wrapped.tag.clone();
            bad_tag[0] ^= 1;
            assert!(gcm_kw_unwrap(&kek, &wrapped.iv, &bad_tag, &wrapped.encrypted_key).is_err());
            let mut bad_ct = wrapped.encrypted_key.clone();
            bad_ct[0] ^= 1;
            assert!(
                gcm_kw_unwrap(&kek, &wrapped.iv, &wrapped.tag, &bad_ct).is_err(),
                "AES-GCM authenticates, so an edited ciphertext cannot pass"
            );
        }
    }

    #[test]
    fn a_wrap_rejects_keys_and_parts_of_the_wrong_shape() {
        // Not a truncated hash or a padded block: AES-GCM wants exact sizes, and
        // guessing here would be guessing at a key.
        assert!(gcm_kw_wrap(&[0u8; 15], b"cek").is_err());
        assert!(gcm_kw_wrap(&[0u8; 33], b"cek").is_err());
        assert!(gcm_kw_unwrap(&[0u8; 15], &[0u8; 12], &[0u8; 16], b"cek").is_err());
        assert!(gcm_kw_unwrap(&[0u8; 16], &[0u8; 11], &[0u8; 16], b"cek").is_err());
        assert!(gcm_kw_unwrap(&[0u8; 16], &[0u8; 12], &[0u8; 15], b"cek").is_err());
    }

    #[test]
    fn the_mandatory_members_are_read_or_refused_by_name() {
        let alg = JweAlgorithm::A128Gcmkw;
        let mut header = gcm_header(alg);
        let missing = required_header_bytes(&header, "iv", 12, alg)
            .unwrap_err()
            .to_string();
        assert!(missing.contains("iv"), "{missing}");
        assert!(missing.contains("requires"), "{missing}");

        header.extra.insert("iv".into(), serde_json::json!(12));
        let wrong_type = required_header_bytes(&header, "iv", 12, alg)
            .unwrap_err()
            .to_string();
        assert!(wrong_type.contains("base64url string"), "{wrong_type}");

        header.extra.insert("iv".into(), serde_json::json!("AAAA"));
        let wrong_len = required_header_bytes(&header, "iv", 12, alg)
            .unwrap_err()
            .to_string();
        assert!(wrong_len.contains("iv must be 12 octets"), "{wrong_len}");

        header.extra.insert(
            "iv".into(),
            serde_json::json!(crate::base64url::encode(&[7u8; 12])),
        );
        assert_eq!(
            required_header_bytes(&header, "iv", 12, alg).unwrap(),
            vec![7u8; 12]
        );
    }

    #[test]
    fn wrap_members_are_generated_here_and_cannot_be_supplied() {
        let alg = JweAlgorithm::A128Gcmkw;
        let wrapped = GcmKeyWrap {
            encrypted_key: vec![1u8; 40],
            iv: vec![2u8; 12],
            tag: vec![3u8; 16],
        };
        let header = with_gcm_members(&gcm_header(alg), &wrapped, alg).unwrap();
        assert!(header.extra.contains_key("iv"));
        assert!(header.extra.contains_key("tag"));

        for member in ["iv", "tag"] {
            let mut caller = gcm_header(alg);
            caller
                .extra
                .insert(member.into(), serde_json::json!("AAAA"));
            let err = with_gcm_members(&caller, &wrapped, alg)
                .unwrap_err()
                .to_string();
            assert!(err.contains(member), "{member}: {err}");
        }
    }

    /// Measure the cost of the PBES2 work budget, on the machine running the tests.
    ///
    /// Ignored by default because it is a measurement, not an assertion: the ADR's
    /// numbers were chosen from timings like these, and anyone who wants to re-derive
    /// them for their own hardware should get the same numbers the decision used
    /// rather than a prose description. Run it in release mode — a debug build makes
    /// the HMAC loop several hundred times slower and the numbers are meaningless:
    /// ```text
    /// cargo test --release --lib -- --ignored --nocapture pbes2
    /// ```
    #[test]
    #[ignore]
    fn pbes2_work_budget_benchmark() {
        use kryptering::algorithm::HashAlgorithm;
        use kryptering::kdf::{pbkdf2_derive, Pbkdf2Params};
        use std::time::Instant;

        for (hash, name) in [
            (HashAlgorithm::Sha256, "PBES2-HS256+A128KW"),
            (HashAlgorithm::Sha384, "PBES2-HS384+A192KW"),
            (HashAlgorithm::Sha512, "PBES2-HS512+A256KW"),
        ] {
            for iterations in [
                1_000u32, 2_048, 8_192, 100_000, 250_000, 1_000_000, 10_000_000,
            ] {
                let params = Pbkdf2Params {
                    hash,
                    salt: b"0123456789abcdef".to_vec(),
                    iteration_count: iterations,
                    key_length: 16,
                };
                let start = Instant::now();
                let derived = pbkdf2_derive(b"a-.password-to-derive-from", &params).unwrap();
                let elapsed = start.elapsed();
                assert_eq!(derived.len(), 16);
                println!(
                    "{name}: {iterations:>10} iterations in {:>9.3} ms",
                    elapsed.as_secs_f64() * 1000.0
                );
            }
        }
    }

    #[test]
    fn pbes2_names_its_hash_and_derived_key_length() {
        // The `alg` name states all of it — PBES2-HS512+A256KW is HMAC-SHA-512
        // producing 32 octets for A256KW — so nothing here may read a length from
        // anywhere else, least of all `enc`.
        use kryptering::HashAlgorithm;
        assert_eq!(
            pbes2_params(JweAlgorithm::Pbes2Hs256A128kw),
            Some((16, HashAlgorithm::Sha256))
        );
        assert_eq!(
            pbes2_params(JweAlgorithm::Pbes2Hs384A192kw),
            Some((24, HashAlgorithm::Sha384))
        );
        assert_eq!(
            pbes2_params(JweAlgorithm::Pbes2Hs512A256kw),
            Some((32, HashAlgorithm::Sha512))
        );
        for alg in [
            JweAlgorithm::A128KW,
            JweAlgorithm::A128Gcmkw,
            JweAlgorithm::EcdhEsA128kw,
            JweAlgorithm::Dir,
        ] {
            assert_eq!(pbes2_params(alg), None, "{alg:?}");
            assert!(!alg_is_pbes2(alg), "{alg:?}");
        }

        // And the derived key is the AES-KW key, at the length the name states, so
        // PBES2 shares one wrap mapping with the RFC 3394 algorithms rather than
        // owning a second spelling of "wrap with AES-KW".
        for alg in [
            JweAlgorithm::Pbes2Hs256A128kw,
            JweAlgorithm::Pbes2Hs384A192kw,
            JweAlgorithm::Pbes2Hs512A256kw,
        ] {
            assert!(jwe_alg_to_keywrap(alg).is_ok(), "{alg:?}");
            assert!(alg_is_pbes2(alg), "{alg:?}");
        }
    }

    #[test]
    fn the_pbes2_salt_carries_the_algorithm_name() {
        // RFC 7518 §4.8.1.1: the salt is UTF8(Alg) || 0x00 || Salt Input. The
        // algorithm identifier inside the salt is what makes the `alg` pin bite —
        // the same password and salt derive three different keys under the three
        // algorithms, so a message cannot be read under a cheaper one.
        let salt_input = [0xAAu8, 0xBB, 0xCC];
        let salt = pbes2_salt(JweAlgorithm::Pbes2Hs256A128kw, &salt_input);
        assert_eq!(
            salt,
            [b"PBES2-HS256+A128KW".as_slice(), &[0x00], &salt_input].concat()
        );
        assert_ne!(
            pbes2_salt(JweAlgorithm::Pbes2Hs512A256kw, &salt_input),
            salt,
            "different algorithms must derive different keys"
        );
        // An empty salt input still produces the algorithm-prefixed salt; the ≥8
        // octet rule is enforced on the member, not here.
        assert_eq!(
            pbes2_salt(JweAlgorithm::Pbes2Hs256A128kw, &[]).len(),
            "PBES2-HS256+A128KW".len() + 1
        );
    }

    #[test]
    fn the_rfc_7520_pbes2_derivation_and_wrap_are_reproduced() {
        // RFC 7520 §5.3: the CEK (Figure 97), salt input (Figure 99), 8192
        // iterations and the Figure 96 password must produce the Figure 100
        // encrypted key. Independent of this implementation end to end: the salt
        // construction, the HMAC-SHA-512 PRF, the 32-octet derived key and the
        // RFC 3394 wrap all have to agree, or the output differs.
        let password = super::super::password::Password::from_utf8(
            "entrap_o\u{2013}peter_long\u{2013}credit_tun",
        );
        let cek = crate::base64url::decode("uwsjJXaBK407Qaf0_zpcpmr1Cs0CC50hIUEyGNEt3m0").unwrap();
        let salt_input = crate::base64url::decode("8Q1SzinasR3xchYz6ZZcHA").unwrap();
        let kek = pbes2_derive(
            JweAlgorithm::Pbes2Hs512A256kw,
            &password,
            &salt_input,
            8192,
            kryptering::kdf::PBKDF2_MAX_ITERATIONS,
        )
        .unwrap();
        assert_eq!(kek.len(), 32, "A256KW's key length, from the alg");

        let wrapped = kryptering::keywrap::wrap(
            jwe_alg_to_keywrap(JweAlgorithm::Pbes2Hs512A256kw).unwrap(),
            &kek,
            &cek,
        )
        .unwrap();
        assert_eq!(
            crate::base64url::encode(&wrapped),
            "d3qNhUWfqheyPp4H8sjOWsDYajoej4c5Je6rlUtFPWdgtURtmeDV1g",
            "RFC 7520 Figure 100"
        );
    }

    #[test]
    fn a_budget_violation_refuses_before_deriving() {
        // The whole point of routing PBKDF2 through here: the sender names the count
        // and the recipient pays, so an out-of-range count must cost nothing. A
        // refusal measured in seconds would mean the check ran after the derivation.
        use super::super::password::Password;
        let password = Password::from_utf8("x");
        let started = std::time::Instant::now();

        let too_low = pbes2_derive(
            JweAlgorithm::Pbes2Hs256A128kw,
            &password,
            &[1u8; 16],
            999,
            10_000,
        )
        .unwrap_err()
        .to_string();
        assert!(too_low.contains("iteration floor"), "{too_low}");

        let too_high = pbes2_derive(
            JweAlgorithm::Pbes2Hs256A128kw,
            &password,
            &[1u8; 16],
            1_000_000,
            10_000,
        )
        .unwrap_err()
        .to_string();
        assert!(too_high.contains("work budget"), "{too_high}");

        assert!(
            started.elapsed() < std::time::Duration::from_millis(200),
            "refusing must be free, not a derivation followed by a complaint"
        );

        // A non-PBES2 algorithm has no parameters to derive with.
        assert!(pbes2_derive(JweAlgorithm::A128KW, &password, &[1u8; 16], 4096, 10_000).is_err());
    }

    #[test]
    fn the_pbes2_members_are_read_or_refused_by_name() {
        let alg = JweAlgorithm::Pbes2Hs256A128kw;
        let mut header = gcm_header(alg);

        // Both mandatory.
        assert!(pbes2_message_params(&header, alg)
            .unwrap_err()
            .to_string()
            .contains("p2s"));
        header.extra.insert(
            "p2s".into(),
            serde_json::json!(crate::base64url::encode(&[7u8; 16])),
        );
        assert!(pbes2_message_params(&header, alg)
            .unwrap_err()
            .to_string()
            .contains("p2c"));

        // §4.8.1.2's "positive JSON integer", exactly: no strings, no floats, no
        // negatives, no coercion.
        for bad in [
            serde_json::json!("8192"),
            serde_json::json!(8192.0),
            serde_json::json!(-1),
            serde_json::json!(true),
            serde_json::json!(u64::from(u32::MAX) + 1),
        ] {
            header.extra.insert("p2c".into(), bad.clone());
            let err = pbes2_message_params(&header, alg).unwrap_err().to_string();
            assert!(
                err.contains("positive JSON integer") || err.contains("larger than"),
                "{bad}: {err}"
            );
        }

        // The salt has a minimum, and it is the RFC's own.
        header.extra.insert(
            "p2s".into(),
            serde_json::json!(crate::base64url::encode(&[7u8; 7])),
        );
        header.extra.insert("p2c".into(), serde_json::json!(4096));
        assert!(pbes2_message_params(&header, alg)
            .unwrap_err()
            .to_string()
            .contains("8 or more octets"));

        // A well-formed pair reads as what it says.
        header.extra.insert(
            "p2s".into(),
            serde_json::json!(crate::base64url::encode(&[7u8; 16])),
        );
        let (salt, iterations) = pbes2_message_params(&header, alg).unwrap();
        assert_eq!(salt, vec![7u8; 16]);
        assert_eq!(iterations, 4096);
    }

    #[test]
    fn pbes2_members_are_generated_here_and_cannot_be_supplied() {
        let alg = JweAlgorithm::Pbes2Hs256A128kw;
        let salt = [0x11u8; 16];
        let header = with_pbes2_members(&gcm_header(alg), &salt, 4096, alg).unwrap();
        assert_eq!(
            header.extra.get("p2s").and_then(|v| v.as_str()),
            Some(crate::base64url::encode(&salt).as_str())
        );
        // A JSON integer, not a quoted number: §4.8.1.2, and a peer reads the type.
        assert!(header.extra.get("p2c").and_then(|v| v.as_u64()).is_some());

        for member in ["p2s", "p2c"] {
            let mut caller = gcm_header(alg);
            caller.extra.insert(member.into(), serde_json::json!(1));
            let err = with_pbes2_members(&caller, &salt, 4096, alg)
                .unwrap_err()
                .to_string();
            assert!(err.contains(member), "{member}: {err}");
        }
    }

    #[test]
    fn a_password_is_routed_only_to_the_password_algorithms() {
        use super::super::password::Password;
        let password = Password::from_utf8("a passphrase");
        for alg in [
            JweAlgorithm::Pbes2Hs256A128kw,
            JweAlgorithm::Pbes2Hs384A192kw,
            JweAlgorithm::Pbes2Hs512A256kw,
        ] {
            assert!(matches!(
                password_key(&password, alg).unwrap(),
                KeyMaterial::Password(_)
            ));
        }
        for alg in [
            JweAlgorithm::A128KW,
            JweAlgorithm::Dir,
            JweAlgorithm::A128Gcmkw,
            JweAlgorithm::EcdhEs,
            JweAlgorithm::RsaOaep256,
        ] {
            // `KeyMaterial` has no `Debug` on purpose — it holds key bytes and a
            // password — so the error is extracted rather than unwrapped.
            let err = password_key(&password, alg)
                .err()
                .expect("refused")
                .to_string();
            assert!(err.contains("does not use a password"), "{alg:?}: {err}");
        }
        // And if a password somehow reached a byte-oriented path, it is refused there
        // too rather than used as key material.
        let key = password_key(&password, JweAlgorithm::Pbes2Hs256A128kw).unwrap();
        // Matched rather than unwrapped: `KeyMaterial` has no `Debug`, on purpose, so
        // neither `unwrap_err` nor `expect_err` is available on it.
        match key.bytes() {
            Ok(bytes) => panic!(
                "a password leaked out as {} bytes of key material",
                bytes.len()
            ),
            Err(err) => assert!(err.to_string().contains("not a key"), "{err}"),
        }
    }

    #[test]
    fn several_recipients_are_refused_naming_the_member_at_issue() {
        // The same refusal serves `epk` and `iv`/`tag`, so a caller gets a reason
        // rather than a generic "unsupported".
        let err =
            per_recipient_member_unsupported(JweAlgorithm::A128Gcmkw, "iv and tag").to_string();
        assert!(err.contains("iv and tag"), "{err}");
        assert!(err.contains("no protected header of its own"), "{err}");
        assert!(err.contains("single-recipient"), "{err}");
    }

    #[test]
    fn other_info_matches_the_rfc_7518_appendix_c_bytes() {
        // RFC 7518 §C prints OtherInfo as an explicit octet array for
        // AlgorithmID = "A128GCM", PartyUInfo = "Alice", PartyVInfo = "Bob" and
        // a 128-bit key. Transcribed here, so the layout is pinned by the RFC
        // rather than by this implementation's own output.
        #[rustfmt::skip]
        let expected: Vec<u8> = vec![
            0, 0, 0, 7, 65, 49, 50, 56, 71, 67, 77, // 7 | "A128GCM"
            0, 0, 0, 5, 65, 108, 105, 99, 101,      // 5 | "Alice"
            0, 0, 0, 3, 66, 111, 98,                // 3 | "Bob"
            0, 0, 0, 128,                            // SuppPubInfo: 128 bits
        ];
        let info = other_info("A128GCM", Some(b"Alice"), Some(b"Bob"), 16);
        assert_eq!(info.as_bytes(), expected);
    }

    #[test]
    fn an_absent_party_info_is_four_zero_octets() {
        // Not "absent": the length prefix stays, and dropping it changes the
        // derived key with no error anywhere.
        #[rustfmt::skip]
        let absent_u: Vec<u8> = vec![
            0, 0, 0, 7, 65, 49, 50, 56, 71, 67, 77, // 7 | "A128GCM"
            0, 0, 0, 0,                              // PartyUInfo: empty
            0, 0, 0, 3, 66, 111, 98,                 // 3 | "Bob"
            0, 0, 0, 128,
        ];
        let info = other_info("A128GCM", None, Some(b"Bob"), 16);
        assert_eq!(info.as_bytes(), absent_u);

        // And the empty octet sequence is what an empty header value encodes to
        // as well, so `""` and an absent parameter coincide — which is the
        // server-behaviour divergence documented in the interop notes, not a
        // bug in either reading.
        assert_eq!(
            other_info("A128GCM", Some(b""), Some(b"Bob"), 16).as_bytes(),
            absent_u
        );
    }

    #[test]
    fn supp_pub_info_carries_the_bit_length_big_endian() {
        for (key_len, expected) in [
            (16usize, vec![0u8, 0, 0, 128]),
            (24, vec![0, 0, 0, 192]),
            (32, vec![0, 0, 1, 0]),
        ] {
            let info = other_info("A128GCM", None, None, key_len);
            let bytes = info.as_bytes();
            let tail = &bytes[bytes.len() - 4..];
            assert_eq!(tail, expected, "{key_len} octets = {} bits", key_len * 8);
        }
    }
}