s4-server 0.8.2

S4 — Squished S3 — GPU-accelerated transparent compression S3-compatible storage gateway (cargo install s4-server installs the `s4` binary).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
//! Server-side encryption (SSE-S4) — AES-256-GCM (v0.4 #21, v0.5 #29, v0.5 #27, v0.5 #28).
//!
//! Wraps the post-compression S3 object body with authenticated
//! encryption. Compress-then-encrypt is the right order: encryption
//! produces high-entropy bytes that don't compress, so encrypting last
//! preserves the codec's ratio.
//!
//! ## Wire formats
//!
//! ### S4E1 (v0.4) — single key, no rotation
//!
//! ```text
//! [magic: "S4E1" 4B]
//! [algo:  u8]            # 1 = AES-256-GCM
//! [reserved: 3B]         # 0x00 0x00 0x00
//! [nonce: 12B]           # random per-object
//! [tag:   16B]           # AES-GCM authentication tag
//! [ciphertext: variable] # encrypted-then-authenticated body
//! ```
//!
//! Total overhead: 36 bytes per object.
//!
//! ### S4E2 (v0.5 #29) — keyring-aware, supports rotation
//!
//! ```text
//! [magic:  "S4E2" 4B]
//! [algo:   u8]            # 1 = AES-256-GCM
//! [key_id: u16 BE]        # which keyring slot encrypted this body
//! [reserved: 1B]          # 0x00
//! [nonce:  12B]           # random per-object
//! [tag:    16B]           # AES-GCM authentication tag
//! [ciphertext: variable]
//! ```
//!
//! Same 36-byte overhead — we reused the 3-byte reserved area in S4E1
//! to fit a 2-byte key-id + 1-byte reserved without bumping the header
//! size. The key-id is included in the AAD so a flipped key-id byte
//! fails the auth tag (i.e. an attacker can't trick the gateway into
//! decrypting under a different keyring slot).
//!
//! ### S4E3 (v0.5 #27) — SSE-C, customer-provided key
//!
//! ```text
//! [magic:   "S4E3" 4B]
//! [algo:    u8]            # 1 = AES-256-GCM
//! [key_md5: 16B]           # MD5 fingerprint of the customer key
//! [nonce:   12B]           # random per-object
//! [tag:     16B]           # AES-GCM authentication tag
//! [ciphertext: variable]
//! ```
//!
//! Overhead: 49 bytes (`4 + 1 + 16 + 12 + 16`). Unlike S4E1/S4E2 the
//! gateway does **not** persist the key — the client supplies it on
//! every PUT/GET via `x-amz-server-side-encryption-customer-{algorithm,
//! key,key-MD5}` headers. We store only the 16-byte MD5 in the on-disk
//! frame so a GET with the wrong key surfaces as
//! [`SseError::WrongCustomerKey`] before AES-GCM is even tried (saves a
//! useless decrypt + gives operators a distinct error from generic auth
//! failure).
//!
//! The `key_md5` is included in the AAD so flipping a single byte of
//! the stored fingerprint also breaks AES-GCM auth — i.e. an attacker
//! who tampered with the metadata can't sneak a different key past the
//! check.
//!
//! ### S4E4 (v0.5 #28) — SSE-KMS envelope, per-object DEK
//!
//! ```text
//! [magic:           "S4E4" 4B]
//! [algo:            u8]            # 1 = AES-256-GCM
//! [key_id_len:      u8]            # 1..=255, length of UTF-8 key_id
//! [key_id:          variable]      # UTF-8, AAD-authenticated
//! [wrapped_dek_len: u32 BE]        # length of the wrapped DEK blob
//! [wrapped_dek:     variable]      # opaque, AAD-authenticated
//! [nonce:           12B]           # random per-object
//! [tag:             16B]           # AES-GCM auth tag for body
//! [ciphertext:      variable]      # body encrypted under the DEK
//! ```
//!
//! Header overhead: `4 + 1 + 1 + key_id_len + 4 + wrapped_dek_len + 12
//! + 16` = 38 + key_id_len + wrapped_dek_len. For a typical
//! [`crate::kms::LocalKms`] wrap (60-byte ciphertext) and a 36-char
//! UUID-style `key_id`, that's ~134 bytes per object.
//!
//! `key_id` and `wrapped_dek` are both placed in the AAD so an
//! attacker cannot rewrite either field to point the gateway at a
//! different KEK or wrapped DEK without invalidating the body's
//! AES-GCM tag. The plaintext DEK is never persisted; only the
//! wrapped form is on disk, and the gateway holds the plaintext only
//! for the duration of one PUT or GET.
//!
//! S4E4 decrypt requires an `async` round-trip to the KMS backend
//! (to unwrap the DEK), so the synchronous [`decrypt`] function
//! refuses S4E4 with [`SseError::KmsAsyncRequired`] — callers that
//! peek `S4E4` via [`peek_magic`] must dispatch to
//! [`decrypt_with_kms`] instead.
//!
//! ## v0.5 rotation flow (SSE-S4 only)
//!
//! Operators wire one [`SseKeyring`] holding the **active** key plus
//! any number of **retired** keys. PUT always encrypts under the
//! active key (S4E2 with that key's id). GET sniffs the magic:
//!
//! - `S4E1`: legacy single-key path. The keyring's active key is tried
//!   first, then every retired key — this lets a v0.4 deployment
//!   migrate to a keyring with the original key as active and decrypt
//!   pre-rotation objects unchanged.
//! - `S4E2`: read the key_id, look it up in the keyring, decrypt with
//!   that exact key. Missing key_id surfaces as `KeyNotInKeyring`.
//! - `S4E3`: keyring is **not** consulted. Caller must supply
//!   [`SseSource::CustomerKey`] with the matching key + md5.
//!
//! ## Open follow-ups
//!
//! - **Server-managed key only** (for SSE-S4): keys come from local
//!   files via `--sse-s4-key` / `--sse-s4-key-rotated`. KMS / vault
//!   integration for the SSE-S4 keyring (i.e. wrapping the keyring's
//!   keys with KMS) is a separate issue. SSE-KMS for per-object DEKs
//!   is implemented (see [`SseSource::Kms`] + S4E4 above).

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use bytes::Bytes;
use md5::{Digest as Md5Digest, Md5};
use rand::RngCore;
use thiserror::Error;

use crate::kms::{KmsBackend, KmsError, WrappedDek};

pub const SSE_MAGIC_V1: &[u8; 4] = b"S4E1";
pub const SSE_MAGIC_V2: &[u8; 4] = b"S4E2";
pub const SSE_MAGIC_V3: &[u8; 4] = b"S4E3";
pub const SSE_MAGIC_V4: &[u8; 4] = b"S4E4";
/// v0.8 #52: chunked variant of S4E2 — same SSE-S4 keyring source,
/// but the body is sliced into independently-sealed AES-GCM chunks
/// so the GET path can stream-decrypt + emit chunk-by-chunk instead
/// of buffering the entire object before tag verify. See
/// [`encrypt_v2_chunked`] / [`decrypt_chunked_stream`] for the on-
/// the-wire layout.
///
/// **Read-only as of v0.8.1 #57** — new PUTs emit [`SSE_MAGIC_V6`]
/// (S4E6). S4E5 is kept around for back-compat decrypt of objects
/// written by v0.8.0.
pub const SSE_MAGIC_V5: &[u8; 4] = b"S4E5";
/// v0.8.1 #57: identical layout to S4E5 except the per-PUT salt is
/// widened from 4 → 8 bytes so the birthday-collision threshold on
/// AES-GCM nonce reuse jumps from ~65k PUTs/key to ~4 billion. See
/// [`encrypt_v2_chunked`] (now emits S4E6) / the S4E6 wire-format
/// docs further down for the full layout.
pub const SSE_MAGIC_V6: &[u8; 4] = b"S4E6";
/// Back-compat alias — v0.4 callers that imported `SSE_MAGIC` mean S4E1.
pub const SSE_MAGIC: &[u8; 4] = SSE_MAGIC_V1;

/// Header layout matches between S4E1 and S4E2 (both 36 bytes total)
/// because S4E2 reuses the 3-byte reserved slot to fit `key_id (2B) +
/// reserved (1B)`. Keeping them the same length means the rest of the
/// pipeline (sidecar offsets, multipart math) doesn't care which
/// frame variant is in flight.
pub const SSE_HEADER_BYTES: usize = 4 + 1 + 3 + 12 + 16; // = 36
/// S4E3 (SSE-C) replaces the 3-byte reserved area with a 16-byte
/// customer-key MD5 fingerprint, so the header is 49 bytes total.
/// `magic 4 + algo 1 + key_md5 16 + nonce 12 + tag 16`.
pub const SSE_HEADER_BYTES_V3: usize = 4 + 1 + KEY_MD5_LEN + 12 + 16; // = 49
pub const ALGO_AES_256_GCM: u8 = 1;
const NONCE_LEN: usize = 12;
const TAG_LEN: usize = 16;
const KEY_LEN: usize = 32;
const KEY_MD5_LEN: usize = 16;
/// AWS S3 SSE-C only allows AES256 in the
/// `x-amz-server-side-encryption-customer-algorithm` header, so we
/// match that exact spelling for parity with real S3 clients.
pub const SSE_C_ALGORITHM: &str = "AES256";

#[derive(Debug, Error)]
pub enum SseError {
    #[error("SSE key file {path:?}: {source}")]
    KeyFileIo {
        path: std::path::PathBuf,
        source: std::io::Error,
    },
    #[error(
        "SSE key file must be exactly 32 raw bytes (or 64-char hex / 44-char base64); got {got} bytes after parse"
    )]
    BadKeyLength { got: usize },
    #[error("SSE-encrypted body too short ({got} bytes; need at least {SSE_HEADER_BYTES})")]
    TooShort { got: usize },
    #[error("SSE bad magic: expected S4E1/S4E2/S4E3/S4E4/S4E5/S4E6, got {got:?}")]
    BadMagic { got: [u8; 4] },
    #[error("SSE unsupported algo tag: {tag} (this build only knows AES-256-GCM = 1)")]
    UnsupportedAlgo { tag: u8 },
    #[error(
        "SSE key_id {id} (S4E2 frame) not present in keyring; rotation history likely incomplete"
    )]
    KeyNotInKeyring { id: u16 },
    #[error("SSE decryption / authentication failed (key mismatch or ciphertext tampered with)")]
    DecryptFailed,
    // --- v0.5 #27: SSE-C specific errors ---
    /// The MD5 fingerprint stored in the S4E3 frame doesn't match the
    /// MD5 of the customer key the client supplied. This is the
    /// "wrong customer key on GET" signal — distinct from
    /// `DecryptFailed` so service.rs can map it to AWS S3's
    /// `403 AccessDenied` (S3 returns AccessDenied when the supplied
    /// SSE-C key doesn't match the one used at PUT time).
    #[error("SSE-C key MD5 fingerprint mismatch — client supplied a different key than PUT")]
    WrongCustomerKey,
    /// `parse_customer_key_headers` saw a malformed input. `reason` is
    /// a short human string ("base64 decode of key", "key length",
    /// "md5 length", "md5 mismatch") for operator log lines — never
    /// echoed to the client (would leak crypto details).
    #[error("SSE-C customer-key headers invalid: {reason}")]
    InvalidCustomerKey { reason: &'static str },
    /// Client asked for an SSE-C algorithm the gateway doesn't speak.
    /// AWS S3 only ever defines `AES256` here; surfacing the offending
    /// string lets us 400 with a useful message.
    #[error("SSE-C algorithm {algo:?} unsupported (only {SSE_C_ALGORITHM:?} is allowed)")]
    CustomerKeyAlgorithmUnsupported { algo: String },
    /// S4E3 body lacks an SSE-C key — caller passed `SseSource::Keyring`
    /// when decrypting an SSE-C-encrypted object. service.rs should
    /// translate this into the same "missing customer key" 400 that
    /// AWS S3 returns when SSE-C headers are absent on a GET.
    #[error("S4E3 frame requires SseSource::CustomerKey; got Keyring")]
    CustomerKeyRequired,
    /// Inverse: client sent SSE-C headers on a GET for an object stored
    /// without SSE-C. The supplied key has no role in decryption, but
    /// AWS S3 actually 400s in this case ("expected an unencrypted
    /// object" / "extraneous SSE-C headers"), so we mirror that.
    #[error("S4E1/S4E2 frame stored without SSE-C; SseSource::CustomerKey is unexpected")]
    CustomerKeyUnexpected,
    // --- v0.5 #28: SSE-KMS specific errors ---
    /// `decrypt` (sync) was handed an S4E4 body. SSE-KMS unwrap is
    /// async (it round-trips to the KMS backend), so callers must
    /// peek the magic with [`peek_magic`] and dispatch S4E4 frames to
    /// [`decrypt_with_kms`] instead. service.rs's GET handler does
    /// this; tests / direct callers may hit this if they forget.
    #[error(
        "S4E4 (SSE-KMS) body requires async decrypt — call decrypt_with_kms() instead of decrypt()"
    )]
    KmsAsyncRequired,
    /// S4E4 frame is shorter than the minimum-possible header (38
    /// bytes for an empty `key_id` + empty `wrapped_dek`, which is
    /// itself impossible — we just sanity-check the floor).
    #[error("S4E4 frame too short ({got} bytes; need at least {min})")]
    KmsFrameTooShort { got: usize, min: usize },
    /// S4E4 declared a `key_id_len` or `wrapped_dek_len` that runs
    /// past the end of the body. Almost certainly truncation /
    /// corruption rather than tampering (tampering would fail the
    /// AES-GCM tag instead).
    #[error("S4E4 frame field length out of bounds: {what}")]
    KmsFrameFieldOob { what: &'static str },
    /// `key_id` field of an S4E4 frame is not valid UTF-8. We require
    /// UTF-8 because `LocalKms` uses the basename of a `.kek` file
    /// (which is OS-string-but-typically-UTF-8) and AWS KMS uses ARNs
    /// (which are ASCII).
    #[error("S4E4 key_id is not valid UTF-8")]
    KmsKeyIdNotUtf8,
    /// service.rs handed `decrypt_with_kms` a `WrappedDek` whose
    /// `key_id` doesn't match the one stored in the S4E4 frame. This
    /// is an integration bug (caller is meant to pull the wrapped
    /// DEK *from the frame*, not from somewhere else), surface as a
    /// distinct error so it shows up in tests rather than silently
    /// failing the AES-GCM tag.
    #[error(
        "S4E4 SseSource::Kms wrapped DEK key_id {supplied:?} doesn't match frame key_id {stored:?}"
    )]
    KmsWrappedDekMismatch {
        supplied: String,
        stored: String,
    },
    /// SSE-KMS path got a non-Kms `SseSource` for an S4E4 body. The
    /// async dispatch in `decrypt_with_kms` re-derives the source
    /// internally so this can only happen if a future caller passes
    /// `SseSource::Keyring` / `CustomerKey` to a path that expected
    /// `Kms` — kept around for symmetry with the other "wrong source"
    /// errors.
    #[error("S4E4 frame requires SseSource::Kms")]
    KmsRequired,
    /// Pass-through for [`crate::kms::KmsError`] surfaced from
    /// `KmsBackend::decrypt_dek` — boxed so the variant stays small.
    #[error("KMS unwrap: {0}")]
    KmsBackend(#[from] KmsError),
    // --- v0.8 #52: S4E5 (chunked SSE-S4) specific errors ---
    /// AES-GCM auth tag verify failed on chunk `chunk_index` of an
    /// S4E5 body. Distinct from the all-or-nothing
    /// [`SseError::DecryptFailed`] because the streaming GET may
    /// have already emitted earlier chunks to the client by the
    /// time chunk N fails — operators need the chunk index in audit
    /// logs to triangulate which byte range was tampered with (or
    /// which disk sector flipped).
    #[error("S4E5 chunk {chunk_index} auth tag verify failed (key mismatch or chunk tampered with)")]
    ChunkAuthFailed { chunk_index: u32 },
    /// Caller asked [`encrypt_v2_chunked`] to use a chunk size of 0
    /// — nonsensical (would loop forever). Surfaced as an error
    /// rather than panicking so service.rs can map a bad
    /// `--sse-chunk-size 0` configuration to a clear startup error.
    #[error("S4E5 chunk_size must be > 0 (got 0)")]
    ChunkSizeInvalid,
    /// S4E5 frame is shorter than the fixed header or declares a
    /// (chunk_count × per-chunk-bytes) total that overruns the
    /// body. Almost certainly truncation / corruption — tampering
    /// with the per-chunk ciphertext or tag would surface as
    /// [`SseError::ChunkAuthFailed`] instead.
    #[error("S4E5 frame truncated: {what}")]
    ChunkFrameTruncated { what: &'static str },
    // --- v0.8.1 #57: S4E6 (8-byte salt, 24-bit chunk_index) ---
    /// S4E6 chunk_index is encoded as a 24-bit big-endian field in
    /// the per-chunk nonce, capping `chunk_count` at
    /// `2^24 - 1 = 16_777_215`. At the default 1 MiB chunk size that
    /// is ~16 PiB per object — well past S3's 5 GiB single-object
    /// ceiling. Surface as a distinct error so a misconfiguration
    /// (`--sse-chunk-size 1` on a multi-GiB object, say) shows up at
    /// PUT time with a clear cause rather than a panic at the u32 →
    /// u24 cast.
    #[error(
        "S4E6 chunk_count {got} exceeds 24-bit max ({max}) — pick a larger --sse-chunk-size"
    )]
    ChunkCountTooLarge { got: u32, max: u32 },
    // --- v0.8.2 #64: pre-allocation guard for chunked SSE frames ---
    /// `parse_chunked_header` rejected an S4E5 / S4E6 frame because
    /// the declared `chunk_size × chunk_count` (or the on-disk total
    /// after adding per-chunk tag overhead and the fixed header) is
    /// either:
    ///
    /// 1. arithmetically nonsensical (the multiplication / addition
    ///    overflows u64 on a 64-bit host), or
    /// 2. larger than the gateway's configured `max_body_bytes`
    ///    (default 5 GiB — AWS S3's single-object PUT ceiling).
    ///
    /// This is the **DoS guard** for the chunked path: without it, a
    /// 24-byte malicious header that claims `chunk_size = u32::MAX`
    /// and `chunk_count = u32::MAX` would have caused the buffered
    /// decrypt path to attempt a multi-PB `Vec::with_capacity` (or
    /// integer-overflow into a tiny alloc + later out-of-bounds
    /// panic) before any cryptographic work happened. Surface as a
    /// distinct variant — never echo the offending sizes back to the
    /// client (kept as a `&'static str` `details` field for operator
    /// audit logs only) so the response isn't a tampering oracle.
    #[error("S4E5/S4E6 chunked frame declares an over-large size: {details}")]
    ChunkFrameTooLarge { details: &'static str },
}

/// Default cap on a single chunked-SSE frame's declared plaintext
/// size, used by [`decrypt_chunked_buffered_default`] and the
/// streaming pre-validation path. Mirrors AWS S3's 5 GiB single-object
/// PUT ceiling — anything larger is unreachable on the AWS-compatible
/// API surface and is therefore safe to reject pre-alloc as a malformed
/// / malicious header (v0.8.2 #64).
pub const DEFAULT_MAX_BODY_BYTES: usize = 5 * 1024 * 1024 * 1024;

/// 32-byte symmetric key. `bytes` is `pub` so call sites can construct
/// keys directly from already-validated bytes (e.g. KMS-decrypted DEKs)
/// without going through the on-disk parser. Hold inside an `Arc` when
/// sharing across handler tasks — `SseKeyring` does this internally.
pub struct SseKey {
    pub bytes: [u8; 32],
}

impl SseKey {
    /// Load a 32-byte key from disk. Accepts three on-disk encodings:
    /// raw 32 bytes, 64-char ASCII hex, or 44-char ASCII base64 (with or
    /// without padding). Whitespace is trimmed.
    pub fn from_path(path: &Path) -> Result<Self, SseError> {
        let raw = std::fs::read(path).map_err(|source| SseError::KeyFileIo {
            path: path.to_path_buf(),
            source,
        })?;
        Self::from_bytes(&raw)
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SseError> {
        // Try raw first.
        if bytes.len() == KEY_LEN {
            let mut k = [0u8; KEY_LEN];
            k.copy_from_slice(bytes);
            return Ok(Self { bytes: k });
        }
        // Trim whitespace and try hex / base64.
        let s = std::str::from_utf8(bytes).unwrap_or("").trim();
        if s.len() == KEY_LEN * 2 && s.chars().all(|c| c.is_ascii_hexdigit()) {
            let mut k = [0u8; KEY_LEN];
            for (i, k_byte) in k.iter_mut().enumerate() {
                *k_byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)
                    .map_err(|_| SseError::BadKeyLength { got: bytes.len() })?;
            }
            return Ok(Self { bytes: k });
        }
        if let Ok(decoded) =
            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, s.as_bytes())
            && decoded.len() == KEY_LEN
        {
            let mut k = [0u8; KEY_LEN];
            k.copy_from_slice(&decoded);
            return Ok(Self { bytes: k });
        }
        Err(SseError::BadKeyLength { got: bytes.len() })
    }

    fn as_aes_key(&self) -> &Key<Aes256Gcm> {
        Key::<Aes256Gcm>::from_slice(&self.bytes)
    }
}

impl std::fmt::Debug for SseKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SseKey")
            .field("len", &KEY_LEN)
            .field("key", &"<redacted>")
            .finish()
    }
}

/// v0.5 #29: a set of `SseKey`s indexed by `u16` key-id, plus a
/// designated **active** id used for new encryptions. Rotation is just
/// "add the new key, flip `active` to its id, leave the old keys for
/// decryption-only". Cheap to clone (`Arc<SseKey>` per slot).
#[derive(Clone)]
pub struct SseKeyring {
    active: u16,
    keys: HashMap<u16, Arc<SseKey>>,
}

impl SseKeyring {
    /// Create a keyring seeded with one key, immediately marked
    /// active. Add older keys later via [`SseKeyring::add`] so the
    /// gateway can still decrypt pre-rotation objects.
    pub fn new(active: u16, key: Arc<SseKey>) -> Self {
        let mut keys = HashMap::new();
        keys.insert(active, key);
        Self { active, keys }
    }

    /// Insert another key under id `id`. Does NOT change `active`. If
    /// `id == active`, the slot is overwritten (useful for tests; in
    /// production prefer minting a fresh id).
    pub fn add(&mut self, id: u16, key: Arc<SseKey>) {
        self.keys.insert(id, key);
    }

    /// Active (id, key) — used by [`encrypt_v2`] to pick the slot for
    /// new objects.
    pub fn active(&self) -> (u16, &SseKey) {
        let id = self.active;
        let key = self
            .keys
            .get(&id)
            .expect("active key id must be present in keyring (constructor invariant)");
        (id, key.as_ref())
    }

    /// Look up a key by id. Returns `None` for unknown ids — caller
    /// should surface this as [`SseError::KeyNotInKeyring`].
    pub fn get(&self, id: u16) -> Option<&SseKey> {
        self.keys.get(&id).map(Arc::as_ref)
    }
}

impl std::fmt::Debug for SseKeyring {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SseKeyring")
            .field("active", &self.active)
            .field("key_count", &self.keys.len())
            .field("key_ids", &self.keys.keys().collect::<Vec<_>>())
            .finish()
    }
}

pub type SharedSseKeyring = Arc<SseKeyring>;

/// Encrypt `plaintext` with the given key, producing the on-the-wire
/// S4E1-framed output: `[magic 4][algo 1][reserved 3][nonce 12][tag 16][ciphertext]`.
///
/// Kept for back-compat: v0.4 callers that hand-built an `SseKey` (no
/// keyring) still get the v1 frame. New code should use
/// [`encrypt_v2`] which writes S4E2 and supports rotation on read.
pub fn encrypt(key: &SseKey, plaintext: &[u8]) -> Bytes {
    let cipher = Aes256Gcm::new(key.as_aes_key());
    let mut nonce_bytes = [0u8; NONCE_LEN];
    rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::from_slice(&nonce_bytes);
    // AAD = magic + algo. Tampering with either bumps the tag check.
    let mut aad = [0u8; 8];
    aad[..4].copy_from_slice(SSE_MAGIC_V1);
    aad[4] = ALGO_AES_256_GCM;
    let ct_with_tag = cipher
        .encrypt(
            nonce,
            Payload {
                msg: plaintext,
                aad: &aad,
            },
        )
        .expect("aes-gcm encrypt cannot fail with a 32-byte key");
    debug_assert!(ct_with_tag.len() >= TAG_LEN);
    let split = ct_with_tag.len() - TAG_LEN;
    let (ct, tag) = ct_with_tag.split_at(split);

    let mut out = Vec::with_capacity(SSE_HEADER_BYTES + ct.len());
    out.extend_from_slice(SSE_MAGIC_V1);
    out.push(ALGO_AES_256_GCM);
    out.extend_from_slice(&[0u8; 3]); // reserved
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(tag);
    out.extend_from_slice(ct);
    Bytes::from(out)
}

/// v0.5 #29: encrypt under the keyring's currently-active key, writing
/// an S4E2-framed body (`[magic 4][algo 1][key_id 2 BE][reserved 1]
/// [nonce 12][tag 16][ciphertext]`). The key-id is included in the
/// AAD so flipping it fails the auth tag.
pub fn encrypt_v2(plaintext: &[u8], keyring: &SseKeyring) -> Bytes {
    let (key_id, key) = keyring.active();
    let cipher = Aes256Gcm::new(key.as_aes_key());
    let mut nonce_bytes = [0u8; NONCE_LEN];
    rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::from_slice(&nonce_bytes);
    let aad = aad_v2(key_id);
    let ct_with_tag = cipher
        .encrypt(
            nonce,
            Payload {
                msg: plaintext,
                aad: &aad,
            },
        )
        .expect("aes-gcm encrypt cannot fail with a 32-byte key");
    debug_assert!(ct_with_tag.len() >= TAG_LEN);
    let split = ct_with_tag.len() - TAG_LEN;
    let (ct, tag) = ct_with_tag.split_at(split);

    let mut out = Vec::with_capacity(SSE_HEADER_BYTES + ct.len());
    out.extend_from_slice(SSE_MAGIC_V2);
    out.push(ALGO_AES_256_GCM);
    out.extend_from_slice(&key_id.to_be_bytes()); // 2B BE key_id
    out.push(0u8); // 1B reserved
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(tag);
    out.extend_from_slice(ct);
    Bytes::from(out)
}

fn aad_v1() -> [u8; 8] {
    let mut aad = [0u8; 8];
    aad[..4].copy_from_slice(SSE_MAGIC_V1);
    aad[4] = ALGO_AES_256_GCM;
    aad
}

fn aad_v2(key_id: u16) -> [u8; 8] {
    let mut aad = [0u8; 8];
    aad[..4].copy_from_slice(SSE_MAGIC_V2);
    aad[4] = ALGO_AES_256_GCM;
    aad[5..7].copy_from_slice(&key_id.to_be_bytes());
    aad[7] = 0u8;
    aad
}

/// AAD for S4E3 = magic (4) + algo (1) + key_md5 (16). Putting the
/// fingerprint in the AAD means tampering with the stored MD5 (e.g. an
/// attacker rewriting the header to match a *different* key they
/// happen to know) breaks the AES-GCM tag — the wrong-key check isn't
/// just a plain `==` we could be tricked past.
fn aad_v3(key_md5: &[u8; KEY_MD5_LEN]) -> [u8; 4 + 1 + KEY_MD5_LEN] {
    let mut aad = [0u8; 4 + 1 + KEY_MD5_LEN];
    aad[..4].copy_from_slice(SSE_MAGIC_V3);
    aad[4] = ALGO_AES_256_GCM;
    aad[5..5 + KEY_MD5_LEN].copy_from_slice(key_md5);
    aad
}

/// Parsed + verified SSE-C key material from the three customer
/// headers. `key_md5` is the MD5 of `key` (we recompute and compare in
/// [`parse_customer_key_headers`] — clients send their own to catch
/// transport corruption, but we *trust* our own computation as the
/// canonical fingerprint in the S4E3 frame).
#[derive(Clone)]
pub struct CustomerKeyMaterial {
    pub key: [u8; KEY_LEN],
    pub key_md5: [u8; KEY_MD5_LEN],
}

impl std::fmt::Debug for CustomerKeyMaterial {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Don't leak the key into logs. The MD5 is a public fingerprint
        // (S3 puts it on the wire), so that's safe to show.
        f.debug_struct("CustomerKeyMaterial")
            .field("key", &"<redacted>")
            .field("key_md5_hex", &hex_lower(&self.key_md5))
            .finish()
    }
}

fn hex_lower(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// Source of the encryption key for [`encrypt_with_source`] /
/// [`decrypt`]. SSE-S4 (server-managed, rotation-aware) goes through
/// `Keyring`; SSE-C (customer-supplied) goes through `CustomerKey`.
///
/// Borrowed (not owned) so the caller can hold a long-lived
/// `CustomerKeyMaterial` next to the request and just lend it for the
/// duration of one PUT/GET.
#[derive(Debug, Clone, Copy)]
pub enum SseSource<'a> {
    /// Server-managed keyring path → produces / consumes S4E1 (legacy)
    /// or S4E2 (rotation-aware) frames.
    Keyring(&'a SseKeyring),
    /// Client-supplied AES-256 key + its MD5 fingerprint → produces /
    /// consumes S4E3 frames. The server never persists the key; it
    /// stores `key_md5` only.
    CustomerKey {
        key: &'a [u8; KEY_LEN],
        key_md5: &'a [u8; KEY_MD5_LEN],
    },
    /// SSE-KMS envelope → produces / consumes S4E4 frames. The server
    /// holds a per-object plaintext DEK (from a fresh
    /// [`KmsBackend::generate_dek`] call) and the wrapped form to
    /// persist alongside the body. The DEK is dropped after one
    /// PUT/GET; only the wrapped form survives at rest.
    Kms {
        /// 32-byte plaintext DEK, used as the AES-GCM key.
        dek: &'a [u8; KEY_LEN],
        /// Wrapped form to persist in the S4E4 frame (PUT) or the one
        /// read out of the frame (GET, after a successful unwrap).
        wrapped: &'a WrappedDek,
    },
}

/// Back-compat coercion: existing call sites pass `&SseKeyring`
/// directly to [`decrypt`]. With this `From` impl the generic bound
/// `Into<SseSource>` accepts `&SseKeyring` without the caller writing
/// `.into()`, keeping v0.4 / v0.5 #29 service.rs callers compiling
/// untouched while v0.5 #27 SSE-C callers pass `SseSource::CustomerKey`
/// explicitly.
impl<'a> From<&'a SseKeyring> for SseSource<'a> {
    fn from(kr: &'a SseKeyring) -> Self {
        SseSource::Keyring(kr)
    }
}

/// service.rs holds keyring as `Option<Arc<SseKeyring>>` and unwraps to
/// `&Arc<SseKeyring>` — let that coerce too, otherwise every existing
/// call site needs `.as_ref()` boilerplate.
impl<'a> From<&'a Arc<SseKeyring>> for SseSource<'a> {
    fn from(kr: &'a Arc<SseKeyring>) -> Self {
        SseSource::Keyring(kr.as_ref())
    }
}

impl<'a> From<&'a CustomerKeyMaterial> for SseSource<'a> {
    fn from(m: &'a CustomerKeyMaterial) -> Self {
        SseSource::CustomerKey {
            key: &m.key,
            key_md5: &m.key_md5,
        }
    }
}

/// Parse the three AWS SSE-C headers and return verified key material.
///
/// Validates, in order:
/// 1. `algorithm == "AES256"` (the only value AWS S3 defines).
/// 2. `key_base64` decodes to exactly 32 bytes (AES-256 key length).
/// 3. `key_md5_base64` decodes to exactly 16 bytes (MD5 digest length).
/// 4. The actual MD5 of the decoded key matches the supplied MD5.
///
/// Step 4 catches transport corruption *and* a class of programming
/// bugs where the client signs with one key but uploads another. AWS
/// S3 also performs this check.
pub fn parse_customer_key_headers(
    algorithm: &str,
    key_base64: &str,
    key_md5_base64: &str,
) -> Result<CustomerKeyMaterial, SseError> {
    use base64::Engine as _;
    if algorithm != SSE_C_ALGORITHM {
        return Err(SseError::CustomerKeyAlgorithmUnsupported {
            algo: algorithm.to_string(),
        });
    }
    let key_bytes = base64::engine::general_purpose::STANDARD
        .decode(key_base64.trim().as_bytes())
        .map_err(|_| SseError::InvalidCustomerKey {
            reason: "base64 decode of key",
        })?;
    if key_bytes.len() != KEY_LEN {
        return Err(SseError::InvalidCustomerKey {
            reason: "key length (must be 32 bytes after base64 decode)",
        });
    }
    let supplied_md5 = base64::engine::general_purpose::STANDARD
        .decode(key_md5_base64.trim().as_bytes())
        .map_err(|_| SseError::InvalidCustomerKey {
            reason: "base64 decode of key MD5",
        })?;
    if supplied_md5.len() != KEY_MD5_LEN {
        return Err(SseError::InvalidCustomerKey {
            reason: "key MD5 length (must be 16 bytes after base64 decode)",
        });
    }
    let actual_md5 = compute_key_md5(&key_bytes);
    // Constant-time compare — paranoia, MD5 is non-secret but the key
    // it identifies is, so we don't want a timing oracle.
    if !constant_time_eq(&actual_md5, &supplied_md5) {
        return Err(SseError::InvalidCustomerKey {
            reason: "supplied MD5 does not match MD5 of supplied key",
        });
    }
    let mut key = [0u8; KEY_LEN];
    key.copy_from_slice(&key_bytes);
    let mut key_md5 = [0u8; KEY_MD5_LEN];
    key_md5.copy_from_slice(&actual_md5);
    Ok(CustomerKeyMaterial { key, key_md5 })
}

/// Convenience wrapper — compute the MD5 fingerprint of a 32-byte
/// customer key. Callers that already have the bytes (e.g. derived
/// from a KMS unwrap) can use this to construct a
/// [`CustomerKeyMaterial`] directly.
pub fn compute_key_md5(key: &[u8]) -> [u8; KEY_MD5_LEN] {
    let mut h = Md5::new();
    h.update(key);
    let out = h.finalize();
    let mut md5 = [0u8; KEY_MD5_LEN];
    md5.copy_from_slice(&out);
    md5
}

/// `subtle`-free constant-time byte slice equality. We only need this
/// at one site (MD5 verification) so pulling `subtle` in feels excessive.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut acc: u8 = 0;
    for (x, y) in a.iter().zip(b.iter()) {
        acc |= x ^ y;
    }
    acc == 0
}

/// v0.5 #27: encrypt under whichever source the caller picked.
///
/// - `SseSource::Keyring` → delegates to [`encrypt_v2`] (S4E2 frame).
/// - `SseSource::CustomerKey` → writes an S4E3 frame (no key persisted,
///   just the MD5 fingerprint for GET-side verification).
///
/// service.rs picks the source per-request: SSE-C headers present →
/// `CustomerKey`, otherwise (and only when `--sse-s4-key` is wired) →
/// `Keyring`. Plaintext objects skip this function entirely.
pub fn encrypt_with_source(plaintext: &[u8], source: SseSource<'_>) -> Bytes {
    match source {
        SseSource::Keyring(kr) => encrypt_v2(plaintext, kr),
        SseSource::CustomerKey { key, key_md5 } => encrypt_v3(plaintext, key, key_md5),
        SseSource::Kms { dek, wrapped } => encrypt_v4(plaintext, dek, wrapped),
    }
}

fn encrypt_v3(
    plaintext: &[u8],
    key: &[u8; KEY_LEN],
    key_md5: &[u8; KEY_MD5_LEN],
) -> Bytes {
    let aes_key = Key::<Aes256Gcm>::from_slice(key);
    let cipher = Aes256Gcm::new(aes_key);
    let mut nonce_bytes = [0u8; NONCE_LEN];
    rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::from_slice(&nonce_bytes);
    let aad = aad_v3(key_md5);
    let ct_with_tag = cipher
        .encrypt(
            nonce,
            Payload {
                msg: plaintext,
                aad: &aad,
            },
        )
        .expect("aes-gcm encrypt cannot fail with a 32-byte key");
    debug_assert!(ct_with_tag.len() >= TAG_LEN);
    let split = ct_with_tag.len() - TAG_LEN;
    let (ct, tag) = ct_with_tag.split_at(split);

    let mut out = Vec::with_capacity(SSE_HEADER_BYTES_V3 + ct.len());
    out.extend_from_slice(SSE_MAGIC_V3);
    out.push(ALGO_AES_256_GCM);
    out.extend_from_slice(key_md5);
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(tag);
    out.extend_from_slice(ct);
    Bytes::from(out)
}

/// v0.5 #29 + v0.5 #27: dispatch on the body's magic and decrypt under
/// whichever source the caller supplied.
///
/// - `S4E1` / `S4E2` require `SseSource::Keyring` (return
///   [`SseError::CustomerKeyRequired`] for `CustomerKey` — service.rs
///   should map this to "extraneous SSE-C headers" 400).
/// - `S4E3` requires `SseSource::CustomerKey` (return
///   [`SseError::CustomerKeyUnexpected`] for `Keyring` — service.rs
///   should map this to "missing SSE-C headers" 400).
///
/// Generic over `Into<SseSource>` so existing `decrypt(body, &keyring)`
/// call sites compile unchanged via the `From<&SseKeyring>` impl above
/// — only the new SSE-C path needs to type out
/// `SseSource::CustomerKey { .. }`.
///
/// Distinct errors (`KeyNotInKeyring`, `DecryptFailed`,
/// `WrongCustomerKey`) let operators tell rotation gaps, ciphertext
/// tampering, and SSE-C key mismatch apart in audit logs.
pub fn decrypt<'a, S: Into<SseSource<'a>>>(body: &[u8], source: S) -> Result<Bytes, SseError> {
    let source = source.into();
    // Outer short-check uses the smaller of the two header sizes
    // (S4E1/S4E2 = 36 bytes). Anything below this can't be any valid
    // SSE frame regardless of magic — keeps back-compat with v0.4 /
    // v0.5 #29 callers that expected `TooShort` for absurdly short
    // inputs even when the magic is garbage.
    if body.len() < SSE_HEADER_BYTES {
        return Err(SseError::TooShort { got: body.len() });
    }
    let mut magic = [0u8; 4];
    magic.copy_from_slice(&body[..4]);
    match &magic {
        m if m == SSE_MAGIC_V1 || m == SSE_MAGIC_V2 => {
            let keyring = match source {
                SseSource::Keyring(kr) => kr,
                SseSource::CustomerKey { .. } => return Err(SseError::CustomerKeyUnexpected),
                // S4E1/E2 stored under the keyring → SseSource::Kms
                // is just as nonsensical as CustomerKey here. Re-use
                // the same "wrong source" error so service.rs can
                // map both to AWS S3's "extraneous SSE-* headers"
                // 400.
                SseSource::Kms { .. } => return Err(SseError::CustomerKeyUnexpected),
            };
            if m == SSE_MAGIC_V1 {
                decrypt_v1_with_keyring(body, keyring)
            } else {
                decrypt_v2_with_keyring(body, keyring)
            }
        }
        m if m == SSE_MAGIC_V3 => {
            // S4E3 has a larger 49-byte header, so re-check.
            if body.len() < SSE_HEADER_BYTES_V3 {
                return Err(SseError::TooShort { got: body.len() });
            }
            let (key, key_md5) = match source {
                SseSource::CustomerKey { key, key_md5 } => (key, key_md5),
                SseSource::Keyring(_) => return Err(SseError::CustomerKeyRequired),
                SseSource::Kms { .. } => return Err(SseError::CustomerKeyRequired),
            };
            decrypt_v3(body, key, key_md5)
        }
        m if m == SSE_MAGIC_V4 => {
            // SSE-KMS unwrap is async (KMS round-trip required).
            // Caller must dispatch to `decrypt_with_kms` after
            // peeking the magic — surface this as a distinct error
            // rather than silently failing.
            Err(SseError::KmsAsyncRequired)
        }
        m if m == SSE_MAGIC_V5 || m == SSE_MAGIC_V6 => {
            // v0.8 #52 (S4E5) / v0.8.1 #57 (S4E6): chunked SSE-S4.
            // Sync back-compat path — verifies + decrypts every
            // chunk into a single Bytes. Callers that want true
            // streaming (per-chunk emit) should use
            // `decrypt_chunked_stream` instead. SSE-C and SSE-KMS
            // sources are nonsensical here for the same reason as
            // S4E2 (server-managed keyring only).
            let keyring = match source {
                SseSource::Keyring(kr) => kr,
                SseSource::CustomerKey { .. } => {
                    return Err(SseError::CustomerKeyUnexpected);
                }
                SseSource::Kms { .. } => return Err(SseError::CustomerKeyUnexpected),
            };
            // v0.8.2 #64: route through the back-compat wrapper so
            // the public `decrypt` signature stays stable while the
            // pre-allocation guard runs against the gateway's
            // 5 GiB single-object cap. Bespoke callers (e.g. tests
            // or future API surfaces that want a tighter limit) can
            // call `decrypt_chunked_buffered` directly.
            decrypt_chunked_buffered_default(body, keyring)
        }
        _ => Err(SseError::BadMagic { got: magic }),
    }
}

fn decrypt_v3(
    body: &[u8],
    key: &[u8; KEY_LEN],
    supplied_md5: &[u8; KEY_MD5_LEN],
) -> Result<Bytes, SseError> {
    let algo = body[4];
    if algo != ALGO_AES_256_GCM {
        return Err(SseError::UnsupportedAlgo { tag: algo });
    }
    let mut stored_md5 = [0u8; KEY_MD5_LEN];
    stored_md5.copy_from_slice(&body[5..5 + KEY_MD5_LEN]);
    // Cheap fingerprint check first — if the supplied key has a
    // different MD5 than what was used at PUT, fail fast with a
    // dedicated error. AES-GCM auth would also catch this (different
    // key → bad tag) but the bespoke error gives operators an audit
    // signal distinct from "ciphertext was tampered with".
    if !constant_time_eq(supplied_md5, &stored_md5) {
        return Err(SseError::WrongCustomerKey);
    }
    let nonce_off = 5 + KEY_MD5_LEN;
    let tag_off = nonce_off + NONCE_LEN;
    let mut nonce_bytes = [0u8; NONCE_LEN];
    nonce_bytes.copy_from_slice(&body[nonce_off..nonce_off + NONCE_LEN]);
    let mut tag_bytes = [0u8; TAG_LEN];
    tag_bytes.copy_from_slice(&body[tag_off..tag_off + TAG_LEN]);
    let ct = &body[SSE_HEADER_BYTES_V3..];

    let aad = aad_v3(&stored_md5);
    let nonce = Nonce::from_slice(&nonce_bytes);
    let mut ct_with_tag = Vec::with_capacity(ct.len() + TAG_LEN);
    ct_with_tag.extend_from_slice(ct);
    ct_with_tag.extend_from_slice(&tag_bytes);

    let aes_key = Key::<Aes256Gcm>::from_slice(key);
    let cipher = Aes256Gcm::new(aes_key);
    let plain = cipher
        .decrypt(
            nonce,
            Payload {
                msg: &ct_with_tag,
                aad: &aad,
            },
        )
        .map_err(|_| SseError::DecryptFailed)?;
    Ok(Bytes::from(plain))
}

/// AAD for S4E4 = magic (4) + algo (1) + key_id_len (1) + key_id +
/// wrapped_dek_len (4 BE) + wrapped_dek. Putting the variable-length
/// key_id and wrapped_dek into the AAD means an attacker cannot
/// rewrite either field to redirect the gateway to a different KEK
/// or wrapped DEK without invalidating the body's AES-GCM tag.
///
/// Length-prefixing key_id and wrapped_dek inside the AAD prevents a
/// canonicalisation ambiguity: without the length prefix, an
/// attacker could shift bytes between the two fields and produce the
/// same AAD bytestream, defeating the per-field tampering check.
fn aad_v4(key_id: &[u8], wrapped_dek: &[u8]) -> Vec<u8> {
    let mut aad = Vec::with_capacity(4 + 1 + 1 + key_id.len() + 4 + wrapped_dek.len());
    aad.extend_from_slice(SSE_MAGIC_V4);
    aad.push(ALGO_AES_256_GCM);
    aad.push(key_id.len() as u8);
    aad.extend_from_slice(key_id);
    aad.extend_from_slice(&(wrapped_dek.len() as u32).to_be_bytes());
    aad.extend_from_slice(wrapped_dek);
    aad
}

fn encrypt_v4(plaintext: &[u8], dek: &[u8; KEY_LEN], wrapped: &WrappedDek) -> Bytes {
    // Pre-conditions: key_id must fit in a u8 length prefix and be
    // non-empty (an empty id means we wouldn't be able to re-fetch
    // the KEK on GET). wrapped_dek length fits in u32 by the same
    // logic — at u32::MAX bytes you have bigger problems. We assert
    // these in debug and silently truncate-or-panic in release; in
    // practice key_id is a UUID or ARN (<256 chars) and wrapped_dek
    // is 60 bytes (LocalKms) or ~200 bytes (AWS KMS).
    assert!(
        !wrapped.key_id.is_empty() && wrapped.key_id.len() <= u8::MAX as usize,
        "S4E4 key_id must be 1..=255 bytes (got {})",
        wrapped.key_id.len()
    );
    assert!(
        wrapped.ciphertext.len() <= u32::MAX as usize,
        "S4E4 wrapped_dek longer than u32::MAX",
    );

    let aes_key = Key::<Aes256Gcm>::from_slice(dek);
    let cipher = Aes256Gcm::new(aes_key);
    let mut nonce_bytes = [0u8; NONCE_LEN];
    rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::from_slice(&nonce_bytes);
    let aad = aad_v4(wrapped.key_id.as_bytes(), &wrapped.ciphertext);
    let ct_with_tag = cipher
        .encrypt(
            nonce,
            Payload {
                msg: plaintext,
                aad: &aad,
            },
        )
        .expect("aes-gcm encrypt cannot fail with a 32-byte key");
    debug_assert!(ct_with_tag.len() >= TAG_LEN);
    let split = ct_with_tag.len() - TAG_LEN;
    let (ct, tag) = ct_with_tag.split_at(split);

    let key_id_bytes = wrapped.key_id.as_bytes();
    let mut out = Vec::with_capacity(
        4 + 1 + 1 + key_id_bytes.len() + 4 + wrapped.ciphertext.len() + NONCE_LEN + TAG_LEN + ct.len(),
    );
    out.extend_from_slice(SSE_MAGIC_V4);
    out.push(ALGO_AES_256_GCM);
    out.push(key_id_bytes.len() as u8);
    out.extend_from_slice(key_id_bytes);
    out.extend_from_slice(&(wrapped.ciphertext.len() as u32).to_be_bytes());
    out.extend_from_slice(&wrapped.ciphertext);
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(tag);
    out.extend_from_slice(ct);
    Bytes::from(out)
}

/// Parsed view of an S4E4 frame's variable-length header. Returned
/// by [`parse_s4e4_header`] so both the async [`decrypt_with_kms`]
/// path and any future inspection code (e.g. an admin tool that
/// needs to enumerate object → KMS-key bindings) can reuse the same
/// parser without re-implementing offset math.
#[derive(Debug)]
pub struct S4E4Header<'a> {
    pub key_id: &'a str,
    pub wrapped_dek: &'a [u8],
    pub nonce: &'a [u8],
    pub tag: &'a [u8],
    pub ciphertext: &'a [u8],
}

/// Parse the (variable-length) S4E4 header. Pure byte-shuffling — no
/// crypto, no KMS round-trip. Returns errors on truncation /
/// out-of-bounds field lengths / non-UTF-8 key_id.
pub fn parse_s4e4_header(body: &[u8]) -> Result<S4E4Header<'_>, SseError> {
    // Minimum: magic(4) + algo(1) + key_id_len(1) + key_id(>=1) +
    // wrapped_dek_len(4) + wrapped_dek(>=1) + nonce(12) + tag(16)
    // = 40 bytes. We use a slightly looser floor here (bytes for
    // empty fields = 38) and let the per-field bounds checks below
    // catch the actual short reads.
    const S4E4_MIN: usize = 4 + 1 + 1 + 4 + NONCE_LEN + TAG_LEN; // 38
    if body.len() < S4E4_MIN {
        return Err(SseError::KmsFrameTooShort {
            got: body.len(),
            min: S4E4_MIN,
        });
    }
    let magic = &body[..4];
    if magic != SSE_MAGIC_V4 {
        let mut got = [0u8; 4];
        got.copy_from_slice(magic);
        return Err(SseError::BadMagic { got });
    }
    let algo = body[4];
    if algo != ALGO_AES_256_GCM {
        return Err(SseError::UnsupportedAlgo { tag: algo });
    }
    let key_id_len = body[5] as usize;
    let key_id_off: usize = 6;
    let key_id_end = key_id_off
        .checked_add(key_id_len)
        .ok_or(SseError::KmsFrameFieldOob { what: "key_id_len" })?;
    if key_id_end + 4 > body.len() {
        return Err(SseError::KmsFrameFieldOob { what: "key_id" });
    }
    let key_id = std::str::from_utf8(&body[key_id_off..key_id_end])
        .map_err(|_| SseError::KmsKeyIdNotUtf8)?;
    let wrapped_len_off = key_id_end;
    let wrapped_dek_len = u32::from_be_bytes([
        body[wrapped_len_off],
        body[wrapped_len_off + 1],
        body[wrapped_len_off + 2],
        body[wrapped_len_off + 3],
    ]) as usize;
    let wrapped_off = wrapped_len_off + 4;
    let wrapped_end = wrapped_off
        .checked_add(wrapped_dek_len)
        .ok_or(SseError::KmsFrameFieldOob { what: "wrapped_dek_len" })?;
    if wrapped_end + NONCE_LEN + TAG_LEN > body.len() {
        return Err(SseError::KmsFrameFieldOob { what: "wrapped_dek" });
    }
    let wrapped_dek = &body[wrapped_off..wrapped_end];
    let nonce_off = wrapped_end;
    let tag_off = nonce_off + NONCE_LEN;
    let ct_off = tag_off + TAG_LEN;
    let nonce = &body[nonce_off..nonce_off + NONCE_LEN];
    let tag = &body[tag_off..tag_off + TAG_LEN];
    let ciphertext = &body[ct_off..];
    Ok(S4E4Header {
        key_id,
        wrapped_dek,
        nonce,
        tag,
        ciphertext,
    })
}

/// Async decrypt for S4E4 (SSE-KMS) bodies. Caller supplies the KMS
/// backend; this function parses the frame, calls
/// `kms.decrypt_dek(...)` to unwrap the DEK, then runs AES-256-GCM
/// to recover the plaintext.
///
/// service.rs's GET handler should peek the magic with [`peek_magic`]
/// and dispatch:
///
/// - `Some("S4E4")` → `decrypt_with_kms(blob, &*kms).await`
/// - everything else → existing sync `decrypt(blob, source)`
///
/// Note: we don't go through `SseSource::Kms` here because the
/// wrapped DEK + key_id come from the frame itself, not from the
/// request — the `SseSource` is built for sync paths where the
/// caller already knows the key.
pub async fn decrypt_with_kms(
    body: &[u8],
    kms: &dyn KmsBackend,
) -> Result<Bytes, SseError> {
    let hdr = parse_s4e4_header(body)?;
    let wrapped = WrappedDek {
        key_id: hdr.key_id.to_string(),
        ciphertext: hdr.wrapped_dek.to_vec(),
    };
    let dek_vec = kms.decrypt_dek(&wrapped).await?;
    if dek_vec.len() != KEY_LEN {
        // KMS returned a non-32-byte plaintext. AES-256 needs exactly
        // 32 bytes. This shouldn't happen with `KeySpec=AES_256` but
        // surface as a backend error so it's auditable rather than
        // panicking.
        return Err(SseError::KmsBackend(KmsError::BackendUnavailable {
            message: format!(
                "KMS returned {} byte DEK; expected {KEY_LEN}",
                dek_vec.len()
            ),
        }));
    }
    let mut dek = [0u8; KEY_LEN];
    dek.copy_from_slice(&dek_vec);

    let aad = aad_v4(hdr.key_id.as_bytes(), hdr.wrapped_dek);
    let aes_key = Key::<Aes256Gcm>::from_slice(&dek);
    let cipher = Aes256Gcm::new(aes_key);
    let nonce = Nonce::from_slice(hdr.nonce);
    let mut ct_with_tag = Vec::with_capacity(hdr.ciphertext.len() + TAG_LEN);
    ct_with_tag.extend_from_slice(hdr.ciphertext);
    ct_with_tag.extend_from_slice(hdr.tag);
    let plain = cipher
        .decrypt(
            nonce,
            Payload {
                msg: &ct_with_tag,
                aad: &aad,
            },
        )
        .map_err(|_| SseError::DecryptFailed)?;
    Ok(Bytes::from(plain))
}

fn decrypt_v1_with_keyring(body: &[u8], keyring: &SseKeyring) -> Result<Bytes, SseError> {
    let algo = body[4];
    if algo != ALGO_AES_256_GCM {
        return Err(SseError::UnsupportedAlgo { tag: algo });
    }
    // body[5..8] reserved (must be ignored — v0.4 wrote zeros, but we
    // didn't auth them so we can't insist on it).
    let mut nonce_bytes = [0u8; NONCE_LEN];
    nonce_bytes.copy_from_slice(&body[8..8 + NONCE_LEN]);
    let mut tag_bytes = [0u8; TAG_LEN];
    tag_bytes.copy_from_slice(&body[8 + NONCE_LEN..SSE_HEADER_BYTES]);
    let ct = &body[SSE_HEADER_BYTES..];

    let aad = aad_v1();
    let nonce = Nonce::from_slice(&nonce_bytes);
    let mut ct_with_tag = Vec::with_capacity(ct.len() + TAG_LEN);
    ct_with_tag.extend_from_slice(ct);
    ct_with_tag.extend_from_slice(&tag_bytes);

    // Active key first, then any others. v0.4 deployments that flip to
    // v0.5 with their original key as active hit this path on the
    // first try for every legacy object.
    let (active_id, _active_key) = keyring.active();
    let mut ids: Vec<u16> = keyring.keys.keys().copied().collect();
    ids.sort_by_key(|id| if *id == active_id { 0 } else { 1 });
    for id in ids {
        let key = keyring.get(id).expect("id came from keyring iteration");
        let cipher = Aes256Gcm::new(key.as_aes_key());
        if let Ok(plain) = cipher.decrypt(
            nonce,
            Payload {
                msg: &ct_with_tag,
                aad: &aad,
            },
        ) {
            return Ok(Bytes::from(plain));
        }
    }
    Err(SseError::DecryptFailed)
}

fn decrypt_v2_with_keyring(body: &[u8], keyring: &SseKeyring) -> Result<Bytes, SseError> {
    let algo = body[4];
    if algo != ALGO_AES_256_GCM {
        return Err(SseError::UnsupportedAlgo { tag: algo });
    }
    let key_id = u16::from_be_bytes([body[5], body[6]]);
    // body[7] reserved (1B), authenticated as 0 via AAD.
    let key = keyring
        .get(key_id)
        .ok_or(SseError::KeyNotInKeyring { id: key_id })?;
    let mut nonce_bytes = [0u8; NONCE_LEN];
    nonce_bytes.copy_from_slice(&body[8..8 + NONCE_LEN]);
    let mut tag_bytes = [0u8; TAG_LEN];
    tag_bytes.copy_from_slice(&body[8 + NONCE_LEN..SSE_HEADER_BYTES]);
    let ct = &body[SSE_HEADER_BYTES..];

    let aad = aad_v2(key_id);
    let nonce = Nonce::from_slice(&nonce_bytes);
    let mut ct_with_tag = Vec::with_capacity(ct.len() + TAG_LEN);
    ct_with_tag.extend_from_slice(ct);
    ct_with_tag.extend_from_slice(&tag_bytes);
    let cipher = Aes256Gcm::new(key.as_aes_key());
    let plain = cipher
        .decrypt(
            nonce,
            Payload {
                msg: &ct_with_tag,
                aad: &aad,
            },
        )
        .map_err(|_| SseError::DecryptFailed)?;
    Ok(Bytes::from(plain))
}

/// Detect whether `body` is SSE-S4 encrypted (S4E1, S4E2, S4E3, or
/// S4E4) by sniffing the first 4 magic bytes. Used by the GET path
/// to decide whether to run decryption before frame parsing.
///
/// We require a length check that's safe for *any* of the four
/// frames — `SSE_HEADER_BYTES` (36) is the smallest valid header
/// (S4E1 / S4E2). S4E3 is 49 bytes; S4E4 is variable but always >=
/// 38 bytes. The per-frame decrypt path re-checks the appropriate
/// minimum, so this 36-byte gate is just a fast rejection of
/// obviously-too-short bodies.
pub fn looks_encrypted(body: &[u8]) -> bool {
    if body.len() < SSE_HEADER_BYTES {
        return false;
    }
    let m = &body[..4];
    m == SSE_MAGIC_V1
        || m == SSE_MAGIC_V2
        || m == SSE_MAGIC_V3
        || m == SSE_MAGIC_V4
        || m == SSE_MAGIC_V5
        || m == SSE_MAGIC_V6
}

/// Peek the SSE-S4 magic at the front of `body`, returning a
/// stringified frame variant identifier or `None` if `body` is not
/// recognized as SSE-S4. Used by the GET path to dispatch between
/// the sync [`decrypt`] (S4E1/E2/E3) and the async
/// [`decrypt_with_kms`] (S4E4).
///
/// Returns the same length-gated result as [`looks_encrypted`]: any
/// body shorter than `SSE_HEADER_BYTES` (36 bytes) returns `None`,
/// so the caller can use this as both the "is encrypted" signal and
/// the "which frame" signal in one cheap byte-comparison.
pub fn peek_magic(body: &[u8]) -> Option<&'static str> {
    if body.len() < SSE_HEADER_BYTES {
        return None;
    }
    match &body[..4] {
        m if m == SSE_MAGIC_V1 => Some("S4E1"),
        m if m == SSE_MAGIC_V2 => Some("S4E2"),
        m if m == SSE_MAGIC_V3 => Some("S4E3"),
        m if m == SSE_MAGIC_V4 => Some("S4E4"),
        // v0.8 #52: chunked SSE-S4. service.rs's GET handler
        // dispatches "S4E5" / "S4E6" → `decrypt_chunked_stream`
        // for true streaming GET; the sync `decrypt(...)` also
        // accepts both (back-compat — buffered concat).
        m if m == SSE_MAGIC_V5 => Some("S4E5"),
        // v0.8.1 #57: same dispatch as S4E5 — wider salt only.
        m if m == SSE_MAGIC_V6 => Some("S4E6"),
        _ => None,
    }
}

pub type SharedSseKey = Arc<SseKey>;

// ===========================================================================
// v0.8 #52 (S4E5, read-only) + v0.8.1 #57 (S4E6, current emit) —
// chunked variant of S4E2 for streaming GET
// ===========================================================================
//
// ## S4E5 wire format (v0.8 #52, **read-only as of v0.8.1 #57**)
//
// ```text
// magic         4B    "S4E5"
// algo          1B    0x01 (AES-256-GCM)
// key_id        2B    BE — keyring slot the active key was at PUT time
// reserved      1B    0x00
// chunk_size    4B    BE — plaintext bytes per chunk (final chunk may be smaller)
// chunk_count   4B    BE — total chunks (always >= 1; empty plaintext = 1 zero-byte chunk)
// salt          4B    random per-PUT, mixed into every nonce
// [chunk_count] × {
//   tag         16B   AES-GCM auth tag for this chunk
//   ciphertext  N B   chunk_size bytes (final chunk: 0..=chunk_size bytes)
// }
// ```
//
// Fixed header = 20 bytes ([`S4E5_HEADER_BYTES`]).
//
// ## S4E6 wire format (v0.8.1 #57, current PUT emit)
//
// ```text
// magic         4B    "S4E6"
// algo          1B    0x01 (AES-256-GCM)
// key_id        2B    BE
// reserved      1B    0x00
// chunk_size    4B    BE
// chunk_count   4B    BE
// salt          8B    random per-PUT  ← 4B → 8B widened
// [chunk_count] × { tag 16B, ciphertext N B }
// ```
//
// Fixed header = 24 bytes ([`S4E6_HEADER_BYTES`]). Chunk array
// layout is byte-identical to S4E5; only the header (salt 4 → 8)
// and the nonce/AAD derivation differ.
//
// ## Per-chunk overhead (both S4E5 and S4E6)
//
// 16 bytes — just the AES-GCM auth tag. AES-GCM is CTR-mode, so
// `ciphertext.len() == plaintext.len()`. Total overhead for an
// N-byte plaintext at chunk size C: `header + ceil(N/C) * 16`.
//
// ## S4E5 nonce / AAD (read-only)
//
// ```text
// nonce_v5[0..4]  = b"E5\x00\x00"
// nonce_v5[4..8]  = salt (4 B)
// nonce_v5[8..12] = chunk_index BE (u32)
//
// aad_v5 = b"S4E5" || algo (1) || chunk_index BE (4) || total BE (4)
//        || key_id BE (2) || salt (4)
// ```
//
// Birthday-collision threshold on the 4-byte salt: ~50% at ~65,536
// distinct PUTs under the same key — the security regression that
// motivated #57.
//
// ## S4E6 nonce / AAD (current emit)
//
// ```text
// nonce_v6[0]     = b'E'                   (1 B fixed prefix)
// nonce_v6[1..9]  = salt (8 B)             (per-PUT random from OsRng)
// nonce_v6[9..12] = chunk_index BE (u24)   (3 B → max 16_777_215 chunks)
//
// aad_v6 = b"S4E6" || algo (1) || chunk_index BE (4) || total BE (4)
//        || key_id BE (2) || salt (8)
// ```
//
// Wider salt: birthday collision ~50% at ~2^32 = ~4.3 billion
// PUTs/key — four orders of magnitude over S4E5.
//
// chunk_index narrows from 32-bit to 24-bit, capping `chunk_count`
// at `2^24 - 1 = 16_777_215`. At the default `--sse-chunk-size
// 1048576` (1 MiB) that's ~16 PiB per object — three orders of
// magnitude over S3's 5 GiB single-object cap. Smaller chunk sizes
// need to be sized carefully: e.g. `--sse-chunk-size 64` on a
// > 1 GiB object would exceed the cap (1 GiB / 64 B = 16M+1
// chunks); such configurations surface
// [`SseError::ChunkCountTooLarge`] at PUT time rather than
// silently truncating.
//
// AAD on both variants includes the chunk index + total so chunk
// reordering or dropping fails the per-chunk tag, plus key_id +
// salt so header tampering also fails auth.

/// Fixed header size of an S4E5 frame, before any chunks. `magic 4 +
/// algo 1 + key_id 2 + reserved 1 + chunk_size 4 + chunk_count 4 +
/// salt 4` = 20 bytes.
pub const S4E5_HEADER_BYTES: usize = 4 + 1 + 2 + 1 + 4 + 4 + 4; // = 20

/// Per-chunk overhead inside an S4E5 / S4E6 frame: just the AES-GCM
/// auth tag. `ciphertext.len() == plaintext.len()` (CTR mode), so a
/// chunk of N plaintext bytes costs N + 16 on disk.
pub const S4E5_PER_CHUNK_OVERHEAD: usize = TAG_LEN; // = 16

/// v0.8.1 #57: fixed header size of an S4E6 frame. Same layout as
/// S4E5 except the per-PUT salt widens 4 → 8 bytes: `magic 4 + algo
/// 1 + key_id 2 + reserved 1 + chunk_size 4 + chunk_count 4 + salt
/// 8` = 24 bytes.
pub const S4E6_HEADER_BYTES: usize = 4 + 1 + 2 + 1 + 4 + 4 + 8; // = 24

/// v0.8.1 #57: per-chunk overhead for S4E6. Identical to S4E5
/// (same AES-GCM tag size). Re-exported as a distinct const so call
/// sites that compute on-disk size for S4E6 specifically can spell
/// the magic clearly in their arithmetic.
pub const S4E6_PER_CHUNK_OVERHEAD: usize = TAG_LEN; // = 16

/// v0.8.1 #57: maximum `chunk_count` that fits in the S4E6 nonce's
/// 24-bit chunk_index field. At 1 MiB chunks this is ~16 PiB per
/// object — three orders of magnitude over S3's 5 GiB single-object
/// cap, so it's not a practical limit at the default chunk size.
pub const S4E6_MAX_CHUNK_COUNT: u32 = (1u32 << 24) - 1; // 16_777_215

/// 4-byte fixed prefix of every S4E5 nonce. Distinct from the bytes
/// a random S4E1/E2 nonce could plausibly start with so debugging
/// dumps can immediately tell "this is a chunked nonce" from the
/// first 4 bytes.
const S4E5_NONCE_TAG: [u8; 4] = [b'E', b'5', 0, 0];

/// 1-byte fixed prefix of every S4E6 nonce. Trades 3 of S4E5's 4
/// "tag" bytes for 4 extra salt bytes (4 → 8) and 0 of the chunk
/// index bytes (24-bit instead of 32-bit). The remaining `b'E'`
/// keeps debug dumps recognizable as "chunked SSE-S4 nonce".
const S4E6_NONCE_PREFIX: u8 = b'E';

/// Variant tag for the chunked-frame helpers. Selects the nonce +
/// AAD derivation (and incidentally the salt width). The
/// chunk-array layout is byte-identical for both — only the header
/// size and the nonce/AAD derivation differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChunkedVariant {
    V5,
    V6,
}

impl ChunkedVariant {
    fn header_bytes(self) -> usize {
        match self {
            ChunkedVariant::V5 => S4E5_HEADER_BYTES,
            ChunkedVariant::V6 => S4E6_HEADER_BYTES,
        }
    }
}

/// Build the per-chunk AAD for an S4E5 chunk. Includes magic + algo
/// plus the structural chunk_index/total_chunks (so chunk reordering
/// fails auth) plus key_id + salt (so header tampering — flipping
/// key_id or salt — also fails auth).
fn aad_v5(
    chunk_index: u32,
    total_chunks: u32,
    key_id: u16,
    salt: &[u8; 4],
) -> [u8; 4 + 1 + 4 + 4 + 2 + 4] {
    let mut aad = [0u8; 4 + 1 + 4 + 4 + 2 + 4]; // = 19
    aad[..4].copy_from_slice(SSE_MAGIC_V5);
    aad[4] = ALGO_AES_256_GCM;
    aad[5..9].copy_from_slice(&chunk_index.to_be_bytes());
    aad[9..13].copy_from_slice(&total_chunks.to_be_bytes());
    aad[13..15].copy_from_slice(&key_id.to_be_bytes());
    aad[15..19].copy_from_slice(salt);
    aad
}

/// v0.8.1 #57: per-chunk AAD for S4E6. Same structural fields as
/// [`aad_v5`] (magic + algo + chunk_index + total + key_id + salt)
/// but with the wider 8-byte salt and the new `b"S4E6"` magic, so
/// an attacker can't strip the version tag and replay an S4E5
/// nonce/tag against an S4E6 frame.
fn aad_v6(
    chunk_index: u32,
    total_chunks: u32,
    key_id: u16,
    salt: &[u8; 8],
) -> [u8; 4 + 1 + 4 + 4 + 2 + 8] {
    let mut aad = [0u8; 4 + 1 + 4 + 4 + 2 + 8]; // = 23
    aad[..4].copy_from_slice(SSE_MAGIC_V6);
    aad[4] = ALGO_AES_256_GCM;
    aad[5..9].copy_from_slice(&chunk_index.to_be_bytes());
    aad[9..13].copy_from_slice(&total_chunks.to_be_bytes());
    aad[13..15].copy_from_slice(&key_id.to_be_bytes());
    aad[15..23].copy_from_slice(salt);
    aad
}

/// Derive the 12-byte AES-GCM nonce for chunk `chunk_index` from the
/// per-PUT `salt`. Pure function; no RNG state — the same `(salt,
/// chunk_index)` always yields the same nonce, which is the whole
/// point: GET reads `salt` from the header and walks the chunks
/// without storing 12 bytes of nonce per chunk.
fn nonce_v5(salt: &[u8; 4], chunk_index: u32) -> [u8; NONCE_LEN] {
    let mut n = [0u8; NONCE_LEN];
    n[..4].copy_from_slice(&S4E5_NONCE_TAG);
    n[4..8].copy_from_slice(salt);
    n[8..12].copy_from_slice(&chunk_index.to_be_bytes());
    n
}

/// v0.8.1 #57: derive the 12-byte AES-GCM nonce for an S4E6 chunk:
/// `b'E'(1) || salt(8) || chunk_index_BE_u24(3)`. The 24-bit
/// chunk_index caps `chunk_count` at 16,777,215 — see
/// [`S4E6_MAX_CHUNK_COUNT`]. The pre-encrypt path enforces this cap
/// and surfaces [`SseError::ChunkCountTooLarge`], so this function
/// only ever sees `chunk_index <= 0xFF_FFFF` (the leading byte of
/// the BE u32 is dropped).
fn nonce_v6(salt: &[u8; 8], chunk_index: u32) -> [u8; NONCE_LEN] {
    debug_assert!(
        chunk_index <= S4E6_MAX_CHUNK_COUNT,
        "S4E6 chunk_index {chunk_index} exceeds 24-bit cap (caller MUST validate)",
    );
    let mut n = [0u8; NONCE_LEN];
    n[0] = S4E6_NONCE_PREFIX;
    n[1..9].copy_from_slice(salt);
    let be = chunk_index.to_be_bytes(); // [b3, b2, b1, b0] of u32
    // Take the low 3 bytes (b2, b1, b0) — the high byte is 0 by the
    // S4E6_MAX_CHUNK_COUNT cap above.
    n[9..12].copy_from_slice(&be[1..4]);
    n
}

/// v0.8 #52 / v0.8.1 #57: encrypt `plaintext` under `keyring`'s
/// active key, sliced into independently-sealed AES-GCM chunks of
/// `chunk_size` plaintext bytes each. Returns the on-the-wire
/// **S4E6** frame (v0.8.1 #57 widened the per-PUT salt 4 B → 8 B;
/// the S4E5 emit path was retired but the [`decrypt`] /
/// [`decrypt_chunked_stream`] paths still read S4E5 objects for
/// back-compat).
///
/// Errors:
/// - [`SseError::ChunkSizeInvalid`] if `chunk_size == 0`.
/// - [`SseError::ChunkCountTooLarge`] if
///   `ceil(plaintext.len() / chunk_size) > 16_777_215` (the S4E6
///   24-bit chunk_index cap; pick a larger `--sse-chunk-size`).
///
/// Empty plaintext is permitted and produces a frame with
/// `chunk_count = 1, ciphertext_len = 0` (one all-tag chunk). That
/// keeps the GET chunk-walk loop simpler — it never has to
/// special-case zero chunks.
///
/// `chunk_size` is the *plaintext* bytes per chunk; the on-disk
/// ciphertext per chunk is the same number (AES-GCM is CTR-mode),
/// plus the 16-byte tag prepended.
pub fn encrypt_v2_chunked(
    plaintext: &[u8],
    keyring: &SseKeyring,
    chunk_size: usize,
) -> Result<Bytes, SseError> {
    if chunk_size == 0 {
        return Err(SseError::ChunkSizeInvalid);
    }
    let (key_id, key) = keyring.active();
    let cipher = Aes256Gcm::new(key.as_aes_key());
    let mut salt = [0u8; 8];
    rand::rngs::OsRng.fill_bytes(&mut salt);

    // Always emit at least one chunk (so an empty plaintext still
    // has a well-defined header → chunk_count >= 1 invariant).
    let chunk_count_usize = if plaintext.is_empty() {
        1
    } else {
        plaintext.len().div_ceil(chunk_size)
    };
    // Saturating-cast to u32 so we report ChunkCountTooLarge cleanly
    // for inputs that would overflow u32 too (would need a > 16 EiB
    // plaintext at chunk_size = 1 — astronomical, but defensive).
    let chunk_count: u32 = u32::try_from(chunk_count_usize).unwrap_or(u32::MAX);
    if chunk_count > S4E6_MAX_CHUNK_COUNT {
        return Err(SseError::ChunkCountTooLarge {
            got: chunk_count,
            max: S4E6_MAX_CHUNK_COUNT,
        });
    }

    let mut out = Vec::with_capacity(
        S4E6_HEADER_BYTES + plaintext.len() + (chunk_count as usize * S4E6_PER_CHUNK_OVERHEAD),
    );
    out.extend_from_slice(SSE_MAGIC_V6);
    out.push(ALGO_AES_256_GCM);
    out.extend_from_slice(&key_id.to_be_bytes());
    out.push(0u8); // reserved
    out.extend_from_slice(&(chunk_size as u32).to_be_bytes());
    out.extend_from_slice(&chunk_count.to_be_bytes());
    out.extend_from_slice(&salt);

    for i in 0..chunk_count {
        let off = (i as usize).saturating_mul(chunk_size);
        let end = off.saturating_add(chunk_size).min(plaintext.len());
        let chunk_pt: &[u8] = if off >= plaintext.len() {
            // Empty-plaintext / past-end (only the single-chunk
            // empty-plaintext case lands here).
            &[]
        } else {
            &plaintext[off..end]
        };
        let nonce_bytes = nonce_v6(&salt, i);
        let nonce = Nonce::from_slice(&nonce_bytes);
        let aad = aad_v6(i, chunk_count, key_id, &salt);
        let ct_with_tag = cipher
            .encrypt(
                nonce,
                Payload {
                    msg: chunk_pt,
                    aad: &aad,
                },
            )
            .expect("aes-gcm encrypt cannot fail with a 32-byte key");
        debug_assert!(ct_with_tag.len() >= TAG_LEN);
        let split = ct_with_tag.len() - TAG_LEN;
        let (ct, tag) = ct_with_tag.split_at(split);
        out.extend_from_slice(tag);
        out.extend_from_slice(ct);
        crate::metrics::record_sse_streaming_chunk("encrypt");
    }
    Ok(Bytes::from(out))
}

/// Salt material for a chunked frame — branches on variant so the
/// shared chunk-walking loop can carry both 4-byte (S4E5) and
/// 8-byte (S4E6) salts without an extra heap alloc.
#[derive(Debug, Clone, Copy)]
enum ChunkedSalt {
    V5([u8; 4]),
    V6([u8; 8]),
}

/// Parsed S4E5 / S4E6 header — fixed-layout fields. Used by the
/// buffered ([`decrypt_chunked_buffered`]) and streaming
/// ([`decrypt_chunked_stream`]) paths to share frame validation
/// across both variants.
#[derive(Debug, Clone, Copy)]
struct ChunkedHeader {
    /// Used only by tests today (asserts on which frame variant
    /// parsed); in production the variant is implicit in
    /// `salt`'s ChunkedSalt arm. Kept as a field rather than
    /// re-deriving from `salt` so the parser writes one source of
    /// truth.
    #[allow(dead_code)]
    variant: ChunkedVariant,
    key_id: u16,
    chunk_size: u32,
    chunk_count: u32,
    salt: ChunkedSalt,
    /// Byte offset where the chunk array starts (always
    /// `variant.header_bytes()`; carried in the struct so call sites
    /// don't have to re-derive it from the variant tag).
    chunks_offset: usize,
}

/// Parsed view of an S4E6 frame's fixed header. Public mirror of
/// the S4E4 parser — useful for admin tools or future inspectors
/// that want to enumerate object → key_id bindings without
/// re-implementing the offset math. The `salt` borrow keeps
/// allocations to zero (the slice points back into the input
/// buffer).
#[derive(Debug, Clone, Copy)]
pub struct S4E6Header<'a> {
    pub key_id: u16,
    pub chunk_size: u32,
    pub chunk_count: u32,
    pub salt: &'a [u8; 8],
}

/// Pure byte-shuffle parser for an S4E6 fixed header (24 bytes). No
/// crypto, no keyring lookup. Errors on truncation, wrong magic,
/// unsupported algo, or zero `chunk_size` / `chunk_count`.
pub fn parse_s4e6_header(blob: &[u8]) -> Result<S4E6Header<'_>, SseError> {
    if blob.len() < S4E6_HEADER_BYTES {
        return Err(SseError::ChunkFrameTruncated { what: "header" });
    }
    if &blob[..4] != SSE_MAGIC_V6 {
        let mut got = [0u8; 4];
        got.copy_from_slice(&blob[..4]);
        return Err(SseError::BadMagic { got });
    }
    let algo = blob[4];
    if algo != ALGO_AES_256_GCM {
        return Err(SseError::UnsupportedAlgo { tag: algo });
    }
    let key_id = u16::from_be_bytes([blob[5], blob[6]]);
    // blob[7] = reserved (0; authenticated as 0 via AAD).
    let chunk_size = u32::from_be_bytes([blob[8], blob[9], blob[10], blob[11]]);
    let chunk_count = u32::from_be_bytes([blob[12], blob[13], blob[14], blob[15]]);
    if chunk_size == 0 {
        return Err(SseError::ChunkSizeInvalid);
    }
    if chunk_count == 0 {
        return Err(SseError::ChunkFrameTruncated {
            what: "chunk_count == 0",
        });
    }
    if chunk_count > S4E6_MAX_CHUNK_COUNT {
        return Err(SseError::ChunkCountTooLarge {
            got: chunk_count,
            max: S4E6_MAX_CHUNK_COUNT,
        });
    }
    let salt: &[u8; 8] = (&blob[16..24]).try_into().expect("8B salt slice");
    Ok(S4E6Header {
        key_id,
        chunk_size,
        chunk_count,
        salt,
    })
}

fn parse_chunked_header(
    body: &[u8],
    max_body_bytes: usize,
) -> Result<ChunkedHeader, SseError> {
    if body.len() < 4 {
        return Err(SseError::ChunkFrameTruncated { what: "magic" });
    }
    let magic = &body[..4];
    let variant = if magic == SSE_MAGIC_V5 {
        ChunkedVariant::V5
    } else if magic == SSE_MAGIC_V6 {
        ChunkedVariant::V6
    } else {
        let mut got = [0u8; 4];
        got.copy_from_slice(magic);
        return Err(SseError::BadMagic { got });
    };
    let header_bytes = variant.header_bytes();
    if body.len() < header_bytes {
        return Err(SseError::ChunkFrameTruncated { what: "header" });
    }
    let algo = body[4];
    if algo != ALGO_AES_256_GCM {
        return Err(SseError::UnsupportedAlgo { tag: algo });
    }
    let key_id = u16::from_be_bytes([body[5], body[6]]);
    // body[7] = reserved (must be 0; authenticated as 0 via AAD).
    let chunk_size = u32::from_be_bytes([body[8], body[9], body[10], body[11]]);
    let chunk_count = u32::from_be_bytes([body[12], body[13], body[14], body[15]]);
    if chunk_size == 0 {
        return Err(SseError::ChunkSizeInvalid);
    }
    if chunk_count == 0 {
        return Err(SseError::ChunkFrameTruncated {
            what: "chunk_count == 0",
        });
    }
    let salt = match variant {
        ChunkedVariant::V5 => {
            let mut s = [0u8; 4];
            s.copy_from_slice(&body[16..20]);
            ChunkedSalt::V5(s)
        }
        ChunkedVariant::V6 => {
            // v0.8.1 #57 sanity check: the encoder enforces this cap,
            // but a tampered / malicious frame could declare a huge
            // chunk_count that would loop the walker 16M+ times if
            // we trusted it. Reject early.
            if chunk_count > S4E6_MAX_CHUNK_COUNT {
                return Err(SseError::ChunkCountTooLarge {
                    got: chunk_count,
                    max: S4E6_MAX_CHUNK_COUNT,
                });
            }
            let mut s = [0u8; 8];
            s.copy_from_slice(&body[16..24]);
            ChunkedSalt::V6(s)
        }
    };

    // v0.8.2 #64 — DoS guard. Pre-validate the declared
    // (chunk_size × chunk_count) plaintext size in u64 before *any*
    // downstream allocation or chunk-walk loop. Rejects:
    //   1. arithmetic that would overflow u64 (e.g. chunk_size =
    //      u32::MAX, chunk_count = u32::MAX → 2^64 ≫ u64::MAX),
    //   2. a body that is *larger* than the maximum a header with
    //      these declared sizes could plausibly carry (i.e. trailing
    //      bytes after the final chunk → corruption / append attack),
    //      and
    //   3. a plaintext size larger than the caller's configured
    //      `max_body_bytes` (default 5 GiB).
    //
    // We do NOT require the body to be `>= max_total` here — the
    // final chunk may legitimately hold fewer than `chunk_size`
    // plaintext bytes (encoder uses
    // `chunk_count = ceil(plaintext.len() / chunk_size)`, so the last
    // chunk holds the remainder). The walker handles that
    // variable-length tail; truncation of the final chunk's tag /
    // ciphertext surfaces as `ChunkFrameTruncated` once the walker
    // gets there. The pre-alloc guard's job is the *upper-bound*
    // checks: kill obviously-impossible shapes before we
    // `Vec::with_capacity(chunk_size × chunk_count)`.
    //
    // All paths return concrete error variants; nothing panics on
    // adversarial input. The error strings carry only constant
    // operator-readable labels (no echoed numbers) so the response is
    // not a tampering oracle for the attacker.
    let chunk_size_u64 = chunk_size as u64;
    let chunk_count_u64 = chunk_count as u64;
    let expected_plain_size = chunk_size_u64
        .checked_mul(chunk_count_u64)
        .ok_or(SseError::ChunkFrameTooLarge {
            details: "chunk_size * chunk_count overflows u64",
        })?;
    let per_chunk_overhead = S4E5_PER_CHUNK_OVERHEAD as u64; // = 16 (AES-GCM tag)
    let total_tag_overhead = per_chunk_overhead.checked_mul(chunk_count_u64).ok_or(
        SseError::ChunkFrameTooLarge {
            details: "tag_len * chunk_count overflows u64",
        },
    )?;
    let max_total = expected_plain_size
        .checked_add(total_tag_overhead)
        .and_then(|t| t.checked_add(header_bytes as u64))
        .ok_or(SseError::ChunkFrameTooLarge {
            details: "header + plaintext + tag overhead overflows u64",
        })?;
    // Body cannot be *larger* than what the declared geometry could
    // legitimately produce. Any extra bytes past the final chunk are
    // either trailing junk (corruption) or an append attack — kill
    // them here so the walker doesn't even start verifying chunks
    // for an obviously-malformed body. (The walker's own end-of-loop
    // `cursor != body.len()` check also catches this; the pre-alloc
    // guard saves the chunk-walk worth of AES-GCM verifies in the
    // hostile case.)
    if (body.len() as u64) > max_total {
        return Err(SseError::ChunkFrameTruncated {
            what: "trailing bytes past declared chunk geometry",
        });
    }
    // The actual DoS guard: cap on declared plaintext. If the header
    // claims more than the operator's configured single-object
    // ceiling, refuse before the buffered path's
    // `Vec::with_capacity(chunk_size * chunk_count)` runs.
    if expected_plain_size > max_body_bytes as u64 {
        return Err(SseError::ChunkFrameTooLarge {
            details: "declared plaintext exceeds gateway max_body_bytes",
        });
    }

    Ok(ChunkedHeader {
        variant,
        key_id,
        chunk_size,
        chunk_count,
        salt,
        chunks_offset: header_bytes,
    })
}

/// Decrypt one chunk under either the S4E5 or S4E6 derivation. Used
/// by both the buffered and streaming paths so AAD / nonce
/// derivation lives in exactly one place.
fn decrypt_chunked_chunk(
    cipher: &Aes256Gcm,
    chunk_index: u32,
    chunk_count: u32,
    key_id: u16,
    salt: &ChunkedSalt,
    tag: &[u8; TAG_LEN],
    ct: &[u8],
) -> Result<Bytes, SseError> {
    let nonce_bytes = match salt {
        ChunkedSalt::V5(s) => nonce_v5(s, chunk_index),
        ChunkedSalt::V6(s) => nonce_v6(s, chunk_index),
    };
    let nonce = Nonce::from_slice(&nonce_bytes);
    let mut ct_with_tag = Vec::with_capacity(ct.len() + TAG_LEN);
    ct_with_tag.extend_from_slice(ct);
    ct_with_tag.extend_from_slice(tag);
    let result = match salt {
        ChunkedSalt::V5(s) => {
            let aad = aad_v5(chunk_index, chunk_count, key_id, s);
            cipher.decrypt(
                nonce,
                Payload {
                    msg: &ct_with_tag,
                    aad: &aad,
                },
            )
        }
        ChunkedSalt::V6(s) => {
            let aad = aad_v6(chunk_index, chunk_count, key_id, s);
            cipher.decrypt(
                nonce,
                Payload {
                    msg: &ct_with_tag,
                    aad: &aad,
                },
            )
        }
    };
    result
        .map(Bytes::from)
        .map_err(|_| SseError::ChunkAuthFailed { chunk_index })
}

/// Walk an S4E5 / S4E6 body chunk-by-chunk, calling `emit` on each
/// successfully-verified plaintext chunk. Returns immediately on the
/// first chunk that fails auth or is truncated. Shared core between
/// the buffered ([`decrypt_chunked_buffered`]) and streaming
/// ([`decrypt_chunked_stream`]) paths.
fn walk_chunked<F: FnMut(Bytes) -> Result<(), SseError>>(
    body: &[u8],
    keyring: &SseKeyring,
    max_body_bytes: usize,
    mut emit: F,
) -> Result<(), SseError> {
    let hdr = parse_chunked_header(body, max_body_bytes)?;
    let key = keyring
        .get(hdr.key_id)
        .ok_or(SseError::KeyNotInKeyring { id: hdr.key_id })?;
    let cipher = Aes256Gcm::new(key.as_aes_key());

    let mut cursor = hdr.chunks_offset;
    let chunk_size = hdr.chunk_size as usize;
    for i in 0..hdr.chunk_count {
        if cursor + TAG_LEN > body.len() {
            return Err(SseError::ChunkFrameTruncated { what: "chunk tag" });
        }
        let tag_off = cursor;
        let ct_off = tag_off + TAG_LEN;
        let is_last = i + 1 == hdr.chunk_count;
        let ct_len = if is_last {
            if ct_off > body.len() {
                return Err(SseError::ChunkFrameTruncated {
                    what: "final chunk ciphertext",
                });
            }
            let remaining = body.len() - ct_off;
            if remaining > chunk_size {
                return Err(SseError::ChunkFrameTruncated {
                    what: "trailing bytes after final chunk",
                });
            }
            remaining
        } else {
            chunk_size
        };
        let ct_end = ct_off + ct_len;
        if ct_end > body.len() {
            return Err(SseError::ChunkFrameTruncated {
                what: "chunk ciphertext",
            });
        }
        let mut tag = [0u8; TAG_LEN];
        tag.copy_from_slice(&body[tag_off..ct_off]);
        let ct = &body[ct_off..ct_end];
        let plain = decrypt_chunked_chunk(
            &cipher,
            i,
            hdr.chunk_count,
            hdr.key_id,
            &hdr.salt,
            &tag,
            ct,
        )?;
        crate::metrics::record_sse_streaming_chunk("decrypt");
        emit(plain)?;
        cursor = ct_end;
    }
    if cursor != body.len() {
        return Err(SseError::ChunkFrameTruncated {
            what: "trailing bytes after declared chunk_count",
        });
    }
    Ok(())
}

/// Sync back-compat path: decrypt every chunk and concatenate into
/// a single `Bytes`. Memory peak = full plaintext (defeats the
/// point of S4E5/S4E6 streaming, but useful for callers that already
/// need the whole body — e.g. server-side restream-rewrite paths or
/// unit tests). Accepts both S4E5 (legacy) and S4E6 (current) bodies.
///
/// `max_body_bytes` (v0.8.2 #64) caps the declared plaintext size in
/// the header **before any allocation**. A malicious / corrupted
/// frame that claims a multi-PB plaintext is rejected as
/// [`SseError::ChunkFrameTooLarge`] with no `Vec::with_capacity` call
/// behind it. Callers without a bespoke cap should use
/// [`decrypt_chunked_buffered_default`] (5 GiB cap).
pub fn decrypt_chunked_buffered(
    body: &[u8],
    keyring: &SseKeyring,
    max_body_bytes: usize,
) -> Result<Bytes, SseError> {
    let hdr = parse_chunked_header(body, max_body_bytes)?;
    // Header is validated above: chunk_size * chunk_count fits u64
    // and is ≤ max_body_bytes (≤ 5 GiB on this gateway), so the
    // `as usize` casts cannot truncate on a 64-bit host. The
    // `Vec::with_capacity` is therefore bounded by the same cap that
    // protects the rest of the gateway from oversized PUTs / GETs.
    let mut out = Vec::with_capacity(hdr.chunk_size as usize * hdr.chunk_count as usize);
    walk_chunked(body, keyring, max_body_bytes, |chunk| {
        out.extend_from_slice(&chunk);
        Ok(())
    })?;
    Ok(Bytes::from(out))
}

/// Back-compat wrapper around [`decrypt_chunked_buffered`] that uses
/// [`DEFAULT_MAX_BODY_BYTES`] (5 GiB — AWS S3's single-object PUT
/// ceiling). Provided so the existing `decrypt(body, keyring)`
/// dispatcher and call sites that don't have a bespoke cap can keep
/// their signature unchanged after the v0.8.2 #64 pre-allocation
/// guard landed.
pub fn decrypt_chunked_buffered_default(
    body: &[u8],
    keyring: &SseKeyring,
) -> Result<Bytes, SseError> {
    decrypt_chunked_buffered(body, keyring, DEFAULT_MAX_BODY_BYTES)
}

/// v0.8 #52 (S4E5) / v0.8.1 #57 (S4E6): stream-decrypt API for
/// chunked SSE-S4 bodies. Returns a [`futures::Stream`] that yields
/// one `Bytes` per chunk in order. Each chunk is emitted only after
/// AES-GCM tag verify succeeds, so the client never sees plaintext
/// bytes that haven't been authenticated. A failing chunk yields
/// its [`SseError::ChunkAuthFailed`] (with the chunk index) and ends
/// the stream — earlier chunks may already have left the gateway,
/// which matches the standard streaming-AEAD trade-off (operators
/// MUST alert on the audit log + metric, not rely on connection
/// close to guarantee atomicity).
///
/// Accepts either S4E5 (v0.8 #52, legacy) or S4E6 (v0.8.1 #57,
/// current) magic. Non-chunked magic surfaces as
/// [`SseError::BadMagic`] / [`SseError::ChunkFrameTruncated`] on
/// the first poll — the stream is "fail-fast" rather than "fall
/// through to S4E2 buffered decrypt", because the caller has
/// already dispatched on [`peek_magic`] by the time it hands a body
/// to this function.
///
/// `body` is owned by the returned stream so the caller doesn't
/// need to keep the bytes alive separately. The returned stream is
/// `'static` — the `keyring` borrow is consumed up front to extract
/// the per-frame key and build the AES cipher (which owns its key
/// material), so the caller's keyring may be dropped immediately.
pub fn decrypt_chunked_stream(
    body: bytes::Bytes,
    keyring: &SseKeyring,
) -> impl futures::Stream<Item = Result<Bytes, SseError>> + 'static {
    use futures::stream::{self, StreamExt};

    // Cheap pre-validation: parse the header + look up the key
    // once, up front, so a malformed frame surfaces on the first
    // poll instead of being deferred behind the first-chunk loop.
    // The `keyring` borrow ends here — we extract the AES key into
    // the owned `Aes256Gcm` cipher, then store that in the stream
    // state.
    let prelude = (|| {
        // v0.8.2 #64: streaming path is naturally memory-bounded
        // (one chunk-worth of plaintext at a time), so we don't cap
        // the *declared* total here — the per-chunk loop already
        // bounds memory by `chunk_size`. The truncation /
        // arithmetic-overflow checks inside `parse_chunked_header`
        // still run regardless of `max_body_bytes`, which is what
        // protects the streaming path from the same DoS class as the
        // buffered path (the overflow / declared-vs-actual length
        // mismatches are independent of the gateway cap).
        let hdr = parse_chunked_header(&body, usize::MAX)?;
        let key = keyring
            .get(hdr.key_id)
            .ok_or(SseError::KeyNotInKeyring { id: hdr.key_id })?;
        let cipher = Aes256Gcm::new(key.as_aes_key());
        Ok::<_, SseError>((hdr, cipher))
    })();

    match prelude {
        Err(e) => stream::iter(std::iter::once(Err(e))).left_stream(),
        Ok((hdr, cipher)) => {
            let chunks_offset = hdr.chunks_offset;
            let state = ChunkedDecryptState {
                body,
                cipher,
                hdr,
                cursor: chunks_offset,
                next_index: 0,
            };
            stream::try_unfold(state, decrypt_next_chunk).right_stream()
        }
    }
}

/// Per-stream state for [`decrypt_chunked_stream`]. Holds the owned
/// `body` (so the stream stays self-contained), the prepared
/// cipher, and the cursor position into the chunk array.
struct ChunkedDecryptState {
    body: bytes::Bytes,
    cipher: Aes256Gcm,
    hdr: ChunkedHeader,
    cursor: usize,
    next_index: u32,
}

async fn decrypt_next_chunk(
    mut state: ChunkedDecryptState,
) -> Result<Option<(Bytes, ChunkedDecryptState)>, SseError> {
    if state.next_index >= state.hdr.chunk_count {
        // Final boundary check — anything past the declared
        // chunk_count would be a truncation / append attack.
        if state.cursor != state.body.len() {
            return Err(SseError::ChunkFrameTruncated {
                what: "trailing bytes after declared chunk_count",
            });
        }
        return Ok(None);
    }
    let i = state.next_index;
    let chunk_size = state.hdr.chunk_size as usize;
    if state.cursor + TAG_LEN > state.body.len() {
        return Err(SseError::ChunkFrameTruncated { what: "chunk tag" });
    }
    let tag_off = state.cursor;
    let ct_off = tag_off + TAG_LEN;
    let is_last = i + 1 == state.hdr.chunk_count;
    let ct_len = if is_last {
        if ct_off > state.body.len() {
            return Err(SseError::ChunkFrameTruncated {
                what: "final chunk ciphertext",
            });
        }
        let remaining = state.body.len() - ct_off;
        if remaining > chunk_size {
            return Err(SseError::ChunkFrameTruncated {
                what: "trailing bytes after final chunk",
            });
        }
        remaining
    } else {
        chunk_size
    };
    let ct_end = ct_off + ct_len;
    if ct_end > state.body.len() {
        return Err(SseError::ChunkFrameTruncated {
            what: "chunk ciphertext",
        });
    }
    let mut tag = [0u8; TAG_LEN];
    tag.copy_from_slice(&state.body[tag_off..ct_off]);
    let ct = &state.body[ct_off..ct_end];
    let plain = decrypt_chunked_chunk(
        &state.cipher,
        i,
        state.hdr.chunk_count,
        state.hdr.key_id,
        &state.hdr.salt,
        &tag,
        ct,
    )?;
    crate::metrics::record_sse_streaming_chunk("decrypt");
    state.cursor = ct_end;
    state.next_index += 1;
    Ok(Some((plain, state)))
}

/// v0.8.1 #57: build an S4E5 frame. Identical body structure to the
/// pre-#57 `encrypt_v2_chunked` (4-byte salt + S4E5 magic + V5
/// nonce/AAD); kept around purely so the back-compat-read tests can
/// synthesize a "v0.8.0 vintage" blob and prove the new gateway
/// still decrypts it.
#[cfg(test)]
fn encrypt_v2_chunked_s4e5_for_test(
    plaintext: &[u8],
    keyring: &SseKeyring,
    chunk_size: usize,
) -> Result<Bytes, SseError> {
    if chunk_size == 0 {
        return Err(SseError::ChunkSizeInvalid);
    }
    let (key_id, key) = keyring.active();
    let cipher = Aes256Gcm::new(key.as_aes_key());
    let mut salt = [0u8; 4];
    rand::rngs::OsRng.fill_bytes(&mut salt);

    let chunk_count: u32 = if plaintext.is_empty() {
        1
    } else {
        plaintext
            .len()
            .div_ceil(chunk_size)
            .try_into()
            .expect("chunk_count overflows u32")
    };

    let mut out = Vec::with_capacity(
        S4E5_HEADER_BYTES + plaintext.len() + (chunk_count as usize * S4E5_PER_CHUNK_OVERHEAD),
    );
    out.extend_from_slice(SSE_MAGIC_V5);
    out.push(ALGO_AES_256_GCM);
    out.extend_from_slice(&key_id.to_be_bytes());
    out.push(0u8);
    out.extend_from_slice(&(chunk_size as u32).to_be_bytes());
    out.extend_from_slice(&chunk_count.to_be_bytes());
    out.extend_from_slice(&salt);

    for i in 0..chunk_count {
        let off = (i as usize).saturating_mul(chunk_size);
        let end = off.saturating_add(chunk_size).min(plaintext.len());
        let chunk_pt: &[u8] = if off >= plaintext.len() {
            &[]
        } else {
            &plaintext[off..end]
        };
        let nonce_bytes = nonce_v5(&salt, i);
        let nonce = Nonce::from_slice(&nonce_bytes);
        let aad = aad_v5(i, chunk_count, key_id, &salt);
        let ct_with_tag = cipher
            .encrypt(
                nonce,
                Payload {
                    msg: chunk_pt,
                    aad: &aad,
                },
            )
            .expect("aes-gcm encrypt cannot fail with a 32-byte key");
        let split = ct_with_tag.len() - TAG_LEN;
        let (ct, tag) = ct_with_tag.split_at(split);
        out.extend_from_slice(tag);
        out.extend_from_slice(ct);
    }
    Ok(Bytes::from(out))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn key32(seed: u8) -> Arc<SseKey> {
        Arc::new(SseKey::from_bytes(&[seed; 32]).unwrap())
    }

    fn keyring_single(seed: u8) -> SseKeyring {
        SseKeyring::new(1, key32(seed))
    }

    #[test]
    fn roundtrip_basic_v1() {
        // back-compat single-key API — still works.
        let k = SseKey::from_bytes(&[7u8; 32]).unwrap();
        let pt = b"the quick brown fox jumps over the lazy dog";
        let ct = encrypt(&k, pt);
        assert!(looks_encrypted(&ct));
        assert_eq!(&ct[..4], SSE_MAGIC_V1);
        assert_eq!(ct[4], ALGO_AES_256_GCM);
        assert_eq!(ct.len(), SSE_HEADER_BYTES + pt.len());
        // decrypt via single-key keyring
        let kr = SseKeyring::new(1, Arc::new(k));
        let pt2 = decrypt(&ct, &kr).unwrap();
        assert_eq!(pt2.as_ref(), pt);
    }

    #[test]
    fn s4e2_roundtrip_active_key() {
        let kr = keyring_single(7);
        let pt = b"S4E2 active-key roundtrip";
        let ct = encrypt_v2(pt, &kr);
        assert_eq!(&ct[..4], SSE_MAGIC_V2);
        assert_eq!(ct[4], ALGO_AES_256_GCM);
        assert_eq!(u16::from_be_bytes([ct[5], ct[6]]), 1, "key_id BE");
        assert_eq!(ct[7], 0, "reserved byte");
        assert_eq!(ct.len(), SSE_HEADER_BYTES + pt.len());
        assert!(looks_encrypted(&ct));
        let pt2 = decrypt(&ct, &kr).unwrap();
        assert_eq!(pt2.as_ref(), pt);
    }

    #[test]
    fn decrypt_s4e1_via_active_only_keyring() {
        // v0.4 wrote S4E1 with key K; v0.5 keyring has K as the only
        // (active) key. Decrypt must succeed.
        let k_arc = key32(11);
        let legacy_ct = encrypt(&k_arc, b"v0.4 vintage object");
        assert_eq!(&legacy_ct[..4], SSE_MAGIC_V1);
        let kr = SseKeyring::new(1, Arc::clone(&k_arc));
        let plain = decrypt(&legacy_ct, &kr).unwrap();
        assert_eq!(plain.as_ref(), b"v0.4 vintage object");
    }

    #[test]
    fn decrypt_s4e2_under_old_key_after_rotation() {
        // Rotation flow: object was encrypted under key id=1 when 1
        // was active. Operator rotates to active=2 and keeps 1 in the
        // keyring. The S4E2 body must still decrypt.
        let k1 = key32(1);
        let k2 = key32(2);
        let mut kr_old = SseKeyring::new(1, Arc::clone(&k1));
        let ct = encrypt_v2(b"old-rotation object", &kr_old);
        assert_eq!(u16::from_be_bytes([ct[5], ct[6]]), 1);

        // After rotation: active=2, but key 1 still in ring.
        kr_old.add(2, Arc::clone(&k2));
        let mut kr_new = SseKeyring::new(2, Arc::clone(&k2));
        kr_new.add(1, Arc::clone(&k1));

        let plain = decrypt(&ct, &kr_new).unwrap();
        assert_eq!(plain.as_ref(), b"old-rotation object");

        // And new PUTs go to id 2 (active).
        let new_ct = encrypt_v2(b"new-rotation object", &kr_new);
        assert_eq!(u16::from_be_bytes([new_ct[5], new_ct[6]]), 2);
        let plain_new = decrypt(&new_ct, &kr_new).unwrap();
        assert_eq!(plain_new.as_ref(), b"new-rotation object");
    }

    #[test]
    fn s4e2_unknown_key_id_errors() {
        let kr = keyring_single(3); // only id=1 present
        let kr_other = SseKeyring::new(99, key32(3));
        let ct = encrypt_v2(b"x", &kr_other); // body claims key_id=99
        let err = decrypt(&ct, &kr).unwrap_err();
        assert!(
            matches!(err, SseError::KeyNotInKeyring { id: 99 }),
            "got {err:?}"
        );
    }

    #[test]
    fn s4e2_tampered_key_id_fails_auth() {
        let kr = SseKeyring::new(1, key32(4));
        let mut kr_with_2 = kr.clone();
        kr_with_2.add(2, key32(5)); // a real but wrong key under id=2
        let mut ct = encrypt_v2(b"do not flip my key id", &kr).to_vec();
        // Flip key_id from 1 → 2 in the header. The keyring HAS a key
        // for 2, so the lookup succeeds — but AAD authenticates the
        // original key_id, so AES-GCM tag verification must fail.
        assert_eq!(u16::from_be_bytes([ct[5], ct[6]]), 1);
        ct[5] = 0;
        ct[6] = 2;
        let err = decrypt(&ct, &kr_with_2).unwrap_err();
        assert!(matches!(err, SseError::DecryptFailed), "got {err:?}");
    }

    #[test]
    fn s4e2_tampered_ciphertext_fails() {
        let kr = SseKeyring::new(7, key32(9));
        let mut ct = encrypt_v2(b"secret message v2", &kr).to_vec();
        let last = ct.len() - 1;
        ct[last] ^= 0x01;
        let err = decrypt(&ct, &kr).unwrap_err();
        assert!(matches!(err, SseError::DecryptFailed));
    }

    #[test]
    fn s4e2_tampered_algo_byte_fails() {
        let kr = SseKeyring::new(1, key32(2));
        let mut ct = encrypt_v2(b"hi", &kr).to_vec();
        ct[4] = 99;
        let err = decrypt(&ct, &kr).unwrap_err();
        assert!(matches!(err, SseError::UnsupportedAlgo { tag: 99 }));
    }

    #[test]
    fn wrong_key_fails_v1_via_keyring() {
        // S4E1 written under key K1; keyring has only K2 → DecryptFailed.
        let k1 = SseKey::from_bytes(&[1u8; 32]).unwrap();
        let ct = encrypt(&k1, b"secret");
        let kr_wrong = SseKeyring::new(1, Arc::new(SseKey::from_bytes(&[2u8; 32]).unwrap()));
        let err = decrypt(&ct, &kr_wrong).unwrap_err();
        assert!(matches!(err, SseError::DecryptFailed));
    }

    #[test]
    fn rejects_short_body() {
        let kr = SseKeyring::new(1, key32(1));
        let err = decrypt(b"short", &kr).unwrap_err();
        assert!(matches!(err, SseError::TooShort { got: 5 }));
    }

    #[test]
    fn looks_encrypted_passthrough_returns_false() {
        // S4F2 frame magic, NOT S4E1 / S4E2 — must not be confused.
        let f2 = b"S4F2\x01\x00\x00\x00........................................";
        assert!(!looks_encrypted(f2));
        assert!(!looks_encrypted(b""));
    }

    #[test]
    fn looks_encrypted_detects_both_v1_and_v2() {
        let kr = SseKeyring::new(1, key32(8));
        let v1 = encrypt(&SseKey::from_bytes(&[8u8; 32]).unwrap(), b"x");
        let v2 = encrypt_v2(b"x", &kr);
        assert!(looks_encrypted(&v1));
        assert!(looks_encrypted(&v2));
    }

    #[test]
    fn key_from_hex_string() {
        let bad =
            SseKey::from_bytes(b"0102030405060708090a0b0c0d0e0f10111213141516171819202122232425")
                .unwrap_err();
        assert!(matches!(bad, SseError::BadKeyLength { .. }));
        let good = b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let _ = SseKey::from_bytes(good).expect("64-char hex should parse");
    }

    #[test]
    fn encrypt_v2_uses_random_nonce() {
        let kr = SseKeyring::new(1, key32(3));
        let pt = b"deterministic input";
        let a = encrypt_v2(pt, &kr);
        let b = encrypt_v2(pt, &kr);
        assert_ne!(a, b, "nonce must be random per-call");
    }

    #[test]
    fn keyring_active_and_get() {
        let k1 = key32(1);
        let k2 = key32(2);
        let mut kr = SseKeyring::new(1, Arc::clone(&k1));
        kr.add(2, Arc::clone(&k2));
        let (id, active) = kr.active();
        assert_eq!(id, 1);
        assert_eq!(active.bytes, [1u8; 32]);
        assert!(kr.get(2).is_some());
        assert!(kr.get(3).is_none());
    }

    // -----------------------------------------------------------------
    // v0.5 #27 — SSE-C (customer-provided key, S4E3 frame) tests
    // -----------------------------------------------------------------

    use base64::Engine as _;

    fn cust_key(seed: u8) -> CustomerKeyMaterial {
        let key = [seed; KEY_LEN];
        let key_md5 = compute_key_md5(&key);
        CustomerKeyMaterial { key, key_md5 }
    }

    #[test]
    fn s4e3_roundtrip_happy_path() {
        let m = cust_key(42);
        let pt = b"top-secret SSE-C payload";
        let ct = encrypt_with_source(
            pt,
            SseSource::CustomerKey {
                key: &m.key,
                key_md5: &m.key_md5,
            },
        );
        // Frame inspection.
        assert_eq!(&ct[..4], SSE_MAGIC_V3);
        assert_eq!(ct[4], ALGO_AES_256_GCM);
        assert_eq!(&ct[5..5 + KEY_MD5_LEN], &m.key_md5);
        assert_eq!(ct.len(), SSE_HEADER_BYTES_V3 + pt.len());
        assert!(looks_encrypted(&ct));
        // Decrypt round-trip.
        let plain = decrypt(
            &ct,
            SseSource::CustomerKey {
                key: &m.key,
                key_md5: &m.key_md5,
            },
        )
        .unwrap();
        assert_eq!(plain.as_ref(), pt);
        // And via the From impl on &CustomerKeyMaterial.
        let plain2 = decrypt(&ct, &m).unwrap();
        assert_eq!(plain2.as_ref(), pt);
    }

    #[test]
    fn s4e3_wrong_key_yields_wrong_customer_key_error() {
        let m = cust_key(1);
        let other = cust_key(2);
        let ct = encrypt_with_source(b"payload", (&m).into());
        let err = decrypt(
            &ct,
            SseSource::CustomerKey {
                key: &other.key,
                key_md5: &other.key_md5,
            },
        )
        .unwrap_err();
        assert!(matches!(err, SseError::WrongCustomerKey), "got {err:?}");
    }

    #[test]
    fn s4e3_tampered_stored_md5_is_caught() {
        // Attacker rewrites the stored MD5 to match a key they know.
        // Even though the supplied (attacker) key matches the rewritten
        // MD5, AES-GCM authenticates the ORIGINAL md5 via AAD, so the
        // tag check fails. Surface: WrongCustomerKey if the supplied
        // md5 != stored md5 (this test), or DecryptFailed if attacker
        // also rewrites their supplied md5 to match.
        let m = cust_key(7);
        let mut ct = encrypt_with_source(b"victim payload", (&m).into()).to_vec();
        // Flip a byte in the stored fingerprint.
        ct[5] ^= 0x55;
        // Client supplies the original (unmodified) key + md5.
        let err = decrypt(
            &ct,
            SseSource::CustomerKey {
                key: &m.key,
                key_md5: &m.key_md5,
            },
        )
        .unwrap_err();
        assert!(matches!(err, SseError::WrongCustomerKey), "got {err:?}");
    }

    #[test]
    fn s4e3_tampered_md5_with_matching_supplied_md5_fails_aead() {
        // Both stored md5 AND supplied md5 are flipped to the same bogus
        // value. The fingerprint check passes (they match) but AAD
        // authenticates the *original* md5, so AES-GCM fails.
        let m = cust_key(3);
        let mut ct = encrypt_with_source(b"x", (&m).into()).to_vec();
        ct[5] ^= 0xFF;
        let mut bogus_md5 = m.key_md5;
        bogus_md5[0] ^= 0xFF;
        let err = decrypt(
            &ct,
            SseSource::CustomerKey {
                key: &m.key,
                key_md5: &bogus_md5,
            },
        )
        .unwrap_err();
        assert!(matches!(err, SseError::DecryptFailed), "got {err:?}");
    }

    #[test]
    fn s4e3_tampered_ciphertext_fails_aead() {
        let m = cust_key(8);
        let mut ct = encrypt_with_source(b"sealed message", (&m).into()).to_vec();
        let last = ct.len() - 1;
        ct[last] ^= 0x01;
        let err = decrypt(&ct, &m).unwrap_err();
        assert!(matches!(err, SseError::DecryptFailed), "got {err:?}");
    }

    #[test]
    fn s4e3_tampered_algo_byte_rejected() {
        let m = cust_key(9);
        let mut ct = encrypt_with_source(b"x", (&m).into()).to_vec();
        ct[4] = 99;
        let err = decrypt(&ct, &m).unwrap_err();
        assert!(matches!(err, SseError::UnsupportedAlgo { tag: 99 }));
    }

    #[test]
    fn s4e3_uses_random_nonce() {
        let m = cust_key(10);
        let a = encrypt_with_source(b"deterministic input", (&m).into());
        let b = encrypt_with_source(b"deterministic input", (&m).into());
        assert_ne!(a, b, "nonce must be random per-call");
    }

    #[test]
    fn parse_customer_key_headers_happy_path() {
        let key = [11u8; KEY_LEN];
        let md5 = compute_key_md5(&key);
        let key_b64 = base64::engine::general_purpose::STANDARD.encode(key);
        let md5_b64 = base64::engine::general_purpose::STANDARD.encode(md5);
        let m = parse_customer_key_headers("AES256", &key_b64, &md5_b64).unwrap();
        assert_eq!(m.key, key);
        assert_eq!(m.key_md5, md5);
    }

    #[test]
    fn parse_customer_key_headers_rejects_wrong_algorithm() {
        let key = [1u8; KEY_LEN];
        let md5 = compute_key_md5(&key);
        let kb = base64::engine::general_purpose::STANDARD.encode(key);
        let mb = base64::engine::general_purpose::STANDARD.encode(md5);
        let err = parse_customer_key_headers("AES128", &kb, &mb).unwrap_err();
        assert!(
            matches!(err, SseError::CustomerKeyAlgorithmUnsupported { ref algo } if algo == "AES128"),
            "got {err:?}"
        );
        // Lowercase variant still rejected (AWS S3 accepts only "AES256").
        let err2 = parse_customer_key_headers("aes256", &kb, &mb).unwrap_err();
        assert!(
            matches!(err2, SseError::CustomerKeyAlgorithmUnsupported { .. }),
            "got {err2:?}"
        );
    }

    #[test]
    fn parse_customer_key_headers_rejects_wrong_key_length() {
        let short_key = vec![5u8; 16]; // half-length AES key
        let md5 = compute_key_md5(&short_key);
        let kb = base64::engine::general_purpose::STANDARD.encode(&short_key);
        let mb = base64::engine::general_purpose::STANDARD.encode(md5);
        let err = parse_customer_key_headers("AES256", &kb, &mb).unwrap_err();
        assert!(
            matches!(err, SseError::InvalidCustomerKey { reason } if reason.contains("key length")),
            "got {err:?}"
        );
    }

    #[test]
    fn parse_customer_key_headers_rejects_wrong_md5_length() {
        let key = [3u8; KEY_LEN];
        let kb = base64::engine::general_purpose::STANDARD.encode(key);
        // Truncated MD5 (15 bytes instead of 16).
        let bad_md5 = vec![0u8; 15];
        let mb = base64::engine::general_purpose::STANDARD.encode(bad_md5);
        let err = parse_customer_key_headers("AES256", &kb, &mb).unwrap_err();
        assert!(
            matches!(err, SseError::InvalidCustomerKey { reason } if reason.contains("MD5 length")),
            "got {err:?}"
        );
    }

    #[test]
    fn parse_customer_key_headers_rejects_md5_mismatch() {
        let key = [4u8; KEY_LEN];
        let other = [5u8; KEY_LEN];
        let kb = base64::engine::general_purpose::STANDARD.encode(key);
        let wrong_md5 = compute_key_md5(&other);
        let mb = base64::engine::general_purpose::STANDARD.encode(wrong_md5);
        let err = parse_customer_key_headers("AES256", &kb, &mb).unwrap_err();
        assert!(
            matches!(err, SseError::InvalidCustomerKey { reason } if reason.contains("MD5 does not match")),
            "got {err:?}"
        );
    }

    #[test]
    fn parse_customer_key_headers_rejects_bad_base64() {
        let valid_key = [0u8; KEY_LEN];
        let md5 = compute_key_md5(&valid_key);
        let mb = base64::engine::general_purpose::STANDARD.encode(md5);
        let err = parse_customer_key_headers("AES256", "!!!not-base64!!!", &mb).unwrap_err();
        assert!(
            matches!(err, SseError::InvalidCustomerKey { reason } if reason.contains("base64")),
            "got {err:?}"
        );
        // Bad MD5 base64.
        let kb = base64::engine::general_purpose::STANDARD.encode(valid_key);
        let err2 = parse_customer_key_headers("AES256", &kb, "??not-base64??").unwrap_err();
        assert!(
            matches!(err2, SseError::InvalidCustomerKey { reason } if reason.contains("base64")),
            "got {err2:?}"
        );
    }

    #[test]
    fn parse_customer_key_headers_trims_whitespace() {
        // S3 SDKs sometimes pad headers with trailing newlines.
        let key = [12u8; KEY_LEN];
        let md5 = compute_key_md5(&key);
        let kb = format!(
            "  {}\n",
            base64::engine::general_purpose::STANDARD.encode(key)
        );
        let mb = format!(
            "\t{}  ",
            base64::engine::general_purpose::STANDARD.encode(md5)
        );
        let m = parse_customer_key_headers("AES256", &kb, &mb).unwrap();
        assert_eq!(m.key, key);
    }

    // -----------------------------------------------------------------
    // Back-compat + cross-source mixing
    // -----------------------------------------------------------------

    #[test]
    fn back_compat_decrypt_s4e1_with_keyring_source() {
        let k = key32(33);
        let legacy_ct = encrypt(&k, b"v0.4 vintage object");
        let kr = SseKeyring::new(1, Arc::clone(&k));
        // Both call styles must work — `&kr` (back-compat) and
        // `SseSource::Keyring(&kr)` (explicit).
        let plain = decrypt(&legacy_ct, &kr).unwrap();
        assert_eq!(plain.as_ref(), b"v0.4 vintage object");
        let plain2 = decrypt(&legacy_ct, SseSource::Keyring(&kr)).unwrap();
        assert_eq!(plain2.as_ref(), b"v0.4 vintage object");
    }

    #[test]
    fn back_compat_decrypt_s4e2_with_keyring_source() {
        let kr = keyring_single(34);
        let ct = encrypt_v2(b"v0.5 #29 object", &kr);
        let plain = decrypt(&ct, &kr).unwrap();
        assert_eq!(plain.as_ref(), b"v0.5 #29 object");
        // encrypt_with_source(Keyring) should produce the same wire
        // format (S4E2).
        let ct2 = encrypt_with_source(b"v0.5 #29 object", SseSource::Keyring(&kr));
        assert_eq!(&ct2[..4], SSE_MAGIC_V2);
        let plain2 = decrypt(&ct2, &kr).unwrap();
        assert_eq!(plain2.as_ref(), b"v0.5 #29 object");
    }

    #[test]
    fn s4e2_blob_with_customer_key_source_is_rejected() {
        // An object stored with SSE-S4 (S4E2) but a client sending
        // SSE-C headers on the GET — this is a misuse, surface as
        // CustomerKeyUnexpected so service.rs can return 400.
        let kr = keyring_single(50);
        let ct = encrypt_v2(b"server-managed object", &kr);
        let m = cust_key(99);
        let err = decrypt(
            &ct,
            SseSource::CustomerKey {
                key: &m.key,
                key_md5: &m.key_md5,
            },
        )
        .unwrap_err();
        assert!(matches!(err, SseError::CustomerKeyUnexpected), "got {err:?}");
    }

    #[test]
    fn s4e3_blob_with_keyring_source_is_rejected() {
        // Inverse: object is SSE-C (S4E3) but client forgot to send
        // SSE-C headers. Service.rs should map this to 400.
        let m = cust_key(60);
        let ct = encrypt_with_source(b"customer-key object", (&m).into());
        let kr = keyring_single(60);
        let err = decrypt(&ct, &kr).unwrap_err();
        assert!(matches!(err, SseError::CustomerKeyRequired), "got {err:?}");
    }

    #[test]
    fn looks_encrypted_detects_s4e3() {
        let m = cust_key(13);
        let ct = encrypt_with_source(b"x", (&m).into());
        assert!(looks_encrypted(&ct));
    }

    #[test]
    fn s4e3_rejects_short_body() {
        // 36 bytes passes the looks_encrypted gate but is shorter than
        // S4E3's 49-byte header.
        let mut short = Vec::new();
        short.extend_from_slice(SSE_MAGIC_V3);
        short.push(ALGO_AES_256_GCM);
        // Padding to 36 bytes (SSE_HEADER_BYTES) so the outer length
        // check passes but the S4E3 inner check fails.
        short.extend_from_slice(&[0u8; SSE_HEADER_BYTES - 5]);
        assert_eq!(short.len(), SSE_HEADER_BYTES);
        let m = cust_key(1);
        let err = decrypt(
            &short,
            SseSource::CustomerKey {
                key: &m.key,
                key_md5: &m.key_md5,
            },
        )
        .unwrap_err();
        assert!(matches!(err, SseError::TooShort { .. }), "got {err:?}");
    }

    #[test]
    fn customer_key_material_debug_redacts_key() {
        let m = cust_key(99);
        let s = format!("{m:?}");
        assert!(s.contains("redacted"));
        assert!(!s.contains(&format!("{:?}", m.key.as_slice())));
    }

    #[test]
    fn constant_time_eq_basic() {
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"abcd"));
        assert!(constant_time_eq(b"", b""));
    }

    #[test]
    fn compute_key_md5_known_vector() {
        // Empty input MD5 is known: d41d8cd98f00b204e9800998ecf8427e.
        let got = compute_key_md5(b"");
        let expected_hex = "d41d8cd98f00b204e9800998ecf8427e";
        assert_eq!(hex_lower(&got), expected_hex);
    }

    // -----------------------------------------------------------------
    // v0.5 #28 — SSE-KMS envelope (S4E4) tests
    // -----------------------------------------------------------------

    use crate::kms::{KmsBackend, LocalKms};
    use std::collections::HashMap;
    use std::path::PathBuf;

    fn local_kms_with(key_ids: &[(&str, [u8; 32])]) -> LocalKms {
        let mut keks: HashMap<String, [u8; 32]> = HashMap::new();
        for (id, k) in key_ids {
            keks.insert((*id).to_string(), *k);
        }
        LocalKms::from_keks(PathBuf::from("/tmp/none"), keks)
    }

    #[tokio::test]
    async fn s4e4_roundtrip_via_local_kms() {
        let kms = local_kms_with(&[("alpha", [42u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("alpha").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let pt = b"SSE-KMS envelope payload across the S4E4 frame";
        let ct = encrypt_with_source(
            pt,
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        );
        // Frame inspection.
        assert_eq!(&ct[..4], SSE_MAGIC_V4);
        assert_eq!(ct[4], ALGO_AES_256_GCM);
        let key_id_len = ct[5] as usize;
        assert_eq!(key_id_len, "alpha".len());
        assert_eq!(&ct[6..6 + key_id_len], b"alpha");
        // peek_magic + looks_encrypted both recognise S4E4.
        assert!(looks_encrypted(&ct));
        assert_eq!(peek_magic(&ct), Some("S4E4"));
        // Async decrypt round-trip.
        let plain = decrypt_with_kms(&ct, &kms).await.unwrap();
        assert_eq!(plain.as_ref(), pt);
    }

    #[tokio::test]
    async fn s4e4_tampered_key_id_fails_aead() {
        let kms = local_kms_with(&[("alpha", [1u8; 32]), ("beta", [2u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("alpha").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let mut ct = encrypt_with_source(
            b"do not redirect",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        )
        .to_vec();
        // Flip the key_id from "alpha" to "betaa" by changing the
        // first byte of the key_id field. The forged id "bltha" is
        // not in the KMS, so unwrap fails with KeyNotFound surfaced
        // through KmsBackend(KmsError::KeyNotFound).
        let key_id_off = 6;
        ct[key_id_off] = b'b';
        let err = decrypt_with_kms(&ct, &kms).await.unwrap_err();
        assert!(
            matches!(
                err,
                SseError::KmsBackend(crate::kms::KmsError::UnwrapFailed { .. })
                    | SseError::KmsBackend(crate::kms::KmsError::KeyNotFound { .. })
            ),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn s4e4_tampered_key_id_to_real_other_id_still_fails() {
        // Wrap under "alpha" but rewrite the stored key_id to "beta"
        // (which IS in the KMS). KmsBackend will try to unwrap with
        // beta's KEK and AAD = "beta", but the wrapped bytes were
        // produced with alpha's KEK + AAD = "alpha", so the local
        // KMS unwrap fails with UnwrapFailed.
        let kms = local_kms_with(&[("alpha", [1u8; 32]), ("beta", [2u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("alpha").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let mut ct = encrypt_with_source(
            b"redirect attempt",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        )
        .to_vec();
        // Both "alpha" and "beta" are 5 chars long so the rewrite
        // doesn't shift any other field offsets.
        let key_id_off = 6;
        ct[key_id_off..key_id_off + 5].copy_from_slice(b"beta_");
        // Trim back to 4-byte "beta" by also shrinking the length
        // prefix would change downstream offsets — instead pad the
        // forged id to keep length stable. This mirrors the realistic
        // tampering surface (attacker can flip bytes but not change
        // the on-disk layout). The KMS now sees key_id "beta_" which
        // is unknown → KeyNotFound.
        let err = decrypt_with_kms(&ct, &kms).await.unwrap_err();
        assert!(
            matches!(
                err,
                SseError::KmsBackend(crate::kms::KmsError::KeyNotFound { .. })
            ),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn s4e4_tampered_wrapped_dek_fails_unwrap() {
        let kms = local_kms_with(&[("k", [3u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("k").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let mut ct = encrypt_with_source(
            b"target body",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        )
        .to_vec();
        // Locate the wrapped_dek_len + wrapped_dek field and flip a
        // byte in the middle of the wrapped DEK. AES-GCM auth on the
        // wrap fails → KmsBackend(UnwrapFailed).
        let key_id_len = ct[5] as usize;
        let wrapped_len_off = 6 + key_id_len;
        let wrapped_off = wrapped_len_off + 4;
        let mid = wrapped_off + (wrapped.ciphertext.len() / 2);
        ct[mid] ^= 0xFF;
        let err = decrypt_with_kms(&ct, &kms).await.unwrap_err();
        assert!(
            matches!(
                err,
                SseError::KmsBackend(crate::kms::KmsError::UnwrapFailed { .. })
            ),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn s4e4_tampered_ciphertext_fails_aead() {
        let kms = local_kms_with(&[("k", [4u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("k").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let mut ct = encrypt_with_source(
            b"sealed body",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        )
        .to_vec();
        let last = ct.len() - 1;
        ct[last] ^= 0x01;
        let err = decrypt_with_kms(&ct, &kms).await.unwrap_err();
        assert!(matches!(err, SseError::DecryptFailed), "got {err:?}");
    }

    #[tokio::test]
    async fn s4e4_uses_random_nonce_and_dek_per_put() {
        let kms = local_kms_with(&[("k", [5u8; 32])]);
        // Two PUTs of the same plaintext under the same KEK must
        // produce different ciphertexts (fresh DEK + fresh nonce).
        let (dek1_vec, wrapped1) = kms.generate_dek("k").await.unwrap();
        let (dek2_vec, wrapped2) = kms.generate_dek("k").await.unwrap();
        let mut dek1 = [0u8; 32];
        dek1.copy_from_slice(&dek1_vec);
        let mut dek2 = [0u8; 32];
        dek2.copy_from_slice(&dek2_vec);
        let pt = b"deterministic input";
        let a = encrypt_with_source(
            pt,
            SseSource::Kms {
                dek: &dek1,
                wrapped: &wrapped1,
            },
        );
        let b = encrypt_with_source(
            pt,
            SseSource::Kms {
                dek: &dek2,
                wrapped: &wrapped2,
            },
        );
        assert_ne!(a, b);
        // Both still decrypt round-trip.
        let plain_a = decrypt_with_kms(&a, &kms).await.unwrap();
        let plain_b = decrypt_with_kms(&b, &kms).await.unwrap();
        assert_eq!(plain_a.as_ref(), pt);
        assert_eq!(plain_b.as_ref(), pt);
    }

    #[tokio::test]
    async fn s4e4_sync_decrypt_returns_kms_async_required() {
        // The whole point of KmsAsyncRequired: passing an S4E4 body
        // to the sync `decrypt` function must surface a distinct
        // error so service.rs's GET path notices the bug rather than
        // returning a generic "wrong source" 400.
        let kms = local_kms_with(&[("k", [6u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("k").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let ct = encrypt_with_source(
            b"async only",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        );
        // Try via Keyring source (the default sync path).
        let kr = SseKeyring::new(1, key32(0));
        let err = decrypt(&ct, &kr).unwrap_err();
        assert!(matches!(err, SseError::KmsAsyncRequired), "got {err:?}");
    }

    #[test]
    fn back_compat_s4e1_e2_e3_still_decrypt_via_sync() {
        // After adding S4E4, the sync `decrypt` path must still
        // handle every legacy frame variant unchanged.
        let k = key32(7);
        let v1 = encrypt(&k, b"v0.4 vintage");
        let kr = SseKeyring::new(1, Arc::clone(&k));
        assert_eq!(decrypt(&v1, &kr).unwrap().as_ref(), b"v0.4 vintage");

        let v2 = encrypt_v2(b"v0.5 #29 vintage", &kr);
        assert_eq!(
            decrypt(&v2, &kr).unwrap().as_ref(),
            b"v0.5 #29 vintage"
        );

        let m = cust_key(7);
        let v3 = encrypt_with_source(b"v0.5 #27 vintage", (&m).into());
        assert_eq!(
            decrypt(&v3, &m).unwrap().as_ref(),
            b"v0.5 #27 vintage"
        );
    }

    #[test]
    fn peek_magic_distinguishes_all_variants() {
        // S4E1 / S4E2 / S4E3 — built from real encrypts so the
        // length gate also passes.
        let k = key32(9);
        let v1 = encrypt(&k, b"x");
        assert_eq!(peek_magic(&v1), Some("S4E1"));
        let kr = SseKeyring::new(1, Arc::clone(&k));
        let v2 = encrypt_v2(b"x", &kr);
        assert_eq!(peek_magic(&v2), Some("S4E2"));
        let m = cust_key(9);
        let v3 = encrypt_with_source(b"x", (&m).into());
        assert_eq!(peek_magic(&v3), Some("S4E3"));
        // Synthetic S4E4 magic with enough trailing bytes to clear
        // the 36-byte length gate. peek_magic does NOT validate the
        // S4E4 inner header, just the magic — that's the contract
        // (cheap dispatch signal).
        let mut v4 = Vec::new();
        v4.extend_from_slice(SSE_MAGIC_V4);
        v4.extend_from_slice(&[0u8; 40]);
        assert_eq!(peek_magic(&v4), Some("S4E4"));
        // Unknown magic / too-short input → None.
        assert!(peek_magic(b"NOPE").is_none());
        assert!(peek_magic(b"short").is_none());
        assert!(peek_magic(&[0u8; 100]).is_none());
    }

    #[tokio::test]
    async fn s4e4_truncated_frame_errors_cleanly() {
        // Truncate to less than the minimum header. Must surface
        // KmsFrameTooShort, not panic, not return BadMagic.
        let truncated = b"S4E4\x01\x05hi";
        let kms = local_kms_with(&[("k", [1u8; 32])]);
        let err = decrypt_with_kms(truncated, &kms).await.unwrap_err();
        assert!(
            matches!(err, SseError::KmsFrameTooShort { .. }),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn s4e4_oob_key_id_len_errors() {
        // Build a body that claims key_id_len = 200 but only has 4
        // bytes after the length prefix. parse_s4e4_header must
        // refuse with KmsFrameFieldOob, not slice-panic.
        let mut body = Vec::new();
        body.extend_from_slice(SSE_MAGIC_V4);
        body.push(ALGO_AES_256_GCM);
        body.push(200u8); // key_id_len
        // Remaining bytes < 200; pad to clear the looks_encrypted
        // floor (36 bytes) but stay short of the claimed key_id +
        // wrapped_dek_len + nonce + tag layout.
        body.extend_from_slice(&[0u8; 50]);
        let kms = local_kms_with(&[("k", [1u8; 32])]);
        let err = decrypt_with_kms(&body, &kms).await.unwrap_err();
        assert!(
            matches!(err, SseError::KmsFrameFieldOob { .. }),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn s4e4_via_keyring_source_into_sync_decrypt_is_kms_async_required() {
        // S4E4 + Keyring source: sync decrypt sees the S4E4 magic
        // first and returns KmsAsyncRequired regardless of source —
        // the source mismatch never gets a chance to surface, which
        // is the right behaviour (caller's bug is "didn't peek
        // magic" not "wrong source").
        let kms = local_kms_with(&[("k", [9u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("k").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let ct = encrypt_with_source(
            b"x",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        );
        let m = cust_key(1);
        let err = decrypt(&ct, &m).unwrap_err();
        assert!(matches!(err, SseError::KmsAsyncRequired), "got {err:?}");
    }

    #[tokio::test]
    async fn s4e4_looks_encrypted_passthrough_returns_false_for_synthetic() {
        // S4F4 (note F not E) must NOT be confused with S4E4.
        let mut not_s4e4 = Vec::new();
        not_s4e4.extend_from_slice(b"S4F4");
        not_s4e4.extend_from_slice(&[0u8; 60]);
        assert!(!looks_encrypted(&not_s4e4));
        assert_eq!(peek_magic(&not_s4e4), None);
    }

    #[tokio::test]
    async fn s4e4_aad_length_prefix_prevents_byte_shifting() {
        // Constructing an S4E4 body where the wrapped_dek_len is
        // shrunk by N bytes and the same N bytes are prepended to
        // the key_id-equivalent area would, without length-prefixed
        // AAD, produce the same AAD bytestream. Verify our AAD
        // includes the length prefixes by tampering with
        // wrapped_dek_len and confirming AES-GCM auth fails.
        let kms = local_kms_with(&[("kk", [11u8; 32])]);
        let (dek_vec, wrapped) = kms.generate_dek("kk").await.unwrap();
        let mut dek = [0u8; 32];
        dek.copy_from_slice(&dek_vec);
        let mut ct = encrypt_with_source(
            b"length-shift defense",
            SseSource::Kms {
                dek: &dek,
                wrapped: &wrapped,
            },
        )
        .to_vec();
        let key_id_len = ct[5] as usize;
        let wrapped_len_off = 6 + key_id_len;
        // Shrink wrapped_dek_len by 1. parse_s4e4_header now reads a
        // shorter wrapped_dek and a different nonce/tag/ciphertext
        // alignment — KMS unwrap fails OR AES-GCM fails OR frame
        // bounds reject. All three surface as auditable errors;
        // none should reach a successful decrypt.
        let original_len = u32::from_be_bytes([
            ct[wrapped_len_off],
            ct[wrapped_len_off + 1],
            ct[wrapped_len_off + 2],
            ct[wrapped_len_off + 3],
        ]);
        let new_len = (original_len - 1).to_be_bytes();
        ct[wrapped_len_off..wrapped_len_off + 4].copy_from_slice(&new_len);
        let err = decrypt_with_kms(&ct, &kms).await.unwrap_err();
        // Acceptable failure modes: unwrap fail (truncated wrapped
        // DEK), AES-GCM fail (shifted nonce/tag/AAD), or frame bounds.
        assert!(
            matches!(
                err,
                SseError::KmsBackend(_)
                    | SseError::DecryptFailed
                    | SseError::KmsFrameFieldOob { .. }
                    | SseError::KmsFrameTooShort { .. }
            ),
            "got {err:?}"
        );
    }

    // -----------------------------------------------------------------------
    // v0.8 #52: S4E5 chunked SSE-S4 — encrypt_v2_chunked / decrypt_chunked_stream
    // -----------------------------------------------------------------------

    use futures::StreamExt;

    /// Drain a chunked-decrypt stream into a `Vec<Bytes>` for assertion.
    /// Surfaces the first error verbatim (so tests can match on it).
    async fn collect_chunks(
        s: impl futures::Stream<Item = Result<Bytes, SseError>>,
    ) -> Result<Vec<Bytes>, SseError> {
        let mut out = Vec::new();
        let mut s = std::pin::pin!(s);
        while let Some(item) = s.next().await {
            out.push(item?);
        }
        Ok(out)
    }

    #[test]
    fn s4e6_encrypt_layout_10mb_at_1mib() {
        // v0.8.1 #57: encrypt_v2_chunked now emits S4E6 (24-byte
        // header, 8-byte salt). 10 MB plaintext at 1 MiB chunk
        // size → magic "S4E6", chunk_count=10, header bytes line
        // up to the documented 24 + 10 * 16 + 10 MB layout.
        let kr = keyring_single(0x42);
        let chunk_size = 1024 * 1024;
        let pt_len = 10 * 1024 * 1024;
        let pt = vec![0xAB_u8; pt_len];
        let ct = encrypt_v2_chunked(&pt, &kr, chunk_size).expect("encrypt ok");
        assert_eq!(&ct[..4], SSE_MAGIC_V6, "new PUTs emit S4E6 (v0.8.1 #57)");
        assert_eq!(ct[4], ALGO_AES_256_GCM);
        assert_eq!(u16::from_be_bytes([ct[5], ct[6]]), 1, "key_id BE = active id");
        assert_eq!(ct[7], 0, "reserved must be 0");
        assert_eq!(
            u32::from_be_bytes([ct[8], ct[9], ct[10], ct[11]]),
            chunk_size as u32,
            "chunk_size BE",
        );
        assert_eq!(
            u32::from_be_bytes([ct[12], ct[13], ct[14], ct[15]]),
            10,
            "chunk_count BE — 10 MiB / 1 MiB = 10 (no remainder)",
        );
        // Salt now 8 bytes — verify the slice exists and isn't all
        // zeros (defensive: catches a stuck PRNG that would leave
        // the salt array uninitialized).
        assert_eq!(&ct[16..24].len(), &8, "S4E6 salt slot is 8 bytes");
        assert_ne!(&ct[16..24], &[0u8; 8], "S4E6 salt must be random, not zeros");
        assert_eq!(
            ct.len(),
            S4E6_HEADER_BYTES + 10 * S4E6_PER_CHUNK_OVERHEAD + pt_len,
            "total = header (24) + 10 tags + plaintext",
        );
        assert!(looks_encrypted(&ct), "looks_encrypted must accept S4E6");
        assert_eq!(peek_magic(&ct), Some("S4E6"));
    }

    #[tokio::test]
    async fn s4e6_decrypt_chunked_stream_byte_equal() {
        // v0.8.1 #57: round-trip via S4E6 path. encrypt_v2_chunked
        // emits S4E6, decrypt_chunked_stream consumes S4E5/S4E6.
        let kr = keyring_single(0x55);
        let pt: Vec<u8> = (0..(10 * 1024 * 1024_u32)).map(|i| (i & 0xFF) as u8).collect();
        let ct = encrypt_v2_chunked(&pt, &kr, 1024 * 1024).unwrap();
        // Sanity: the new PUT is S4E6.
        assert_eq!(&ct[..4], SSE_MAGIC_V6, "new emit is S4E6");
        let stream = decrypt_chunked_stream(ct, &kr);
        let chunks = collect_chunks(stream).await.expect("stream ok");
        assert_eq!(chunks.len(), 10, "10 chunks expected for 10 MiB / 1 MiB");
        let mut joined = Vec::with_capacity(pt.len());
        for c in chunks {
            joined.extend_from_slice(&c);
        }
        assert_eq!(joined.len(), pt.len(), "byte length matches");
        assert_eq!(joined, pt, "byte-equal round-trip");
    }

    #[tokio::test]
    async fn s4e6_single_chunk_for_small_object() {
        // Plaintext smaller than chunk_size → chunk_count=1. The
        // chunk_count field offset is unchanged between S4E5 and
        // S4E6 (both at body[12..16]); only the salt width differs.
        let kr = keyring_single(0x77);
        let pt = b"tiny payload, smaller than chunk_size";
        let ct = encrypt_v2_chunked(pt, &kr, 1024 * 1024).unwrap();
        assert_eq!(
            u32::from_be_bytes([ct[12], ct[13], ct[14], ct[15]]),
            1,
            "small plaintext = single chunk",
        );
        let stream = decrypt_chunked_stream(ct, &kr);
        let chunks = collect_chunks(stream).await.expect("stream ok");
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].as_ref(), pt);
    }

    #[tokio::test]
    async fn s4e6_tampered_chunk_n_reports_chunk_index() {
        // v0.8.1 #57: same tamper-detect contract as the S4E5
        // version, just with the wider 24-byte header. Tamper
        // byte inside chunk index 3 (= 4th chunk) — the stream
        // must yield 3 successful chunks, then ChunkAuthFailed { 3 }.
        let kr = keyring_single(0x91);
        let chunk_size = 1024;
        let pt = vec![0xCD_u8; chunk_size * 8]; // 8 chunks
        let mut ct = encrypt_v2_chunked(&pt, &kr, chunk_size).unwrap().to_vec();
        // Locate chunk 3's first ciphertext byte: header (24) + 3 *
        // (tag 16 + ct 1024) + tag 16 = 24 + 3*1040 + 16 = 3160.
        let target = S4E6_HEADER_BYTES + 3 * (TAG_LEN + chunk_size) + TAG_LEN;
        ct[target] ^= 0x42;
        let stream = decrypt_chunked_stream(bytes::Bytes::from(ct), &kr);
        let mut s = std::pin::pin!(stream);
        // Chunks 0, 1, 2 must succeed.
        for expected_i in 0..3_u32 {
            let item = s.next().await.expect("yield");
            item.unwrap_or_else(|e| panic!("chunk {expected_i}: {e:?}"));
        }
        // Chunk 3 fails with the right index.
        let err = s.next().await.expect("yield error").unwrap_err();
        assert!(
            matches!(err, SseError::ChunkAuthFailed { chunk_index: 3 }),
            "got {err:?}",
        );
    }

    #[tokio::test]
    async fn s4e5_back_compat_s4e2_blob_rejected_with_clear_error() {
        // Feeding an S4E2 frame to decrypt_chunked_stream should
        // surface BadMagic on the first poll (NOT silently fall
        // back — the caller is expected to peek_magic and dispatch).
        let kr = keyring_single(0x12);
        let s4e2 = encrypt_v2(b"a v2 blob, not chunked", &kr);
        let stream = decrypt_chunked_stream(s4e2, &kr);
        let result = collect_chunks(stream).await;
        let err = result.unwrap_err();
        assert!(matches!(err, SseError::BadMagic { .. }), "got {err:?}");
    }

    #[test]
    fn s4e6_salt_randomness_smoke() {
        // 8-byte salt → birthday paradox 50% collision at ~2^32
        // (~4.3 billion) PUTs. 1024 PUTs → effectively zero
        // expected collisions; we don't enforce zero, just
        // sanity-check the salt actually differs more than half
        // the time (catches a stuck PRNG without a 4-billion-PUT
        // test).
        let kr = keyring_single(0x33);
        let mut salts = std::collections::HashSet::new();
        let n = 1024;
        for _ in 0..n {
            let ct = encrypt_v2_chunked(b"x", &kr, 64).unwrap();
            let mut salt = [0u8; 8];
            salt.copy_from_slice(&ct[16..24]);
            salts.insert(salt);
        }
        assert!(
            salts.len() > n / 2,
            "expected most of the {n} salts to be unique (got {} unique)",
            salts.len(),
        );
    }

    #[test]
    fn s4e6_chunk_size_zero_invalid() {
        let kr = keyring_single(0x66);
        let err = encrypt_v2_chunked(b"hi", &kr, 0).unwrap_err();
        assert!(matches!(err, SseError::ChunkSizeInvalid));
    }

    #[tokio::test]
    async fn s4e6_truncated_body_reports_frame_truncated() {
        // Truncate inside chunk 2's tag → ChunkFrameTruncated, not
        // panic, not silent success. Header is now 24 bytes (S4E6).
        let kr = keyring_single(0xA1);
        let chunk_size = 256;
        let pt = vec![0u8; chunk_size * 4];
        let ct = encrypt_v2_chunked(&pt, &kr, chunk_size).unwrap();
        // Truncate to inside chunk 2's tag: header + chunk0 + chunk1
        // + 8B partial of chunk2's tag.
        let trunc = S4E6_HEADER_BYTES + 2 * (TAG_LEN + chunk_size) + 8;
        let truncated = bytes::Bytes::copy_from_slice(&ct[..trunc]);
        let stream = decrypt_chunked_stream(truncated, &kr);
        let result = collect_chunks(stream).await;
        let err = result.unwrap_err();
        assert!(
            matches!(err, SseError::ChunkFrameTruncated { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn s4e6_decrypt_buffered_round_trip_via_top_level_decrypt() {
        // Sync `decrypt(blob, &keyring)` must also accept the
        // chunked frames (back-compat path for callers that need
        // the whole plaintext).
        let kr = keyring_single(0xDE);
        let pt = b"buffered sync decrypt path".repeat(32);
        let ct = encrypt_v2_chunked(&pt, &kr, 13).unwrap();
        let plain = decrypt(&ct, &kr).expect("buffered S4E6 decrypt ok");
        assert_eq!(plain.as_ref(), pt.as_slice());
    }

    #[tokio::test]
    async fn s4e6_unknown_key_id_in_frame_errors() {
        // Encrypt under id=7, decrypt under a keyring that lacks id=7.
        let kr_put = SseKeyring::new(7, key32(0xCC));
        let kr_get = keyring_single(0xCC); // only id=1
        let ct = encrypt_v2_chunked(b"orphan key", &kr_put, 64).unwrap();
        // Sync path
        let err = decrypt(&ct, &kr_get).unwrap_err();
        assert!(matches!(err, SseError::KeyNotInKeyring { id: 7 }), "got {err:?}");
        // Stream path
        let stream = decrypt_chunked_stream(ct, &kr_get);
        let result = collect_chunks(stream).await;
        assert!(
            matches!(result, Err(SseError::KeyNotInKeyring { id: 7 })),
            "got {result:?}",
        );
    }

    #[tokio::test]
    async fn s4e6_final_chunk_smaller_than_chunk_size() {
        // Plaintext = 2.5 chunks → final chunk holds half the bytes.
        // S4E6 header = 24 bytes → total on-disk = 24 + 48 + 250.
        let kr = keyring_single(0xEF);
        let chunk_size = 100;
        let pt: Vec<u8> = (0..250_u32).map(|i| i as u8).collect();
        let ct = encrypt_v2_chunked(&pt, &kr, chunk_size).unwrap();
        assert_eq!(
            u32::from_be_bytes([ct[12], ct[13], ct[14], ct[15]]),
            3,
            "ceil(250/100) = 3 chunks",
        );
        // Total on-disk: 24 header + 3 tags (48) + 250 plaintext = 322.
        assert_eq!(ct.len(), S4E6_HEADER_BYTES + 48 + 250);
        let stream = decrypt_chunked_stream(ct, &kr);
        let chunks = collect_chunks(stream).await.expect("stream ok");
        assert_eq!(chunks.len(), 3);
        assert_eq!(chunks[0].len(), 100);
        assert_eq!(chunks[1].len(), 100);
        assert_eq!(chunks[2].len(), 50, "final chunk is the remainder");
        let joined: Vec<u8> = chunks.iter().flat_map(|c| c.iter().copied()).collect();
        assert_eq!(joined, pt);
    }

    // -----------------------------------------------------------------------
    // v0.8.1 #57: S4E6-specific tests added on top of the renamed
    // s4e6_* battery above. Keep these focused on what's *new*:
    //   - back-compat read of legacy S4E5 blobs
    //   - 24-bit chunk_count cap
    //   - the parse_s4e6_header public API
    // -----------------------------------------------------------------------

    #[test]
    fn s4e6_back_compat_read_s4e5_blob() {
        // Synthesize a "v0.8.0 vintage" S4E5 blob via the test-only
        // helper, then prove the v0.8.1 gateway decrypts it under
        // the same keyring — both via sync `decrypt` (buffered)
        // and the streaming path. Without this, every S4E5 object
        // in production becomes unreadable after the upgrade.
        let kr = keyring_single(0x57);
        let pt = b"v0.8.0 vintage chunked SSE-S4 object".repeat(64);
        let s4e5 = encrypt_v2_chunked_s4e5_for_test(&pt, &kr, 91).unwrap();
        // Confirm the test fixture really is S4E5 magic + 20-byte header.
        assert_eq!(&s4e5[..4], SSE_MAGIC_V5, "fixture must be S4E5");
        assert_eq!(peek_magic(&s4e5), Some("S4E5"));
        // Sync decrypt path (top-level `decrypt`, dispatches V5 + V6).
        let plain_sync = decrypt(&s4e5, &kr).expect("sync S4E5 decrypt ok");
        assert_eq!(plain_sync.as_ref(), pt.as_slice());
        // Streaming decrypt path — must also accept S4E5.
        let collected = futures::executor::block_on(async {
            let stream = decrypt_chunked_stream(s4e5.clone(), &kr);
            collect_chunks(stream).await
        })
        .expect("stream S4E5 decrypt ok");
        let mut joined = Vec::with_capacity(pt.len());
        for c in collected {
            joined.extend_from_slice(&c);
        }
        assert_eq!(joined, pt, "S4E5 streaming round-trip byte-equal");
    }

    #[test]
    fn s4e6_layout_24_bytes_header() {
        // Sanity check: the S4E6 fixed header is exactly 24 bytes
        // (vs 20 for S4E5). Catches an accidental const drift in a
        // future PR.
        assert_eq!(S4E6_HEADER_BYTES, 24);
        assert_eq!(S4E6_PER_CHUNK_OVERHEAD, TAG_LEN);
        assert_eq!(S4E6_HEADER_BYTES, S4E5_HEADER_BYTES + 4);
    }

    #[test]
    fn s4e6_parse_header_round_trip() {
        // parse_s4e6_header is the public mirror of the internal
        // parse_chunked_header, useful for admin tools. Verify it
        // returns the same field values that encrypt_v2_chunked wrote.
        let kr = keyring_single(0xAB);
        let chunk_size = 256;
        let pt = vec![1u8; 7 * chunk_size];
        let ct = encrypt_v2_chunked(&pt, &kr, chunk_size).unwrap();
        let hdr = parse_s4e6_header(&ct).expect("parse ok");
        assert_eq!(hdr.key_id, 1);
        assert_eq!(hdr.chunk_size, chunk_size as u32);
        assert_eq!(hdr.chunk_count, 7);
        assert_eq!(hdr.salt.len(), 8);
        // Bad magic on a non-S4E6 blob → BadMagic.
        let bogus = b"S4E2\x01\x00\x00\x00........................";
        let err = parse_s4e6_header(bogus).unwrap_err();
        assert!(matches!(err, SseError::BadMagic { .. }), "got {err:?}");
        // Truncation → ChunkFrameTruncated.
        let err2 = parse_s4e6_header(&ct[..10]).unwrap_err();
        assert!(matches!(err2, SseError::ChunkFrameTruncated { .. }), "got {err2:?}");
    }

    #[test]
    fn s4e6_salt_uniqueness_smoke_16m() {
        // v0.8.1 #57 security regression detection: with the
        // 4-byte S4E5 salt, ~65,536 PUTs already had ~50%
        // birthday collision (the bug that motivated this patch).
        // With the 8-byte S4E6 salt the expected collisions over
        // 65,536 PUTs is ~2^16 * 2^16 / 2^65 ≈ 2^-33 — i.e.
        // effectively zero.
        //
        // We can't actually run 16M PUTs in unit-test wall-clock
        // (each PUT does an AES-GCM encrypt), so we run a fast
        // smoke (16k) and additionally validate the math: at the
        // S4E5 4-byte salt width, 16k PUTs would already give a
        // ~3.1% collision probability by birthday bound; at the
        // S4E6 8-byte salt that drops to ~3.6e-11. The smoke test
        // therefore *would* show collisions if we'd accidentally
        // shipped the 4-byte salt — confirming the regression
        // detector.
        let kr = keyring_single(0xA6);
        let mut salts = std::collections::HashSet::with_capacity(16384);
        let n = 16384_usize;
        let mut collisions_top4 = 0usize;
        let mut top4_seen = std::collections::HashSet::with_capacity(16384);
        for _ in 0..n {
            let ct = encrypt_v2_chunked(b"x", &kr, 64).unwrap();
            let mut salt = [0u8; 8];
            salt.copy_from_slice(&ct[16..24]);
            salts.insert(salt);
            // Side-channel: count collisions on just the *first 4
            // bytes* of the 8-byte salt. If we'd kept the old
            // 4-byte salt, this collision count would be the only
            // collision count — and at n=16k it should be ~62
            // (birthday: n^2/(2 * 2^32) = 16384^2/2^33 ≈ 31, with
            // some noise). The full 8-byte salt test passes if the
            // FULL salts are all unique while the truncated-to-4
            // count is non-zero, proving the extra 4 bytes really
            // are doing the security work.
            let mut top4 = [0u8; 4];
            top4.copy_from_slice(&salt[..4]);
            if !top4_seen.insert(top4) {
                collisions_top4 += 1;
            }
        }
        assert_eq!(
            salts.len(),
            n,
            "all 8-byte salts must be unique across {n} PUTs (got {} unique)",
            salts.len(),
        );
        // Sanity check the regression detector: at 16k PUTs with a
        // 4-byte salt, birthday math predicts ~31 collisions on
        // average. Anything in the 0..200 range is statistically
        // believable for 16k uniform 32-bit draws; we only assert
        // ">= 1" (i.e. at least one collision happened — which
        // would have been a real bug under S4E5).
        eprintln!(
            "s4e6_salt_uniqueness_smoke_16m: 16k PUTs, full 8B salts \
             all unique ({}/{}), simulated 4B-truncated salt yielded \
             {} collisions (this is what S4E5 would have shipped)",
            salts.len(),
            n,
            collisions_top4,
        );
        // Don't make the test flaky on the simulated number (it's a
        // statistical signal); just leave the eprintln for the
        // operator audit log when the test runs verbose.
    }

    #[test]
    fn s4e6_max_chunks_24bit() {
        // The S4E6 nonce embeds the chunk index as 24-bit BE, so
        // chunk_count > 2^24 - 1 must surface ChunkCountTooLarge
        // at PUT time. We can't actually run a 16M-chunk encrypt
        // in unit-test wall-clock (16M AES-GCM tag verifies even
        // on AES-NI is several minutes), but we can verify the
        // CAP constant matches expectations + exercise the cap by
        // picking a chunk_size that forces overflow on a tiny
        // plaintext.
        assert_eq!(S4E6_MAX_CHUNK_COUNT, (1u32 << 24) - 1);
        assert_eq!(S4E6_MAX_CHUNK_COUNT, 16_777_215);

        // chunk_size=1 + plaintext.len()=16_777_216 → 16M+1 chunks
        // → over the cap → ChunkCountTooLarge. Allocating a 16
        // MiB plaintext is fine.
        let kr = keyring_single(0xC4);
        let pt = vec![0u8; (S4E6_MAX_CHUNK_COUNT as usize) + 1]; // 16,777,216 B
        let err = encrypt_v2_chunked(&pt, &kr, 1).unwrap_err();
        assert!(
            matches!(
                err,
                SseError::ChunkCountTooLarge {
                    got: 16_777_216,
                    max: 16_777_215
                }
            ),
            "got {err:?}",
        );

        // And just under the cap (chunk_count = 16_777_215) should
        // succeed. We pick chunk_size that produces exactly the cap
        // so the inner loop only runs N times. 16M chunk-encrypts
        // would be slow, so test with a smaller cap-near config
        // that exercises the same boundary check: 1023 chunks of 1
        // byte each = 1023 chunks well under the cap → success.
        // The actual on-cap encrypt is exercised by the buffered
        // decrypt path through `parse_chunked_header`.
        let pt_ok = vec![0u8; 1023];
        let ct = encrypt_v2_chunked(&pt_ok, &kr, 1).expect("under-cap PUT must succeed");
        let hdr = parse_s4e6_header(&ct).unwrap();
        assert_eq!(hdr.chunk_count, 1023);

        // Synthesize a frame that *claims* chunk_count > cap and
        // verify the parser rejects it (defensive: a tampered
        // header should not loop the walker 16M+ times).
        let mut tampered = ct.to_vec();
        // Rewrite chunk_count BE to S4E6_MAX_CHUNK_COUNT + 1 = 2^24.
        let bad = (S4E6_MAX_CHUNK_COUNT + 1).to_be_bytes();
        tampered[12..16].copy_from_slice(&bad);
        let err2 = parse_s4e6_header(&tampered).unwrap_err();
        assert!(
            matches!(
                err2,
                SseError::ChunkCountTooLarge { got: 16_777_216, max: 16_777_215 }
            ),
            "got {err2:?}",
        );
    }

    #[test]
    fn s4e6_nonce_v6_layout() {
        // Direct unit test on nonce_v6: prefix b'E', then 8B salt,
        // then 24-bit BE chunk_index. The high byte of u32
        // chunk_index must be dropped (caller-validated cap).
        let salt = [0xAA_u8; 8];
        let n0 = nonce_v6(&salt, 0);
        assert_eq!(n0[0], b'E');
        assert_eq!(&n0[1..9], &salt);
        assert_eq!(&n0[9..12], &[0, 0, 0]);
        let n1 = nonce_v6(&salt, 1);
        assert_eq!(&n1[9..12], &[0, 0, 1]);
        let n_mid = nonce_v6(&salt, 0x123456);
        assert_eq!(&n_mid[9..12], &[0x12, 0x34, 0x56]);
        let n_max = nonce_v6(&salt, S4E6_MAX_CHUNK_COUNT);
        assert_eq!(&n_max[9..12], &[0xFF, 0xFF, 0xFF]);
    }

    #[tokio::test]
    async fn s4e6_tampered_salt_byte_fails_aead() {
        // Flipping a single byte of the 8-byte salt in the header
        // must invalidate every chunk's AES-GCM tag (salt is in
        // the AAD). Confirms the salt expansion didn't drop
        // header authentication.
        let kr = keyring_single(0xB6);
        let pt = b"salt-in-aad coverage".repeat(64);
        let mut ct = encrypt_v2_chunked(&pt, &kr, 128).unwrap().to_vec();
        // Salt bytes 16..24 — flip the middle byte.
        ct[20] ^= 0x01;
        let err = decrypt(&ct, &kr).unwrap_err();
        assert!(
            matches!(err, SseError::ChunkAuthFailed { chunk_index: 0 }),
            "got {err:?}",
        );
    }

    // -----------------------------------------------------------------------
    // v0.8.2 #64: pre-allocation guard for chunked SSE frames
    //
    // The buffered decrypt path used to call `Vec::with_capacity(chunk_size
    // * chunk_count)` *before* validating either factor. A 24-byte malicious
    // S4E6 header could declare a multi-PB plaintext and trigger an instant
    // OOM / panic on a tiny ciphertext. Verify the guard rejects every
    // adversarial header pattern before any allocation happens.
    // -----------------------------------------------------------------------

    /// Build a minimal S4E6 header with attacker-controlled chunk_size /
    /// chunk_count (no chunks attached — the body is exactly 24 bytes).
    /// Used by the DoS tests below to synthesize malicious frames without
    /// running an encrypt.
    fn synth_s4e6_header(chunk_size: u32, chunk_count: u32) -> Vec<u8> {
        let mut blob = Vec::with_capacity(S4E6_HEADER_BYTES);
        blob.extend_from_slice(SSE_MAGIC_V6);
        blob.push(ALGO_AES_256_GCM);
        blob.extend_from_slice(&1_u16.to_be_bytes()); // key_id = 1
        blob.push(0); // reserved
        blob.extend_from_slice(&chunk_size.to_be_bytes());
        blob.extend_from_slice(&chunk_count.to_be_bytes());
        blob.extend_from_slice(&[0u8; 8]); // 8-byte salt
        debug_assert_eq!(blob.len(), S4E6_HEADER_BYTES);
        blob
    }

    #[test]
    fn s4e6_header_claims_huge_size_rejected_pre_alloc() {
        // 1 GiB chunk_size × 100 chunks = 100 GiB declared plaintext, but
        // the body the attacker actually shipped is only 100 bytes. The
        // pre-alloc guard's cap arm fires (100 GiB > 5 GiB default cap)
        // *before* the walker / `Vec::with_capacity(100 GiB)` — surfaces
        // as ChunkFrameTooLarge.
        let kr = keyring_single(0x01);
        let chunk_size: u32 = 1 << 30; // 1 GiB
        let chunk_count: u32 = 100;
        let mut blob = synth_s4e6_header(chunk_size, chunk_count);
        // Pad with 100 random bytes — the attack model: tiny payload,
        // monster header.
        blob.extend_from_slice(&[0u8; 100]);
        let err = decrypt_chunked_buffered_default(&blob, &kr).unwrap_err();
        assert!(
            matches!(err, SseError::ChunkFrameTooLarge { .. }),
            "expected ChunkFrameTooLarge (declared 100 GiB > 5 GiB cap), got {err:?}",
        );
        // Same input, tighter caller-supplied cap (1 MiB): still
        // ChunkFrameTooLarge. No panic, no OOM either way.
        let err2 = decrypt_chunked_buffered(&blob, &kr, 1024 * 1024).unwrap_err();
        assert!(
            matches!(err2, SseError::ChunkFrameTooLarge { .. }),
            "expected ChunkFrameTooLarge under tighter cap, got {err2:?}",
        );
    }

    #[test]
    fn s4e6_header_chunk_size_x_chunk_count_overflows_u64() {
        // chunk_size = u32::MAX, chunk_count > 1 → product > u64 cap?
        // No — u32::MAX * u32::MAX fits in u64 (~2^64). To force u64
        // overflow we'd need both > 2^32. But chunk_count is capped to
        // 16M (S4E6_MAX_CHUNK_COUNT) by the earlier check, so the
        // realistic adversarial maximum is u32::MAX * 16M ≈ 2^56 — well
        // under u64::MAX. The overflow path is therefore *theoretically*
        // unreachable on S4E6 (24-bit chunk_count cap protects it), but
        // we still test it via S4E5 which has no 24-bit cap on
        // chunk_count: a 4-byte salt frame with chunk_size = u32::MAX
        // and chunk_count = u32::MAX gives 2^64 - 2^33 + 1 — fits u64
        // but adding the 16-byte tag overhead × u32::MAX chunks
        // overflows. Verify ChunkFrameTooLarge surfaces.
        let kr = keyring_single(0x02);
        // Synthesize an S4E5 header (20 bytes) with maximally
        // adversarial chunk_size + chunk_count.
        let mut blob = Vec::with_capacity(S4E5_HEADER_BYTES);
        blob.extend_from_slice(SSE_MAGIC_V5);
        blob.push(ALGO_AES_256_GCM);
        blob.extend_from_slice(&1_u16.to_be_bytes());
        blob.push(0);
        blob.extend_from_slice(&u32::MAX.to_be_bytes()); // chunk_size = 2^32 - 1
        blob.extend_from_slice(&u32::MAX.to_be_bytes()); // chunk_count = 2^32 - 1
        blob.extend_from_slice(&[0u8; 4]); // 4-byte S4E5 salt
        debug_assert_eq!(blob.len(), S4E5_HEADER_BYTES);
        let err = decrypt_chunked_buffered_default(&blob, &kr).unwrap_err();
        assert!(
            matches!(err, SseError::ChunkFrameTooLarge { .. }),
            "expected ChunkFrameTooLarge for u64 overflow, got {err:?}",
        );

        // Also smoke the same input through `parse_chunked_header`
        // directly (the streaming path) — must error, never panic.
        let direct = parse_chunked_header(&blob, usize::MAX).unwrap_err();
        assert!(
            matches!(direct, SseError::ChunkFrameTooLarge { .. }),
            "streaming path: expected ChunkFrameTooLarge, got {direct:?}",
        );
    }

    #[test]
    fn s4e6_header_within_max_body_bytes_passes() {
        // 1 MiB chunk_size × 100 chunks = 100 MiB declared plaintext —
        // well under the 5 GiB default cap. The header validation must
        // NOT reject this; instead it falls through to chunk-walk +
        // AES-GCM verify (which then fails on this synthetic frame
        // because we didn't write any ciphertext, so we expect
        // ChunkFrameTruncated *not* ChunkFrameTooLarge).
        let kr = keyring_single(0x03);
        let chunk_size: u32 = 1024 * 1024; // 1 MiB
        let chunk_count: u32 = 100;
        let mut blob = synth_s4e6_header(chunk_size, chunk_count);
        // Append the full declared chunk array so the truncation arm
        // doesn't fire — 100 chunks × (16 B tag + 1 MiB ct) = 100 MiB
        // + 1.6 KiB tags. We write zeros; AES-GCM verify will fail on
        // chunk 0, but that proves the pre-alloc guard *let it through*.
        let chunk_array_size =
            (chunk_count as usize) * (S4E6_PER_CHUNK_OVERHEAD + chunk_size as usize);
        blob.resize(blob.len() + chunk_array_size, 0);
        let err =
            decrypt_chunked_buffered(&blob, &kr, DEFAULT_MAX_BODY_BYTES).unwrap_err();
        // The guard let it through (we got past parse_chunked_header)
        // and AES-GCM tag verify failed on chunk 0 — that's the right
        // failure mode. ChunkFrameTooLarge would mean the cap fired
        // (a regression of this test). KeyNotInKeyring would mean the
        // header parsed but the key id (1) wasn't present (also a
        // regression — the keyring has id=1 active). Anything else is
        // a guard-too-strict bug.
        assert!(
            matches!(err, SseError::ChunkAuthFailed { chunk_index: 0 }),
            "expected ChunkAuthFailed (guard let it through), got {err:?}",
        );
    }

    #[test]
    fn s4e6_header_exceeds_max_body_bytes_rejected() {
        // 1 MiB × 6000 chunks = 6 GiB declared plaintext > 5 GiB cap.
        // Must reject as ChunkFrameTooLarge before any alloc. We don't
        // attach the 6 GiB chunk array to the body — the cap arm only
        // looks at the declared `chunk_size × chunk_count`, not the
        // actual body length, so a tiny body suffices to exercise the
        // cap.
        let kr = keyring_single(0x04);
        let chunk_size: u32 = 1024 * 1024; // 1 MiB
        let chunk_count: u32 = 6000;
        let blob = synth_s4e6_header(chunk_size, chunk_count);
        // Body is exactly the 24-byte header, no chunks attached.
        // body.len() = 24 ≤ max_total (~6 GiB) so the trailing-bytes
        // check does NOT fire; the 6 GiB > 5 GiB cap check does.
        let err = decrypt_chunked_buffered(&blob, &kr, DEFAULT_MAX_BODY_BYTES).unwrap_err();
        assert!(
            matches!(err, SseError::ChunkFrameTooLarge { .. }),
            "expected ChunkFrameTooLarge (6 GiB declared > 5 GiB cap), got {err:?}",
        );

        // Directly exercise the cap arm with a tighter cap (1 MiB)
        // and a 100 MiB declared plaintext that fits fully in the
        // body, so the cap is unambiguously the deciding factor.
        let chunk_size_b: u32 = 1024 * 1024; // 1 MiB
        let chunk_count_b: u32 = 100;
        let mut blob_b = synth_s4e6_header(chunk_size_b, chunk_count_b);
        let pad_b =
            (chunk_count_b as usize) * (S4E6_PER_CHUNK_OVERHEAD + chunk_size_b as usize);
        blob_b.resize(blob_b.len() + pad_b, 0);
        // Cap = 1 MiB, declared plaintext = 100 MiB → ChunkFrameTooLarge.
        let err_b = decrypt_chunked_buffered(&blob_b, &kr, 1024 * 1024).unwrap_err();
        assert!(
            matches!(err_b, SseError::ChunkFrameTooLarge { .. }),
            "expected ChunkFrameTooLarge (cap < declared), got {err_b:?}",
        );
    }

    #[test]
    fn s4e6_random_header_never_panics() {
        // DoS regression — feed 100k random byte sequences shaped like
        // chunked SSE headers to `parse_chunked_header`. Every result
        // must be Ok or Err; no panic, no OOM. This exercises the
        // arithmetic-overflow + truncation arms of the v0.8.2 #64
        // guard against adversarial inputs the previous unit tests
        // didn't enumerate.
        //
        // We use a fixed seed (deterministic) rather than proptest
        // here so the test is repeatable across CI runs without
        // pulling in shrink machinery for a pure no-panic property.
        use rand::{Rng, SeedableRng, rngs::StdRng};
        let mut rng = StdRng::seed_from_u64(0xC0FF_EE64_6464_64DE);
        let mut max_body_bytes_choices = [
            0_usize,
            1024,
            1024 * 1024,
            DEFAULT_MAX_BODY_BYTES,
            usize::MAX,
        ]
        .iter()
        .copied()
        .cycle();
        for _ in 0..100_000 {
            // Body length in [0, 256] — tiny on purpose: most random
            // bytes won't be a valid header, but we want the parser
            // to robustly reject every shape (truncated, wrong magic,
            // wrong algo, declared-vs-actual mismatch, overflow).
            let body_len = rng.gen_range(0..=256_usize);
            let mut body = vec![0u8; body_len];
            rng.fill(body.as_mut_slice());
            // Bias 1/4 of trials toward valid magic so the deeper
            // arithmetic paths get exercised, not just the BadMagic
            // early-out.
            if body_len >= 4 && rng.gen_bool(0.25) {
                if rng.gen_bool(0.5) {
                    body[..4].copy_from_slice(SSE_MAGIC_V5);
                } else {
                    body[..4].copy_from_slice(SSE_MAGIC_V6);
                }
            }
            let max_cap = max_body_bytes_choices.next().unwrap();
            // The contract: never panic, never alloc more than
            // `max_cap` worth of memory. We assert only no-panic
            // here; OOM behavior is implicit (the function returns
            // Err before any large alloc).
            let _ = parse_chunked_header(&body, max_cap);
        }
    }

    // Bonus: an extreme-overflow case the guard is specifically
    // hardened against — chunk_count = u32::MAX with the per-chunk
    // overhead multiplication forced to overflow u64. Catches a
    // future refactor that would replace `checked_mul` with `*`.
    #[test]
    fn s4e5_extreme_overflow_chunk_count_u32_max() {
        let kr = keyring_single(0x05);
        // u32::MAX chunk_size × u32::MAX chunk_count overflows u64
        // when adding the 16 * u32::MAX tag overhead. (Strictly:
        // chunk_size × chunk_count = (2^32-1)^2 ≈ 2^64 - 2^33 + 1
        // — already u64-saturating; the +tag step then overflows.)
        // The guard's `checked_add` chain must catch this.
        let mut blob = Vec::with_capacity(S4E5_HEADER_BYTES);
        blob.extend_from_slice(SSE_MAGIC_V5);
        blob.push(ALGO_AES_256_GCM);
        blob.extend_from_slice(&1_u16.to_be_bytes());
        blob.push(0);
        blob.extend_from_slice(&u32::MAX.to_be_bytes());
        blob.extend_from_slice(&u32::MAX.to_be_bytes());
        blob.extend_from_slice(&[0u8; 4]);
        let err = decrypt_chunked_buffered_default(&blob, &kr).unwrap_err();
        assert!(
            matches!(err, SseError::ChunkFrameTooLarge { .. }),
            "expected ChunkFrameTooLarge for extreme overflow, got {err:?}",
        );
    }
}