1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
//! `s3s::S3` 実装 — `s3s_aws::Proxy` への delegation を default にしつつ、
//! `put_object` / `get_object` 経路で `s4_codec::CodecRegistry` を呼ぶ。
//!
//! ## カバー範囲 (Phase 1 月 2)
//!
//! - 圧縮 hook あり: `put_object`, `get_object`
//! - 純 delegation (圧縮なし): `head_bucket`, `list_buckets`, `create_bucket`, `delete_bucket`,
//! `head_object`, `delete_object`, `delete_objects`, `copy_object`, `list_objects`,
//! `list_objects_v2`, `create_multipart_upload`, `upload_part`,
//! `complete_multipart_upload`, `abort_multipart_upload`, `list_multipart_uploads`,
//! `list_parts`
//! - 未対応 (デフォルトで NotImplemented): その他 80+ ops (Tagging / ACL / Lifecycle 等は Phase 2)
//!
//! ## アーキテクチャ
//!
//! - `S4Service<B>` は backend (B: S3) と `Arc<CodecRegistry>` と `Arc<dyn CodecDispatcher>`
//! を保持する。`CodecRegistry` 経由で複数 codec を抱えられるので、ひとつの S4 インスタンスが
//! 複数 codec で書かれた object を透過的に GET できる
//! - PUT: dispatcher が body の先頭 sample から codec を選び、registry で compress、
//! manifest を S3 metadata に書いて backend に forward
//! - GET: backend から取得 → metadata から manifest を復元 → registry.decompress で
//! manifest 指定の codec で解凍 → 元の bytes を return
//!
//! ## 既知の制限事項
//!
//! - **Multipart Upload は per-part 圧縮が未実装**: 現状は upload_part を素通し。
//! Phase 1 月 2 後半で per-part compress + complete_multipart_upload で manifest 集約。
//! - **PUT body は memory に collect**: max_body_bytes 上限あり (default 5 GiB = S3 単発 PUT 上限)。
//! Streaming-aware 圧縮は Phase 2。
use std::sync::Arc;
use base64::Engine as _;
use bytes::BytesMut;
use s3s::dto::*;
use s3s::{S3, S3Error, S3ErrorCode, S3Request, S3Response, S3Result};
use s4_codec::index::{FrameIndex, build_index_from_body, decode_index, encode_index, sidecar_key};
use s4_codec::multipart::{
FRAME_HEADER_BYTES, FrameHeader, FrameIter, S3_MULTIPART_MIN_PART_BYTES, pad_to_minimum,
write_frame,
};
use s4_codec::{ChunkManifest, CodecDispatcher, CodecKind, CodecRegistry, CompressTelemetry};
use std::time::Instant;
use tracing::{debug, info};
use crate::blob::{
bytes_to_blob, chain_sample_with_rest, collect_blob, collect_with_sample, peek_sample,
};
use crate::streaming::{
cpu_zstd_decompress_stream, pick_chunk_size, streaming_compress_to_frames,
supports_streaming_compress, supports_streaming_decompress,
};
/// PUT body の先頭 sampling で渡す最大 byte 数。
const SAMPLE_BYTES: usize = 4096;
/// v0.8 #55: stamp the GPU pipeline metrics (`s4_gpu_compress_seconds`,
/// `s4_gpu_throughput_bytes_per_sec`, `s4_gpu_oom_total`) from a
/// `CompressTelemetry` returned by `CodecRegistry::compress_with_telemetry`.
/// CPU codecs (`gpu_seconds = None`) are no-ops here — they're already
/// covered by the existing `s4_request_latency_seconds` / `s4_bytes_*`
/// counters in the request-level `record_put` / `record_get` calls.
#[inline]
fn stamp_gpu_compress_telemetry(tel: &CompressTelemetry) {
if let Some(secs) = tel.gpu_seconds {
crate::metrics::record_gpu_compress(tel.codec, secs, tel.bytes_in, tel.bytes_out);
}
if tel.oom {
crate::metrics::record_gpu_oom(tel.codec);
}
}
/// v0.7 #49: percent-encoding set covering everything that is **not** an
/// `unreserved` character per RFC 3986 §2.3, **plus** we additionally
/// encode the path-reserved sub-delims that `http::Uri` rejects in a
/// path segment (`?`, `#`, `%`, control bytes, space, etc.). We
/// deliberately keep `/` un-encoded because S3 keys legally use `/` as
/// a logical separator and the rest of the synthetic URI relies on the
/// path layout `/{bucket}/{key}` round-tripping byte-for-byte.
const URI_KEY_ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'`')
.add(b'{')
.add(b'}')
.add(b'|')
.add(b'\\')
.add(b'^')
.add(b'[')
.add(b']')
.add(b'%');
/// v0.7 #49: build the synthetic `/{bucket}/{key}` request URI used by
/// the sidecar / replication helpers when they re-enter the backend
/// trait without going through the HTTP layer. S3 object keys can
/// contain spaces, control bytes, and arbitrary Unicode that would
/// make `format!(...).parse::<http::Uri>()` panic; we percent-encode
/// the key bytes (RFC 3986 path segment) and the bucket name (defensive
/// — bucket names are normally DNS-safe, but the helper is the single
/// choke-point) before splicing them in. If the encoded form *still*
/// fails to parse (extremely unlikely once everything outside the
/// unreserved set is escaped) we surface a typed `400 InvalidObjectName`
/// instead of crashing the worker.
pub(crate) fn safe_object_uri(bucket: &str, key: &str) -> S3Result<http::Uri> {
use percent_encoding::utf8_percent_encode;
let bucket_enc = utf8_percent_encode(bucket, URI_KEY_ENCODE_SET);
let key_enc = utf8_percent_encode(key, URI_KEY_ENCODE_SET);
let raw = format!("/{bucket_enc}/{key_enc}");
raw.parse::<http::Uri>().map_err(|e| {
// S3 spec uses `InvalidObjectName` (HTTP 400) for keys that
// can't be represented in a request URI. The generated
// `S3ErrorCode` enum doesn't expose a typed variant for it,
// so we round-trip through `from_bytes` which preserves the
// canonical wire string while falling back to InvalidArgument
// if even that lookup fails (cannot happen at runtime — kept
// as a belt-and-suspenders branch so this helper never
// panics).
let code = S3ErrorCode::from_bytes(b"InvalidObjectName")
.unwrap_or(S3ErrorCode::InvalidArgument);
S3Error::with_message(
code,
format!("object key cannot be encoded as a request URI: {e}"),
)
})
}
/// v0.4 #20: captured at the start of a handler, before the request is
/// consumed by the backend call, so the matching `record_access` at
/// end-of-request can fill in the structured access log entry.
struct AccessLogPreamble {
remote_ip: Option<String>,
requester: Option<String>,
request_uri: String,
user_agent: Option<String>,
}
pub struct S4Service<B: S3> {
/// Wrapped in `Arc` so the v0.6 #40 cross-bucket replication
/// dispatcher can clone it into a detached `tokio::spawn` task
/// (Arc::clone is cheap; backend trait methods take `&self` so no
/// other handler is affected by the indirection).
backend: Arc<B>,
registry: Arc<CodecRegistry>,
dispatcher: Arc<dyn CodecDispatcher>,
max_body_bytes: usize,
policy: Option<crate::policy::SharedPolicy>,
/// v0.3 #13: surfaced as the `aws:SecureTransport` Condition key. Set
/// to `true` when the listener is wrapped in TLS (or ACME), so policies
/// gating "deny if not over TLS" can do their job. Defaults to `false`
/// (HTTP); set via [`S4Service::with_secure_transport`] at boot.
secure_transport: bool,
/// v0.4 #19: optional per-(principal, bucket) token-bucket limiter.
rate_limits: Option<crate::rate_limit::SharedRateLimits>,
/// v0.4 #20: optional S3-style access log emitter.
access_log: Option<crate::access_log::SharedAccessLog>,
/// v0.4 #21 / v0.5 #29: optional server-side encryption keyring
/// (AES-256-GCM). When set, every PUT body gets wrapped in S4E2
/// (with the keyring's active key id) after the compress + framing
/// steps; every GET that sniffs as S4E1/S4E2 is decrypted before
/// frame parsing. A `with_sse_key(...)` call wraps the supplied
/// key in a 1-slot keyring so single-key (v0.4) operators get the
/// same behaviour they had before, just on the v2 frame.
sse_keyring: Option<crate::sse::SharedSseKeyring>,
/// v0.5 #34: optional first-class versioning state machine. When
/// `Some(...)`, S4-server itself owns the per-bucket versioning
/// state + per-(bucket, key) version chain; PUT / GET / DELETE /
/// list_object_versions / get_bucket_versioning /
/// put_bucket_versioning handlers consult the manager instead of
/// passing through. When `None` (default), the legacy
/// backend-passthrough behaviour applies so existing v0.4
/// deployments are unaffected until they explicitly call
/// `with_versioning(...)`.
versioning: Option<Arc<crate::versioning::VersioningManager>>,
/// v0.5 #28: optional SSE-KMS envelope-encryption backend. When
/// `Some(...)`, PUTs carrying `x-amz-server-side-encryption: aws:kms`
/// generate a fresh DEK via the backend, encrypt the body with it
/// (S4E4 frame), and persist only the wrapped DEK. GETs sniffing as
/// S4E4 unwrap the DEK through the same backend before decrypt.
/// `kms_default_key_id` is used when the request omits an explicit
/// `x-amz-server-side-encryption-aws-kms-key-id` (mirrors AWS S3
/// bucket-default behaviour).
kms: Option<Arc<dyn crate::kms::KmsBackend>>,
kms_default_key_id: Option<String>,
/// v0.5 #30: optional Object Lock (WORM) enforcement layer. When
/// `Some(...)`, `delete_object` and overwrite-style `put_object`
/// consult the manager and refuse the operation with HTTP 403
/// `AccessDenied` while the object is locked (Compliance until
/// expiry, Governance unless the bypass header is set, or any time
/// a legal hold is on). PUT also auto-applies the bucket-default
/// retention to brand-new objects when configured. When `None`
/// (default), the legacy backend-passthrough behaviour applies, so
/// existing v0.4 deployments are unaffected until they explicitly
/// call `with_object_lock(...)`.
object_lock: Option<Arc<crate::object_lock::ObjectLockManager>>,
/// v0.6 #38: optional first-class CORS bucket configuration manager.
/// When `Some(...)`, S4-server itself owns per-bucket CORS rules and
/// `put_bucket_cors` / `get_bucket_cors` / `delete_bucket_cors`
/// consult the manager instead of passing through to the backend.
/// `handle_preflight` (public method on `S4Service`) routes OPTIONS-
/// style preflight matching through the same store; the actual HTTP
/// OPTIONS routing wire-up at the listener level is a follow-up
/// (s3s framework does not surface OPTIONS as a typed handler).
cors: Option<Arc<crate::cors::CorsManager>>,
/// v0.6 #36: optional first-class S3 Inventory manager. When
/// `Some(...)`, S4-server itself owns per-(bucket, id) inventory
/// configurations and `put_bucket_inventory_configuration` /
/// `get_bucket_inventory_configuration` /
/// `list_bucket_inventory_configurations` /
/// `delete_bucket_inventory_configuration` consult the manager
/// instead of passing through to the backend. The actual periodic
/// CSV emission is driven by a tokio task in `main.rs` that calls
/// `InventoryManager::run_once_for_test` on a fixed cadence; the
/// service handlers below only deal with config-level CRUD.
inventory: Option<Arc<crate::inventory::InventoryManager>>,
/// v0.6 #35: optional first-class S3 bucket-notification manager.
/// When `Some(...)`, S4-server itself owns per-bucket notification
/// configurations and `put_bucket_notification_configuration` /
/// `get_bucket_notification_configuration` consult the manager
/// instead of passing through to the backend. Successful PUT /
/// DELETE handlers fire matching destinations on a detached tokio
/// task (best-effort; see `crate::notifications::dispatch_event`).
notifications: Option<Arc<crate::notifications::NotificationManager>>,
/// v0.6 #37: optional first-class S3 Lifecycle configuration
/// manager. When `Some(...)`, S4-server itself owns per-bucket
/// lifecycle rules and `put_bucket_lifecycle_configuration` /
/// `get_bucket_lifecycle_configuration` /
/// `delete_bucket_lifecycle` consult the manager instead of
/// passing through to the backend. The actual background scanner
/// (list_objects_v2 -> evaluate -> delete / metadata-rewrite per
/// rule) is a v0.7+ follow-up; the test path
/// `S4Service::run_lifecycle_once_for_test` exercises the
/// evaluator end-to-end so this v0.6 #37 wiring is enough to ship
/// the configuration-management half without putting a
/// half-wired bucket-walk in front of users.
lifecycle: Option<Arc<crate::lifecycle::LifecycleManager>>,
/// v0.6 #39: optional first-class object + bucket Tagging manager.
/// When `Some(...)`, S4-server itself owns per-(bucket, key) and
/// per-bucket tag state — `PutObjectTagging` /
/// `GetObjectTagging` / `DeleteObjectTagging` /
/// `PutBucketTagging` / `GetBucketTagging` /
/// `DeleteBucketTagging` route through the manager (replacing the
/// previous backend-passthrough behaviour). `put_object` also
/// pre-parses the `x-amz-tagging` header / `Tagging` input field
/// so the IAM policy evaluator can gate on
/// `s3:RequestObjectTag/<key>` and `s3:ExistingObjectTag/<key>`.
/// On a successful PUT the parsed tags are persisted; on a
/// successful DELETE the matching tag entry is dropped.
tagging: Option<Arc<crate::tagging::TagManager>>,
/// v0.6 #40: optional first-class cross-bucket replication manager.
/// When `Some(...)`, S4-server itself owns per-bucket replication
/// rules; `PutBucketReplication` / `GetBucketReplication` /
/// `DeleteBucketReplication` route through the manager (replacing
/// the previous backend-passthrough behaviour). On every successful
/// `put_object` the manager's rule list is consulted; the
/// highest-priority matching enabled rule wins, the per-key status
/// is recorded as `Pending`, and the source body and metadata are
/// handed to a detached tokio task that PUTs to the destination
/// bucket through the same backend. The replica is stamped with
/// `x-amz-replication-status: REPLICA` in its metadata; the
/// source-side status is updated to `Completed` on success or
/// `Failed` after the 3-attempt retry budget is exhausted (drop
/// counter bumps in either-side case so dashboards see the loss).
/// `head_object` / `get_object` echo the recorded status back as
/// `x-amz-replication-status` so consumers can poll progress.
/// Limited to single-instance (same `S4Service`) replication; true
/// cross-region (multi-instance) is a v0.7+ follow-up.
replication: Option<Arc<crate::replication::ReplicationManager>>,
/// v0.6 #42: optional MFA-Delete enforcement layer. When `Some(...)`,
/// every DELETE / DELETE-version / delete-marker / `PutBucketVersioning`
/// request against a bucket whose MFA-Delete state is `Enabled`
/// must carry `x-amz-mfa: <serial> <code>` (RFC 6238 6-digit TOTP);
/// missing or invalid tokens return HTTP 403 `AccessDenied`. When
/// `None` (default), the gate is a no-op so existing v0.4 / v0.5
/// deployments are unaffected until they explicitly call
/// `with_mfa_delete(...)`.
mfa_delete: Option<Arc<crate::mfa::MfaDeleteManager>>,
/// v0.5 #32: when `true`, every PUT must carry an SSE indicator
/// (`x-amz-server-side-encryption`, the SSE-C customer-key headers,
/// or be matched against a configured server-managed keyring/KMS).
/// Set by `--compliance-mode strict` after the boot-time
/// prerequisite check passes.
compliance_strict: bool,
/// v0.7 #47: optional SigV4a (asymmetric ECDSA-P256-SHA256) verify
/// gate. When `Some(...)`, the listener-side middleware (see
/// [`crate::routing::try_sigv4a_verify`]) inspects every incoming
/// request and short-circuits SigV4a-signed ones — verifying the
/// signature against the credential store and returning 403
/// `SignatureDoesNotMatch` / `InvalidAccessKeyId` on failure. Plain
/// SigV4 (HMAC-SHA256) requests pass through to s3s untouched. When
/// `None`, the middleware is a no-op so the existing SigV4 path is
/// unaffected (operators opt in via `--sigv4a-credentials <DIR>`).
sigv4a_gate: Option<Arc<SigV4aGate>>,
/// v0.8 #54 BUG-5..10: per-`upload_id` side-table that ferries the
/// SSE / Tagging / Object-Lock context captured at
/// `CreateMultipartUpload` time through to `UploadPart` /
/// `CompleteMultipartUpload`. Always-on (no `with_*` flag) — the
/// store is gateway-internal and idle when no multipart is in
/// flight. See [`crate::multipart_state`] for rationale.
multipart_state: Arc<crate::multipart_state::MultipartStateStore>,
/// v0.8 #52: plaintext bytes per S4E5 chunk on the SSE-S4 PUT
/// path. `0` (default) → use the legacy buffered S4E2 path
/// (whole-body AES-GCM tag, GET buffers + verifies before
/// emitting). Non-zero → use the chunked S4E5 frame so GET can
/// stream-decrypt chunk-by-chunk. Wired by `--sse-chunk-size`
/// in `main.rs`. SSE-C and SSE-KMS are intentionally unaffected
/// (chunked variants tracked in a follow-up issue).
sse_chunk_size: usize,
}
impl<B: S3> S4Service<B> {
/// AWS S3 単発 PUT の API 上限 (5 GiB)
pub const DEFAULT_MAX_BODY_BYTES: usize = 5 * 1024 * 1024 * 1024;
pub fn new(
backend: B,
registry: Arc<CodecRegistry>,
dispatcher: Arc<dyn CodecDispatcher>,
) -> Self {
Self {
backend: Arc::new(backend),
registry,
dispatcher,
max_body_bytes: Self::DEFAULT_MAX_BODY_BYTES,
policy: None,
secure_transport: false,
rate_limits: None,
access_log: None,
sse_keyring: None,
versioning: None,
kms: None,
kms_default_key_id: None,
object_lock: None,
cors: None,
inventory: None,
notifications: None,
lifecycle: None,
tagging: None,
replication: None,
mfa_delete: None,
compliance_strict: false,
sigv4a_gate: None,
multipart_state: Arc::new(crate::multipart_state::MultipartStateStore::new()),
// v0.8 #52: chunked SSE-S4 disabled by default — opt
// in via `S4Service::with_sse_chunk_size(...)` /
// `--sse-chunk-size <BYTES>`. Default keeps the legacy
// S4E2 buffered path so existing deployments are
// bit-for-bit unchanged.
sse_chunk_size: 0,
}
}
/// v0.7 #47: attach the SigV4a verify gate. Once set, the
/// listener-side middleware (`crate::routing::try_sigv4a_verify`)
/// short-circuits any incoming `AWS4-ECDSA-P256-SHA256` request,
/// verifying it against the supplied credential store and
/// returning 403 on failure. Plain SigV4 (HMAC-SHA256) requests
/// are unaffected. When the gate is unset (default), the
/// middleware skips entirely so existing SigV4 deployments keep
/// working.
#[must_use]
pub fn with_sigv4a_gate(mut self, gate: Arc<SigV4aGate>) -> Self {
self.sigv4a_gate = Some(gate);
self
}
/// v0.7 #47: borrow the attached SigV4a gate. Used by `main.rs`
/// to snapshot the gate `Arc` before the s3s `ServiceBuilder`
/// consumes the `S4Service` (the listener-side middleware needs
/// the same `Arc` because s3s' SigV4 verifier rejects SigV4a
/// algorithm tokens with "unknown algorithm" — match has to
/// happen at the hyper layer instead).
#[must_use]
pub fn sigv4a_gate(&self) -> Option<&Arc<SigV4aGate>> {
self.sigv4a_gate.as_ref()
}
/// v0.8.2 #62: borrow the multipart state store so `main.rs` can
/// snapshot the `Arc` before the s3s `ServiceBuilder` consumes
/// the `S4Service`. The background `sweep_stale` task in `main.rs`
/// holds this `Arc` and ticks once an hour to drop abandoned
/// upload contexts (and their `Zeroizing<[u8; 32]>` SSE-C keys).
#[must_use]
pub fn multipart_state(&self) -> &Arc<crate::multipart_state::MultipartStateStore> {
&self.multipart_state
}
/// v0.6 #39: attach the in-memory object + bucket Tagging manager.
/// Once set, `Put/Get/Delete` `Object/Bucket Tagging` route
/// through the manager (instead of forwarding to the backend),
/// and `put_object`'s `x-amz-tagging` parse path becomes the
/// source of `s3:RequestObjectTag/<key>` for the IAM policy
/// evaluator. The manager itself is shared via `Arc`.
#[must_use]
pub fn with_tagging(mut self, mgr: Arc<crate::tagging::TagManager>) -> Self {
self.tagging = Some(mgr);
self
}
/// v0.6 #39: borrow the attached tagging manager (test /
/// introspection — the snapshotter in `main.rs`, when wired,
/// will keep its own `Arc` clone).
#[must_use]
pub fn tag_manager(&self) -> Option<&Arc<crate::tagging::TagManager>> {
self.tagging.as_ref()
}
/// v0.6 #36: attach the in-memory S3 Inventory manager. Once set,
/// `put_bucket_inventory_configuration` /
/// `get_bucket_inventory_configuration` /
/// `list_bucket_inventory_configurations` /
/// `delete_bucket_inventory_configuration` route through the
/// manager. The actual periodic CSV / manifest emission is
/// orchestrated by a tokio task started in `main.rs`; the manager
/// itself is shared between the handler and the scheduler via
/// `Arc`.
#[must_use]
pub fn with_inventory(mut self, mgr: Arc<crate::inventory::InventoryManager>) -> Self {
self.inventory = Some(mgr);
self
}
/// v0.6 #36: borrow the attached inventory manager (test /
/// introspection — the background scheduler in `main.rs` keeps its
/// own `Arc` clone, so this accessor is for the test path that
/// invokes `run_once_for_test` directly).
#[must_use]
pub fn inventory_manager(&self) -> Option<&Arc<crate::inventory::InventoryManager>> {
self.inventory.as_ref()
}
/// v0.6 #37: attach the in-memory S3 Lifecycle configuration
/// manager. Once set, `put_bucket_lifecycle_configuration` /
/// `get_bucket_lifecycle_configuration` / `delete_bucket_lifecycle`
/// route through the manager (replacing the previous backend-
/// passthrough behaviour). The actual periodic scanner that walks
/// the source bucket and invokes Expiration / Transition /
/// NoncurrentExpiration actions is a v0.7+ follow-up — see
/// [`Self::run_lifecycle_once_for_test`] for the in-memory test
/// path that exercises the evaluator end-to-end.
#[must_use]
pub fn with_lifecycle(mut self, mgr: Arc<crate::lifecycle::LifecycleManager>) -> Self {
self.lifecycle = Some(mgr);
self
}
/// v0.6 #37: borrow the attached lifecycle manager (test /
/// introspection — the background scheduler in `main.rs` keeps its
/// own `Arc` clone, so this accessor is for the test path that
/// invokes the evaluator directly).
#[must_use]
pub fn lifecycle_manager(&self) -> Option<&Arc<crate::lifecycle::LifecycleManager>> {
self.lifecycle.as_ref()
}
/// v0.6 #37: synchronous test entry that runs the lifecycle evaluator
/// against a caller-provided list of `(key, age, size, tags)` tuples
/// and returns the `(key, action)` pairs that should fire. The actual
/// backend invocation (S3.delete_object / metadata rewrite) is left
/// to the caller — the unit + E2E tests use this to verify the
/// evaluator without spawning the (deferred) background scanner.
/// Returns an empty `Vec` when no lifecycle manager is attached or
/// no rule matches.
#[must_use]
pub fn run_lifecycle_once_for_test(
&self,
bucket: &str,
objects: &[crate::lifecycle::EvaluateBatchEntry],
) -> Vec<(String, crate::lifecycle::LifecycleAction)> {
let Some(mgr) = self.lifecycle.as_ref() else {
return Vec::new();
};
crate::lifecycle::evaluate_batch(mgr, bucket, objects)
}
/// v0.6 #35: attach the in-memory bucket-notification manager. Once
/// set, `put_bucket_notification_configuration` /
/// `get_bucket_notification_configuration` route through the manager
/// (replacing the previous backend-passthrough behaviour); successful
/// `put_object` / `delete_object` calls fire matching destinations
/// on a detached tokio task via
/// `crate::notifications::dispatch_event` (best-effort, fire-and-
/// forget — failures bump the manager's `dropped_total` counter and
/// log at warn but do NOT fail the originating S3 request).
#[must_use]
pub fn with_notifications(
mut self,
mgr: Arc<crate::notifications::NotificationManager>,
) -> Self {
self.notifications = Some(mgr);
self
}
/// v0.6 #35: borrow the attached notifications manager (test /
/// introspection — used by the metrics layer to read
/// `dropped_total`).
#[must_use]
pub fn notifications_manager(
&self,
) -> Option<&Arc<crate::notifications::NotificationManager>> {
self.notifications.as_ref()
}
/// v0.6 #35: internal helper used by the DELETE handlers to fire a
/// matching notification on a detached tokio task. No-op when no
/// manager is attached or no rule on the bucket matches the given
/// (event, key) tuple.
fn fire_delete_notification(
&self,
bucket: &str,
key: &str,
event: crate::notifications::EventType,
version_id: Option<String>,
) {
let Some(mgr) = self.notifications.as_ref() else {
return;
};
let dests = mgr.match_destinations(bucket, &event, key);
if dests.is_empty() {
return;
}
tokio::spawn(crate::notifications::dispatch_event(
Arc::clone(mgr),
bucket.to_owned(),
key.to_owned(),
event,
None,
None,
version_id,
format!("S4-{}", uuid::Uuid::new_v4()),
));
}
/// v0.6 #40: attach the in-memory cross-bucket replication manager.
/// Once set, `put_bucket_replication` / `get_bucket_replication` /
/// `delete_bucket_replication` route through the manager (replacing
/// the previous backend-passthrough behaviour); a successful
/// `put_object` whose key matches an enabled rule fires a detached
/// tokio task that PUTs the same body + metadata to the rule's
/// destination bucket, stamping the replica with
/// `x-amz-replication-status: REPLICA`. Failures after the retry
/// budget bump the manager's `dropped_total` counter and are
/// surfaced in the `s4_replication_dropped_total` Prometheus
/// counter; successes bump `s4_replication_replicated_total`.
#[must_use]
pub fn with_replication(
mut self,
mgr: Arc<crate::replication::ReplicationManager>,
) -> Self {
self.replication = Some(mgr);
self
}
/// v0.6 #40: borrow the attached replication manager (test /
/// introspection — used by the metrics layer to read
/// `dropped_total`).
#[must_use]
pub fn replication_manager(
&self,
) -> Option<&Arc<crate::replication::ReplicationManager>> {
self.replication.as_ref()
}
/// v0.6 #40: internal helper used by the PUT handlers to fire a
/// detached cross-bucket replication task. No-op when no manager
/// is attached, the source backend PUT failed, or no rule on the
/// source bucket matches the (key, tags) tuple. The `body` is the
/// post-compression / post-encryption `Bytes` that was sent to
/// the source backend (refcount-cloned), and `metadata` is the
/// metadata map that already includes the manifest /
/// `s4-encrypted` markers — the replica decodes through the same
/// path. The destination PUT runs through `Arc<B>::put_object`.
///
/// ## v0.8.2 #61: generation token + shadow-key destination
///
/// `pending_version` is the source-side `PutOutcome` minted by the
/// caller's versioning branch (or `None` for unversioned /
/// suspended buckets). When `pending_version.versioned_response`
/// is `true`, the dispatcher writes the destination under the same
/// shadow path the source uses (`<key>.__s4ver__/<vid>`) so the
/// destination's version chain receives the new version the same
/// way `?versionId=` GET resolves it. Closes audit C-1.
///
/// The dispatcher also mints a fresh `generation` token before
/// spawning, threaded through to [`crate::replication::
/// replicate_object`]. Closes audit C-3 — a stale retry of an
/// older PUT can no longer overwrite the destination's newer bytes
/// because the CAS guard sees the higher stored generation and
/// drops its destination write.
///
/// ## Asymmetric versioning policy (out of scope)
///
/// We assume source + destination buckets share the same
/// versioning policy (both Enabled or both Suspended /
/// Unversioned). Cross-bucket policy queries would require a
/// backend round-trip per replication, which is not worth it for
/// the single-instance scope. Operators who configure asymmetric
/// versioning will see destination-side `?versionId=` lookups
/// miss — documented as out-of-scope until a future per-rule
/// `destination_versioning_policy` knob lands.
// 8 args is the post-#61 shape: replication needs the
// source bucket+key, the canonical tag set for rule-matching,
// the post-codec body+metadata for the destination PUT, the
// backend-success gate, and the pending version-id for the
// shadow-key destination override. A shape struct would just
// split the (single) call site so opt for the inline form.
#[allow(clippy::too_many_arguments)]
fn spawn_replication_if_matched(
&self,
source_bucket: &str,
source_key: &str,
request_tags: &Option<crate::tagging::TagSet>,
body: &bytes::Bytes,
metadata: &Option<std::collections::HashMap<String, String>>,
backend_ok: bool,
pending_version: Option<&crate::versioning::PutOutcome>,
) where
B: Send + Sync + 'static,
{
if !backend_ok {
return;
}
let Some(mgr) = self.replication.as_ref() else {
return;
};
// Pull the request's tags into the (k, v) shape the matcher
// expects. The tagging manager would have the canonical
// post-PUT view but at this point in the pipeline it's
// already been written above; for the rule-match decision
// the request's tags are sufficient (= the tags this PUT
// applies, S3 PutObject is full-replace on tags).
let object_tags: Vec<(String, String)> = request_tags
.as_ref()
.map(|ts| ts.iter().cloned().collect())
.unwrap_or_default();
let Some(rule) = mgr.match_rule(source_bucket, source_key, &object_tags) else {
return;
};
// v0.8.2 #61: mint the per-PUT generation BEFORE the eager
// Pending stamp so the stamp itself carries the right
// generation (the CAS in `record_status_if_newer` would
// otherwise see a `generation=0` Pending and accept any
// stale retry).
let generation = mgr.next_generation();
// Eagerly mark the source key as Pending so a HEAD between
// the source PUT returning and the spawned task completing
// surfaces the in-flight state. CAS-guarded so a slower
// older PUT can't downgrade a newer Completed back to Pending.
let _ = mgr.record_status_if_newer(
source_bucket,
source_key,
generation,
crate::replication::ReplicationStatus::Pending,
);
// v0.8.2 #61: derive the destination storage key. For a
// versioning-Enabled source the destination receives the
// same shadow-key path so a `?versionId=<vid>` GET on the
// destination resolves through the same lookup the source
// uses. Suspended / Unversioned sources keep the logical
// key (= `None` override = dispatcher uses `source_key`).
let destination_key_override = pending_version
.filter(|pv| pv.versioned_response)
.map(|pv| versioned_shadow_key(source_key, &pv.version_id));
let mgr_cl = Arc::clone(mgr);
let backend = Arc::clone(&self.backend);
let body_cl = body.clone();
let metadata_cl = metadata.clone();
let source_bucket_cl = source_bucket.to_owned();
let source_key_cl = source_key.to_owned();
tokio::spawn(async move {
let do_put = move |dest_bucket: String,
dest_key: String,
dest_body: bytes::Bytes,
dest_meta: Option<std::collections::HashMap<String, String>>| {
let backend = Arc::clone(&backend);
async move {
let req = S3Request {
input: PutObjectInput {
bucket: dest_bucket,
key: dest_key,
body: Some(bytes_to_blob(dest_body)),
metadata: dest_meta,
..Default::default()
},
method: http::Method::PUT,
uri: "/".parse().unwrap(),
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
backend
.put_object(req)
.await
.map(|_| ())
.map_err(|e| format!("destination put_object: {e}"))
}
};
crate::replication::replicate_object(
rule,
source_bucket_cl,
source_key_cl,
body_cl,
metadata_cl,
do_put,
mgr_cl,
generation,
destination_key_override,
)
.await;
});
}
/// v0.6 #42: attach the in-memory MFA-Delete enforcement manager.
/// Once set, every DELETE / DELETE-version / delete-marker /
/// `PutBucketVersioning` request against a bucket whose MFA-Delete
/// state is `Enabled` requires a valid `x-amz-mfa: <serial> <code>`
/// header (RFC 6238 6-digit TOTP); the gate is a no-op for buckets
/// where MFA-Delete is `Disabled` (S3 default).
#[must_use]
pub fn with_mfa_delete(mut self, mgr: Arc<crate::mfa::MfaDeleteManager>) -> Self {
self.mfa_delete = Some(mgr);
self
}
/// v0.6 #42: borrow the attached MFA-Delete manager (test /
/// introspection — used by the snapshot path in `main.rs` to call
/// `to_json` for restart-recoverable state).
#[must_use]
pub fn mfa_delete_manager(&self) -> Option<&Arc<crate::mfa::MfaDeleteManager>> {
self.mfa_delete.as_ref()
}
/// v0.6 #38: attach the in-memory CORS configuration manager. Once
/// set, `put_bucket_cors` / `get_bucket_cors` / `delete_bucket_cors`
/// route through the manager instead of forwarding to the backend,
/// and [`Self::handle_preflight`] becomes useful for the (future)
/// listener-side OPTIONS interceptor.
#[must_use]
pub fn with_cors(mut self, mgr: Arc<crate::cors::CorsManager>) -> Self {
self.cors = Some(mgr);
self
}
/// v0.6 #38: Borrow the attached CORS manager (test / introspection).
#[must_use]
pub fn cors_manager(&self) -> Option<&Arc<crate::cors::CorsManager>> {
self.cors.as_ref()
}
/// v0.6 #38: evaluate a CORS preflight request against the bucket's
/// configured rules and, if a rule matches, return the headers that
/// the (future) listener-side OPTIONS interceptor must put on the
/// 200 response: `Access-Control-Allow-Origin`, `Access-Control-
/// Allow-Methods`, `Access-Control-Allow-Headers`, optionally
/// `Access-Control-Max-Age` and `Access-Control-Expose-Headers`.
///
/// Returns `None` when no manager is attached, no config is
/// registered for the bucket, or no rule matches the (origin,
/// method, headers) triple. The caller is responsible for turning
/// `None` into the appropriate 403 response.
///
/// **Note:** the OPTIONS routing itself (i.e. wiring this method
/// into the hyper-util listener path) is a follow-up — s3s does not
/// surface OPTIONS as a typed S3 handler, so this method is
/// currently call-able only from inside other handlers and tests.
#[must_use]
pub fn handle_preflight(
&self,
bucket: &str,
origin: &str,
method: &str,
request_headers: &[String],
) -> Option<std::collections::HashMap<String, String>> {
let mgr = self.cors.as_ref()?;
let rule = mgr.match_preflight(bucket, origin, method, request_headers)?;
let mut h = std::collections::HashMap::new();
// Echo the matched origin back. If the rule used "*" we still
// echo "*" (S3 spec — the spec does not require us to echo the
// *requesting* origin when the wildcard matched).
let allow_origin = if rule.allowed_origins.iter().any(|o| o == "*") {
"*".to_string()
} else {
origin.to_string()
};
h.insert("Access-Control-Allow-Origin".to_string(), allow_origin);
h.insert(
"Access-Control-Allow-Methods".to_string(),
rule.allowed_methods.join(", "),
);
if !rule.allowed_headers.is_empty() {
// For the Allow-Headers response, echo back the rule's
// pattern list verbatim (S3 echoes the configured list,
// including "*" if present). Browsers honour exact-match
// rules.
h.insert(
"Access-Control-Allow-Headers".to_string(),
rule.allowed_headers.join(", "),
);
}
if let Some(secs) = rule.max_age_seconds {
h.insert("Access-Control-Max-Age".to_string(), secs.to_string());
}
if !rule.expose_headers.is_empty() {
h.insert(
"Access-Control-Expose-Headers".to_string(),
rule.expose_headers.join(", "),
);
}
Some(h)
}
/// v0.5 #32: enable strict compliance mode. Every PUT must carry an
/// SSE indicator (server-side encryption header or SSE-C customer
/// key); requests without one are rejected with 400 InvalidRequest.
/// Boot-time prerequisite checking lives in the binary
/// (`validate_compliance_mode`) so this flag is purely the runtime
/// switch.
#[must_use]
pub fn with_compliance_strict(mut self, on: bool) -> Self {
self.compliance_strict = on;
self
}
/// v0.5 #30: attach the in-memory Object Lock (WORM) enforcement
/// manager. Once set, `delete_object` and overwrite-path
/// `put_object` refuse operations on locked keys with HTTP 403
/// `AccessDenied`; new PUTs to a bucket with a default retention
/// policy auto-create per-object lock state.
#[must_use]
pub fn with_object_lock(
mut self,
mgr: Arc<crate::object_lock::ObjectLockManager>,
) -> Self {
self.object_lock = Some(mgr);
self
}
/// v0.7 #45: borrow the attached Object Lock manager (read-only —
/// the lifecycle scanner uses this to skip currently-locked objects
/// before issuing `delete_object`, since an Object Lock always wins
/// over Lifecycle Expiration in AWS S3 semantics). Mirrors the
/// shape of [`Self::lifecycle_manager`] /
/// [`Self::tag_manager`] — purely additive accessor, no handler
/// behaviour change.
#[must_use]
pub fn object_lock_manager(&self) -> Option<&Arc<crate::object_lock::ObjectLockManager>> {
self.object_lock.as_ref()
}
/// v0.5 #28: attach an SSE-KMS backend. `default_key_id` is used
/// when a PUT requests SSE-KMS without naming a specific KMS key
/// (operators set this to mirror AWS S3's bucket-default key).
#[must_use]
pub fn with_kms_backend(
mut self,
kms: Arc<dyn crate::kms::KmsBackend>,
default_key_id: Option<String>,
) -> Self {
self.kms = Some(kms);
self.kms_default_key_id = default_key_id;
self
}
/// v0.5 #34: attach the first-class versioning state machine. Once
/// set, this `S4Service` owns the per-bucket versioning state +
/// per-(bucket, key) version chain; `put_object` / `get_object` /
/// `delete_object` / `list_object_versions` /
/// `get_bucket_versioning` / `put_bucket_versioning` consult the
/// manager instead of passing through to the backend. The backend
/// is still used as the byte store: Suspended / Unversioned buckets
/// keep using `<key>` directly (legacy), Enabled buckets redirect
/// each version's bytes to a shadow key
/// (`<key>.__s4ver__/<version-id>`) so older versions survive newer
/// PUTs to the same logical key.
#[must_use]
pub fn with_versioning(mut self, mgr: Arc<crate::versioning::VersioningManager>) -> Self {
self.versioning = Some(mgr);
self
}
/// v0.4 #21 (kept for back-compat): attach a single SSE-S4 key.
/// Internally wraps it in a 1-slot keyring with id=1 active, so
/// new objects ride the v0.5 S4E2 frame while previously-written
/// S4E1 bytes (this same key) still decrypt via the keyring's S4E1
/// fallback path. Operators wanting true rotation should call
/// [`Self::with_sse_keyring`] instead.
#[must_use]
pub fn with_sse_key(mut self, key: crate::sse::SharedSseKey) -> Self {
let keyring = crate::sse::SseKeyring::new(1, key);
self.sse_keyring = Some(std::sync::Arc::new(keyring));
self
}
/// v0.5 #29: attach a multi-key SSE-S4 keyring. PUT encrypts under
/// the active key (S4E2 frame stamped with that key's id); GET
/// dispatches on the body's magic — S4E1 falls back to trying every
/// key in the ring (active first) so v0.4 objects survive a
/// migration; S4E2 looks up the explicit key_id from the header.
#[must_use]
pub fn with_sse_keyring(mut self, keyring: crate::sse::SharedSseKeyring) -> Self {
self.sse_keyring = Some(keyring);
self
}
/// v0.8 #52: opt the SSE-S4 PUT path into the chunked S4E5 frame
/// (so the matching GET can stream-decrypt chunk-by-chunk
/// instead of buffering the entire body before tag verify).
/// `bytes` is the plaintext slice size — typically 1 MiB; 0
/// disables the path and reverts to the legacy S4E2 buffered
/// frame.
///
/// SSE-C (S4E3) and SSE-KMS (S4E4) are intentionally untouched:
/// the chunked envelopes for those flows are a follow-up issue
/// (the customer-key wire surface needs separate version
/// negotiation).
///
/// Has no effect when `with_sse_keyring` / `with_sse_key` is
/// not also set — the chunked path runs only on the SSE-S4
/// branch of `put_object`.
#[must_use]
pub fn with_sse_chunk_size(mut self, bytes: usize) -> Self {
self.sse_chunk_size = bytes;
self
}
/// v0.4 #20: attach an S3-style access-log emitter. Each completed
/// PUT / GET / DELETE / List handler emits one entry into the
/// emitter's buffer; a background flusher (started separately, see
/// [`crate::access_log::AccessLog::spawn_flusher`]) writes hourly
/// rotated `.log` files into the configured directory.
#[must_use]
pub fn with_access_log(mut self, log: crate::access_log::SharedAccessLog) -> Self {
self.access_log = Some(log);
self
}
/// Capture the per-request access-log preamble before the request is
/// consumed by the backend call. Returns `None` if no access logger
/// is configured (cheap early-out so the handler doesn't pay the
/// header-clone cost when access logging is off).
fn access_log_preamble<I>(&self, req: &S3Request<I>) -> Option<AccessLogPreamble> {
self.access_log.as_ref()?;
Some(AccessLogPreamble {
remote_ip: req
.headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|raw| raw.split(',').next())
.map(|s| s.trim().to_owned()),
requester: Self::principal_of(req).map(str::to_owned),
request_uri: format!("{} {}", req.method, req.uri.path()),
user_agent: req
.headers
.get("user-agent")
.and_then(|v| v.to_str().ok())
.map(str::to_owned),
})
}
/// Internal — called by handlers at end-of-request with a captured
/// preamble. Best-effort: swallows the await fast (clones Arc +
/// pushes), no error propagation back to the request path.
#[allow(clippy::too_many_arguments)]
async fn record_access(
&self,
preamble: Option<AccessLogPreamble>,
operation: &'static str,
bucket: &str,
key: Option<&str>,
http_status: u16,
bytes_sent: u64,
object_size: u64,
total_time_ms: u64,
error_code: Option<&str>,
) {
let (Some(log), Some(p)) = (self.access_log.as_ref(), preamble) else {
return;
};
log.record(crate::access_log::AccessLogEntry {
time: std::time::SystemTime::now(),
bucket: bucket.to_owned(),
remote_ip: p.remote_ip,
requester: p.requester,
operation,
key: key.map(str::to_owned),
request_uri: p.request_uri,
http_status,
error_code: error_code.map(str::to_owned),
bytes_sent,
object_size,
total_time_ms,
user_agent: p.user_agent,
})
.await;
}
/// v0.4 #19: attach a per-(principal, bucket) token-bucket rate limiter.
/// When set, every PUT / GET / DELETE / List / Copy / multipart op is
/// throttle-checked before the policy gate; throttled requests return
/// `S3ErrorCode::SlowDown` (HTTP 503) and bump
/// `s4_rate_limit_throttled_total{principal,bucket}`.
#[must_use]
pub fn with_rate_limits(mut self, rl: crate::rate_limit::SharedRateLimits) -> Self {
self.rate_limits = Some(rl);
self
}
/// Helper used by request handlers to apply the rate limit. Returns
/// `Ok(())` when allowed (or no rate limiter is configured), or a
/// `SlowDown` S3Error otherwise.
fn enforce_rate_limit<I>(&self, req: &S3Request<I>, bucket: &str) -> S3Result<()> {
let Some(rl) = self.rate_limits.as_ref() else {
return Ok(());
};
let principal_id = Self::principal_of(req);
if !rl.check(principal_id, bucket) {
crate::metrics::record_rate_limit_throttle(principal_id.unwrap_or("-"), bucket);
return Err(S3Error::with_message(
S3ErrorCode::SlowDown,
format!("rate-limited: bucket={bucket}"),
));
}
Ok(())
}
/// Tell the policy evaluator that the listener is reached over TLS
/// (or ACME). When `true`, the `aws:SecureTransport` Condition key
/// resolves to `true`. Defaults to `false`.
#[must_use]
pub fn with_secure_transport(mut self, on: bool) -> Self {
self.secure_transport = on;
self
}
#[must_use]
pub fn with_max_body_bytes(mut self, n: usize) -> Self {
self.max_body_bytes = n;
self
}
/// Attach an optional bucket policy (v0.2 #7). When `Some(...)`, every
/// PUT / GET / DELETE / List handler runs `policy.evaluate(...)` before
/// delegating to the backend; failures return `S3ErrorCode::AccessDenied`.
/// When `None` (the default), no policy enforcement happens.
#[must_use]
pub fn with_policy(mut self, policy: crate::policy::SharedPolicy) -> Self {
self.policy = Some(policy);
self
}
/// Pull the SigV4 access key id off the request's credentials, if any.
/// Used as the `principal_id` for policy evaluation.
fn principal_of<I>(req: &S3Request<I>) -> Option<&str> {
req.credentials.as_ref().map(|c| c.access_key.as_str())
}
/// v0.3 #13: build the per-request policy context from the incoming
/// `S3Request`. Pulls `aws:UserAgent` from the User-Agent header,
/// `aws:SourceIp` from the standard `X-Forwarded-For` header (most
/// production deployments are behind an LB / reverse proxy that sets
/// this), `aws:CurrentTime` from the system clock, and
/// `aws:SecureTransport` from the per-listener TLS flag.
fn request_context<I>(&self, req: &S3Request<I>) -> crate::policy::RequestContext {
let user_agent = req
.headers
.get("user-agent")
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
// X-Forwarded-For is `client, proxy1, proxy2`; the leftmost entry
// is the original client. Trim and parse leniently.
let source_ip = req
.headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|raw| raw.split(',').next())
.and_then(|s| s.trim().parse().ok());
crate::policy::RequestContext {
source_ip,
user_agent,
request_time: Some(std::time::SystemTime::now()),
secure_transport: self.secure_transport,
existing_object_tags: None,
request_object_tags: None,
extra: Default::default(),
}
}
/// Helper used by request handlers to enforce the optional policy.
/// Returns `Ok(())` when allowed (or no policy is configured), or an
/// `AccessDenied` S3Error otherwise. Bumps the policy denial Prometheus
/// counter on deny.
fn enforce_policy<I>(
&self,
req: &S3Request<I>,
action: &'static str,
bucket: &str,
key: Option<&str>,
) -> S3Result<()> {
self.enforce_policy_with_extra(req, action, bucket, key, None, None)
}
/// v0.6 #39: variant of [`Self::enforce_policy`] that lets the
/// caller plumb tag context (existing-on-object + on-request) into
/// the policy evaluator. Both arguments default to `None`, in
/// which case the resulting `RequestContext` is identical to
/// [`Self::enforce_policy`]'s — so for handlers that don't deal
/// with tags this is a transparent no-op.
fn enforce_policy_with_extra<I>(
&self,
req: &S3Request<I>,
action: &'static str,
bucket: &str,
key: Option<&str>,
request_tags: Option<&crate::tagging::TagSet>,
existing_tags: Option<&crate::tagging::TagSet>,
) -> S3Result<()> {
let Some(policy) = self.policy.as_ref() else {
return Ok(());
};
let principal_id = Self::principal_of(req);
let mut ctx = self.request_context(req);
if let Some(t) = request_tags {
ctx.request_object_tags = Some(t.clone());
}
if let Some(t) = existing_tags {
ctx.existing_object_tags = Some(t.clone());
}
let decision = policy.evaluate_with(action, bucket, key, principal_id, &ctx);
if decision.allow {
Ok(())
} else {
crate::metrics::record_policy_denial(action, bucket);
tracing::info!(
action,
bucket,
key = ?key,
principal = ?principal_id,
source_ip = ?ctx.source_ip,
user_agent = ?ctx.user_agent,
secure_transport = ctx.secure_transport,
matched_sid = ?decision.matched_sid,
effect = ?decision.matched_effect,
"S4 policy denied request"
);
Err(S3Error::with_message(
S3ErrorCode::AccessDenied,
format!("denied by S4 policy: {action} on bucket={bucket}"),
))
}
}
/// テスト用: backend を取り戻す (test helper、production では使わない).
/// v0.6 #40 で `backend` が `Arc<B>` 化したので `Arc::try_unwrap` で
/// 1-clone の場合のみ返す。共有されている (= replication dispatcher が
/// 同じ Arc を持っていて未完了) 場合は `Err` を返さず panic させる
/// (test 用途専用 helper の caller 契約を維持)。
pub fn into_backend(self) -> B {
Arc::try_unwrap(self.backend)
.unwrap_or_else(|_| panic!("into_backend: backend Arc still shared (replication dispatcher in flight?)"))
}
/// 必要 frame だけを backend に Range GET し、frame parse + decompress + slice
/// した結果を返す sidecar fast path。Range request の **帯域節約版**。
async fn partial_range_get(
&self,
req: &S3Request<GetObjectInput>,
plan: s4_codec::index::RangePlan,
client_start: u64,
client_end_exclusive: u64,
total_original: u64,
get_start: Instant,
) -> S3Result<S3Response<GetObjectOutput>> {
// 必要 byte 範囲だけを backend に partial GET
let backend_range = s3s::dto::Range::Int {
first: plan.byte_start,
last: Some(plan.byte_end_exclusive - 1),
};
let backend_input = GetObjectInput {
bucket: req.input.bucket.clone(),
key: req.input.key.clone(),
range: Some(backend_range),
..Default::default()
};
let backend_req = S3Request {
input: backend_input,
method: req.method.clone(),
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let mut backend_resp = self.backend.get_object(backend_req).await?;
let blob = backend_resp.output.body.take().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InternalError,
"backend partial GET returned empty body",
)
})?;
let bytes = collect_blob(blob, self.max_body_bytes)
.await
.map_err(internal("collect partial body"))?;
// frame parse + decompress
let mut combined = BytesMut::new();
for frame in FrameIter::new(bytes) {
let (header, payload) = frame.map_err(|e| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("partial-range frame parse: {e}"),
)
})?;
let chunk_manifest = ChunkManifest {
codec: header.codec,
original_size: header.original_size,
compressed_size: header.compressed_size,
crc32c: header.crc32c,
};
let decompressed = self
.registry
.decompress(payload, &chunk_manifest)
.await
.map_err(internal("partial-range decompress"))?;
combined.extend_from_slice(&decompressed);
}
let combined = combined.freeze();
let sliced = combined
.slice(plan.slice_start_in_combined as usize..plan.slice_end_in_combined as usize);
// response 組立て
let returned_size = sliced.len() as u64;
backend_resp.output.content_length = Some(returned_size as i64);
backend_resp.output.content_range = Some(format!(
"bytes {client_start}-{}/{total_original}",
client_end_exclusive - 1
));
backend_resp.output.checksum_crc32 = None;
backend_resp.output.checksum_crc32c = None;
backend_resp.output.checksum_crc64nvme = None;
backend_resp.output.checksum_sha1 = None;
backend_resp.output.checksum_sha256 = None;
backend_resp.output.e_tag = None;
backend_resp.output.body = Some(bytes_to_blob(sliced));
backend_resp.status = Some(http::StatusCode::PARTIAL_CONTENT);
let elapsed = get_start.elapsed();
crate::metrics::record_get(
"partial",
plan.byte_end_exclusive - plan.byte_start,
returned_size,
elapsed.as_secs_f64(),
true,
);
info!(
op = "get_object",
bucket = %req.input.bucket,
key = %req.input.key,
bytes_in = plan.byte_end_exclusive - plan.byte_start,
bytes_out = returned_size,
total_object_size = total_original,
range = true,
path = "sidecar-partial",
latency_ms = elapsed.as_millis() as u64,
"S4 partial Range GET via sidecar index"
);
Ok(backend_resp)
}
/// `<key>.s4index` sidecar object を backend に書く。失敗しても本体 PUT は
/// 成功扱いにしたいので、err は warn ログのみ (Range GET の partial path が
/// 使えなくなるが、full read fallback で意味的には正しい結果を返す)。
async fn write_sidecar(&self, bucket: &str, key: &str, index: &FrameIndex) {
let bytes = encode_index(index);
let len = bytes.len() as i64;
let sidecar = sidecar_key(key);
// v0.7 #49: synthetic re-entry URI must be percent-encoded; if
// the (already legally-arbitrary) S3 key produces something we
// cannot encode at all, drop the sidecar PUT (the GET path
// falls back to a full read on a missing sidecar) instead of
// panicking on `parse().unwrap()`.
let uri = match safe_object_uri(bucket, &sidecar) {
Ok(u) => u,
Err(e) => {
tracing::warn!(
bucket,
key,
"S4 write_sidecar skipped (key not URI-encodable): {e}"
);
return;
}
};
let put_input = PutObjectInput {
bucket: bucket.into(),
key: sidecar,
body: Some(bytes_to_blob(bytes)),
content_length: Some(len),
content_type: Some("application/x-s4-index".into()),
..Default::default()
};
let put_req = S3Request {
input: put_input,
method: http::Method::PUT,
uri,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
if let Err(e) = self.backend.put_object(put_req).await {
tracing::warn!(
bucket,
key,
"S4 write_sidecar failed (Range GET will fall back to full read): {e}"
);
}
}
/// `<key>.s4index` sidecar を backend から読み出す。なければ None。
async fn read_sidecar(&self, bucket: &str, key: &str) -> Option<FrameIndex> {
let sidecar = sidecar_key(key);
// v0.7 #49: same encode-or-bail treatment as write_sidecar.
let uri = safe_object_uri(bucket, &sidecar).ok()?;
let get_input = GetObjectInput {
bucket: bucket.into(),
key: sidecar,
..Default::default()
};
let get_req = S3Request {
input: get_input,
method: http::Method::GET,
uri,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let resp = self.backend.get_object(get_req).await.ok()?;
let blob = resp.output.body?;
let bytes = collect_blob(blob, 64 * 1024 * 1024).await.ok()?;
decode_index(bytes).ok()
}
/// Multipart object (frame 列) を解凍 → 元 bytes を再構築。
///
/// **per-frame codec dispatch**: 各 frame header に codec_id が入っているので、
/// frame ごとに registry が違う codec を呼ぶことができる。同一 object 内で
/// 異なる codec が混在していても透過的に解凍可能 (parquet 風 mixed columns 等)。
async fn decompress_multipart(&self, bytes: bytes::Bytes) -> S3Result<bytes::Bytes> {
let mut out = BytesMut::new();
for frame in FrameIter::new(bytes) {
let (header, payload) = frame.map_err(|e| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("multipart frame parse: {e}"),
)
})?;
let chunk_manifest = ChunkManifest {
codec: header.codec,
original_size: header.original_size,
compressed_size: header.compressed_size,
crc32c: header.crc32c,
};
let decompressed = self
.registry
.decompress(payload, &chunk_manifest)
.await
.map_err(internal("multipart frame decompress"))?;
out.extend_from_slice(&decompressed);
}
Ok(out.freeze())
}
}
/// Parse a CopySourceRange header value (`bytes=N-M`, `bytes=N-`, `bytes=-N`)
/// into the s3s::dto::Range used by the GetObject path. The S3 spec only
/// allows `bytes=N-M` for upload_part_copy (no suffix or open-ended), so
/// reject the other variants for parity with AWS.
fn parse_copy_source_range(s: &str) -> Result<s3s::dto::Range, String> {
let rest = s
.strip_prefix("bytes=")
.ok_or_else(|| format!("CopySourceRange must start with 'bytes=', got {s:?}"))?;
let (a, b) = rest
.split_once('-')
.ok_or_else(|| format!("CopySourceRange must be 'bytes=N-M', got {s:?}"))?;
let first: u64 = a
.parse()
.map_err(|_| format!("CopySourceRange first byte not a number: {a:?}"))?;
let last: u64 = b
.parse()
.map_err(|_| format!("CopySourceRange last byte not a number: {b:?}"))?;
if last < first {
return Err(format!("CopySourceRange last < first: {s:?}"));
}
Ok(s3s::dto::Range::Int {
first,
last: Some(last),
})
}
/// v0.5 #34: synthesize the backend storage key for a given
/// (logical key, version-id) pair on an Enabled-versioning bucket.
///
/// Uses the `__s4ver__/` infix because:
/// - it's not a substring of `.s4index` / `.s4ver` natural keys (no false-positive
/// listing filter collisions)
/// - directory-style separator keeps S3 console "browse by prefix" UX intact
/// (versions roll up under one virtual folder per object)
/// - human-readable on debug logs / `aws s3 ls`
///
/// `list_objects` / `list_objects_v2` / `list_object_versions` MUST filter
/// keys containing `.__s4ver__/` from results so customers don't see internal
/// shadow objects.
pub fn versioned_shadow_key(key: &str, version_id: &str) -> String {
format!("{key}.__s4ver__/{version_id}")
}
/// Test for the marker substring used by [`versioned_shadow_key`]. Cheap str
/// scan; both list_objects filter and the GET passthrough check use this.
fn is_versioning_shadow_key(key: &str) -> bool {
key.contains(".__s4ver__/")
}
/// v0.6 #42: wall-clock seconds since the UNIX epoch — fed to
/// `mfa::check_mfa` so the TOTP verifier can match the client's
/// authenticator app's view of "now". Falls back to `0` on the
/// (impossible-in-practice) clock-before-1970 path so the verifier
/// rejects rather than panicking.
fn current_unix_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// v0.6 #42: translate an `MfaError` into the matching S3 wire error.
///
/// - `Missing` / `SerialMismatch` / `InvalidCode` → `403 AccessDenied`
/// (S3 spec for MFA Delete: every gating failure surfaces as
/// `AccessDenied`, not a separate `MFA*` code).
/// - `Malformed` → `400 InvalidRequest` (the request itself is
/// syntactically broken, not a permission issue).
fn mfa_error_to_s3(e: crate::mfa::MfaError) -> S3Error {
match e {
crate::mfa::MfaError::Missing => S3Error::with_message(
S3ErrorCode::AccessDenied,
"MFA token required for this operation",
),
crate::mfa::MfaError::Malformed => S3Error::with_message(
S3ErrorCode::InvalidRequest,
"malformed x-amz-mfa header",
),
crate::mfa::MfaError::SerialMismatch => S3Error::with_message(
S3ErrorCode::AccessDenied,
"MFA serial does not match configured device",
),
crate::mfa::MfaError::InvalidCode => S3Error::with_message(
S3ErrorCode::AccessDenied,
"invalid MFA code",
),
}
}
fn is_multipart_object(metadata: &Option<Metadata>) -> bool {
metadata
.as_ref()
.and_then(|m| m.get(META_MULTIPART))
.map(|v| v == "true")
.unwrap_or(false)
}
const META_CODEC: &str = "s4-codec";
const META_ORIGINAL_SIZE: &str = "s4-original-size";
const META_COMPRESSED_SIZE: &str = "s4-compressed-size";
const META_CRC32C: &str = "s4-crc32c";
/// Multipart upload で per-part frame format を使ったオブジェクトであることを示す。
/// GET 時にこの flag を見て frame parser を起動する。
const META_MULTIPART: &str = "s4-multipart";
/// v0.2 #4: single-PUT でも S4F2 framed format で書かれていることを示す。
/// 旧 v0.1 single-PUT は raw 圧縮 bytes (この flag なし)。GET 時にこの flag を
/// 見て framed 経路 (= multipart と同じ FrameIter parse) に流す。
const META_FRAMED: &str = "s4-framed";
fn is_framed_v2_object(metadata: &Option<Metadata>) -> bool {
metadata
.as_ref()
.and_then(|m| m.get(META_FRAMED))
.map(|v| v == "true")
.unwrap_or(false)
}
/// v0.4 #21: detect SSE-S4 by the metadata flag we set on PUT.
fn is_sse_encrypted(metadata: &Option<Metadata>) -> bool {
metadata
.as_ref()
.and_then(|m| m.get("s4-encrypted"))
.map(|v| v == "aes-256-gcm")
.unwrap_or(false)
}
/// v0.5 #27: pull the three SSE-C headers off an input struct. The S3
/// contract is "all three or none" — partial sets are a 400.
///
/// Returns `Ok(None)` when no SSE-C headers were sent (server-managed or
/// no encryption), `Ok(Some(material))` on validated client key, and
/// `Err` for malformed or partial inputs.
fn extract_sse_c_material(
algorithm: &Option<String>,
key: &Option<String>,
md5: &Option<String>,
) -> S3Result<Option<crate::sse::CustomerKeyMaterial>> {
match (algorithm, key, md5) {
(None, None, None) => Ok(None),
(Some(a), Some(k), Some(m)) => crate::sse::parse_customer_key_headers(a, k, m)
.map(Some)
.map_err(sse_c_error_to_s3),
_ => Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"SSE-C requires all three of: x-amz-server-side-encryption-customer-{algorithm,key,key-MD5}",
)),
}
}
/// v0.5 #28: detect SSE-KMS request — `x-amz-server-side-encryption: aws:kms`.
/// Returns the key-id to wrap under, falling back to the gateway default.
fn extract_kms_key_id(
sse: &Option<ServerSideEncryption>,
sse_kms_key_id: &Option<String>,
gateway_default: Option<&str>,
) -> Option<String> {
let asks_for_kms = sse
.as_ref()
.map(|s| s.as_str() == ServerSideEncryption::AWS_KMS)
.unwrap_or(false);
if !asks_for_kms {
return None;
}
sse_kms_key_id
.clone()
.or_else(|| gateway_default.map(str::to_owned))
}
/// v0.5 #28: map kms module errors to AWS-shaped S3 error codes.
/// `KeyNotFound` is operator misconfig (400); `BackendUnavailable` is a
/// transient KMS outage (503). Other variants are 500 InternalError.
fn kms_error_to_s3(e: crate::kms::KmsError) -> S3Error {
use crate::kms::KmsError as K;
match e {
K::KeyNotFound { key_id } => S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("KMS key not found: {key_id}"),
),
K::BackendUnavailable { message } => S3Error::with_message(
S3ErrorCode::ServiceUnavailable,
format!("KMS backend unavailable: {message}"),
),
other => S3Error::with_message(
S3ErrorCode::InternalError,
format!("KMS error: {other}"),
),
}
}
/// v0.5 #27: map sse module errors to AWS-shaped S3 error codes.
/// `WrongCustomerKey` → 403 AccessDenied (matches AWS behaviour);
/// `InvalidCustomerKey` / algorithm / required / unexpected → 400.
fn sse_c_error_to_s3(e: crate::sse::SseError) -> S3Error {
use crate::sse::SseError as E;
match e {
E::WrongCustomerKey => S3Error::with_message(
S3ErrorCode::AccessDenied,
"SSE-C key does not match the key used at PUT time",
),
E::InvalidCustomerKey { reason } => S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("SSE-C: {reason}"),
),
E::CustomerKeyAlgorithmUnsupported { algo } => S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("SSE-C unsupported algorithm: {algo:?} (only AES256 is allowed)"),
),
E::CustomerKeyRequired => S3Error::with_message(
S3ErrorCode::InvalidRequest,
"object is SSE-C encrypted; supply x-amz-server-side-encryption-customer-* headers",
),
E::CustomerKeyUnexpected => S3Error::with_message(
S3ErrorCode::InvalidRequest,
"object is not SSE-C encrypted; do not send x-amz-server-side-encryption-customer-* headers",
),
other => S3Error::with_message(S3ErrorCode::InternalError, format!("SSE error: {other}")),
}
}
fn extract_manifest(metadata: &Option<Metadata>) -> Option<ChunkManifest> {
let m = metadata.as_ref()?;
let codec = m
.get(META_CODEC)
.and_then(|s| s.parse::<CodecKind>().ok())?;
let original_size = m.get(META_ORIGINAL_SIZE)?.parse().ok()?;
let compressed_size = m.get(META_COMPRESSED_SIZE)?.parse().ok()?;
let crc32c = m.get(META_CRC32C)?.parse().ok()?;
Some(ChunkManifest {
codec,
original_size,
compressed_size,
crc32c,
})
}
fn write_manifest(metadata: &mut Option<Metadata>, manifest: &ChunkManifest) {
let meta = metadata.get_or_insert_with(Default::default);
meta.insert(META_CODEC.into(), manifest.codec.as_str().into());
meta.insert(
META_ORIGINAL_SIZE.into(),
manifest.original_size.to_string(),
);
meta.insert(
META_COMPRESSED_SIZE.into(),
manifest.compressed_size.to_string(),
);
meta.insert(META_CRC32C.into(), manifest.crc32c.to_string());
}
fn internal<E: std::fmt::Display>(prefix: &'static str) -> impl FnOnce(E) -> S3Error {
move |e| S3Error::with_message(S3ErrorCode::InternalError, format!("{prefix}: {e}"))
}
/// v0.6 #41: map a `select::SelectError` to the S3 error surface. AWS
/// uses a domain-specific `InvalidSqlExpression` code for parse / unsupported
/// errors, but s3s 0.13 doesn't expose that as a typed variant — we
/// fall back to the well-known `InvalidRequest` 400 with a descriptive
/// message that includes the original error context.
fn select_error_to_s3(e: crate::select::SelectError, fmt: &str) -> S3Error {
use crate::select::SelectError;
match e {
SelectError::Parse(msg) => S3Error::with_message(
S3ErrorCode::InvalidRequest,
format!("SQL parse error: {msg}"),
),
SelectError::UnsupportedFeature(msg) => S3Error::with_message(
S3ErrorCode::InvalidRequest,
format!("unsupported SQL feature: {msg}"),
),
SelectError::RowEval(msg) => S3Error::with_message(
S3ErrorCode::InvalidRequest,
format!("SQL row evaluation error: {msg}"),
),
SelectError::InputFormat(msg) => S3Error::with_message(
S3ErrorCode::InvalidRequest,
format!("{fmt} input format error: {msg}"),
),
}
}
/// v0.5 #30: parse the `x-amz-bypass-governance-retention` header into a
/// boolean flag. AWS S3 accepts `true` (case-insensitive); any other value
/// (including missing) is treated as `false`.
fn parse_bypass_governance_header(headers: &http::HeaderMap) -> bool {
headers
.get("x-amz-bypass-governance-retention")
.and_then(|v| v.to_str().ok())
.map(|s| s.eq_ignore_ascii_case("true"))
.unwrap_or(false)
}
/// Convert s3s `Timestamp` into a `chrono::DateTime<Utc>` by formatting it
/// as an RFC3339 string and re-parsing through `chrono`. The string format
/// avoids pulling the `time` crate (transitive dep of s3s, not declared by
/// s4-server) into our direct deps. Returns `None` if the format/parse fails
/// or the value is outside `chrono`'s supported range.
fn timestamp_to_chrono_utc(ts: &Timestamp) -> Option<chrono::DateTime<chrono::Utc>> {
let mut buf = Vec::new();
ts.format(s3s::dto::TimestampFormat::DateTime, &mut buf).ok()?;
let s = std::str::from_utf8(&buf).ok()?;
chrono::DateTime::parse_from_rfc3339(s)
.ok()
.map(|dt| dt.with_timezone(&chrono::Utc))
}
/// Inverse of [`timestamp_to_chrono_utc`] — emit RFC3339 (the s3s
/// `DateTime` wire format) and re-parse via `Timestamp::parse`.
fn chrono_utc_to_timestamp(dt: chrono::DateTime<chrono::Utc>) -> Timestamp {
// chrono's RFC3339 output format matches s3s' parser ("...Z" with
// optional sub-second precision). Fall back to UNIX_EPOCH if anything
// unexpected happens — we never produce malformed strings, so this
// branch is unreachable in practice.
let s = dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
Timestamp::parse(s3s::dto::TimestampFormat::DateTime, &s).unwrap_or_default()
}
/// v0.6 #39: convert our internal [`crate::tagging::TagSet`] into the
/// s3s `Vec<Tag>` wire shape used on `GetObject/BucketTaggingOutput`.
/// Both halves of every pair land in the `Some(_)` slot — AWS marks
/// the field optional but always populates it on response.
fn tagset_to_aws(set: &crate::tagging::TagSet) -> Vec<Tag> {
set.iter()
.map(|(k, v)| Tag {
key: Some(k.clone()),
value: Some(v.clone()),
})
.collect()
}
/// v0.6 #39: inverse of [`tagset_to_aws`] for input handlers. Missing
/// keys / values become empty strings (mirrors AWS, which rejects
/// `<Key/>` with InvalidTag at the parser layer; downstream
/// `TagSet::validate` then enforces our size limits).
fn aws_to_tagset(tags: &[Tag]) -> Result<crate::tagging::TagSet, crate::tagging::TagError> {
let pairs = tags
.iter()
.map(|t| {
(
t.key.clone().unwrap_or_default(),
t.value.clone().unwrap_or_default(),
)
})
.collect();
crate::tagging::TagSet::from_pairs(pairs)
}
/// `Range` request を decompressed object サイズ `total` に適用して `(start, end_exclusive)`
/// を返す。`Range::Int { first, last }` は `bytes=first-last` (last は inclusive)、
/// `Range::Suffix { length }` は末尾 `length` byte。S3 仕様に準拠。
pub fn resolve_range(range: &s3s::dto::Range, total: u64) -> Result<(u64, u64), String> {
if total == 0 {
return Err("cannot range-get zero-length object".into());
}
match range {
s3s::dto::Range::Int { first, last } => {
let start = *first;
let end_inclusive = match last {
Some(l) => (*l).min(total - 1),
None => total - 1,
};
if start > end_inclusive || start >= total {
return Err(format!(
"range bytes={start}-{:?} out of object size {total}",
last
));
}
Ok((start, end_inclusive + 1))
}
s3s::dto::Range::Suffix { length } => {
let len = (*length).min(total);
Ok((total - len, total))
}
}
}
#[async_trait::async_trait]
impl<B: S3> S3 for S4Service<B> {
// === 圧縮を挟む path (PUT) ===
#[tracing::instrument(
name = "s4.put_object",
skip(self, req),
fields(bucket = %req.input.bucket, key = %req.input.key, codec, bytes_in, bytes_out, latency_ms)
)]
async fn put_object(
&self,
mut req: S3Request<PutObjectInput>,
) -> S3Result<S3Response<PutObjectOutput>> {
let put_start = Instant::now();
let put_bucket = req.input.bucket.clone();
let put_key = req.input.key.clone();
let access_preamble = self.access_log_preamble(&req);
self.enforce_rate_limit(&req, &put_bucket)?;
// v0.6 #39: parse `x-amz-tagging` (URL-encoded query string) so
// the IAM policy gate sees the request's tags via
// `s3:RequestObjectTag/<key>`. `existing_object_tags` is also
// resolved from the Tagging manager (when wired) so
// `s3:ExistingObjectTag/<key>` works on overwrite.
let request_tags: Option<crate::tagging::TagSet> = req
.input
.tagging
.as_deref()
.map(crate::tagging::parse_tagging_header)
.transpose()
.map_err(|e| S3Error::with_message(S3ErrorCode::InvalidArgument, e.to_string()))?;
let existing_tags: Option<crate::tagging::TagSet> = self
.tagging
.as_ref()
.and_then(|m| m.get_object_tags(&put_bucket, &put_key));
self.enforce_policy_with_extra(
&req,
"s3:PutObject",
&put_bucket,
Some(&put_key),
request_tags.as_ref(),
existing_tags.as_ref(),
)?;
// v0.5 #30: an Object Lock-protected key cannot be overwritten by
// a non-versioned PUT (Suspended / Unversioned bucket). Enabled
// bucket PUTs are exempt because they materialise a fresh
// version under a shadow key (`<key>.__s4ver__/<vid>`) — the
// locked version's bytes are untouched. The check mirrors the
// delete path (Compliance never bypassable, Governance via the
// bypass header, legal hold never).
if let Some(mgr) = self.object_lock.as_ref()
&& let Some(state) = mgr.get(&put_bucket, &put_key)
{
let bucket_versioned_enabled = self
.versioning
.as_ref()
.map(|v| v.state(&put_bucket) == crate::versioning::VersioningState::Enabled)
.unwrap_or(false);
if !bucket_versioned_enabled {
let bypass = parse_bypass_governance_header(&req.headers);
let now = chrono::Utc::now();
if !state.can_delete(now, bypass) {
crate::metrics::record_policy_denial("s3:PutObject", &put_bucket);
return Err(S3Error::with_message(
S3ErrorCode::AccessDenied,
"Access Denied because object protected by object lock",
));
}
}
}
// v0.5 #30: per-PUT explicit retention / legal hold (S3
// `x-amz-object-lock-mode`, `x-amz-object-lock-retain-until-date`,
// `x-amz-object-lock-legal-hold`). Captured before the body
// moves into the backend; persisted into the manager only on
// backend success below.
let explicit_lock_mode: Option<crate::object_lock::LockMode> = req
.input
.object_lock_mode
.as_ref()
.and_then(|m| crate::object_lock::LockMode::from_aws_str(m.as_str()));
let explicit_retain_until: Option<chrono::DateTime<chrono::Utc>> = req
.input
.object_lock_retain_until_date
.as_ref()
.and_then(timestamp_to_chrono_utc);
let explicit_legal_hold_on: Option<bool> = req
.input
.object_lock_legal_hold_status
.as_ref()
.map(|s| s.as_str().eq_ignore_ascii_case("ON"));
if let Some(blob) = req.input.body.take() {
// Sample 4 KiB から codec を決定。streaming-aware codec なら streaming
// compress fast path、そうでなければ従来の collect-then-compress。
let (sample, rest_stream) = peek_sample(blob, SAMPLE_BYTES)
.await
.map_err(internal("peek put sample"))?;
let sample_len = sample.len().min(SAMPLE_BYTES);
// v0.8 #56: pass the request's Content-Length (when present) so
// the sampling dispatcher can promote large objects to a GPU
// codec. Chunked transfers (no Content-Length) keep CPU.
let total_size_hint = req.input.content_length.and_then(|n| u64::try_from(n).ok());
let kind = self
.dispatcher
.pick_with_size_hint(&sample[..sample_len], total_size_hint)
.await;
// Passthrough buys nothing from S4F2 wrapping (no compression =
// no per-chunk frame to skip past) and the +28-byte header
// overhead breaks size-sensitive callers that expect a true
// pass-through. So passthrough always uses the legacy raw-blob
// path; only compressing codecs go through the framed path.
let use_framed = supports_streaming_compress(kind) && kind != CodecKind::Passthrough;
let (compressed, manifest, is_framed) = if use_framed {
// streaming fast path: input は memory に collect しない
let chained = chain_sample_with_rest(sample, rest_stream);
debug!(
bucket = ?req.input.bucket,
key = ?req.input.key,
codec = kind.as_str(),
path = "streaming-framed",
"S4 put_object: compressing (streaming, S4F2 multi-frame)"
);
// v0.4 #16: pick the chunk size based on the request's
// Content-Length when known, falling back to the 4 MiB
// default for chunked transfers.
let chunk_size = pick_chunk_size(req.input.content_length.map(|n| n as u64));
let (body, manifest) = streaming_compress_to_frames(
chained,
Arc::clone(&self.registry),
kind,
chunk_size,
)
.await
.map_err(internal("streaming framed compress"))?;
(body, manifest, true)
} else {
// GPU codec 等で streaming-aware でないものは bytes-buffered path
// (raw 圧縮 bytes、framed なし — back-compat 互換 path)
let bytes = collect_with_sample(sample, rest_stream, self.max_body_bytes)
.await
.map_err(internal("collect put body (buffered path)"))?;
debug!(
bucket = ?req.input.bucket,
key = ?req.input.key,
bytes = bytes.len(),
codec = kind.as_str(),
path = "buffered",
"S4 put_object: compressing (buffered, raw blob)"
);
// v0.8 #55: telemetry-returning compress so we can stamp
// GPU-pipeline Prometheus metrics (`s4_gpu_compress_seconds`,
// throughput gauge, OOM counter) for nvcomp / dietgpu codecs.
// CPU codecs come back with `gpu_seconds = None` and the
// stamp helper short-circuits — no extra cost on CPU path.
let (compress_res, tel) =
self.registry.compress_with_telemetry(bytes, kind).await;
stamp_gpu_compress_telemetry(&tel);
let (body, m) = compress_res.map_err(internal("registry compress"))?;
(body, m, false)
};
write_manifest(&mut req.input.metadata, &manifest);
if is_framed {
// v0.2 #4: framed body であることを GET 側に伝える meta flag。
req.input
.metadata
.get_or_insert_with(Default::default)
.insert(META_FRAMED.into(), "true".into());
}
// 重要: content_length を圧縮後サイズで更新する。
// これを忘れると下流 (aws-sdk-s3 → S3) が宣言サイズ分の bytes を
// 待ち続けて RequestTimeout で失敗する (S3 仕様)。
req.input.content_length = Some(compressed.len() as i64);
// body を書き換えたので、客側が送ってきた original body 用の
// checksum / MD5 ヘッダは無効化する (そのまま転送すると下流 S3 が
// XAmzContentChecksumMismatch を返す)。S4 自身の整合性は
// ChunkManifest.crc32c で担保している。
req.input.checksum_algorithm = None;
req.input.checksum_crc32 = None;
req.input.checksum_crc32c = None;
req.input.checksum_crc64nvme = None;
req.input.checksum_sha1 = None;
req.input.checksum_sha256 = None;
req.input.content_md5 = None;
let original_size = manifest.original_size;
let compressed_size = manifest.compressed_size;
let codec_label = manifest.codec.as_str();
// framed body は GET 側で sidecar partial-fetch を効かせるため
// build_index_from_body で sidecar を組み立てて backend に PUT する。
let sidecar_index = if is_framed {
s4_codec::index::build_index_from_body(&compressed).ok()
} else {
None
};
// v0.4 #21 / v0.5 #29 / v0.5 #27: encrypt-after-compress.
// Precedence:
// - SSE-C headers present → per-request customer key (S4E3)
// - server-managed keyring configured → active key (S4E2)
// - neither → no encryption (raw compressed body)
// The `s4-encrypted: aes-256-gcm` metadata flag is set in
// both encrypted modes; the on-disk frame magic distinguishes
// S4E1 / S4E2 / S4E3 so GET picks the right decrypt path.
// v0.7 #48 BUG-2/3 fix: take() the SSE fields off req.input
// so the encryption headers are NOT forwarded to the
// backend. S4 owns the encrypt-then-store contract; if we
// leave the headers in place, real S3-compat backends
// (MinIO / AWS) try to apply their own SSE on top and
// either reject (MinIO requires HTTPS for SSE-C) or fail
// (MinIO has no KMS configured). MemoryBackend ignored
// these so mock tests passed.
let sse_c_alg = req.input.sse_customer_algorithm.take();
let sse_c_key = req.input.sse_customer_key.take();
let sse_c_md5 = req.input.sse_customer_key_md5.take();
let sse_header = req.input.server_side_encryption.take();
let sse_kms_key = req.input.ssekms_key_id.take();
let sse_c_material = extract_sse_c_material(&sse_c_alg, &sse_c_key, &sse_c_md5)?;
// v0.5 #28: SSE-KMS request? Resolves to None unless the
// request asks for `aws:kms` AND a key id is available
// (explicit header or gateway default). When set, we'll
// generate a per-object DEK below.
let kms_key_id = extract_kms_key_id(
&sse_header,
&sse_kms_key,
self.kms_default_key_id.as_deref(),
);
// v0.5 #32: in compliance-strict mode, every PUT must
// declare SSE — either client-supplied (SSE-C), KMS, or by
// virtue of a server-side keyring being configured (which
// applies SSE-S4 to every PUT automatically). Requests that
// would otherwise land as plain compressed bytes are
// rejected with 400 InvalidRequest.
if self.compliance_strict
&& sse_c_material.is_none()
&& kms_key_id.is_none()
&& self.sse_keyring.is_none()
&& sse_header.as_ref().map(|s| s.as_str())
!= Some(ServerSideEncryption::AES256)
{
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"compliance-mode strict: PUT must include x-amz-server-side-encryption \
(AES256 or aws:kms) or x-amz-server-side-encryption-customer-* headers",
));
}
// SSE-C and SSE-KMS are mutually exclusive on a single PUT
// (AWS S3 returns 400 InvalidArgument). SSE-C wins by spec.
if sse_c_material.is_some() && kms_key_id.is_some() {
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
"SSE-C and SSE-KMS cannot be used together on the same PUT",
));
}
// KMS path needs to call generate_dek().await before the
// body_to_send branch; capture the result here.
//
// v0.8.1 #58: the plaintext DEK lives in three places
// during one PUT:
//
// 1. The `Zeroizing<Vec<u8>>` returned by `generate_dek`
// — wiped when the binding `dek` falls out of scope at
// the end of this `if`-arm.
// 2. The stack `[u8; 32]` we copy into for `SseSource::Kms`
// — wrapped in `Zeroizing<[u8; 32]>` so it's wiped when
// the outer `kms_wrap` `Option` is dropped at the end
// of `put_object`.
// 3. AES-GCM internal key state inside the `aes-gcm`
// crate during `encrypt_with_source` — out of scope
// for this fix; tracked separately in v0.8.2.
let kms_wrap: Option<(zeroize::Zeroizing<[u8; 32]>, crate::kms::WrappedDek)> =
if let Some(ref key_id) = kms_key_id {
let kms = self.kms.as_ref().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"SSE-KMS requested but no --kms-local-dir / --kms-aws-region is configured on this gateway",
)
})?;
// `dek` is `Zeroizing<Vec<u8>>`; deref + slice access
// works unchanged via `Deref<Target=Vec<u8>>`.
let (dek, wrapped) = kms
.generate_dek(key_id)
.await
.map_err(kms_error_to_s3)?;
if dek.len() != 32 {
return Err(S3Error::with_message(
S3ErrorCode::InternalError,
format!("KMS backend returned a DEK of {} bytes (expected 32)", dek.len()),
));
}
let mut dek_arr: zeroize::Zeroizing<[u8; 32]> =
zeroize::Zeroizing::new([0u8; 32]);
dek_arr.copy_from_slice(&dek);
// `dek` (the `Zeroizing<Vec<u8>>`) is dropped at the
// end of this scope, wiping the heap allocation.
Some((dek_arr, wrapped))
} else {
None
};
// v0.7 #48 BUG-4 fix: stamp the SSE *type* into metadata
// alongside `s4-encrypted` so HEAD (which doesn't fetch the
// body) can echo the correct `x-amz-server-side-encryption`
// value. Without this, HEAD on an SSE-KMS object would not
// echo `aws:kms` because the frame magic is only available
// on the body (which HEAD doesn't read).
let body_to_send = if let Some(ref m) = sse_c_material {
let meta = req.input.metadata.get_or_insert_with(Default::default);
meta.insert("s4-encrypted".into(), "aes-256-gcm".into());
meta.insert("s4-sse-type".into(), "AES256".into());
meta.insert("s4-sse-c-key-md5".into(),
base64::engine::general_purpose::STANDARD.encode(m.key_md5));
crate::sse::encrypt_with_source(
&compressed,
crate::sse::SseSource::CustomerKey {
key: &m.key,
key_md5: &m.key_md5,
},
)
} else if let Some((ref dek, ref wrapped)) = kms_wrap {
let meta = req.input.metadata.get_or_insert_with(Default::default);
meta.insert("s4-encrypted".into(), "aes-256-gcm".into());
meta.insert("s4-sse-type".into(), "aws:kms".into());
meta.insert("s4-sse-kms-key-id".into(), wrapped.key_id.clone());
// v0.8.1 #58: `dek` is `&Zeroizing<[u8; 32]>`; `SseSource::Kms`
// wants `&[u8; 32]`. Rust auto-derefs `&Zeroizing<T>` to
// `&T` here via `Deref<Target=T>`, so the binding picks
// up the inner array reference without copying. The array
// stays in the `Zeroizing` wrapper that owns it and gets
// wiped when `kms_wrap` drops at the end of `put_object`.
let dek_ref: &[u8; 32] = dek;
crate::sse::encrypt_with_source(
&compressed,
crate::sse::SseSource::Kms { dek: dek_ref, wrapped },
)
} else if let Some(keyring) = self.sse_keyring.as_ref() {
// SSE-S4 is server-driven transparent encryption; the
// client didn't ask for SSE. We stamp `s4-encrypted`
// (internal flag the GET path needs) but deliberately
// do NOT stamp `s4-sse-type` — that lights up the HEAD
// echo of `x-amz-server-side-encryption: AES256`,
// which would falsely advertise AWS-style SSE-S3
// semantics the operator didn't request.
let meta = req.input.metadata.get_or_insert_with(Default::default);
meta.insert("s4-encrypted".into(), "aes-256-gcm".into());
// v0.8 #52: when `--sse-chunk-size > 0` is configured,
// emit the chunked S4E5 frame so the matching GET can
// stream-decrypt instead of buffering 5 GiB before
// emitting a byte. Falls back to the buffered S4E2
// frame at chunk_size=0 (default) so existing
// deployments are bit-for-bit unchanged.
if self.sse_chunk_size > 0 {
crate::sse::encrypt_v2_chunked(
&compressed,
keyring,
self.sse_chunk_size,
)
.map_err(|e| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("SSE-S4 chunked encrypt failed: {e}"),
)
})?
} else {
crate::sse::encrypt_v2(&compressed, keyring)
}
} else {
compressed.clone()
};
// v0.6 #40: capture the about-to-be-sent body + metadata so
// the replication dispatcher (run after the source PUT
// succeeds) can hand the same backend bytes to the
// destination bucket. `Bytes` clone is cheap (refcounted).
let replication_body = body_to_send.clone();
let replication_metadata = req.input.metadata.clone();
// v0.7 #48 BUG-1 fix: SSE encryption (S4E1/E2/E3/E4 frames)
// makes the body longer than the post-compression bytes
// (header + nonce + tag overhead). The earlier
// content_length stamp at compressed.len() is now stale, so
// re-stamp from the actual bytes about to be sent or the
// backend (real S3 / MinIO) rejects with
// `StreamLengthMismatch`. MemoryBackend never validated
// this, which is why mock-only tests passed.
req.input.content_length = Some(body_to_send.len() as i64);
req.input.body = Some(bytes_to_blob(body_to_send));
// v0.5 #34: pre-allocate a version-id when the bucket is
// Enabled, then redirect the backend storage key to the
// shadow path so older versions survive newer PUTs.
// Suspended / Unversioned buckets keep using the plain
// `<key>` (S3 spec: Suspended overwrites the same backend
// object). Pre-allocation (instead of recording after PUT)
// ensures the shadow key + the response's
// `x-amz-version-id` use the same vid.
let pending_version: Option<crate::versioning::PutOutcome> = self
.versioning
.as_ref()
.map(|mgr| mgr.state(&put_bucket))
.map(|state| match state {
crate::versioning::VersioningState::Enabled => {
crate::versioning::PutOutcome {
version_id: crate::versioning::VersioningManager::new_version_id(),
versioned_response: true,
}
}
crate::versioning::VersioningState::Suspended
| crate::versioning::VersioningState::Unversioned => {
crate::versioning::PutOutcome {
version_id: crate::versioning::NULL_VERSION_ID.to_owned(),
versioned_response: false,
}
}
});
if let Some(ref pv) = pending_version
&& pv.versioned_response
{
req.input.key = versioned_shadow_key(&put_key, &pv.version_id);
}
let mut backend_resp = self.backend.put_object(req).await;
if let Some(idx) = sidecar_index
&& backend_resp.is_ok()
&& idx.entries.len() > 1
{
// 1 chunk しかない (small object) なら sidecar は意味がない (=
// partial fetch しても full body と同じ範囲) ので省略。
// Sidecar は user-visible key で書く (latest version の
// partial fetch path 用)。Old versions の Range GET は今 task
// の scope 外 (full read fallback でも意味的には正しい)。
self.write_sidecar(&put_bucket, &put_key, &idx).await;
}
// v0.5 #34: commit the new version into the manager only on
// backend success. Use the pre-allocated vid so the response
// header and the chain entry agree.
if let (Some(mgr), Some(pv), Ok(resp)) = (
self.versioning.as_ref(),
pending_version.as_ref(),
backend_resp.as_mut(),
) {
let etag = resp
.output
.e_tag
.clone()
.map(ETag::into_value)
.unwrap_or_else(|| format!("\"crc32c-{}\"", manifest.crc32c));
let now = chrono::Utc::now();
mgr.commit_put_with_version(
&put_bucket,
&put_key,
crate::versioning::VersionEntry {
version_id: pv.version_id.clone(),
etag,
size: original_size,
is_delete_marker: false,
created_at: now,
},
);
if pv.versioned_response {
resp.output.version_id = Some(pv.version_id.clone());
}
}
// v0.5 #27: AWS S3 echoes the SSE-C headers back on success
// so the client knows the server actually applied the
// requested algorithm and which key fingerprint matched.
if let (Some(m), Ok(resp)) = (sse_c_material.as_ref(), backend_resp.as_mut()) {
resp.output.sse_customer_algorithm = Some(crate::sse::SSE_C_ALGORITHM.into());
resp.output.sse_customer_key_md5 = Some(
base64::engine::general_purpose::STANDARD.encode(m.key_md5),
);
}
// v0.5 #28: SSE-KMS echo — `aws:kms` + the canonical key id
// the backend returned (AWS KMS returns the ARN even when
// the request used an alias).
if let (Some((_, wrapped)), Ok(resp)) =
(kms_wrap.as_ref(), backend_resp.as_mut())
{
resp.output.server_side_encryption =
Some(ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS));
resp.output.ssekms_key_id = Some(wrapped.key_id.clone());
}
// v0.5 #30: persist any per-PUT explicit retention / legal
// hold the client supplied, then auto-apply the bucket
// default (no-op when state is already populated). The
// explicit fields take precedence — the bucket-default
// helper bails out as soon as it sees any retention.
if let (Some(mgr), Ok(_)) = (self.object_lock.as_ref(), backend_resp.as_ref()) {
if explicit_lock_mode.is_some()
|| explicit_retain_until.is_some()
|| explicit_legal_hold_on.is_some()
{
let mut state = mgr.get(&put_bucket, &put_key).unwrap_or_default();
if let Some(m) = explicit_lock_mode {
state.mode = Some(m);
}
if let Some(u) = explicit_retain_until {
state.retain_until = Some(u);
}
if let Some(lh) = explicit_legal_hold_on {
state.legal_hold_on = lh;
}
mgr.set(&put_bucket, &put_key, state);
}
mgr.apply_default_on_put(&put_bucket, &put_key, chrono::Utc::now());
}
let _ = (original_size, compressed_size); // mute unused warnings
let elapsed = put_start.elapsed();
crate::metrics::record_put(
codec_label,
original_size,
compressed_size,
elapsed.as_secs_f64(),
backend_resp.is_ok(),
);
// v0.4 #20: structured access-log entry (best-effort).
self.record_access(
access_preamble,
"REST.PUT.OBJECT",
&put_bucket,
Some(&put_key),
if backend_resp.is_ok() { 200 } else { 500 },
compressed_size,
original_size,
elapsed.as_millis() as u64,
backend_resp.as_ref().err().map(|e| e.code().as_str()),
)
.await;
info!(
op = "put_object",
bucket = %put_bucket,
key = %put_key,
codec = codec_label,
bytes_in = original_size,
bytes_out = compressed_size,
ratio = format!(
"{:.3}",
if original_size == 0 { 1.0 } else { compressed_size as f64 / original_size as f64 }
),
latency_ms = elapsed.as_millis() as u64,
ok = backend_resp.is_ok(),
"S4 put completed"
);
// v0.6 #35: fire bucket-notification destinations (best-effort,
// detached). Skipped when no manager is attached or when the
// bucket has no rule matching `s3:ObjectCreated:Put` for this
// key.
if backend_resp.is_ok()
&& let Some(mgr) = self.notifications.as_ref()
{
let dests = mgr.match_destinations(
&put_bucket,
&crate::notifications::EventType::ObjectCreatedPut,
&put_key,
);
if !dests.is_empty() {
let etag = backend_resp
.as_ref()
.ok()
.and_then(|r| r.output.e_tag.clone())
.map(ETag::into_value);
let version_id = pending_version
.as_ref()
.filter(|pv| pv.versioned_response)
.map(|pv| pv.version_id.clone());
tokio::spawn(crate::notifications::dispatch_event(
Arc::clone(mgr),
put_bucket.clone(),
put_key.clone(),
crate::notifications::EventType::ObjectCreatedPut,
Some(original_size),
etag,
version_id,
format!("S4-{}", uuid::Uuid::new_v4()),
));
}
}
// v0.6 #39: persist parsed `x-amz-tagging` tags into the
// tagging manager on a successful PUT. AWS PutObject's
// tagging is a full-replace operation (not a merge), so
// any pre-existing entry for `(bucket, key)` is overwritten.
if backend_resp.is_ok()
&& let (Some(mgr), Some(tags)) =
(self.tagging.as_ref(), request_tags.clone())
{
mgr.put_object_tags(&put_bucket, &put_key, tags);
}
// v0.6 #40: cross-bucket replication fire-point. On
// successful source PUT, consult the replication manager;
// when an enabled rule matches, mark the source key
// `Pending` and spawn a detached task that PUTs the same
// backend bytes + metadata to the rule's destination
// bucket. The dispatcher itself records `Completed` /
// `Failed` and bumps the drop counter on retry-budget
// exhaustion.
self.spawn_replication_if_matched(
&put_bucket,
&put_key,
&request_tags,
&replication_body,
&replication_metadata,
backend_resp.is_ok(),
pending_version.as_ref(),
);
return backend_resp;
}
// Body-less PUT (rare: zero-length object). Mirror the body-full
// versioning hooks so list_object_versions / GET-by-version still see
// empty-body objects in the chain.
let pending_version: Option<crate::versioning::PutOutcome> = self
.versioning
.as_ref()
.map(|mgr| mgr.state(&put_bucket))
.map(|state| match state {
crate::versioning::VersioningState::Enabled => crate::versioning::PutOutcome {
version_id: crate::versioning::VersioningManager::new_version_id(),
versioned_response: true,
},
_ => crate::versioning::PutOutcome {
version_id: crate::versioning::NULL_VERSION_ID.to_owned(),
versioned_response: false,
},
});
if let Some(ref pv) = pending_version
&& pv.versioned_response
{
req.input.key = versioned_shadow_key(&put_key, &pv.version_id);
}
let mut backend_resp = self.backend.put_object(req).await;
if let (Some(mgr), Some(pv), Ok(resp)) = (
self.versioning.as_ref(),
pending_version.as_ref(),
backend_resp.as_mut(),
) {
let etag = resp
.output
.e_tag
.clone()
.map(ETag::into_value)
.unwrap_or_default();
let now = chrono::Utc::now();
mgr.commit_put_with_version(
&put_bucket,
&put_key,
crate::versioning::VersionEntry {
version_id: pv.version_id.clone(),
etag,
size: 0,
is_delete_marker: false,
created_at: now,
},
);
if pv.versioned_response {
resp.output.version_id = Some(pv.version_id.clone());
}
}
// v0.5 #30: same explicit-then-default lock-state commit as the
// body-bearing branch above, so a zero-length PUT also picks up
// bucket-default retention.
if let (Some(mgr), Ok(_)) = (self.object_lock.as_ref(), backend_resp.as_ref()) {
if explicit_lock_mode.is_some()
|| explicit_retain_until.is_some()
|| explicit_legal_hold_on.is_some()
{
let mut state = mgr.get(&put_bucket, &put_key).unwrap_or_default();
if let Some(m) = explicit_lock_mode {
state.mode = Some(m);
}
if let Some(u) = explicit_retain_until {
state.retain_until = Some(u);
}
if let Some(lh) = explicit_legal_hold_on {
state.legal_hold_on = lh;
}
mgr.set(&put_bucket, &put_key, state);
}
mgr.apply_default_on_put(&put_bucket, &put_key, chrono::Utc::now());
}
// v0.6 #35: same notification fire-point as the body-bearing PUT
// branch above (zero-length objects still match `ObjectCreated:Put`
// rules per the AWS event taxonomy).
if backend_resp.is_ok()
&& let Some(mgr) = self.notifications.as_ref()
{
let dests = mgr.match_destinations(
&put_bucket,
&crate::notifications::EventType::ObjectCreatedPut,
&put_key,
);
if !dests.is_empty() {
let etag = backend_resp
.as_ref()
.ok()
.and_then(|r| r.output.e_tag.clone())
.map(ETag::into_value);
let version_id = pending_version
.as_ref()
.filter(|pv| pv.versioned_response)
.map(|pv| pv.version_id.clone());
tokio::spawn(crate::notifications::dispatch_event(
Arc::clone(mgr),
put_bucket.clone(),
put_key.clone(),
crate::notifications::EventType::ObjectCreatedPut,
Some(0),
etag,
version_id,
format!("S4-{}", uuid::Uuid::new_v4()),
));
}
}
// v0.6 #39: persist parsed `x-amz-tagging` for the body-less
// (zero-length) PUT branch too — same shape as the body-bearing
// branch above.
if backend_resp.is_ok()
&& let (Some(mgr), Some(tags)) = (self.tagging.as_ref(), request_tags.clone())
{
mgr.put_object_tags(&put_bucket, &put_key, tags);
}
// v0.6 #40: cross-bucket replication for the zero-length PUT
// branch — same shape as the body-bearing branch above.
// v0.8.2 #61: pass `pending_version` so a versioned source's
// destination receives the same shadow-key path.
self.spawn_replication_if_matched(
&put_bucket,
&put_key,
&request_tags,
&bytes::Bytes::new(),
&None,
backend_resp.is_ok(),
pending_version.as_ref(),
);
backend_resp
}
// === 圧縮を解く path (GET) ===
#[tracing::instrument(
name = "s4.get_object",
skip(self, req),
fields(bucket = %req.input.bucket, key = %req.input.key, codec, bytes_out, range, path)
)]
async fn get_object(
&self,
mut req: S3Request<GetObjectInput>,
) -> S3Result<S3Response<GetObjectOutput>> {
let get_start = Instant::now();
let get_bucket = req.input.bucket.clone();
let get_key = req.input.key.clone();
self.enforce_rate_limit(&req, &get_bucket)?;
self.enforce_policy(&req, "s3:GetObject", &get_bucket, Some(&get_key))?;
// Range request の事前検出 (decompress 後 slice する path に使う)。
let range_request = req.input.range.take();
// v0.5 #27: pull SSE-C material from the input headers before
// the request is moved into the backend. A header parse error
// fails fast (no body fetch). The material is consumed below
// when decrypting an S4E3-framed body; the SSE-C headers on
// `req.input` are cleared so the backend doesn't see them.
let sse_c_alg = req.input.sse_customer_algorithm.take();
let sse_c_key = req.input.sse_customer_key.take();
let sse_c_md5 = req.input.sse_customer_key_md5.take();
let get_sse_c_material =
extract_sse_c_material(&sse_c_alg, &sse_c_key, &sse_c_md5)?;
// v0.5 #34: route the GET through the VersioningManager when
// attached AND the bucket is in a versioning-aware state.
// Resolves which version to fetch (explicit `?versionId=` query
// param vs. chain latest), translates a delete-marker into 404
// NoSuchKey, and rewrites the backend storage key to the shadow
// path (`<key>.__s4ver__/<vid>`) for non-null Enabled-bucket
// versions. `resolved_version_id` is stamped onto the response
// so clients see a coherent `x-amz-version-id` header.
//
// When the bucket is Unversioned (or no manager attached), the
// chain-resolution step is skipped and the request flows
// through the existing single-key path unchanged.
let resolved_version_id: Option<String> = match self.versioning.as_ref() {
Some(mgr)
if mgr.state(&get_bucket) != crate::versioning::VersioningState::Unversioned =>
{
let req_vid = req.input.version_id.take();
let entry = match req_vid.as_deref() {
Some(vid) => mgr.lookup_version(&get_bucket, &get_key, vid).ok_or_else(
|| S3Error::with_message(
S3ErrorCode::NoSuchVersion,
format!("no such version: {vid}"),
),
)?,
None => mgr.lookup_latest(&get_bucket, &get_key).ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::NoSuchKey,
format!("no such key: {get_key}"),
)
})?,
};
if entry.is_delete_marker {
// S3 spec: GET without versionId on a
// delete-marker latest → 404 NoSuchKey + the
// response carries `x-amz-delete-marker: true`.
// GET with explicit versionId pointing at a delete
// marker → 405 MethodNotAllowed; we surface
// NoSuchKey here for both since s3s collapses them
// into the same not-found error path.
return Err(S3Error::with_message(
S3ErrorCode::NoSuchKey,
format!("delete marker is the current version of {get_key}"),
));
}
if entry.version_id != crate::versioning::NULL_VERSION_ID {
req.input.key = versioned_shadow_key(&get_key, &entry.version_id);
}
Some(entry.version_id)
}
_ => None,
};
// ====== Range GET の partial-fetch fast path (sidecar index 利用) ======
// sidecar `<key>.s4index` が存在し、multipart-framed object であれば
// 必要 frame だけを backend に Range GET し帯域節約する。
if let Some(ref r) = range_request
&& let Some(index) = self.read_sidecar(&req.input.bucket, &req.input.key).await
{
let total = index.total_original_size();
let (start, end_exclusive) = match resolve_range(r, total) {
Ok(v) => v,
Err(e) => {
return Err(S3Error::with_message(S3ErrorCode::InvalidRange, e));
}
};
if let Some(plan) = index.lookup_range(start, end_exclusive) {
return self
.partial_range_get(&req, plan, start, end_exclusive, total, get_start)
.await;
}
}
let mut resp = self.backend.get_object(req).await?;
// v0.5 #34: stamp the resolved version-id so the client sees a
// coherent `x-amz-version-id` header (only for chains owned by
// the manager — Unversioned buckets / no-manager paths never
// set this).
if let Some(ref vid) = resolved_version_id {
resp.output.version_id = Some(vid.clone());
}
let is_multipart = is_multipart_object(&resp.output.metadata);
let is_framed_v2 = is_framed_v2_object(&resp.output.metadata);
// v0.2 #4: framed-v2 single-PUT は多 frame parse が必要なので
// multipart と同じ path に流す。
let needs_frame_parse = is_multipart || is_framed_v2;
let manifest_opt = extract_manifest(&resp.output.metadata);
if !needs_frame_parse && manifest_opt.is_none() {
// S4 が書いていないオブジェクトは透過 (raw bucket pre-existing object 等)
debug!("S4 get_object: object lacks s4-codec metadata, returning as-is");
return Ok(resp);
}
if let Some(blob) = resp.output.body.take() {
// v0.4 #21 / v0.5 #27: if the object was stored under SSE
// (metadata flag `s4-encrypted: aes-256-gcm`), decrypt
// before any frame parse / streaming decompress. Encrypted
// bodies are opaque to the codec; this also forces the
// buffered path because AES-GCM needs the full body for tag
// verify. SSE-C uses the per-request customer key, SSE-S4
// falls back to the configured keyring.
let blob = if is_sse_encrypted(&resp.output.metadata) {
let body = collect_blob(blob, self.max_body_bytes)
.await
.map_err(internal("collect SSE-encrypted body"))?;
// v0.5 #28: peek the frame magic to route the right
// decrypt path. S4E4 means SSE-KMS — unwrap the DEK
// through the KMS backend (async). S4E1/E2/E3 take
// the sync path (keyring or customer key).
//
// v0.8 #52 (S4E5) / v0.8.1 #57 (S4E6): the chunked
// SSE-S4 frames take the *streaming* path — we hand
// the response body a per-chunk verify-and-emit
// Stream so the client sees chunk 0 plaintext after
// one chunk-worth of AES-GCM verify (vs. waiting
// for the whole body's tag), and the gateway no
// longer needs to materialize the full plaintext
// in memory before responding. SSE-C is out of
// scope for the chunked path (chunked S4E3 is a
// follow-up), so this branch requires the SSE-S4
// keyring to be wired and `get_sse_c_material` to
// be absent — otherwise we surface a clear
// misconfiguration error instead of silently
// falling through to the buffered chunked path.
if matches!(
crate::sse::peek_magic(&body),
Some("S4E5") | Some("S4E6")
) && get_sse_c_material.is_none()
{
let keyring_arc = self.sse_keyring.clone().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"object is SSE-S4 encrypted (S4E5/S4E6) but no --sse-s4-key is configured on this gateway",
)
})?;
let body_len = body.len() as u64;
let stream =
crate::sse::decrypt_chunked_stream(body, keyring_arc.as_ref());
// Stream is `'static` (the keyring borrow is
// consumed up front; the cipher lives inside
// the stream state — see decrypt_chunked_stream
// doc), so we can move it straight into a
// StreamingBlob without lifetime gymnastics.
use futures::StreamExt;
let mapped = stream.map(|r| {
r.map_err(|e| std::io::Error::other(format!(
"SSE-S4 chunked decrypt: {e}"
)))
});
use s3s::dto::StreamingBlob;
resp.output.body = Some(StreamingBlob::wrap(mapped));
// Plaintext content_length is unknown until all
// chunks have been verified; null it out so the
// ByteStream wrapper reports `unknown` to the
// HTTP layer (which then emits chunked transfer-
// encoding) rather than lying about the size.
resp.output.content_length = None;
// The backend's checksums + ETag describe the
// encrypted body (S4E5/S4E6 wire format), not
// the plaintext we're about to stream — clear them
// so the AWS SDK doesn't fail the GET with a
// ChecksumMismatch on a successful round-trip.
// Mirrors the streaming-zstd path at L1180-1185.
resp.output.checksum_crc32 = None;
resp.output.checksum_crc32c = None;
resp.output.checksum_crc64nvme = None;
resp.output.checksum_sha1 = None;
resp.output.checksum_sha256 = None;
resp.output.e_tag = None;
let elapsed = get_start.elapsed();
crate::metrics::record_get(
"sse-s4-chunked",
body_len,
body_len,
elapsed.as_secs_f64(),
true,
);
return Ok(resp);
}
let plain = match crate::sse::peek_magic(&body) {
Some("S4E4") => {
let kms = self.kms.as_ref().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"object is SSE-KMS encrypted but no --kms-local-dir / --kms-aws-region is configured on this gateway",
)
})?;
let kms_ref: &dyn crate::kms::KmsBackend = kms.as_ref();
crate::sse::decrypt_with_kms(&body, kms_ref)
.await
.map_err(|e| match e {
crate::sse::SseError::KmsBackend(k) => kms_error_to_s3(k),
other => S3Error::with_message(
S3ErrorCode::InternalError,
format!("SSE-KMS decrypt failed: {other}"),
),
})?
}
_ => {
if let Some(ref m) = get_sse_c_material {
crate::sse::decrypt(
&body,
crate::sse::SseSource::CustomerKey {
key: &m.key,
key_md5: &m.key_md5,
},
)
.map_err(sse_c_error_to_s3)?
} else {
let keyring = self.sse_keyring.as_ref().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"object is SSE-S4 encrypted but no --sse-s4-key is configured on this gateway",
)
})?;
crate::sse::decrypt(&body, keyring).map_err(|e| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("SSE-S4 decrypt failed: {e}"),
)
})?
}
}
};
// v0.5 #28: parse out the on-disk wrapped DEK's key id
// so the GET response can echo `x-amz-server-side-encryption-aws-kms-key-id`.
if matches!(crate::sse::peek_magic(&body), Some("S4E4"))
&& let Ok(hdr) = crate::sse::parse_s4e4_header(&body)
{
resp.output.server_side_encryption = Some(
ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS),
);
resp.output.ssekms_key_id = Some(hdr.key_id.to_string());
}
bytes_to_blob(plain)
} else if let Some(ref m) = get_sse_c_material {
// Client sent SSE-C headers for an unencrypted object —
// mirror AWS S3's 400 InvalidRequest.
let _ = m;
return Err(sse_c_error_to_s3(crate::sse::SseError::CustomerKeyUnexpected));
} else {
blob
};
// v0.5 #27: SSE-C echo on success — algorithm + key MD5
// tell the client that the supplied key was the one used.
if let Some(ref m) = get_sse_c_material {
resp.output.sse_customer_algorithm = Some(crate::sse::SSE_C_ALGORITHM.into());
resp.output.sse_customer_key_md5 = Some(
base64::engine::general_purpose::STANDARD.encode(m.key_md5),
);
}
// ====== Streaming fast path (CpuZstd, non-multipart, codec supports it) ======
// 大規模 object (e.g. 5 GB) を memory に collect すると OOM するので、
// codec が streaming-aware なら body を chunk-by-chunk で decompress して
// 即座に client に流す。
//
// ただし Range request 時は streaming できない (slice するため total bytes
// が必要) → buffered path に fall through。
if range_request.is_none()
&& !needs_frame_parse
&& let Some(ref m) = manifest_opt
&& supports_streaming_decompress(m.codec)
&& m.codec == CodecKind::CpuZstd
{
let decompressed_blob = cpu_zstd_decompress_stream(blob);
resp.output.content_length = Some(m.original_size as i64);
resp.output.checksum_crc32 = None;
resp.output.checksum_crc32c = None;
resp.output.checksum_crc64nvme = None;
resp.output.checksum_sha1 = None;
resp.output.checksum_sha256 = None;
resp.output.e_tag = None;
resp.output.body = Some(decompressed_blob);
let elapsed = get_start.elapsed();
crate::metrics::record_get(
m.codec.as_str(),
m.compressed_size,
m.original_size,
elapsed.as_secs_f64(),
true,
);
info!(
op = "get_object",
bucket = %get_bucket,
key = %get_key,
codec = m.codec.as_str(),
bytes_in = m.compressed_size,
bytes_out = m.original_size,
path = "streaming",
setup_latency_ms = elapsed.as_millis() as u64,
"S4 get started (streaming)"
);
return Ok(resp);
}
// Passthrough: そのまま流す (Range なしの場合のみ streaming)
if range_request.is_none()
&& !needs_frame_parse
&& let Some(ref m) = manifest_opt
&& m.codec == CodecKind::Passthrough
{
resp.output.content_length = Some(m.original_size as i64);
resp.output.checksum_crc32 = None;
resp.output.checksum_crc32c = None;
resp.output.checksum_crc64nvme = None;
resp.output.checksum_sha1 = None;
resp.output.checksum_sha256 = None;
resp.output.e_tag = None;
resp.output.body = Some(blob);
debug!("S4 get_object: passthrough streaming");
return Ok(resp);
}
// ====== Buffered slow path (multipart frame parser, GPU codecs) ======
let bytes = collect_blob(blob, self.max_body_bytes)
.await
.map_err(internal("collect get body"))?;
let decompressed = if needs_frame_parse {
// multipart objects と framed-v2 single-PUT objects は同じ
// S4F2 frame 列なので decompress_multipart で統一処理
self.decompress_multipart(bytes).await?
} else {
let manifest = manifest_opt.as_ref().expect("non-multipart guarded above");
self.registry
.decompress(bytes, manifest)
.await
.map_err(internal("registry decompress"))?
};
// Range request があれば slice。なければ full body を返す。
let total_size = decompressed.len() as u64;
let (final_bytes, status_override) = if let Some(r) = range_request.as_ref() {
let (start, end) = resolve_range(r, total_size)
.map_err(|e| S3Error::with_message(S3ErrorCode::InvalidRange, e))?;
let sliced = decompressed.slice(start as usize..end as usize);
resp.output.content_range = Some(format!(
"bytes {start}-{}/{total_size}",
end.saturating_sub(1)
));
(sliced, Some(http::StatusCode::PARTIAL_CONTENT))
} else {
(decompressed, None)
};
// 解凍後の真のサイズを返す (S3 client は content_length を信頼するので
// 圧縮 size のままだと downstream が body を途中で切ってしまう)
resp.output.content_length = Some(final_bytes.len() as i64);
// 圧縮済 bytes の checksum を返すと AWS SDK 側で StreamingError
// (ChecksumMismatch) になる。ETag も backend が返した「圧縮済 bytes の
// MD5/checksum」なので意味的にズレる — クリアして S4 自身の crc32c
// (manifest 内 / frame 内) で integrity を保証する設計にする。
resp.output.checksum_crc32 = None;
resp.output.checksum_crc32c = None;
resp.output.checksum_crc64nvme = None;
resp.output.checksum_sha1 = None;
resp.output.checksum_sha256 = None;
resp.output.e_tag = None;
let returned_size = final_bytes.len() as u64;
let codec_label = manifest_opt
.as_ref()
.map(|m| m.codec.as_str())
.unwrap_or("multipart");
resp.output.body = Some(bytes_to_blob(final_bytes));
if let Some(status) = status_override {
resp.status = Some(status);
}
let elapsed = get_start.elapsed();
crate::metrics::record_get(codec_label, 0, returned_size, elapsed.as_secs_f64(), true);
info!(
op = "get_object",
bucket = %get_bucket,
key = %get_key,
codec = codec_label,
bytes_out = returned_size,
total_object_size = total_size,
range = range_request.is_some(),
path = "buffered",
latency_ms = elapsed.as_millis() as u64,
"S4 get completed (buffered)"
);
}
// v0.6 #40: echo the recorded `x-amz-replication-status` so
// consumers can poll progress (PENDING / COMPLETED / FAILED).
if let Some(mgr) = self.replication.as_ref()
&& let Some(status) = mgr.lookup_status(&get_bucket, &get_key)
{
resp.output.replication_status =
Some(s3s::dto::ReplicationStatus::from(status.as_aws_str().to_owned()));
}
Ok(resp)
}
// === passthrough delegations ===
async fn head_bucket(
&self,
req: S3Request<HeadBucketInput>,
) -> S3Result<S3Response<HeadBucketOutput>> {
self.backend.head_bucket(req).await
}
async fn list_buckets(
&self,
req: S3Request<ListBucketsInput>,
) -> S3Result<S3Response<ListBucketsOutput>> {
self.backend.list_buckets(req).await
}
async fn create_bucket(
&self,
req: S3Request<CreateBucketInput>,
) -> S3Result<S3Response<CreateBucketOutput>> {
self.backend.create_bucket(req).await
}
async fn delete_bucket(
&self,
req: S3Request<DeleteBucketInput>,
) -> S3Result<S3Response<DeleteBucketOutput>> {
self.backend.delete_bucket(req).await
}
async fn head_object(
&self,
req: S3Request<HeadObjectInput>,
) -> S3Result<S3Response<HeadObjectOutput>> {
// v0.6 #40: capture bucket/key before req is consumed so the
// replication-status echo can look the entry up.
let head_bucket = req.input.bucket.clone();
let head_key = req.input.key.clone();
let mut resp = self.backend.head_object(req).await?;
if let Some(manifest) = extract_manifest(&resp.output.metadata) {
// 客側には decompress 後の意味のある content_length / checksum を返す。
// backend が返す圧縮済 bytes の checksum / e_tag は意味が違うため除去
// (S4 は manifest 内の crc32c で integrity を担保する)。
resp.output.content_length = Some(manifest.original_size as i64);
resp.output.checksum_crc32 = None;
resp.output.checksum_crc32c = None;
resp.output.checksum_crc64nvme = None;
resp.output.checksum_sha1 = None;
resp.output.checksum_sha256 = None;
resp.output.e_tag = None;
}
// v0.6 #40: echo `x-amz-replication-status` (PENDING / COMPLETED
// / FAILED) so consumers can poll progress without a GET.
if let Some(mgr) = self.replication.as_ref()
&& let Some(status) = mgr.lookup_status(&head_bucket, &head_key)
{
resp.output.replication_status =
Some(s3s::dto::ReplicationStatus::from(status.as_aws_str().to_owned()));
}
// v0.7 #48 BUG-4 fix: HEAD must echo SSE indicators so SDKs
// and pipelines see the same posture they got on PUT. The PUT
// path stamps `s4-sse-type` metadata for exactly this — HEAD
// doesn't fetch the body, so it can't peek frame magic.
if let Some(meta) = resp.output.metadata.as_ref()
&& let Some(sse_type) = meta.get("s4-sse-type")
{
{
match sse_type.as_str() {
"aws:kms" => {
resp.output.server_side_encryption = Some(
ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS),
);
if let Some(key_id) = meta.get("s4-sse-kms-key-id") {
resp.output.ssekms_key_id = Some(key_id.clone());
}
}
_ => {
resp.output.server_side_encryption = Some(
ServerSideEncryption::from_static(ServerSideEncryption::AES256),
);
if let Some(md5) = meta.get("s4-sse-c-key-md5") {
resp.output.sse_customer_algorithm =
Some(crate::sse::SSE_C_ALGORITHM.into());
resp.output.sse_customer_key_md5 = Some(md5.clone());
}
}
}
}
}
Ok(resp)
}
async fn delete_object(
&self,
mut req: S3Request<DeleteObjectInput>,
) -> S3Result<S3Response<DeleteObjectOutput>> {
let bucket = req.input.bucket.clone();
let key = req.input.key.clone();
self.enforce_rate_limit(&req, &bucket)?;
self.enforce_policy(&req, "s3:DeleteObject", &bucket, Some(&key))?;
// v0.6 #42: MFA Delete enforcement. When the bucket has
// MFA-Delete = Enabled, every DELETE / DELETE-version /
// delete-marker form needs `x-amz-mfa: <serial> <code>` (RFC 6238
// 6-digit TOTP). Runs *before* the WORM / versioning routers so
// a missing token is denied for free regardless of which delete
// path the request would otherwise take.
if let Some(mgr) = self.mfa_delete.as_ref()
&& mgr.is_enabled(&bucket)
{
let header = req.input.mfa.as_deref();
if let Err(e) = crate::mfa::check_mfa(&bucket, header, mgr, current_unix_secs()) {
crate::metrics::record_mfa_delete_denial(&bucket);
return Err(mfa_error_to_s3(e));
}
}
// v0.5 #30: refuse the delete while a WORM lock is in effect.
// Compliance can never be bypassed; Governance can be overridden
// via `x-amz-bypass-governance-retention: true`; legal hold
// never. The check happens before the versioning router so a
// locked object can't be soft-deleted (delete-marker push) on an
// Enabled bucket either — S3 spec says lock applies to all
// delete forms.
if let Some(mgr) = self.object_lock.as_ref()
&& let Some(state) = mgr.get(&bucket, &key)
{
let bypass = req.input.bypass_governance_retention.unwrap_or(false);
let now = chrono::Utc::now();
if !state.can_delete(now, bypass) {
crate::metrics::record_policy_denial("s3:DeleteObject", &bucket);
return Err(S3Error::with_message(
S3ErrorCode::AccessDenied,
"Access Denied because object protected by object lock",
));
}
}
// v0.5 #34: route DELETE through the VersioningManager when the
// bucket is in a versioning-aware state.
//
// - Enabled bucket, no version_id → push a delete marker into
// the chain. NO backend object is touched (older versions
// stay reachable via specific-version GET).
// - Enabled / Suspended bucket, with version_id → physical
// delete. Backend bytes at the shadow key (or `<key>` for
// `null`) are removed; chain entry is dropped. If the deleted
// entry was a delete marker, no backend bytes exist for it
// (record-only).
// - Suspended bucket, no version_id → push a "null" delete
// marker (S3 spec); backend bytes at `<key>` are physically
// removed (same as legacy).
// - Unversioned bucket → fall through to legacy passthrough.
if let Some(mgr) = self.versioning.as_ref() {
let state = mgr.state(&bucket);
if state != crate::versioning::VersioningState::Unversioned {
let req_vid = req.input.version_id.take();
if let Some(vid) = req_vid {
// Specific-version DELETE: touch backend bytes only
// when the entry was a real version (not a delete
// marker, which has no backend bytes).
let outcome = mgr.record_delete_specific(&bucket, &key, &vid);
let backend_target = if vid == crate::versioning::NULL_VERSION_ID {
key.clone()
} else {
versioned_shadow_key(&key, &vid)
};
let was_real_version = outcome
.as_ref()
.map(|o| !o.is_delete_marker)
.unwrap_or(false);
if was_real_version {
// Best-effort backend cleanup; missing bytes
// are not an error (e.g. shadow key already
// GC'd).
let backend_input = DeleteObjectInput {
bucket: bucket.clone(),
key: backend_target,
..Default::default()
};
let backend_req = S3Request {
input: backend_input,
method: http::Method::DELETE,
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let _ = self.backend.delete_object(backend_req).await;
}
let mut output = DeleteObjectOutput {
version_id: Some(vid.clone()),
..Default::default()
};
if let Some(o) = outcome.as_ref()
&& o.is_delete_marker
{
output.delete_marker = Some(true);
}
// v0.6 #35: specific-version DELETE always counts as
// a hard `ObjectRemoved:Delete` event (the chain
// entry, marker or not, is gone after this call).
self.fire_delete_notification(
&bucket,
&key,
crate::notifications::EventType::ObjectRemovedDelete,
Some(vid.clone()),
);
return Ok(S3Response::new(output));
}
// No version_id: record a delete marker (state-aware).
let outcome = mgr.record_delete(&bucket, &key);
if state == crate::versioning::VersioningState::Suspended {
// Suspended buckets also evict the prior `<key>`
// bytes (the previous null version is gone too).
let backend_input = DeleteObjectInput {
bucket: bucket.clone(),
key: key.clone(),
..Default::default()
};
let backend_req = S3Request {
input: backend_input,
method: http::Method::DELETE,
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let _ = self.backend.delete_object(backend_req).await;
}
let output = DeleteObjectOutput {
delete_marker: Some(true),
version_id: outcome.version_id.clone(),
..Default::default()
};
// v0.6 #35: versioned bucket DELETE without a version-id
// creates a delete marker — the dedicated AWS event
// taxonomy entry. Suspended-state buckets also push a
// (null) marker, so the same event fires there.
self.fire_delete_notification(
&bucket,
&key,
crate::notifications::EventType::ObjectRemovedDeleteMarker,
outcome.version_id,
);
return Ok(S3Response::new(output));
}
}
// Legacy / Unversioned path: physical delete on the backend +
// best-effort sidecar cleanup (mirrors v0.4 behaviour).
let resp = self.backend.delete_object(req).await?;
// v0.5 #30: drop any per-object lock state once the delete has
// succeeded so the freed key can be re-armed by a future PUT
// under the bucket default. Reaching here implies the lock had
// already passed `can_delete` above, so this is purely cleanup.
if let Some(mgr) = self.object_lock.as_ref() {
mgr.clear(&bucket, &key);
}
// v0.6 #39: drop any object-level tag set on physical delete —
// the freed key starts a fresh tag history if a future PUT
// re-creates it. (Versioned-delete branches above return early
// and do NOT touch tags, mirroring AWS where tag state is
// attached to the logical key, not the version chain.)
if let Some(mgr) = self.tagging.as_ref() {
mgr.delete_object_tags(&bucket, &key);
}
let sidecar = sidecar_key(&key);
// v0.7 #49: skip the sidecar DELETE if the key + sidecar suffix
// can't be encoded into a request URI — the primary delete
// already succeeded and a stale sidecar is harmless (Range GET
// re-validates the underlying object on next read).
if let Ok(uri) = safe_object_uri(&bucket, &sidecar) {
let sidecar_input = DeleteObjectInput {
bucket: bucket.clone(),
key: sidecar,
..Default::default()
};
let sidecar_req = S3Request {
input: sidecar_input,
method: http::Method::DELETE,
uri,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let _ = self.backend.delete_object(sidecar_req).await;
}
// v0.6 #35: legacy unversioned-bucket hard delete fires the
// canonical `ObjectRemoved:Delete` event.
self.fire_delete_notification(
&bucket,
&key,
crate::notifications::EventType::ObjectRemovedDelete,
None,
);
Ok(resp)
}
async fn delete_objects(
&self,
req: S3Request<DeleteObjectsInput>,
) -> S3Result<S3Response<DeleteObjectsOutput>> {
// v0.6 #42: MFA Delete applies once to the whole batch (S3 spec:
// when MFA-Delete is on the bucket, a missing / invalid token
// fails the entire DeleteObjects request, not per-object).
if let Some(mgr) = self.mfa_delete.as_ref()
&& mgr.is_enabled(&req.input.bucket)
{
let header = req.input.mfa.as_deref();
if let Err(e) =
crate::mfa::check_mfa(&req.input.bucket, header, mgr, current_unix_secs())
{
crate::metrics::record_mfa_delete_denial(&req.input.bucket);
return Err(mfa_error_to_s3(e));
}
}
self.backend.delete_objects(req).await
}
async fn copy_object(
&self,
mut req: S3Request<CopyObjectInput>,
) -> S3Result<S3Response<CopyObjectOutput>> {
// copy is conceptually "GetObject src + PutObject dst" — enforce both.
let dst_bucket = req.input.bucket.clone();
let dst_key = req.input.key.clone();
self.enforce_policy(&req, "s3:PutObject", &dst_bucket, Some(&dst_key))?;
if let CopySource::Bucket { bucket, key, .. } = &req.input.copy_source {
self.enforce_policy(&req, "s3:GetObject", bucket, Some(key))?;
}
// S4-aware copy: source object に s4-* metadata がある場合、それを
// destination に確実に preserve する。
//
// - MetadataDirective::COPY (default): backend が source metadata を
// そのまま copy するので S4 metadata も自動で渡る。介入不要
// - MetadataDirective::REPLACE: 客が指定した metadata で source を
// 上書き → s4-* metadata が消えると destination は decompress 不能に
// なる (silent corruption)。S4 が source metadata を HEAD で取得し、
// s4-* fields を input.metadata に強制 merge する
let needs_merge = req
.input
.metadata_directive
.as_ref()
.map(|d| d.as_str() == MetadataDirective::REPLACE)
.unwrap_or(false);
if needs_merge && let CopySource::Bucket { bucket, key, .. } = &req.input.copy_source {
let head_input = HeadObjectInput {
bucket: bucket.to_string(),
key: key.to_string(),
..Default::default()
};
let head_req = S3Request {
input: head_input,
method: req.method.clone(),
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
if let Ok(head) = self.backend.head_object(head_req).await
&& let Some(src_meta) = head.output.metadata.as_ref()
{
let dest_meta = req.input.metadata.get_or_insert_with(Default::default);
for key in [
META_CODEC,
META_ORIGINAL_SIZE,
META_COMPRESSED_SIZE,
META_CRC32C,
META_MULTIPART,
META_FRAMED,
] {
if let Some(v) = src_meta.get(key) {
// 客が同じ key を指定していたら preserve しない (= 上書き許可)
// していたら何もしない。指定していなければ insert
dest_meta
.entry(key.to_string())
.or_insert_with(|| v.clone());
}
}
debug!(
src_bucket = %bucket,
src_key = %key,
"S4 copy_object: preserved s4-* metadata across REPLACE directive"
);
}
}
self.backend.copy_object(req).await
}
async fn list_objects(
&self,
req: S3Request<ListObjectsInput>,
) -> S3Result<S3Response<ListObjectsOutput>> {
self.enforce_rate_limit(&req, &req.input.bucket)?;
self.enforce_policy(&req, "s3:ListBucket", &req.input.bucket, None)?;
let mut resp = self.backend.list_objects(req).await?;
// S4 内部 object (`*.s4index` sidecar、`.__s4ver__/` shadow versions
// — v0.5 #34) を顧客から隠す。
if let Some(contents) = resp.output.contents.as_mut() {
contents.retain(|o| {
o.key
.as_ref()
.map(|k| !k.ends_with(".s4index") && !is_versioning_shadow_key(k))
.unwrap_or(true)
});
}
Ok(resp)
}
async fn list_objects_v2(
&self,
req: S3Request<ListObjectsV2Input>,
) -> S3Result<S3Response<ListObjectsV2Output>> {
self.enforce_rate_limit(&req, &req.input.bucket)?;
self.enforce_policy(&req, "s3:ListBucket", &req.input.bucket, None)?;
let mut resp = self.backend.list_objects_v2(req).await?;
if let Some(contents) = resp.output.contents.as_mut() {
let before = contents.len();
contents.retain(|o| {
o.key
.as_ref()
.map(|k| !k.ends_with(".s4index") && !is_versioning_shadow_key(k))
.unwrap_or(true)
});
// key_count も補正 (S3 spec compliance)
if let Some(kc) = resp.output.key_count.as_mut() {
*kc -= (before - contents.len()) as i32;
}
}
Ok(resp)
}
/// v0.4 #17: filter S4-internal sidecars from versioned listings.
/// v0.5 #34: when a [`crate::versioning::VersioningManager`] is
/// attached AND the bucket is in a versioning-aware state, build
/// the `Versions` / `DeleteMarkers` arrays directly from the
/// in-memory chain (paginated + ordered the S3 way: key asc,
/// version newest-first inside each key). Otherwise fall back to
/// passthrough + sidecar-filter (legacy v0.4 behaviour).
async fn list_object_versions(
&self,
req: S3Request<ListObjectVersionsInput>,
) -> S3Result<S3Response<ListObjectVersionsOutput>> {
self.enforce_rate_limit(&req, &req.input.bucket)?;
self.enforce_policy(&req, "s3:ListBucket", &req.input.bucket, None)?;
// v0.5 #34: VersioningManager-owned path.
if let Some(mgr) = self.versioning.as_ref()
&& mgr.state(&req.input.bucket) != crate::versioning::VersioningState::Unversioned
{
let max_keys = req.input.max_keys.unwrap_or(1000) as usize;
let page = mgr.list_versions(
&req.input.bucket,
req.input.prefix.as_deref(),
req.input.key_marker.as_deref(),
req.input.version_id_marker.as_deref(),
max_keys,
);
let versions: Vec<ObjectVersion> = page
.versions
.into_iter()
.map(|e| ObjectVersion {
key: Some(e.key),
version_id: Some(e.version_id),
is_latest: Some(e.is_latest),
e_tag: Some(ETag::Strong(e.etag)),
size: Some(e.size as i64),
last_modified: Some(std::time::SystemTime::from(e.last_modified).into()),
..Default::default()
})
.collect();
let delete_markers: Vec<DeleteMarkerEntry> = page
.delete_markers
.into_iter()
.map(|e| DeleteMarkerEntry {
key: Some(e.key),
version_id: Some(e.version_id),
is_latest: Some(e.is_latest),
last_modified: Some(std::time::SystemTime::from(e.last_modified).into()),
..Default::default()
})
.collect();
let output = ListObjectVersionsOutput {
name: Some(req.input.bucket.clone()),
prefix: req.input.prefix.clone(),
key_marker: req.input.key_marker.clone(),
version_id_marker: req.input.version_id_marker.clone(),
max_keys: req.input.max_keys,
versions: if versions.is_empty() {
None
} else {
Some(versions)
},
delete_markers: if delete_markers.is_empty() {
None
} else {
Some(delete_markers)
},
is_truncated: Some(page.is_truncated),
next_key_marker: page.next_key_marker,
next_version_id_marker: page.next_version_id_marker,
..Default::default()
};
return Ok(S3Response::new(output));
}
// Legacy passthrough path (v0.4 #17 sidecar filter retained).
let mut resp = self.backend.list_object_versions(req).await?;
if let Some(versions) = resp.output.versions.as_mut() {
versions.retain(|v| {
v.key
.as_ref()
.map(|k| !k.ends_with(".s4index") && !is_versioning_shadow_key(k))
.unwrap_or(true)
});
}
if let Some(markers) = resp.output.delete_markers.as_mut() {
markers.retain(|m| {
m.key
.as_ref()
.map(|k| !k.ends_with(".s4index") && !is_versioning_shadow_key(k))
.unwrap_or(true)
});
}
Ok(resp)
}
async fn create_multipart_upload(
&self,
mut req: S3Request<CreateMultipartUploadInput>,
) -> S3Result<S3Response<CreateMultipartUploadOutput>> {
// Multipart object は per-part 圧縮 + frame 形式で書く。GET 時に
// frame parse を起動するため、object metadata に flag を立てる。
// codec は dispatcher の default kind を採用 (per-part 別 codec は Phase 2)。
let codec_kind = self.registry.default_kind();
let meta = req.input.metadata.get_or_insert_with(Default::default);
meta.insert(META_MULTIPART.into(), "true".into());
meta.insert(META_CODEC.into(), codec_kind.as_str().into());
// v0.8 #54 BUG-10 fix: take() the SSE request fields off
// `req.input` so they are NOT forwarded to the backend on
// CreateMultipartUpload. Same root cause as v0.7 #48 BUG-2/3 on
// single-PUT — MinIO rejects SSE-C with "HTTPS required" and
// SSE-KMS with "KMS not configured" when the headers reach it.
// S4 owns the encrypt-then-store contract; we capture the
// recipe in `multipart_state` here and apply it on Complete.
let sse_c_alg = req.input.sse_customer_algorithm.take();
let sse_c_key = req.input.sse_customer_key.take();
let sse_c_md5 = req.input.sse_customer_key_md5.take();
let sse_header = req.input.server_side_encryption.take();
let sse_kms_key = req.input.ssekms_key_id.take();
// Strip the encryption-context too — leaving it would make
// MinIO try to validate it against a non-existent KMS key.
let _ = req.input.ssekms_encryption_context.take();
let sse_c_material = extract_sse_c_material(&sse_c_alg, &sse_c_key, &sse_c_md5)?;
let kms_key_id = extract_kms_key_id(
&sse_header,
&sse_kms_key,
self.kms_default_key_id.as_deref(),
);
// SSE-C / SSE-KMS exclusivity (mirrors put_object L1870).
if sse_c_material.is_some() && kms_key_id.is_some() {
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
"SSE-C and SSE-KMS cannot be used together on the same multipart upload",
));
}
let sse_mode = if let Some(ref m) = sse_c_material {
// v0.8.2 #62 (H-6 audit fix): wrap the customer-supplied
// 32-byte key in `Zeroizing` so abandoned uploads (or
// normal Complete/Abort) wipe the key bytes on drop. The
// `key_md5` is the public fingerprint and stays as a
// bare `[u8; 16]`.
crate::multipart_state::MultipartSseMode::SseC {
key: zeroize::Zeroizing::new(m.key),
key_md5: m.key_md5,
}
} else if let Some(ref kid) = kms_key_id {
// KMS pre-flight: fail at Create rather than at Complete if
// the gateway has no KMS backend wired (mirrors the
// put_object L1879 check).
if self.kms.is_none() {
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"SSE-KMS requested but no --kms-local-dir / --kms-aws-region is configured on this gateway",
));
}
crate::multipart_state::MultipartSseMode::SseKms { key_id: kid.clone() }
} else if self.sse_keyring.is_some() {
// SSE-S4: server-driven transparent encryption. Activates
// whenever the gateway has a keyring configured AND the
// client didn't pick a different SSE mode.
crate::multipart_state::MultipartSseMode::SseS4
} else {
crate::multipart_state::MultipartSseMode::None
};
// v0.8 #54 BUG-9 fix: parse the Tagging header on Create. The
// single-PUT path does this on PutObject; the multipart path
// captures it now and commits via TagManager on Complete.
let request_tags: Option<crate::tagging::TagSet> = req
.input
.tagging
.as_deref()
.map(crate::tagging::parse_tagging_header)
.transpose()
.map_err(|e| S3Error::with_message(S3ErrorCode::InvalidArgument, e.to_string()))?;
// Strip the `Tagging` field off the input so the backend
// doesn't try to apply it (no-op on MinIO but keeps the wire
// clean).
let _ = req.input.tagging.take();
// Object Lock recipe (BUG-7 — captured here, applied on Complete).
let explicit_lock_mode: Option<crate::object_lock::LockMode> = req
.input
.object_lock_mode
.as_ref()
.and_then(|m| crate::object_lock::LockMode::from_aws_str(m.as_str()));
let explicit_retain_until: Option<chrono::DateTime<chrono::Utc>> = req
.input
.object_lock_retain_until_date
.as_ref()
.and_then(timestamp_to_chrono_utc);
let explicit_legal_hold_on: bool = req
.input
.object_lock_legal_hold_status
.as_ref()
.map(|s| s.as_str().eq_ignore_ascii_case("ON"))
.unwrap_or(false);
let bucket = req.input.bucket.clone();
let key = req.input.key.clone();
debug!(
bucket = %bucket,
key = %key,
codec = codec_kind.as_str(),
sse = ?sse_mode,
"S4 create_multipart_upload: marking object for per-part compression"
);
let mut resp = self.backend.create_multipart_upload(req).await?;
// Stash the per-upload context only after the backend handed
// us an upload_id (failed Creates leave nothing in the store).
if let Some(upload_id) = resp.output.upload_id.as_ref() {
self.multipart_state.put(
upload_id,
crate::multipart_state::MultipartUploadContext {
bucket,
key,
sse: sse_mode.clone(),
tags: request_tags,
object_lock_mode: explicit_lock_mode,
object_lock_retain_until: explicit_retain_until,
object_lock_legal_hold: explicit_legal_hold_on,
},
);
}
// SSE-C / SSE-KMS response echo (mirrors put_object L2036-L2050).
match &sse_mode {
crate::multipart_state::MultipartSseMode::SseC { key_md5, .. } => {
resp.output.sse_customer_algorithm = Some(crate::sse::SSE_C_ALGORITHM.into());
resp.output.sse_customer_key_md5 = Some(
base64::engine::general_purpose::STANDARD.encode(key_md5),
);
}
crate::multipart_state::MultipartSseMode::SseKms { key_id } => {
resp.output.server_side_encryption = Some(
ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS),
);
resp.output.ssekms_key_id = Some(key_id.clone());
}
_ => {}
}
Ok(resp)
}
async fn upload_part(
&self,
mut req: S3Request<UploadPartInput>,
) -> S3Result<S3Response<UploadPartOutput>> {
// 各 part を圧縮して frame header 付きで forward。GET 時に
// `decompress_multipart` が frame iter で順に解凍する。
// **per-part codec dispatch**: dispatcher が body 先頭 sample から
// codec を選ぶので、parquet 風の mixed-content multipart で part ごとに
// 最適 codec を使える (整数列 part → Bitcomp、text 列 part → zstd 等)。
//
// v0.8 #54 BUG-5/BUG-10 fix: lookup the per-upload SSE
// context captured by `create_multipart_upload` and (a) strip
// any SSE-C request headers off `req.input` so the backend
// doesn't see them — same root cause as v0.7 #48 BUG-2/3 on
// single-PUT; MinIO refuses SSE-C parts over HTTP — and (b)
// observe that an upload context exists for `upload_id`. The
// actual encrypt happens once at `complete_multipart_upload`
// time on the assembled body (the per-part-encrypt approach
// would require a matching multi-segment decrypt path on GET;
// encrypting the whole assembled body keeps the GET path's
// `is_sse_encrypted` branch in get_object L2429 working
// unchanged).
let sse_ctx = self
.multipart_state
.get(req.input.upload_id.as_str());
// v0.8.2 #62 (H-1 audit fix): SSE-C key consistency check.
// The AWS S3 spec requires the same SSE-C key headers on
// every UploadPart and rejects mismatches with 400. Prior to
// #62 we silently stripped the headers (BUG-10 fix) without
// validating them, allowing a client to send part 1 under
// key-A and part 2 under key-B; both got stored, then
// re-encrypted with key-A on Complete — the client thinks
// part 2 is under key-B but a GET with key-B would in fact
// hit the part-1 ciphertext that was actually encrypted with
// key-A. That would either decrypt successfully (silent
// corruption: client lost track of which key encrypts what)
// or fail in a confusing way. Validate the per-part headers
// now and reject with 400 InvalidArgument on mismatch /
// omission / partial supply, matching real-S3 behaviour.
if let Some(ref ctx) = sse_ctx {
if let crate::multipart_state::MultipartSseMode::SseC { key_md5: ctx_md5, .. } =
&ctx.sse
{
let alg = req.input.sse_customer_algorithm.take();
let key_b64 = req.input.sse_customer_key.take();
let md5_b64 = req.input.sse_customer_key_md5.take();
match (alg, key_b64, md5_b64) {
(Some(a), Some(k), Some(m)) => {
// Parse + validate; if the per-part headers
// are themselves malformed (algorithm not
// AES256, MD5 mismatch, key not 32 bytes)
// surface the same 400 the single-PUT path
// would. Then compare the parsed MD5 to the
// upload-context's MD5; mismatch is a
// different-key UploadPart and must reject.
let part_material =
crate::sse::parse_customer_key_headers(&a, &k, &m)
.map_err(sse_c_error_to_s3)?;
if part_material.key_md5 != *ctx_md5 {
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
"SSE-C key on UploadPart does not match the key supplied on CreateMultipartUpload",
));
}
// OK — same key as Create. Headers are
// already taken off `req.input` so the
// backend never sees them.
}
(None, None, None) => {
// AWS S3 spec: SSE-C headers MUST be replayed
// on every UploadPart of an SSE-C multipart.
// Real-S3 returns 400 InvalidRequest in this
// case; mirror that.
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"SSE-C requires customer-key headers on every UploadPart (CreateMultipartUpload was SSE-C)",
));
}
_ => {
// Partial header set (e.g. algorithm + key
// but no MD5) — same handling as the
// single-PUT `extract_sse_c_material` helper.
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"SSE-C requires all three of: x-amz-server-side-encryption-customer-{algorithm,key,key-MD5}",
));
}
}
} else {
// CreateMultipartUpload was non-SSE-C (None / SseS4 /
// SseKms). A part that arrives carrying SSE-C headers
// is either a confused client or an attempt to
// smuggle SSE-C around the gateway-internal SSE
// recipe. Reject with 400 InvalidRequest rather than
// silently strip — the strip would let the client
// believe the part was encrypted under their key
// when in fact the upload's encryption recipe is
// whatever the Create captured.
if req.input.sse_customer_algorithm.is_some()
|| req.input.sse_customer_key.is_some()
|| req.input.sse_customer_key_md5.is_some()
{
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"UploadPart sent SSE-C headers but CreateMultipartUpload was not SSE-C",
));
}
}
} else {
// No upload context registered (gateway crashed between
// Create and Part, or pre-#62 abandoned-upload restore).
// We can't check key consistency in this case — strip
// the headers and let the request through unchanged so
// the backend's `NoSuchUpload` reply (or whatever it
// chooses to do) flows back to the client.
let _ = req.input.sse_customer_algorithm.take();
let _ = req.input.sse_customer_key.take();
let _ = req.input.sse_customer_key_md5.take();
}
let _sse_ctx = sse_ctx;
if let Some(blob) = req.input.body.take() {
let bytes = collect_blob(blob, self.max_body_bytes)
.await
.map_err(internal("collect upload_part body"))?;
let sample_len = bytes.len().min(SAMPLE_BYTES);
// v0.8 #56: full part body is already in memory here; use its
// length as the size hint so the dispatcher can promote to GPU
// if it's big enough.
let codec_kind = self
.dispatcher
.pick_with_size_hint(&bytes[..sample_len], Some(bytes.len() as u64))
.await;
let original_size = bytes.len() as u64;
// v0.8 #55: telemetry-returning compress (GPU metrics stamp).
let (compress_res, tel) = self
.registry
.compress_with_telemetry(bytes, codec_kind)
.await;
stamp_gpu_compress_telemetry(&tel);
let (compressed, manifest) = compress_res.map_err(internal("registry compress part"))?;
let header = FrameHeader {
codec: codec_kind,
original_size,
compressed_size: compressed.len() as u64,
crc32c: manifest.crc32c,
};
let mut framed = BytesMut::with_capacity(FRAME_HEADER_BYTES + compressed.len());
write_frame(&mut framed, header, &compressed);
// v0.2 #5: heuristic-based padding skip for likely-final parts.
//
// AWS SDK / aws-cli / boto3 always send the final (and only the
// final) part below the configured part_size. So if the raw user
// part is already smaller than S3's 5 MiB multipart minimum, this
// is overwhelmingly likely to be the final part — and the final
// part is exempt from S3's size constraint. Skipping padding here
// saves up to ~5 MiB per object on highly compressible workloads.
//
// If a misbehaving client sends a tiny **non-final** part, S3
// itself rejects with EntityTooSmall at CompleteMultipartUpload —
// identical outcome to a vanilla S3 PUT, just earlier than
// padding-then-complete would catch it.
let likely_final = original_size < S3_MULTIPART_MIN_PART_BYTES as u64;
if !likely_final {
pad_to_minimum(&mut framed, S3_MULTIPART_MIN_PART_BYTES);
}
let framed_bytes = framed.freeze();
let new_len = framed_bytes.len() as i64;
// 同じ wire 互換問題が multipart にもある (content-length / checksum)
req.input.content_length = Some(new_len);
req.input.checksum_algorithm = None;
req.input.checksum_crc32 = None;
req.input.checksum_crc32c = None;
req.input.checksum_crc64nvme = None;
req.input.checksum_sha1 = None;
req.input.checksum_sha256 = None;
req.input.content_md5 = None;
req.input.body = Some(bytes_to_blob(framed_bytes));
debug!(
part_number = ?req.input.part_number,
upload_id = ?req.input.upload_id,
original_size,
framed_size = new_len,
"S4 upload_part: framed compressed payload"
);
}
self.backend.upload_part(req).await
}
async fn complete_multipart_upload(
&self,
mut req: S3Request<CompleteMultipartUploadInput>,
) -> S3Result<S3Response<CompleteMultipartUploadOutput>> {
let bucket = req.input.bucket.clone();
let key = req.input.key.clone();
let upload_id = req.input.upload_id.clone();
// v0.8.1 #59: serialise concurrent Complete invocations on the
// same `(bucket, key)`. The race window the lock closes is the
// GET-assembled-body → encrypt → PUT-encrypted-body triple
// below (BUG-5 fix); without serialisation, two Completes for
// different `upload_id` but the same logical key could each
// read the other's plaintext assembled body and overwrite the
// peer's encrypted result. The guard is held to function exit
// (drop on `Ok` / `Err`), covering version-id mint, object-
// lock apply, tagging persist, and replication enqueue too.
let completion_lock = self.multipart_state.completion_lock(&bucket, &key);
let _completion_guard = completion_lock.lock().await;
// v0.8 #54 — fetch the per-upload context captured on Create.
// `None` means an abandoned / unknown upload_id (gateway
// crashed between Create and Complete, or pre-v0.8 state
// restore); we still let the backend do its thing for
// transparency, but we can't apply any SSE / version / lock /
// tag / replication post-processing because we never captured
// the recipe.
let ctx = self.multipart_state.get(upload_id.as_str());
// v0.8 #54 BUG-10 fix: same SSE-C header strip as upload_part
// — some clients (boto3 / aws-sdk-cpp older versions) replay
// the SSE-C triple on Complete too, and MinIO will choke if
// they reach the backend.
let _ = req.input.sse_customer_algorithm.take();
let _ = req.input.sse_customer_key.take();
let _ = req.input.sse_customer_key_md5.take();
let mut resp = self.backend.complete_multipart_upload(req).await?;
// CompleteMultipartUpload 成功 → 完成した object を full fetch して frame
// index を build、`<key>.s4index` sidecar として保存。これで Range GET の
// partial fetch path が利用可能になる (Range request の帯域節約)。
// 注: 巨大 object の場合この pass は重いが、Range query は一度 sidecar が
// できれば爆速になるので 1 回の cost は payback される
//
// v0.8 #54 BUG-5..9: this same fetch is the choke-point for
// the SSE encrypt re-PUT + versioning shadow-key rewrite +
// replication source-bytes capture, so we GET once and reuse
// the bytes for every post-processing step.
let assembled_body: Option<bytes::Bytes> =
if let Ok(uri) = safe_object_uri(&bucket, &key) {
let get_input = GetObjectInput {
bucket: bucket.clone(),
key: key.clone(),
..Default::default()
};
let get_req = S3Request {
input: get_input,
method: http::Method::GET,
uri,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
match self.backend.get_object(get_req).await {
Ok(get_resp) => match get_resp.output.body {
Some(blob) => collect_blob(blob, self.max_body_bytes).await.ok(),
None => None,
},
Err(_) => None,
}
} else {
None
};
// Sidecar build (existing behaviour, gated on assembled body).
if let Some(ref body) = assembled_body
&& let Ok(index) = build_index_from_body(body)
{
self.write_sidecar(&bucket, &key, &index).await;
}
// From here on, post-processing depends on the context —
// short-circuit when the upload had no captured recipe
// (legacy / crashed-Create / pre-v0.8 state restore).
if let Some(ctx) = ctx {
// v0.8 #54 BUG-6 fix: mint a version-id when the bucket
// is versioning-Enabled. The single-PUT path does this in
// `put_object` ~L1968; multipart was the missing branch.
// We mint here (post-Complete, before any re-PUT) so the
// same vid threads into both the shadow-key rewrite and
// the VersionEntry the manager records.
let pending_version: Option<crate::versioning::PutOutcome> = self
.versioning
.as_ref()
.map(|mgr| mgr.state(&bucket))
.map(|state| match state {
crate::versioning::VersioningState::Enabled => {
crate::versioning::PutOutcome {
version_id: crate::versioning::VersioningManager::new_version_id(),
versioned_response: true,
}
}
crate::versioning::VersioningState::Suspended
| crate::versioning::VersioningState::Unversioned => {
crate::versioning::PutOutcome {
version_id: crate::versioning::NULL_VERSION_ID.to_owned(),
versioned_response: false,
}
}
});
// v0.8 #54 BUG-5 fix: encrypt the assembled framed body
// and re-PUT it to the backend so the on-disk bytes are
// SSE-encrypted. The single-PUT path does this body-by-
// body inside `put_object` (L1907-L1942); for multipart,
// encrypt-per-part would require a multi-segment decrypt
// path on GET — we instead do a single encrypt over the
// assembled framed body so the existing GET decrypt
// branch (`is_sse_encrypted` → `decrypt(body, source)` →
// FrameIter) handles it unchanged.
//
// The cost is one extra round-trip per Complete for SSE-
// enabled multipart (already-paid for the sidecar build).
// For single-instance gateways pointing at a co-located
// backend this is negligible; cross-region operators
// would benefit from per-part encrypt + multi-segment
// decrypt as a follow-up.
let needs_re_put = matches!(
ctx.sse,
crate::multipart_state::MultipartSseMode::SseS4
| crate::multipart_state::MultipartSseMode::SseC { .. }
| crate::multipart_state::MultipartSseMode::SseKms { .. }
) || pending_version
.as_ref()
.map(|pv| pv.versioned_response)
.unwrap_or(false);
// Snapshot replication body in advance so we can pass it
// to the spawn helper after the (possibly absent) re-PUT.
let replication_body = assembled_body.clone();
let mut applied_metadata: Option<std::collections::HashMap<String, String>> = None;
if needs_re_put && let Some(body) = assembled_body {
// v0.8.1 #58: same Zeroizing pattern as put_object's
// single-PUT KMS branch — DEK plaintext lives in
// `Zeroizing<[u8; 32]>` for the lifetime of this
// Complete handler, then is wiped on drop.
let kms_wrap: Option<(
zeroize::Zeroizing<[u8; 32]>,
crate::kms::WrappedDek,
)> = if let crate::multipart_state::MultipartSseMode::SseKms {
ref key_id,
} = ctx.sse
{
let kms = self.kms.as_ref().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"SSE-KMS requested but no --kms-local-dir / --kms-aws-region is configured on this gateway",
)
})?;
let (dek, wrapped) = kms
.generate_dek(key_id)
.await
.map_err(kms_error_to_s3)?;
if dek.len() != 32 {
return Err(S3Error::with_message(
S3ErrorCode::InternalError,
format!(
"KMS backend returned a DEK of {} bytes (expected 32)",
dek.len()
),
));
}
let mut dek_arr: zeroize::Zeroizing<[u8; 32]> =
zeroize::Zeroizing::new([0u8; 32]);
dek_arr.copy_from_slice(&dek);
// `dek` (Zeroizing<Vec<u8>>) is dropped at scope end.
Some((dek_arr, wrapped))
} else {
None
};
// Build the new metadata map: re-fetch via HEAD so
// the multipart / codec markers the backend stamped
// on Create flow through unchanged, then layer the
// SSE markers on top.
let head_req = S3Request {
input: HeadObjectInput {
bucket: bucket.clone(),
key: key.clone(),
..Default::default()
},
method: http::Method::HEAD,
uri: safe_object_uri(&bucket, &key)?,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let mut new_metadata: std::collections::HashMap<String, String> =
match self.backend.head_object(head_req).await {
Ok(h) => h.output.metadata.unwrap_or_default(),
Err(_) => std::collections::HashMap::new(),
};
let new_body = match &ctx.sse {
crate::multipart_state::MultipartSseMode::SseC { key, key_md5 } => {
new_metadata.insert("s4-encrypted".into(), "aes-256-gcm".into());
new_metadata.insert("s4-sse-type".into(), "AES256".into());
new_metadata.insert(
"s4-sse-c-key-md5".into(),
base64::engine::general_purpose::STANDARD.encode(key_md5),
);
// v0.8.2 #62: `key` is `&Zeroizing<[u8; 32]>`;
// auto-deref through one explicit binding so
// `SseSource::CustomerKey` gets the `&[u8; 32]`
// it expects (mirrors the SSE-KMS DEK shape
// a few lines down).
let key_ref: &[u8; 32] = key;
crate::sse::encrypt_with_source(
&body,
crate::sse::SseSource::CustomerKey { key: key_ref, key_md5 },
)
}
crate::multipart_state::MultipartSseMode::SseKms { .. } => {
let (dek, wrapped) = kms_wrap
.as_ref()
.expect("SseKms branch implies kms_wrap is Some");
new_metadata.insert("s4-encrypted".into(), "aes-256-gcm".into());
new_metadata.insert("s4-sse-type".into(), "aws:kms".into());
new_metadata
.insert("s4-sse-kms-key-id".into(), wrapped.key_id.clone());
// v0.8.1 #58: auto-deref from `&Zeroizing<[u8; 32]>`
// to `&[u8; 32]` (same shape as the put_object
// single-PUT branch).
let dek_ref: &[u8; 32] = dek;
crate::sse::encrypt_with_source(
&body,
crate::sse::SseSource::Kms { dek: dek_ref, wrapped },
)
}
crate::multipart_state::MultipartSseMode::SseS4 => {
let keyring = self.sse_keyring.as_ref().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InternalError,
"SSE-S4 captured at Create but keyring missing at Complete",
)
})?;
new_metadata.insert("s4-encrypted".into(), "aes-256-gcm".into());
// SSE-S4 deliberately omits `s4-sse-type` so
// HEAD doesn't falsely advertise AWS-style
// SSE-S3 (matches the put_object L1929-L1939
// comment).
// v0.8 #52: same chunk_size dispatch as the
// single-PUT branch — multipart Complete
// re-encrypts the assembled body, so honoring
// the chunked path here is required to keep
// GET streaming on multipart-uploaded objects.
if self.sse_chunk_size > 0 {
crate::sse::encrypt_v2_chunked(
&body,
keyring,
self.sse_chunk_size,
)
.map_err(|e| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!(
"SSE-S4 chunked encrypt failed at Complete: {e}"
),
)
})?
} else {
crate::sse::encrypt_v2(&body, keyring)
}
}
crate::multipart_state::MultipartSseMode::None => body.clone(),
};
// v0.8 #54 BUG-6 fix: write the re-PUT under the
// shadow key so the version chain doesn't overwrite
// the previous version on a versioned bucket. The
// original (unshadowed) key was assembled by the
// backend on Complete; we delete it after the shadow
// PUT lands.
let put_target_key = if let Some(pv) = pending_version.as_ref() {
if pv.versioned_response {
versioned_shadow_key(&key, &pv.version_id)
} else {
key.clone()
}
} else {
key.clone()
};
let new_body_len = new_body.len() as i64;
let put_req = S3Request {
input: PutObjectInput {
bucket: bucket.clone(),
key: put_target_key.clone(),
body: Some(bytes_to_blob(new_body.clone())),
metadata: Some(new_metadata.clone()),
content_length: Some(new_body_len),
..Default::default()
},
method: http::Method::PUT,
uri: safe_object_uri(&bucket, &put_target_key)?,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
self.backend.put_object(put_req).await?;
// If we rewrote the storage key (versioning shadow),
// we must drop the original (unshadowed) Complete-
// assembled bytes so subsequent listings don't see a
// duplicate.
if put_target_key != key {
let del_req = S3Request {
input: DeleteObjectInput {
bucket: bucket.clone(),
key: key.clone(),
..Default::default()
},
method: http::Method::DELETE,
uri: safe_object_uri(&bucket, &key)?,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: None,
region: None,
service: None,
trailing_headers: None,
};
let _ = self.backend.delete_object(del_req).await;
}
applied_metadata = Some(new_metadata);
}
// v0.8 #54 BUG-6 commit: register the new version with
// the VersioningManager so list_object_versions /
// GET ?versionId= see it.
if let (Some(mgr), Some(pv)) = (self.versioning.as_ref(), pending_version.as_ref()) {
let etag = resp
.output
.e_tag
.clone()
.map(ETag::into_value)
.unwrap_or_default();
let now = chrono::Utc::now();
mgr.commit_put_with_version(
&bucket,
&key,
crate::versioning::VersionEntry {
version_id: pv.version_id.clone(),
etag,
size: replication_body
.as_ref()
.map(|b| b.len() as u64)
.unwrap_or(0),
is_delete_marker: false,
created_at: now,
},
);
if pv.versioned_response {
resp.output.version_id = Some(pv.version_id.clone());
}
}
// v0.8 #54 BUG-7 fix: persist any per-upload Object Lock
// recipe + auto-apply the bucket default. Mirrors the
// put_object L2057-L2074 block.
if let Some(mgr) = self.object_lock.as_ref() {
if ctx.object_lock_mode.is_some()
|| ctx.object_lock_retain_until.is_some()
|| ctx.object_lock_legal_hold
{
let mut state = mgr.get(&bucket, &key).unwrap_or_default();
if let Some(m) = ctx.object_lock_mode {
state.mode = Some(m);
}
if let Some(u) = ctx.object_lock_retain_until {
state.retain_until = Some(u);
}
if ctx.object_lock_legal_hold {
state.legal_hold_on = true;
}
mgr.set(&bucket, &key, state);
}
mgr.apply_default_on_put(&bucket, &key, chrono::Utc::now());
}
// v0.8 #54 BUG-9 fix: persist the captured tags via the
// TagManager so GetObjectTagging returns them.
if let (Some(mgr), Some(tags)) = (self.tagging.as_ref(), ctx.tags.as_ref()) {
mgr.put_object_tags(&bucket, &key, tags.clone());
}
// SSE-C / SSE-KMS response echo. The
// CompleteMultipartUploadOutput only exposes
// `server_side_encryption` + `ssekms_key_id` (no
// sse_customer_* — those round-tripped on Create / parts).
match &ctx.sse {
crate::multipart_state::MultipartSseMode::SseC { .. } => {
resp.output.server_side_encryption = Some(
ServerSideEncryption::from_static(ServerSideEncryption::AES256),
);
}
crate::multipart_state::MultipartSseMode::SseKms { key_id } => {
resp.output.server_side_encryption = Some(
ServerSideEncryption::from_static(ServerSideEncryption::AWS_KMS),
);
resp.output.ssekms_key_id = Some(key_id.clone());
}
_ => {}
}
// v0.8 #54 BUG-8 fix: fire cross-bucket replication just
// like put_object L2165 does. We hand the dispatcher the
// assembled body bytes (post-encrypt where applicable, so
// the destination ends up byte-identical to the source's
// on-disk shape) plus the metadata that was actually
// committed.
let replication_body_bytes = replication_body.unwrap_or_default();
// v0.8.2 #61: thread the multipart-Complete `pending_version`
// through so a versioning-Enabled source's destination
// receives the same shadow-key path (mirror of the
// single-PUT branch above).
self.spawn_replication_if_matched(
&bucket,
&key,
&ctx.tags,
&replication_body_bytes,
&applied_metadata,
true,
pending_version.as_ref(),
);
self.multipart_state.remove(upload_id.as_str());
}
// v0.8.1 #59 janitor: best-effort sweep of stale completion
// locks while we are still on the critical path of a single
// Complete (so steady-state workloads of unique keys don't
// accumulate `DashMap` entries). The sweep only retires
// entries whose `Arc::strong_count == 1`, so any other in-
// flight Complete on a different key keeps its lock alive.
// Our own `_completion_guard` keeps `bucket`/`key`'s entry
// alive across this call; it's reaped on the next Complete or
// the next caller-driven prune.
self.multipart_state.prune_completion_locks();
Ok(resp)
}
async fn abort_multipart_upload(
&self,
req: S3Request<AbortMultipartUploadInput>,
) -> S3Result<S3Response<AbortMultipartUploadOutput>> {
// v0.8 #54: drop the per-upload state (SSE-C key bytes / tag
// set) promptly so an aborted upload doesn't leak the
// customer's key into a long-running gateway's RSS.
self.multipart_state.remove(req.input.upload_id.as_str());
self.backend.abort_multipart_upload(req).await
}
async fn list_multipart_uploads(
&self,
req: S3Request<ListMultipartUploadsInput>,
) -> S3Result<S3Response<ListMultipartUploadsOutput>> {
self.backend.list_multipart_uploads(req).await
}
async fn list_parts(
&self,
req: S3Request<ListPartsInput>,
) -> S3Result<S3Response<ListPartsOutput>> {
self.backend.list_parts(req).await
}
// =========================================================================
// Phase 2 — pure passthrough delegations。S4 はこれらに対して圧縮 hook を
// 持たないので、backend (= AWS S3) の動作と完全に同一。
//
// 既知の制限事項:
// - copy_object / upload_part_copy: source object が S4-compressed の場合、
// backend が bytes を copy するだけなので metadata (s4-codec etc) も一緒に
// coppied される (AWS S3 default = MetadataDirective COPY)。GET は manifest
// 経由で正しく decompress できる。MetadataDirective REPLACE で上書き
// されると圧縮 metadata が消えて壊れる — 顧客側の運用で注意
// - list_object_versions: versioning enabled bucket では各 version も S4
// metadata を維持する。古い version も S4 経由で正しく GET できる。
// =========================================================================
// ---- Object ACL / tagging / attributes ----
async fn get_object_acl(
&self,
req: S3Request<GetObjectAclInput>,
) -> S3Result<S3Response<GetObjectAclOutput>> {
self.backend.get_object_acl(req).await
}
async fn put_object_acl(
&self,
req: S3Request<PutObjectAclInput>,
) -> S3Result<S3Response<PutObjectAclOutput>> {
self.backend.put_object_acl(req).await
}
// v0.6 #39: object tagging — when a `TagManager` is attached the
// configuration / per-(bucket, key) state lives in the manager and
// these handlers serve directly from it; when no manager is
// attached they fall back to the backend (legacy passthrough so
// v0.5 deployments are unaffected).
async fn get_object_tagging(
&self,
req: S3Request<GetObjectTaggingInput>,
) -> S3Result<S3Response<GetObjectTaggingOutput>> {
let Some(mgr) = self.tagging.as_ref() else {
return self.backend.get_object_tagging(req).await;
};
let tags = mgr
.get_object_tags(&req.input.bucket, &req.input.key)
.unwrap_or_default();
Ok(S3Response::new(GetObjectTaggingOutput {
tag_set: tagset_to_aws(&tags),
..Default::default()
}))
}
async fn put_object_tagging(
&self,
req: S3Request<PutObjectTaggingInput>,
) -> S3Result<S3Response<PutObjectTaggingOutput>> {
let Some(mgr) = self.tagging.as_ref() else {
return self.backend.put_object_tagging(req).await;
};
let bucket = req.input.bucket.clone();
let key = req.input.key.clone();
let parsed = aws_to_tagset(&req.input.tagging.tag_set).map_err(|e| {
S3Error::with_message(S3ErrorCode::InvalidArgument, e.to_string())
})?;
// v0.6 #39: gate via IAM policy with both the request tags
// (`s3:RequestObjectTag/<key>`) and any existing tags on the
// target object (`s3:ExistingObjectTag/<key>`).
let existing = mgr.get_object_tags(&bucket, &key);
self.enforce_policy_with_extra(
&req,
"s3:PutObjectTagging",
&bucket,
Some(&key),
Some(&parsed),
existing.as_ref(),
)?;
mgr.put_object_tags(&bucket, &key, parsed);
Ok(S3Response::new(PutObjectTaggingOutput::default()))
}
async fn delete_object_tagging(
&self,
req: S3Request<DeleteObjectTaggingInput>,
) -> S3Result<S3Response<DeleteObjectTaggingOutput>> {
let Some(mgr) = self.tagging.as_ref() else {
return self.backend.delete_object_tagging(req).await;
};
let bucket = req.input.bucket.clone();
let key = req.input.key.clone();
let existing = mgr.get_object_tags(&bucket, &key);
self.enforce_policy_with_extra(
&req,
"s3:DeleteObjectTagging",
&bucket,
Some(&key),
None,
existing.as_ref(),
)?;
mgr.delete_object_tags(&bucket, &key);
Ok(S3Response::new(DeleteObjectTaggingOutput::default()))
}
async fn get_object_attributes(
&self,
req: S3Request<GetObjectAttributesInput>,
) -> S3Result<S3Response<GetObjectAttributesOutput>> {
self.backend.get_object_attributes(req).await
}
async fn restore_object(
&self,
req: S3Request<RestoreObjectInput>,
) -> S3Result<S3Response<RestoreObjectOutput>> {
self.backend.restore_object(req).await
}
async fn upload_part_copy(
&self,
req: S3Request<UploadPartCopyInput>,
) -> S3Result<S3Response<UploadPartCopyOutput>> {
// v0.2 #6: byte-range aware copy when the source is S4-framed.
//
// For a framed source (multipart upload OR single-PUT framed-v2),
// a naive byte-range passthrough would copy compressed bytes that
// don't align with S4 frame boundaries — silently corrupting the
// result. Instead we GET the source through S4 (which handles
// decompression + Range), re-compress + re-frame as a new part,
// and forward as upload_part. For non-framed sources (S4-untouched
// raw objects), passthrough is correct and we keep the original
// (cheaper) code path.
let CopySource::Bucket {
bucket: src_bucket,
key: src_key,
..
} = &req.input.copy_source
else {
return self.backend.upload_part_copy(req).await;
};
let src_bucket = src_bucket.to_string();
let src_key = src_key.to_string();
// Probe metadata to decide whether the source needs S4-aware copy.
let head_input = HeadObjectInput {
bucket: src_bucket.clone(),
key: src_key.clone(),
..Default::default()
};
let head_req = S3Request {
input: head_input,
method: http::Method::HEAD,
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let needs_s4_copy = match self.backend.head_object(head_req).await {
Ok(h) => {
is_multipart_object(&h.output.metadata) || is_framed_v2_object(&h.output.metadata)
}
Err(_) => false,
};
if !needs_s4_copy {
return self.backend.upload_part_copy(req).await;
}
// Resolve the optional source byte range to pass to GET.
let source_range = req
.input
.copy_source_range
.as_ref()
.map(|r| parse_copy_source_range(r))
.transpose()
.map_err(|e| S3Error::with_message(S3ErrorCode::InvalidRange, e))?;
// GET source via S4 (handles decompression + sidecar partial fetch
// when range is present). The result is the requested user-visible
// byte range, fully decompressed.
let mut get_input = GetObjectInput {
bucket: src_bucket.clone(),
key: src_key.clone(),
..Default::default()
};
get_input.range = source_range;
let get_req = S3Request {
input: get_input,
method: http::Method::GET,
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let get_resp = self.get_object(get_req).await?;
let blob = get_resp.output.body.ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InternalError,
"upload_part_copy: empty body from source GET",
)
})?;
let bytes = collect_blob(blob, self.max_body_bytes)
.await
.map_err(internal("collect upload_part_copy source body"))?;
// Compress + frame as a fresh part (mirrors upload_part path).
let sample_len = bytes.len().min(SAMPLE_BYTES);
// v0.8 #56: same size-hint promotion as the upload_part path.
let codec_kind = self
.dispatcher
.pick_with_size_hint(&bytes[..sample_len], Some(bytes.len() as u64))
.await;
let original_size = bytes.len() as u64;
// v0.8 #55: telemetry-returning compress (GPU metrics stamp).
let (compress_res, tel) = self
.registry
.compress_with_telemetry(bytes, codec_kind)
.await;
stamp_gpu_compress_telemetry(&tel);
let (compressed, manifest) =
compress_res.map_err(internal("registry compress upload_part_copy"))?;
let header = FrameHeader {
codec: codec_kind,
original_size,
compressed_size: compressed.len() as u64,
crc32c: manifest.crc32c,
};
let mut framed = BytesMut::with_capacity(FRAME_HEADER_BYTES + compressed.len());
write_frame(&mut framed, header, &compressed);
let likely_final = original_size < S3_MULTIPART_MIN_PART_BYTES as u64;
if !likely_final {
pad_to_minimum(&mut framed, S3_MULTIPART_MIN_PART_BYTES);
}
let framed_bytes = framed.freeze();
let framed_len = framed_bytes.len() as i64;
// Forward as upload_part to the destination multipart upload.
let part_input = UploadPartInput {
bucket: req.input.bucket.clone(),
key: req.input.key.clone(),
part_number: req.input.part_number,
upload_id: req.input.upload_id.clone(),
body: Some(bytes_to_blob(framed_bytes)),
content_length: Some(framed_len),
..Default::default()
};
let part_req = S3Request {
input: part_input,
method: http::Method::PUT,
uri: req.uri.clone(),
headers: req.headers.clone(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let upload_resp = self.backend.upload_part(part_req).await?;
let copy_output = UploadPartCopyOutput {
copy_part_result: Some(CopyPartResult {
e_tag: upload_resp.output.e_tag.clone(),
..Default::default()
}),
..Default::default()
};
Ok(S3Response::new(copy_output))
}
// ---- Object lock / retention / legal hold (v0.5 #30) ----
//
// When an `ObjectLockManager` is attached the configuration / per-object
// state lives in the manager and these handlers serve directly from it;
// when no manager is attached they fall back to the backend (legacy
// passthrough so v0.4 deployments are unaffected).
async fn get_object_lock_configuration(
&self,
req: S3Request<GetObjectLockConfigurationInput>,
) -> S3Result<S3Response<GetObjectLockConfigurationOutput>> {
if let Some(mgr) = self.object_lock.as_ref() {
let cfg = mgr.bucket_default(&req.input.bucket).map(|d| {
ObjectLockConfiguration {
object_lock_enabled: Some(ObjectLockEnabled::from_static(
ObjectLockEnabled::ENABLED,
)),
rule: Some(ObjectLockRule {
default_retention: Some(DefaultRetention {
days: Some(d.retention_days as i32),
mode: Some(ObjectLockRetentionMode::from_static(
match d.mode {
crate::object_lock::LockMode::Governance => {
ObjectLockRetentionMode::GOVERNANCE
}
crate::object_lock::LockMode::Compliance => {
ObjectLockRetentionMode::COMPLIANCE
}
},
)),
years: None,
}),
}),
}
});
let output = GetObjectLockConfigurationOutput {
object_lock_configuration: cfg,
};
return Ok(S3Response::new(output));
}
self.backend.get_object_lock_configuration(req).await
}
async fn put_object_lock_configuration(
&self,
req: S3Request<PutObjectLockConfigurationInput>,
) -> S3Result<S3Response<PutObjectLockConfigurationOutput>> {
if let Some(mgr) = self.object_lock.as_ref() {
let bucket = req.input.bucket.clone();
if let Some(cfg) = req.input.object_lock_configuration.as_ref()
&& let Some(rule) = cfg.rule.as_ref()
&& let Some(d) = rule.default_retention.as_ref()
{
let mode = d
.mode
.as_ref()
.and_then(|m| crate::object_lock::LockMode::from_aws_str(m.as_str()))
.ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"Object Lock default retention requires a valid Mode (GOVERNANCE | COMPLIANCE)",
)
})?;
// S3 spec: exactly one of Days / Years (we accept Days
// outright and convert Years → Days for storage; Years
// is just a UX shorthand on the wire).
let days: u32 = match (d.days, d.years) {
(Some(d), None) if d > 0 => d as u32,
(None, Some(y)) if y > 0 => (y as u32).saturating_mul(365),
_ => {
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"Object Lock default retention requires exactly one of Days or Years (positive integer)",
));
}
};
mgr.set_bucket_default(
&bucket,
crate::object_lock::BucketObjectLockDefault {
mode,
retention_days: days,
},
);
}
return Ok(S3Response::new(PutObjectLockConfigurationOutput::default()));
}
self.backend.put_object_lock_configuration(req).await
}
async fn get_object_legal_hold(
&self,
req: S3Request<GetObjectLegalHoldInput>,
) -> S3Result<S3Response<GetObjectLegalHoldOutput>> {
if let Some(mgr) = self.object_lock.as_ref() {
let on = mgr
.get(&req.input.bucket, &req.input.key)
.map(|s| s.legal_hold_on)
.unwrap_or(false);
let status = ObjectLockLegalHoldStatus::from_static(if on {
ObjectLockLegalHoldStatus::ON
} else {
ObjectLockLegalHoldStatus::OFF
});
let output = GetObjectLegalHoldOutput {
legal_hold: Some(ObjectLockLegalHold {
status: Some(status),
}),
};
return Ok(S3Response::new(output));
}
self.backend.get_object_legal_hold(req).await
}
async fn put_object_legal_hold(
&self,
req: S3Request<PutObjectLegalHoldInput>,
) -> S3Result<S3Response<PutObjectLegalHoldOutput>> {
if let Some(mgr) = self.object_lock.as_ref() {
let on = req
.input
.legal_hold
.as_ref()
.and_then(|h| h.status.as_ref())
.map(|s| s.as_str().eq_ignore_ascii_case("ON"))
.unwrap_or(false);
mgr.set_legal_hold(&req.input.bucket, &req.input.key, on);
return Ok(S3Response::new(PutObjectLegalHoldOutput::default()));
}
self.backend.put_object_legal_hold(req).await
}
async fn get_object_retention(
&self,
req: S3Request<GetObjectRetentionInput>,
) -> S3Result<S3Response<GetObjectRetentionOutput>> {
if let Some(mgr) = self.object_lock.as_ref() {
let retention = mgr
.get(&req.input.bucket, &req.input.key)
.filter(|s| s.mode.is_some() || s.retain_until.is_some())
.map(|s| {
let mode = s.mode.map(|m| {
ObjectLockRetentionMode::from_static(match m {
crate::object_lock::LockMode::Governance => {
ObjectLockRetentionMode::GOVERNANCE
}
crate::object_lock::LockMode::Compliance => {
ObjectLockRetentionMode::COMPLIANCE
}
})
});
let until = s.retain_until.map(chrono_utc_to_timestamp);
ObjectLockRetention {
mode,
retain_until_date: until,
}
});
let output = GetObjectRetentionOutput { retention };
return Ok(S3Response::new(output));
}
self.backend.get_object_retention(req).await
}
async fn put_object_retention(
&self,
req: S3Request<PutObjectRetentionInput>,
) -> S3Result<S3Response<PutObjectRetentionOutput>> {
if let Some(mgr) = self.object_lock.as_ref() {
let bucket = req.input.bucket.clone();
let key = req.input.key.clone();
let bypass = req.input.bypass_governance_retention.unwrap_or(false);
let retention = req.input.retention.as_ref().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InvalidRequest,
"PutObjectRetention requires a Retention element",
)
})?;
let new_mode = retention
.mode
.as_ref()
.and_then(|m| crate::object_lock::LockMode::from_aws_str(m.as_str()));
let new_until = retention
.retain_until_date
.as_ref()
.map(timestamp_to_chrono_utc)
.unwrap_or(None);
let now = chrono::Utc::now();
let existing = mgr.get(&bucket, &key).unwrap_or_default();
// S3 immutability rules:
// - Compliance is one-way: once set, mode cannot move to
// Governance, and retain-until cannot be shortened.
// - Governance can be lengthened freely; shortened only
// with bypass=true.
if let Some(existing_mode) = existing.mode
&& existing_mode == crate::object_lock::LockMode::Compliance
&& existing.is_locked(now)
{
if matches!(new_mode, Some(crate::object_lock::LockMode::Governance)) {
return Err(S3Error::with_message(
S3ErrorCode::AccessDenied,
"Cannot downgrade Compliance retention to Governance while lock is active",
));
}
if let (Some(prev), Some(next)) = (existing.retain_until, new_until)
&& next < prev
{
return Err(S3Error::with_message(
S3ErrorCode::AccessDenied,
"Cannot shorten Compliance retention while lock is active",
));
}
}
if let Some(existing_mode) = existing.mode
&& existing_mode == crate::object_lock::LockMode::Governance
&& existing.is_locked(now)
&& !bypass
&& let (Some(prev), Some(next)) = (existing.retain_until, new_until)
&& next < prev
{
return Err(S3Error::with_message(
S3ErrorCode::AccessDenied,
"Shortening Governance retention requires x-amz-bypass-governance-retention: true",
));
}
let mut state = existing;
if new_mode.is_some() {
state.mode = new_mode;
}
if new_until.is_some() {
state.retain_until = new_until;
}
mgr.set(&bucket, &key, state);
return Ok(S3Response::new(PutObjectRetentionOutput::default()));
}
self.backend.put_object_retention(req).await
}
// ---- Versioning ----
// list_object_versions is implemented above in the compression-hook
// section so it filters S4-internal sidecars (v0.4 #17) AND, when a
// VersioningManager is attached (v0.5 #34), serves chains directly
// from the in-memory index.
async fn get_bucket_versioning(
&self,
req: S3Request<GetBucketVersioningInput>,
) -> S3Result<S3Response<GetBucketVersioningOutput>> {
// v0.5 #34: when a VersioningManager is attached, the bucket's
// versioning state lives in the manager (= S4-server's
// authoritative source). Pass-through hits the backend only
// when no manager is configured (legacy v0.4 behaviour).
if let Some(mgr) = self.versioning.as_ref() {
let output = match mgr.state(&req.input.bucket).as_aws_status() {
Some(s) => GetBucketVersioningOutput {
status: Some(BucketVersioningStatus::from(s.to_owned())),
..Default::default()
},
None => GetBucketVersioningOutput::default(),
};
return Ok(S3Response::new(output));
}
self.backend.get_bucket_versioning(req).await
}
async fn put_bucket_versioning(
&self,
req: S3Request<PutBucketVersioningInput>,
) -> S3Result<S3Response<PutBucketVersioningOutput>> {
// v0.6 #42: MFA gating on the `PutBucketVersioning` request
// itself. S3 spec: when the request body carries an
// `MfaDelete` element (either `Enabled` or `Disabled`), the
// request must include a valid `x-amz-mfa` token — both for
// the *first* enable (so the operator can't quietly side-step
// the gate by never enabling it) and for any subsequent
// change (so a leaked credential alone can't disable MFA
// Delete to bypass it on subsequent DELETEs). Requests that
// omit the `MfaDelete` element entirely (i.e. they flip only
// `Status`) skip this gate, matching AWS.
if let Some(mgr) = self.mfa_delete.as_ref()
&& let Some(target_enabled) = req
.input
.versioning_configuration
.mfa_delete
.as_ref()
.map(|m| m.as_str().eq_ignore_ascii_case("Enabled"))
{
let bucket = req.input.bucket.clone();
let header = req.input.mfa.as_deref();
let secret = mgr.lookup_secret(&bucket);
let verified = match (header, secret.as_ref()) {
(Some(h), Some(s)) => match crate::mfa::parse_mfa_header(h) {
Ok((serial, code)) => {
serial == s.serial
&& crate::mfa::verify_totp(
&s.secret_base32,
&code,
current_unix_secs(),
)
}
Err(_) => false,
},
_ => false,
};
if !verified {
crate::metrics::record_mfa_delete_denial(&bucket);
let err = if header.is_none() {
crate::mfa::MfaError::Missing
} else {
crate::mfa::MfaError::InvalidCode
};
return Err(mfa_error_to_s3(err));
}
mgr.set_bucket_state(&bucket, target_enabled);
}
// v0.5 #34: stash the new state in the manager, then forward to
// the backend so any downstream that *also* tracks state
// (e.g. a real S3 backend) stays in sync. Manager-attached but
// backend rejection is treated as a soft-fail (state is still
// owned by the manager).
if let Some(mgr) = self.versioning.as_ref() {
let new_state = match req
.input
.versioning_configuration
.status
.as_ref()
.map(|s| s.as_str())
{
Some(s) if s.eq_ignore_ascii_case("Enabled") => {
crate::versioning::VersioningState::Enabled
}
Some(s) if s.eq_ignore_ascii_case("Suspended") => {
crate::versioning::VersioningState::Suspended
}
_ => crate::versioning::VersioningState::Unversioned,
};
mgr.set_state(&req.input.bucket, new_state);
return Ok(S3Response::new(PutBucketVersioningOutput::default()));
}
self.backend.put_bucket_versioning(req).await
}
// ---- Bucket location ----
async fn get_bucket_location(
&self,
req: S3Request<GetBucketLocationInput>,
) -> S3Result<S3Response<GetBucketLocationOutput>> {
self.backend.get_bucket_location(req).await
}
// ---- Bucket policy ----
async fn get_bucket_policy(
&self,
req: S3Request<GetBucketPolicyInput>,
) -> S3Result<S3Response<GetBucketPolicyOutput>> {
self.backend.get_bucket_policy(req).await
}
async fn put_bucket_policy(
&self,
req: S3Request<PutBucketPolicyInput>,
) -> S3Result<S3Response<PutBucketPolicyOutput>> {
self.backend.put_bucket_policy(req).await
}
async fn delete_bucket_policy(
&self,
req: S3Request<DeleteBucketPolicyInput>,
) -> S3Result<S3Response<DeleteBucketPolicyOutput>> {
self.backend.delete_bucket_policy(req).await
}
async fn get_bucket_policy_status(
&self,
req: S3Request<GetBucketPolicyStatusInput>,
) -> S3Result<S3Response<GetBucketPolicyStatusOutput>> {
self.backend.get_bucket_policy_status(req).await
}
// ---- Bucket ACL ----
async fn get_bucket_acl(
&self,
req: S3Request<GetBucketAclInput>,
) -> S3Result<S3Response<GetBucketAclOutput>> {
self.backend.get_bucket_acl(req).await
}
async fn put_bucket_acl(
&self,
req: S3Request<PutBucketAclInput>,
) -> S3Result<S3Response<PutBucketAclOutput>> {
self.backend.put_bucket_acl(req).await
}
// ---- Bucket CORS (v0.6 #38) ----
async fn get_bucket_cors(
&self,
req: S3Request<GetBucketCorsInput>,
) -> S3Result<S3Response<GetBucketCorsOutput>> {
if let Some(mgr) = self.cors.as_ref() {
let cfg = mgr.get(&req.input.bucket).ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::NoSuchCORSConfiguration,
"The CORS configuration does not exist".to_string(),
)
})?;
let rules: Vec<CORSRule> = cfg
.rules
.into_iter()
.map(|r| CORSRule {
allowed_headers: if r.allowed_headers.is_empty() {
None
} else {
Some(r.allowed_headers)
},
allowed_methods: r.allowed_methods,
allowed_origins: r.allowed_origins,
expose_headers: if r.expose_headers.is_empty() {
None
} else {
Some(r.expose_headers)
},
id: r.id,
max_age_seconds: r.max_age_seconds.map(|s| s as i32),
})
.collect();
return Ok(S3Response::new(GetBucketCorsOutput {
cors_rules: Some(rules),
}));
}
self.backend.get_bucket_cors(req).await
}
async fn put_bucket_cors(
&self,
req: S3Request<PutBucketCorsInput>,
) -> S3Result<S3Response<PutBucketCorsOutput>> {
if let Some(mgr) = self.cors.as_ref() {
let cfg = crate::cors::CorsConfig {
rules: req
.input
.cors_configuration
.cors_rules
.into_iter()
.map(|r| crate::cors::CorsRule {
allowed_origins: r.allowed_origins,
allowed_methods: r.allowed_methods,
allowed_headers: r.allowed_headers.unwrap_or_default(),
expose_headers: r.expose_headers.unwrap_or_default(),
max_age_seconds: r.max_age_seconds.and_then(|s| {
if s < 0 { None } else { Some(s as u32) }
}),
id: r.id,
})
.collect(),
};
mgr.put(&req.input.bucket, cfg);
return Ok(S3Response::new(PutBucketCorsOutput::default()));
}
self.backend.put_bucket_cors(req).await
}
async fn delete_bucket_cors(
&self,
req: S3Request<DeleteBucketCorsInput>,
) -> S3Result<S3Response<DeleteBucketCorsOutput>> {
if let Some(mgr) = self.cors.as_ref() {
mgr.delete(&req.input.bucket);
return Ok(S3Response::new(DeleteBucketCorsOutput::default()));
}
self.backend.delete_bucket_cors(req).await
}
// ---- Bucket lifecycle (v0.6 #37) ----
async fn get_bucket_lifecycle_configuration(
&self,
req: S3Request<GetBucketLifecycleConfigurationInput>,
) -> S3Result<S3Response<GetBucketLifecycleConfigurationOutput>> {
if let Some(mgr) = self.lifecycle.as_ref() {
let cfg = mgr.get(&req.input.bucket).ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::NoSuchLifecycleConfiguration,
"The lifecycle configuration does not exist".to_string(),
)
})?;
let rules: Vec<LifecycleRule> = cfg.rules.iter().map(internal_rule_to_dto).collect();
return Ok(S3Response::new(GetBucketLifecycleConfigurationOutput {
rules: Some(rules),
transition_default_minimum_object_size: None,
}));
}
self.backend.get_bucket_lifecycle_configuration(req).await
}
async fn put_bucket_lifecycle_configuration(
&self,
req: S3Request<PutBucketLifecycleConfigurationInput>,
) -> S3Result<S3Response<PutBucketLifecycleConfigurationOutput>> {
if let Some(mgr) = self.lifecycle.as_ref() {
let bucket = req.input.bucket.clone();
let dto_cfg = req.input.lifecycle_configuration.unwrap_or_default();
let cfg = dto_lifecycle_to_internal(&dto_cfg);
mgr.put(&bucket, cfg);
return Ok(S3Response::new(
PutBucketLifecycleConfigurationOutput::default(),
));
}
self.backend.put_bucket_lifecycle_configuration(req).await
}
async fn delete_bucket_lifecycle(
&self,
req: S3Request<DeleteBucketLifecycleInput>,
) -> S3Result<S3Response<DeleteBucketLifecycleOutput>> {
if let Some(mgr) = self.lifecycle.as_ref() {
mgr.delete(&req.input.bucket);
return Ok(S3Response::new(DeleteBucketLifecycleOutput::default()));
}
self.backend.delete_bucket_lifecycle(req).await
}
// ---- Bucket tagging (v0.6 #39) ----
async fn get_bucket_tagging(
&self,
req: S3Request<GetBucketTaggingInput>,
) -> S3Result<S3Response<GetBucketTaggingOutput>> {
let Some(mgr) = self.tagging.as_ref() else {
return self.backend.get_bucket_tagging(req).await;
};
let tags = mgr.get_bucket_tags(&req.input.bucket).unwrap_or_default();
Ok(S3Response::new(GetBucketTaggingOutput {
tag_set: tagset_to_aws(&tags),
}))
}
async fn put_bucket_tagging(
&self,
req: S3Request<PutBucketTaggingInput>,
) -> S3Result<S3Response<PutBucketTaggingOutput>> {
let Some(mgr) = self.tagging.as_ref() else {
return self.backend.put_bucket_tagging(req).await;
};
let bucket = req.input.bucket.clone();
let parsed = aws_to_tagset(&req.input.tagging.tag_set).map_err(|e| {
S3Error::with_message(S3ErrorCode::InvalidArgument, e.to_string())
})?;
self.enforce_policy(&req, "s3:PutBucketTagging", &bucket, None)?;
mgr.put_bucket_tags(&bucket, parsed);
Ok(S3Response::new(PutBucketTaggingOutput::default()))
}
async fn delete_bucket_tagging(
&self,
req: S3Request<DeleteBucketTaggingInput>,
) -> S3Result<S3Response<DeleteBucketTaggingOutput>> {
let Some(mgr) = self.tagging.as_ref() else {
return self.backend.delete_bucket_tagging(req).await;
};
let bucket = req.input.bucket.clone();
self.enforce_policy(&req, "s3:PutBucketTagging", &bucket, None)?;
mgr.delete_bucket_tags(&bucket);
Ok(S3Response::new(DeleteBucketTaggingOutput::default()))
}
// ---- Bucket encryption ----
async fn get_bucket_encryption(
&self,
req: S3Request<GetBucketEncryptionInput>,
) -> S3Result<S3Response<GetBucketEncryptionOutput>> {
self.backend.get_bucket_encryption(req).await
}
async fn put_bucket_encryption(
&self,
req: S3Request<PutBucketEncryptionInput>,
) -> S3Result<S3Response<PutBucketEncryptionOutput>> {
self.backend.put_bucket_encryption(req).await
}
async fn delete_bucket_encryption(
&self,
req: S3Request<DeleteBucketEncryptionInput>,
) -> S3Result<S3Response<DeleteBucketEncryptionOutput>> {
self.backend.delete_bucket_encryption(req).await
}
// ---- Bucket logging ----
async fn get_bucket_logging(
&self,
req: S3Request<GetBucketLoggingInput>,
) -> S3Result<S3Response<GetBucketLoggingOutput>> {
self.backend.get_bucket_logging(req).await
}
async fn put_bucket_logging(
&self,
req: S3Request<PutBucketLoggingInput>,
) -> S3Result<S3Response<PutBucketLoggingOutput>> {
self.backend.put_bucket_logging(req).await
}
// ---- Bucket notification (v0.6 #35) ----
//
// When a `NotificationManager` is attached, S4 itself owns per-bucket
// notification configurations and the PUT / GET handlers route through
// the manager. The wire DTO's queue / topic configurations map onto
// S4's `Destination::Sqs` / `Destination::Sns`; LambdaFunction and
// EventBridge configurations are accepted on PUT but silently dropped
// (out of scope for v0.6 #35). When no manager is attached the legacy
// backend-passthrough behaviour applies.
async fn get_bucket_notification_configuration(
&self,
req: S3Request<GetBucketNotificationConfigurationInput>,
) -> S3Result<S3Response<GetBucketNotificationConfigurationOutput>> {
if let Some(mgr) = self.notifications.as_ref() {
let cfg = mgr.get(&req.input.bucket).unwrap_or_default();
let dto = notif_to_dto(&cfg);
return Ok(S3Response::new(GetBucketNotificationConfigurationOutput {
event_bridge_configuration: dto.event_bridge_configuration,
lambda_function_configurations: dto.lambda_function_configurations,
queue_configurations: dto.queue_configurations,
topic_configurations: dto.topic_configurations,
}));
}
self.backend
.get_bucket_notification_configuration(req)
.await
}
async fn put_bucket_notification_configuration(
&self,
req: S3Request<PutBucketNotificationConfigurationInput>,
) -> S3Result<S3Response<PutBucketNotificationConfigurationOutput>> {
if let Some(mgr) = self.notifications.as_ref() {
let cfg = notif_from_dto(&req.input.notification_configuration);
mgr.put(&req.input.bucket, cfg);
return Ok(S3Response::new(
PutBucketNotificationConfigurationOutput::default(),
));
}
self.backend
.put_bucket_notification_configuration(req)
.await
}
// ---- Bucket request payment ----
async fn get_bucket_request_payment(
&self,
req: S3Request<GetBucketRequestPaymentInput>,
) -> S3Result<S3Response<GetBucketRequestPaymentOutput>> {
self.backend.get_bucket_request_payment(req).await
}
async fn put_bucket_request_payment(
&self,
req: S3Request<PutBucketRequestPaymentInput>,
) -> S3Result<S3Response<PutBucketRequestPaymentOutput>> {
self.backend.put_bucket_request_payment(req).await
}
// ---- Bucket website ----
async fn get_bucket_website(
&self,
req: S3Request<GetBucketWebsiteInput>,
) -> S3Result<S3Response<GetBucketWebsiteOutput>> {
self.backend.get_bucket_website(req).await
}
async fn put_bucket_website(
&self,
req: S3Request<PutBucketWebsiteInput>,
) -> S3Result<S3Response<PutBucketWebsiteOutput>> {
self.backend.put_bucket_website(req).await
}
async fn delete_bucket_website(
&self,
req: S3Request<DeleteBucketWebsiteInput>,
) -> S3Result<S3Response<DeleteBucketWebsiteOutput>> {
self.backend.delete_bucket_website(req).await
}
// ---- Bucket replication (v0.6 #40) ----
async fn get_bucket_replication(
&self,
req: S3Request<GetBucketReplicationInput>,
) -> S3Result<S3Response<GetBucketReplicationOutput>> {
if let Some(mgr) = self.replication.as_ref() {
return match mgr.get(&req.input.bucket) {
Some(cfg) => Ok(S3Response::new(GetBucketReplicationOutput {
replication_configuration: Some(replication_to_dto(&cfg)),
})),
None => Err(S3Error::with_message(
S3ErrorCode::Custom("ReplicationConfigurationNotFoundError".into()),
format!("no replication configuration on bucket {}", req.input.bucket),
)),
};
}
self.backend.get_bucket_replication(req).await
}
async fn put_bucket_replication(
&self,
req: S3Request<PutBucketReplicationInput>,
) -> S3Result<S3Response<PutBucketReplicationOutput>> {
if let Some(mgr) = self.replication.as_ref() {
let cfg = replication_from_dto(&req.input.replication_configuration);
mgr.put(&req.input.bucket, cfg);
return Ok(S3Response::new(PutBucketReplicationOutput::default()));
}
self.backend.put_bucket_replication(req).await
}
async fn delete_bucket_replication(
&self,
req: S3Request<DeleteBucketReplicationInput>,
) -> S3Result<S3Response<DeleteBucketReplicationOutput>> {
if let Some(mgr) = self.replication.as_ref() {
mgr.delete(&req.input.bucket);
return Ok(S3Response::new(DeleteBucketReplicationOutput::default()));
}
self.backend.delete_bucket_replication(req).await
}
// ---- Bucket accelerate ----
async fn get_bucket_accelerate_configuration(
&self,
req: S3Request<GetBucketAccelerateConfigurationInput>,
) -> S3Result<S3Response<GetBucketAccelerateConfigurationOutput>> {
self.backend.get_bucket_accelerate_configuration(req).await
}
async fn put_bucket_accelerate_configuration(
&self,
req: S3Request<PutBucketAccelerateConfigurationInput>,
) -> S3Result<S3Response<PutBucketAccelerateConfigurationOutput>> {
self.backend.put_bucket_accelerate_configuration(req).await
}
// ---- Bucket ownership controls ----
async fn get_bucket_ownership_controls(
&self,
req: S3Request<GetBucketOwnershipControlsInput>,
) -> S3Result<S3Response<GetBucketOwnershipControlsOutput>> {
self.backend.get_bucket_ownership_controls(req).await
}
async fn put_bucket_ownership_controls(
&self,
req: S3Request<PutBucketOwnershipControlsInput>,
) -> S3Result<S3Response<PutBucketOwnershipControlsOutput>> {
self.backend.put_bucket_ownership_controls(req).await
}
async fn delete_bucket_ownership_controls(
&self,
req: S3Request<DeleteBucketOwnershipControlsInput>,
) -> S3Result<S3Response<DeleteBucketOwnershipControlsOutput>> {
self.backend.delete_bucket_ownership_controls(req).await
}
// ---- Public access block ----
async fn get_public_access_block(
&self,
req: S3Request<GetPublicAccessBlockInput>,
) -> S3Result<S3Response<GetPublicAccessBlockOutput>> {
self.backend.get_public_access_block(req).await
}
async fn put_public_access_block(
&self,
req: S3Request<PutPublicAccessBlockInput>,
) -> S3Result<S3Response<PutPublicAccessBlockOutput>> {
self.backend.put_public_access_block(req).await
}
async fn delete_public_access_block(
&self,
req: S3Request<DeletePublicAccessBlockInput>,
) -> S3Result<S3Response<DeletePublicAccessBlockOutput>> {
self.backend.delete_public_access_block(req).await
}
// ====================================================================
// v0.6 #41: S3 Select — server-side SQL filter on object body.
//
// Fetch the object via the regular `get_object` path (so SSE-C /
// SSE-S4 / SSE-KMS / S4 codec all decompress + decrypt transparently),
// run a small SQL subset (CSV + JSON Lines, equality / inequality /
// LIKE / AND / OR / NOT) over the in-memory body, and stream the
// matched rows back as AWS event-stream `Records` + `Stats` + `End`
// frames.
//
// Limitations (deliberate, documented):
// - Parquet input is rejected with NotImplemented.
// - Aggregates / GROUP BY / JOIN / ORDER BY / LIMIT are rejected at
// parse time as InvalidRequest (s3s 0.13 doesn't expose AWS's
// domain-specific `InvalidSqlExpression` code).
// - The body is fully buffered before SQL evaluation (S3 Select
// streaming-during-evaluation is v0.7 scope).
// - GPU-accelerated WHERE evaluation is stubbed out (always None).
async fn select_object_content(
&self,
req: S3Request<SelectObjectContentInput>,
) -> S3Result<S3Response<SelectObjectContentOutput>> {
use crate::select::{
EventStreamWriter, SelectInputFormat, SelectOutputFormat, run_select_csv,
run_select_jsonlines,
};
let select_bucket = req.input.bucket.clone();
let select_key = req.input.key.clone();
self.enforce_rate_limit(&req, &select_bucket)?;
self.enforce_policy(
&req,
"s3:GetObject",
&select_bucket,
Some(&select_key),
)?;
let request = req.input.request;
let sql = request.expression.clone();
if request.expression_type.as_str() != "SQL" {
return Err(S3Error::with_message(
S3ErrorCode::InvalidExpressionType,
format!(
"ExpressionType must be SQL, got: {}",
request.expression_type.as_str()
),
));
}
let input_format = if let Some(_json) = request.input_serialization.json.as_ref() {
SelectInputFormat::JsonLines
} else if let Some(csv) = request.input_serialization.csv.as_ref() {
let has_header = csv
.file_header_info
.as_ref()
.map(|h| {
let s = h.as_str();
s.eq_ignore_ascii_case("USE") || s.eq_ignore_ascii_case("IGNORE")
})
.unwrap_or(false);
let delim = csv
.field_delimiter
.as_deref()
.and_then(|s| s.chars().next())
.unwrap_or(',');
SelectInputFormat::Csv {
has_header,
delimiter: delim,
}
} else if request.input_serialization.parquet.is_some() {
return Err(S3Error::with_message(
S3ErrorCode::NotImplemented,
"Parquet input is not supported by this S3 Select implementation (v0.6: CSV / JSON Lines only)",
));
} else {
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"InputSerialization requires exactly one of CSV / JSON / Parquet",
));
};
if let Some(ct) = request.input_serialization.compression_type.as_ref()
&& !ct.as_str().eq_ignore_ascii_case("NONE")
{
return Err(S3Error::with_message(
S3ErrorCode::NotImplemented,
format!(
"InputSerialization CompressionType={} is not supported (v0.6: NONE only)",
ct.as_str()
),
));
}
let output_format = if request.output_serialization.json.is_some() {
SelectOutputFormat::Json
} else if request.output_serialization.csv.is_some() {
SelectOutputFormat::Csv
} else {
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
"OutputSerialization requires exactly one of CSV / JSON",
));
};
let get_input = GetObjectInput {
bucket: select_bucket.clone(),
key: select_key.clone(),
sse_customer_algorithm: req.input.sse_customer_algorithm.clone(),
sse_customer_key: req.input.sse_customer_key.clone(),
sse_customer_key_md5: req.input.sse_customer_key_md5.clone(),
..Default::default()
};
let get_req = S3Request {
input: get_input,
method: http::Method::GET,
uri: format!("/{}/{}", select_bucket, select_key)
.parse()
.map_err(|e| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("constructing inner GET URI: {e}"),
)
})?,
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
credentials: req.credentials.clone(),
region: req.region.clone(),
service: req.service.clone(),
trailing_headers: None,
};
let mut get_resp = self.get_object(get_req).await?;
let blob = get_resp.output.body.take().ok_or_else(|| {
S3Error::with_message(
S3ErrorCode::InternalError,
"Select: object body was empty after GET",
)
})?;
let body_bytes = crate::blob::collect_blob(blob, self.max_body_bytes)
.await
.map_err(internal("collect Select body"))?;
let scanned = body_bytes.len() as u64;
let matched_payload = match input_format {
SelectInputFormat::JsonLines => {
run_select_jsonlines(&sql, &body_bytes, output_format).map_err(
|e| select_error_to_s3(e, "JSON Lines"),
)?
}
SelectInputFormat::Csv { .. } => {
run_select_csv(&sql, &body_bytes, input_format, output_format)
.map_err(|e| select_error_to_s3(e, "CSV"))?
}
};
let returned = matched_payload.len() as u64;
let processed = scanned;
let mut events: Vec<S3Result<SelectObjectContentEvent>> = Vec::with_capacity(3);
if !matched_payload.is_empty() {
events.push(Ok(SelectObjectContentEvent::Records(RecordsEvent {
payload: Some(bytes::Bytes::from(matched_payload)),
})));
}
events.push(Ok(SelectObjectContentEvent::Stats(StatsEvent {
details: Some(Stats {
bytes_scanned: Some(scanned as i64),
bytes_processed: Some(processed as i64),
bytes_returned: Some(returned as i64),
}),
})));
events.push(Ok(SelectObjectContentEvent::End(EndEvent {})));
// Touch EventStreamWriter so the public API stays linked into the
// build (the actual wire framing is delegated to s3s).
let _writer = EventStreamWriter::new();
let stream =
SelectObjectContentEventStream::new(futures::stream::iter(events));
let output = SelectObjectContentOutput {
payload: Some(stream),
};
Ok(S3Response::new(output))
}
// ---- Bucket Inventory configuration (v0.6 #36) ----
//
// When an `InventoryManager` is attached, S4-server owns the
// configuration store and these handlers no longer pass through to
// the backend. The mapping between the s3s-typed
// `InventoryConfiguration` and the inventory module's internal
// `InventoryConfig` is intentionally lossy: only the fields S4
// actually uses for periodic CSV emission survive the round trip
// (id, source bucket, destination bucket / prefix, format, included
// versions, schedule frequency). Optional fields, encryption, and
// filter prefixes are accepted on PUT and re-surfaced on GET via
// a best-effort default-shape `InventoryConfiguration` so the
// client sees a roundtrip-clean response.
async fn put_bucket_inventory_configuration(
&self,
req: S3Request<PutBucketInventoryConfigurationInput>,
) -> S3Result<S3Response<PutBucketInventoryConfigurationOutput>> {
if let Some(mgr) = self.inventory.as_ref() {
let cfg = inv_from_dto(
&req.input.bucket,
&req.input.id,
&req.input.inventory_configuration,
);
mgr.put(cfg);
return Ok(S3Response::new(PutBucketInventoryConfigurationOutput::default()));
}
self.backend.put_bucket_inventory_configuration(req).await
}
async fn get_bucket_inventory_configuration(
&self,
req: S3Request<GetBucketInventoryConfigurationInput>,
) -> S3Result<S3Response<GetBucketInventoryConfigurationOutput>> {
if let Some(mgr) = self.inventory.as_ref() {
let cfg = mgr.get(&req.input.bucket, &req.input.id);
if let Some(cfg) = cfg {
let out = GetBucketInventoryConfigurationOutput {
inventory_configuration: Some(inv_to_dto(&cfg)),
};
return Ok(S3Response::new(out));
}
// AWS returns `NoSuchConfiguration` (404) when the id has no
// matching inventory configuration on the bucket. The
// generated `S3ErrorCode` enum doesn't expose a typed variant
// for this code, so we round-trip through `from_bytes` which
// wraps unknown codes as `Custom(...)` (= the AWS-canonical
// error-code string survives into the XML response envelope).
let code = S3ErrorCode::from_bytes(b"NoSuchConfiguration")
.unwrap_or(S3ErrorCode::NoSuchKey);
return Err(S3Error::with_message(
code,
format!(
"no inventory configuration with id={} on bucket={}",
req.input.id, req.input.bucket
),
));
}
self.backend.get_bucket_inventory_configuration(req).await
}
async fn list_bucket_inventory_configurations(
&self,
req: S3Request<ListBucketInventoryConfigurationsInput>,
) -> S3Result<S3Response<ListBucketInventoryConfigurationsOutput>> {
if let Some(mgr) = self.inventory.as_ref() {
let list = mgr.list_for_bucket(&req.input.bucket);
let dto_list: Vec<InventoryConfiguration> = list.iter().map(inv_to_dto).collect();
let out = ListBucketInventoryConfigurationsOutput {
continuation_token: req.input.continuation_token.clone(),
inventory_configuration_list: if dto_list.is_empty() {
None
} else {
Some(dto_list)
},
is_truncated: Some(false),
next_continuation_token: None,
};
return Ok(S3Response::new(out));
}
self.backend.list_bucket_inventory_configurations(req).await
}
async fn delete_bucket_inventory_configuration(
&self,
req: S3Request<DeleteBucketInventoryConfigurationInput>,
) -> S3Result<S3Response<DeleteBucketInventoryConfigurationOutput>> {
if let Some(mgr) = self.inventory.as_ref() {
mgr.delete(&req.input.bucket, &req.input.id);
return Ok(S3Response::new(
DeleteBucketInventoryConfigurationOutput::default(),
));
}
self.backend.delete_bucket_inventory_configuration(req).await
}
}
// ---------------------------------------------------------------------------
// v0.6 #36: Convert between the s3s-typed `InventoryConfiguration` (the wire
// surface) and our internal `crate::inventory::InventoryConfig`. Only the
// fields S4 actually uses for CSV emission survive the round trip; the
// missing fields (filter prefix, optional fields, encryption) are dropped on
// PUT and re-rendered as the AWS-default shape on GET so the client sees a
// well-formed `InventoryConfiguration`.
// ---------------------------------------------------------------------------
fn inv_from_dto(
bucket: &str,
id: &str,
dto: &InventoryConfiguration,
) -> crate::inventory::InventoryConfig {
let frequency_hours = match dto.schedule.frequency.as_str() {
"Weekly" => 24 * 7,
// Daily is the default; anything S4 doesn't recognise (incl.
// empty, which is the s3s-default) maps to Daily so the
// operator's PUT doesn't silently turn into a no-op cadence.
_ => 24,
};
// Parquet/ORC are not supported (issue #36 scope); we still accept
// the PUT so callers don't fail-loud, but we record CSV and rely on
// the operator catching the discrepancy on GET.
let format = crate::inventory::InventoryFormat::Csv;
crate::inventory::InventoryConfig {
id: id.to_owned(),
bucket: bucket.to_owned(),
destination_bucket: dto.destination.s3_bucket_destination.bucket.clone(),
destination_prefix: dto
.destination
.s3_bucket_destination
.prefix
.clone()
.unwrap_or_default(),
frequency_hours,
format,
included_object_versions: crate::inventory::IncludedVersions::from_aws_str(
dto.included_object_versions.as_str(),
),
}
}
fn inv_to_dto(cfg: &crate::inventory::InventoryConfig) -> InventoryConfiguration {
InventoryConfiguration {
id: cfg.id.clone(),
is_enabled: true,
included_object_versions: InventoryIncludedObjectVersions::from(
cfg.included_object_versions.as_aws_str().to_owned(),
),
destination: InventoryDestination {
s3_bucket_destination: InventoryS3BucketDestination {
account_id: None,
bucket: cfg.destination_bucket.clone(),
encryption: None,
format: InventoryFormat::from(cfg.format.as_aws_str().to_owned()),
prefix: if cfg.destination_prefix.is_empty() {
None
} else {
Some(cfg.destination_prefix.clone())
},
},
},
schedule: InventorySchedule {
// `frequency_hours == 168` -> Weekly; everything else maps to
// Daily for the wire response (the manager keeps the precise
// hour count internally for due-checking).
frequency: InventoryFrequency::from(
if cfg.frequency_hours == 24 * 7 {
"Weekly"
} else {
"Daily"
}
.to_owned(),
),
},
filter: None,
optional_fields: None,
}
}
// ---------------------------------------------------------------------------
// v0.6 #35: Convert between the s3s-typed `NotificationConfiguration` (the
// wire surface) and our internal `crate::notifications::NotificationConfig`.
//
// We support TopicConfiguration (-> Destination::Sns) and QueueConfiguration
// (-> Destination::Sqs). LambdaFunction and EventBridge configurations are
// silently dropped on PUT (out of scope for v0.6 #35); the GET response only
// surfaces topic / queue rules.
//
// The webhook destination has no AWS-native wire form: operators configure
// webhooks via the JSON snapshot file (`--notifications-state-file`) or by
// poking `NotificationManager::put` directly from a custom binary. This
// keeps the wire surface AWS-compatible while still letting the always-
// available `Webhook` destination be reachable.
// ---------------------------------------------------------------------------
fn notif_from_dto(
dto: &NotificationConfiguration,
) -> crate::notifications::NotificationConfig {
let mut rules: Vec<crate::notifications::NotificationRule> = Vec::new();
if let Some(topics) = dto.topic_configurations.as_ref() {
for (idx, t) in topics.iter().enumerate() {
let events = events_from_dto(&t.events);
let (prefix, suffix) = filter_from_dto(t.filter.as_ref());
rules.push(crate::notifications::NotificationRule {
id: t.id.clone().unwrap_or_else(|| format!("topic-{idx}")),
events,
destination: crate::notifications::Destination::Sns {
topic_arn: t.topic_arn.clone(),
},
filter_prefix: prefix,
filter_suffix: suffix,
});
}
}
if let Some(queues) = dto.queue_configurations.as_ref() {
for (idx, q) in queues.iter().enumerate() {
let events = events_from_dto(&q.events);
let (prefix, suffix) = filter_from_dto(q.filter.as_ref());
rules.push(crate::notifications::NotificationRule {
id: q.id.clone().unwrap_or_else(|| format!("queue-{idx}")),
events,
destination: crate::notifications::Destination::Sqs {
queue_arn: q.queue_arn.clone(),
},
filter_prefix: prefix,
filter_suffix: suffix,
});
}
}
crate::notifications::NotificationConfig { rules }
}
fn notif_to_dto(
cfg: &crate::notifications::NotificationConfig,
) -> NotificationConfiguration {
let mut topics: Vec<TopicConfiguration> = Vec::new();
let mut queues: Vec<QueueConfiguration> = Vec::new();
for rule in &cfg.rules {
let events: Vec<Event> = rule
.events
.iter()
.map(|e| Event::from(e.as_aws_str().to_owned()))
.collect();
let filter = filter_to_dto(rule.filter_prefix.as_deref(), rule.filter_suffix.as_deref());
match &rule.destination {
crate::notifications::Destination::Sns { topic_arn } => {
topics.push(TopicConfiguration {
events,
filter,
id: Some(rule.id.clone()),
topic_arn: topic_arn.clone(),
});
}
crate::notifications::Destination::Sqs { queue_arn } => {
queues.push(QueueConfiguration {
events,
filter,
id: Some(rule.id.clone()),
queue_arn: queue_arn.clone(),
});
}
// Webhook destinations have no AWS wire equivalent — they
// round-trip through the JSON snapshot only. Skip them on the
// GET surface (an SDK consumer wouldn't know what to do with
// them anyway).
crate::notifications::Destination::Webhook { .. } => {}
}
}
NotificationConfiguration {
event_bridge_configuration: None,
lambda_function_configurations: None,
queue_configurations: if queues.is_empty() { None } else { Some(queues) },
topic_configurations: if topics.is_empty() { None } else { Some(topics) },
}
}
fn events_from_dto(events: &[Event]) -> Vec<crate::notifications::EventType> {
events
.iter()
.filter_map(|e| crate::notifications::EventType::from_aws_str(e.as_ref()))
.collect()
}
fn filter_from_dto(
f: Option<&NotificationConfigurationFilter>,
) -> (Option<String>, Option<String>) {
let Some(f) = f else {
return (None, None);
};
let Some(key) = f.key.as_ref() else {
return (None, None);
};
let Some(rules) = key.filter_rules.as_ref() else {
return (None, None);
};
let mut prefix = None;
let mut suffix = None;
for r in rules {
let name = r.name.as_ref().map(|n| n.as_str().to_ascii_lowercase());
let value = r.value.clone();
match name.as_deref() {
Some("prefix") => prefix = value,
Some("suffix") => suffix = value,
_ => {}
}
}
(prefix, suffix)
}
fn filter_to_dto(
prefix: Option<&str>,
suffix: Option<&str>,
) -> Option<NotificationConfigurationFilter> {
if prefix.is_none() && suffix.is_none() {
return None;
}
let mut rules: Vec<FilterRule> = Vec::new();
if let Some(p) = prefix {
rules.push(FilterRule {
name: Some(FilterRuleName::from("prefix".to_owned())),
value: Some(p.to_owned()),
});
}
if let Some(s) = suffix {
rules.push(FilterRule {
name: Some(FilterRuleName::from("suffix".to_owned())),
value: Some(s.to_owned()),
});
}
Some(NotificationConfigurationFilter {
key: Some(S3KeyFilter {
filter_rules: Some(rules),
}),
})
}
// ---------------------------------------------------------------------------
// v0.6 #40: Convert between the s3s-typed `ReplicationConfiguration` (the
// wire surface) and our internal `crate::replication::ReplicationConfig`.
// AWS's `ReplicationRuleFilter` is a sum type — `Prefix | Tag | And { Prefix,
// Tags }`; we flatten it into the single `(prefix, tag-vec)` representation
// the matcher needs. Sub-blocks v0.6 #40 does not implement
// (DeleteMarkerReplication / SourceSelectionCriteria / ReplicationTime /
// Metrics / EncryptionConfiguration) round-trip as `None` on GET — operators
// who set them on PUT see them silently dropped, mirroring "feature not
// supported in this release" semantics.
// ---------------------------------------------------------------------------
fn replication_from_dto(
dto: &ReplicationConfiguration,
) -> crate::replication::ReplicationConfig {
let rules = dto
.rules
.iter()
.enumerate()
.map(|(idx, r)| {
let id = r
.id
.as_ref()
.map(|s| s.as_str().to_owned())
.unwrap_or_else(|| format!("rule-{idx}"));
let priority = r.priority.unwrap_or(0).max(0) as u32;
let status_enabled = r.status.as_str() == ReplicationRuleStatus::ENABLED;
let filter = replication_filter_from_dto(r.filter.as_ref(), r.prefix.as_deref());
let destination_bucket = r.destination.bucket.clone();
let destination_storage_class = r
.destination
.storage_class
.as_ref()
.map(|s| s.as_str().to_owned());
crate::replication::ReplicationRule {
id,
priority,
status_enabled,
filter,
destination_bucket,
destination_storage_class,
}
})
.collect();
crate::replication::ReplicationConfig {
role: dto.role.clone(),
rules,
}
}
fn replication_to_dto(
cfg: &crate::replication::ReplicationConfig,
) -> ReplicationConfiguration {
let rules = cfg
.rules
.iter()
.map(|r| {
let status = if r.status_enabled {
ReplicationRuleStatus::from_static(ReplicationRuleStatus::ENABLED)
} else {
ReplicationRuleStatus::from_static(ReplicationRuleStatus::DISABLED)
};
let destination = Destination {
access_control_translation: None,
account: None,
bucket: r.destination_bucket.clone(),
encryption_configuration: None,
metrics: None,
replication_time: None,
storage_class: r
.destination_storage_class
.as_ref()
.map(|s| StorageClass::from(s.clone())),
};
let filter = Some(replication_filter_to_dto(&r.filter));
ReplicationRule {
delete_marker_replication: None,
destination,
existing_object_replication: None,
filter,
id: Some(r.id.clone()),
prefix: None,
priority: Some(r.priority as i32),
source_selection_criteria: None,
status,
}
})
.collect();
ReplicationConfiguration {
role: cfg.role.clone(),
rules,
}
}
fn replication_filter_from_dto(
f: Option<&ReplicationRuleFilter>,
rule_level_prefix: Option<&str>,
) -> crate::replication::ReplicationFilter {
let mut prefix: Option<String> = rule_level_prefix.map(str::to_owned);
let mut tags: Vec<(String, String)> = Vec::new();
if let Some(f) = f {
if let Some(p) = f.prefix.as_ref()
&& prefix.is_none()
{
prefix = Some(p.clone());
}
if let Some(t) = f.tag.as_ref()
&& let (Some(k), Some(v)) = (t.key.as_ref(), t.value.as_ref())
{
tags.push((k.clone(), v.clone()));
}
if let Some(and) = f.and.as_ref() {
if let Some(p) = and.prefix.as_ref()
&& prefix.is_none()
{
prefix = Some(p.clone());
}
if let Some(ts) = and.tags.as_ref() {
for t in ts {
if let (Some(k), Some(v)) = (t.key.as_ref(), t.value.as_ref()) {
tags.push((k.clone(), v.clone()));
}
}
}
}
}
crate::replication::ReplicationFilter { prefix, tags }
}
fn replication_filter_to_dto(
f: &crate::replication::ReplicationFilter,
) -> ReplicationRuleFilter {
if f.tags.is_empty() {
ReplicationRuleFilter {
and: None,
prefix: f.prefix.clone(),
tag: None,
}
} else if f.tags.len() == 1 && f.prefix.is_none() {
let (k, v) = &f.tags[0];
ReplicationRuleFilter {
and: None,
prefix: None,
tag: Some(Tag {
key: Some(k.clone()),
value: Some(v.clone()),
}),
}
} else {
let tags: Vec<Tag> = f
.tags
.iter()
.map(|(k, v)| Tag {
key: Some(k.clone()),
value: Some(v.clone()),
})
.collect();
ReplicationRuleFilter {
and: Some(ReplicationRuleAndOperator {
prefix: f.prefix.clone(),
tags: Some(tags),
}),
prefix: None,
tag: None,
}
}
}
// ---------------------------------------------------------------------------
// v0.6 #37: Convert between the s3s-typed `BucketLifecycleConfiguration`
// (the wire surface) and our internal `crate::lifecycle::LifecycleConfig`.
// The internal representation flattens AWS's "Filter | And" disjunction
// into a single `LifecycleFilter` struct of optional fields plus a tag
// vector. Fields S4's evaluator does not consume
// (`expired_object_delete_marker`, `noncurrent_version_transitions`,
// `transition_default_minimum_object_size`, the storage class on the
// noncurrent expiration) are dropped on PUT and re-rendered as their
// AWS-default shape on GET so the client always sees a well-formed
// configuration.
// ---------------------------------------------------------------------------
fn dto_lifecycle_to_internal(
dto: &BucketLifecycleConfiguration,
) -> crate::lifecycle::LifecycleConfig {
crate::lifecycle::LifecycleConfig {
rules: dto.rules.iter().map(dto_rule_to_internal).collect(),
}
}
fn dto_rule_to_internal(rule: &LifecycleRule) -> crate::lifecycle::LifecycleRule {
let status = crate::lifecycle::LifecycleStatus::from_aws_str(rule.status.as_str());
let filter = rule
.filter
.as_ref()
.map(dto_filter_to_internal)
.unwrap_or_default();
let expiration_days = rule
.expiration
.as_ref()
.and_then(|e| e.days)
.and_then(|d| u32::try_from(d).ok());
let expiration_date = rule
.expiration
.as_ref()
.and_then(|e| e.date.as_ref())
.and_then(timestamp_to_chrono_utc);
let transitions: Vec<crate::lifecycle::TransitionRule> = rule
.transitions
.as_ref()
.map(|ts| {
ts.iter()
.filter_map(|t| {
let days = u32::try_from(t.days?).ok()?;
let storage_class = t.storage_class.as_ref()?.as_str().to_owned();
Some(crate::lifecycle::TransitionRule {
days,
storage_class,
})
})
.collect()
})
.unwrap_or_default();
let noncurrent_version_expiration_days = rule
.noncurrent_version_expiration
.as_ref()
.and_then(|n| n.noncurrent_days)
.and_then(|d| u32::try_from(d).ok());
let abort_incomplete_multipart_upload_days = rule
.abort_incomplete_multipart_upload
.as_ref()
.and_then(|a| a.days_after_initiation)
.and_then(|d| u32::try_from(d).ok());
crate::lifecycle::LifecycleRule {
id: rule.id.clone().unwrap_or_default(),
status,
filter,
expiration_days,
expiration_date,
transitions,
noncurrent_version_expiration_days,
abort_incomplete_multipart_upload_days,
}
}
fn dto_filter_to_internal(filter: &LifecycleRuleFilter) -> crate::lifecycle::LifecycleFilter {
let mut prefix = filter.prefix.clone();
let mut tags: Vec<(String, String)> = Vec::new();
let mut size_gt: Option<u64> = filter
.object_size_greater_than
.and_then(|n| u64::try_from(n).ok());
let mut size_lt: Option<u64> = filter
.object_size_less_than
.and_then(|n| u64::try_from(n).ok());
if let Some(t) = &filter.tag
&& let (Some(k), Some(v)) = (t.key.as_ref(), t.value.as_ref())
{
tags.push((k.clone(), v.clone()));
}
if let Some(and) = &filter.and {
if prefix.is_none() {
prefix = and.prefix.clone();
}
if size_gt.is_none() {
size_gt = and
.object_size_greater_than
.and_then(|n| u64::try_from(n).ok());
}
if size_lt.is_none() {
size_lt = and
.object_size_less_than
.and_then(|n| u64::try_from(n).ok());
}
if let Some(ts) = &and.tags {
for t in ts {
if let (Some(k), Some(v)) = (t.key.as_ref(), t.value.as_ref()) {
tags.push((k.clone(), v.clone()));
}
}
}
}
crate::lifecycle::LifecycleFilter {
prefix,
tags,
object_size_greater_than: size_gt,
object_size_less_than: size_lt,
}
}
fn internal_rule_to_dto(rule: &crate::lifecycle::LifecycleRule) -> LifecycleRule {
let expiration = if rule.expiration_days.is_some() || rule.expiration_date.is_some() {
Some(LifecycleExpiration {
date: rule.expiration_date.map(chrono_utc_to_timestamp),
days: rule.expiration_days.map(|d| d as i32),
expired_object_delete_marker: None,
})
} else {
None
};
let transitions: Option<TransitionList> = if rule.transitions.is_empty() {
None
} else {
Some(
rule.transitions
.iter()
.map(|t| Transition {
date: None,
days: Some(t.days as i32),
storage_class: Some(TransitionStorageClass::from(t.storage_class.clone())),
})
.collect(),
)
};
let noncurrent_version_expiration =
rule.noncurrent_version_expiration_days
.map(|d| NoncurrentVersionExpiration {
newer_noncurrent_versions: None,
noncurrent_days: Some(d as i32),
});
let abort_incomplete_multipart_upload =
rule.abort_incomplete_multipart_upload_days
.map(|d| AbortIncompleteMultipartUpload {
days_after_initiation: Some(d as i32),
});
let filter = if rule.filter.tags.is_empty()
&& rule.filter.object_size_greater_than.is_none()
&& rule.filter.object_size_less_than.is_none()
{
rule.filter.prefix.as_ref().map(|p| LifecycleRuleFilter {
and: None,
object_size_greater_than: None,
object_size_less_than: None,
prefix: Some(p.clone()),
tag: None,
})
} else if rule.filter.tags.len() == 1
&& rule.filter.prefix.is_none()
&& rule.filter.object_size_greater_than.is_none()
&& rule.filter.object_size_less_than.is_none()
{
let (k, v) = rule.filter.tags[0].clone();
Some(LifecycleRuleFilter {
and: None,
object_size_greater_than: None,
object_size_less_than: None,
prefix: None,
tag: Some(Tag {
key: Some(k),
value: Some(v),
}),
})
} else {
let tags = if rule.filter.tags.is_empty() {
None
} else {
Some(
rule.filter
.tags
.iter()
.map(|(k, v)| Tag {
key: Some(k.clone()),
value: Some(v.clone()),
})
.collect(),
)
};
Some(LifecycleRuleFilter {
and: Some(LifecycleRuleAndOperator {
object_size_greater_than: rule
.filter
.object_size_greater_than
.and_then(|n| i64::try_from(n).ok()),
object_size_less_than: rule
.filter
.object_size_less_than
.and_then(|n| i64::try_from(n).ok()),
prefix: rule.filter.prefix.clone(),
tags,
}),
object_size_greater_than: None,
object_size_less_than: None,
prefix: None,
tag: None,
})
};
LifecycleRule {
abort_incomplete_multipart_upload,
expiration,
filter,
id: if rule.id.is_empty() {
None
} else {
Some(rule.id.clone())
},
noncurrent_version_expiration,
noncurrent_version_transitions: None,
prefix: None,
status: ExpirationStatus::from(rule.status.as_aws_str().to_owned()),
transitions,
}
}
// (timestamp <-> chrono helpers `timestamp_to_chrono_utc` /
// `chrono_utc_to_timestamp` are defined earlier in this file for the
// tagging/notifications work; the lifecycle DTO converters reuse them.)
// ---------------------------------------------------------------------------
// v0.5 #33: SigV4a (asymmetric ECDSA-P256) integration hook.
//
// Kept as a self-contained block at the bottom of the file so it doesn't
// touch the existing `S4Service` struct, `new()`, or any of the per-op
// handlers above. The hook is wired in by the binary at server-build time
// as a hyper middleware layer (see `main.rs`), NOT inside `S4Service`.
//
// Lifecycle:
// 1. `SigV4aGate::new(store)` is constructed once at boot from the
// operator-supplied credential directory.
// 2. For each incoming request, `SigV4aGate::pre_route(&req,
// &requested_region, &canonical_request_bytes)` is invoked BEFORE
// the request hits the S3 framework. If the request claims SigV4a
// and verifies, control returns to the framework. Otherwise a 403
// `SignatureDoesNotMatch` is produced.
// 3. Plain SigV4 (HMAC-SHA256) requests pass through untouched.
// ---------------------------------------------------------------------------
/// Gate that fronts the S3 service path with SigV4a verification (v0.5 #33).
///
/// Wraps a [`crate::sigv4a::SigV4aCredentialStore`] and exposes a single
/// `pre_route` entry point that returns `Ok(())` for both
/// "request is plain SigV4 — pass through" and "request is SigV4a and
/// verified", and an `Err(...)` containing a 403-equivalent diagnostic
/// otherwise. Cheap to clone (the inner store is `Arc`-backed).
#[derive(Debug, Clone)]
pub struct SigV4aGate {
store: crate::sigv4a::SharedSigV4aCredentialStore,
}
impl SigV4aGate {
#[must_use]
pub fn new(store: crate::sigv4a::SharedSigV4aCredentialStore) -> Self {
Self { store }
}
/// Inspect an incoming HTTP request. Behaviour:
///
/// - Not SigV4a (no `X-Amz-Region-Set` and no SigV4a `Authorization`
/// prefix) → returns `Ok(())`; the framework's existing SigV4
/// path handles the request.
/// - SigV4a + valid signature + region match → `Ok(())`.
/// - SigV4a + unknown access-key-id → `Err` with `InvalidAccessKeyId`.
/// - SigV4a + bad signature / region mismatch → `Err` with
/// `SignatureDoesNotMatch`.
///
/// `canonical_request_bytes` is the SigV4a string-to-sign (or
/// canonical-request bytes; the caller decides) that the framework
/// has already produced for this request. Keeping it as a parameter
/// instead of rebuilding it inside the hook avoids duplicating the
/// canonicalisation logic.
pub fn pre_route<B>(
&self,
req: &http::Request<B>,
requested_region: &str,
canonical_request_bytes: &[u8],
) -> Result<(), SigV4aGateError> {
if !crate::sigv4a::detect(req) {
return Ok(());
}
let auth_hdr = req
.headers()
.get(http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.ok_or(SigV4aGateError::MissingAuthorization)?;
let parsed = crate::sigv4a::parse_authorization_header(auth_hdr)
.ok_or(SigV4aGateError::MalformedAuthorization)?;
let region_set = req
.headers()
.get(crate::sigv4a::REGION_SET_HEADER)
.and_then(|v| v.to_str().ok())
.unwrap_or("*");
let key = self
.store
.get(&parsed.access_key_id)
.ok_or_else(|| SigV4aGateError::UnknownAccessKey(parsed.access_key_id.clone()))?;
crate::sigv4a::verify(
&crate::sigv4a::CanonicalRequest::new(canonical_request_bytes),
&parsed.signature_der,
key,
region_set,
requested_region,
)
.map_err(SigV4aGateError::Verify)?;
Ok(())
}
}
/// Failure modes from [`SigV4aGate::pre_route`]. All variants map to
/// HTTP 403 with one of the two AWS-standard error codes
/// (`InvalidAccessKeyId` or `SignatureDoesNotMatch`).
#[derive(Debug, thiserror::Error)]
pub enum SigV4aGateError {
#[error("missing Authorization header")]
MissingAuthorization,
#[error("malformed SigV4a Authorization header")]
MalformedAuthorization,
#[error("unknown SigV4a access-key-id: {0}")]
UnknownAccessKey(String),
#[error("SigV4a verification failed: {0}")]
Verify(#[source] crate::sigv4a::SigV4aError),
}
impl SigV4aGateError {
/// AWS S3 error code that should accompany a 403 response.
#[must_use]
pub fn s3_error_code(&self) -> &'static str {
match self {
Self::UnknownAccessKey(_) => "InvalidAccessKeyId",
_ => "SignatureDoesNotMatch",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manifest_roundtrip_via_metadata() {
let original = ChunkManifest {
codec: CodecKind::CpuZstd,
original_size: 1234,
compressed_size: 567,
crc32c: 0xdead_beef,
};
let mut meta: Option<Metadata> = None;
write_manifest(&mut meta, &original);
let extracted = extract_manifest(&meta).expect("manifest must round-trip");
assert_eq!(extracted.codec, original.codec);
assert_eq!(extracted.original_size, original.original_size);
assert_eq!(extracted.compressed_size, original.compressed_size);
assert_eq!(extracted.crc32c, original.crc32c);
}
#[test]
fn missing_metadata_yields_none() {
let meta: Option<Metadata> = None;
assert!(extract_manifest(&meta).is_none());
}
#[test]
fn partial_metadata_yields_none() {
let mut meta = Metadata::new();
meta.insert(META_CODEC.into(), "cpu-zstd".into());
let opt = Some(meta);
assert!(extract_manifest(&opt).is_none());
}
#[test]
fn parse_copy_source_range_basic() {
let r = parse_copy_source_range("bytes=10-20").unwrap();
match r {
s3s::dto::Range::Int { first, last } => {
assert_eq!(first, 10);
assert_eq!(last, Some(20));
}
_ => panic!("expected Int range"),
}
}
#[test]
fn parse_copy_source_range_rejects_inverted() {
let err = parse_copy_source_range("bytes=20-10").unwrap_err();
assert!(err.contains("last < first"));
}
#[test]
fn parse_copy_source_range_rejects_missing_prefix() {
let err = parse_copy_source_range("10-20").unwrap_err();
assert!(err.contains("must start with 'bytes='"));
}
#[test]
fn parse_copy_source_range_rejects_open_ended() {
// S3 upload_part_copy spec requires N-M (closed); suffix and
// open-ended forms are not allowed for this header.
assert!(parse_copy_source_range("bytes=10-").is_err());
assert!(parse_copy_source_range("bytes=-10").is_err());
}
// v0.7 #49: safe_object_uri must round-trip every legal S3 key
// (which includes spaces, slashes, control chars, raw UTF-8) into
// a parseable `http::Uri` instead of panicking like the previous
// `format!(...).parse().unwrap()` call sites did.
#[test]
fn safe_object_uri_basic_ascii() {
let uri = safe_object_uri("bucket", "key").expect("ascii must be safe");
assert_eq!(uri.path(), "/bucket/key");
}
#[test]
fn safe_object_uri_encodes_spaces() {
let uri = safe_object_uri("bucket", "key with spaces").expect("must encode spaces");
// RFC 3986 path-segment encoding turns ' ' into %20.
assert!(
uri.path().contains("%20"),
"expected percent-encoded space, got {}",
uri.path()
);
assert!(uri.path().starts_with("/bucket/"));
}
#[test]
fn safe_object_uri_preserves_slashes() {
// S3 keys legally contain '/' as a logical path separator —
// the helper must NOT escape it (otherwise the synthetic URI
// changes the perceived hierarchy).
let uri =
safe_object_uri("bucket", "key/with/slashes").expect("slashes must round-trip");
assert_eq!(uri.path(), "/bucket/key/with/slashes");
}
#[test]
fn safe_object_uri_handles_newline_without_panic() {
// Newlines are control chars in URIs; whether the result is
// Ok (encoded as %0A) or Err (parse rejects), the helper
// MUST NOT panic. Either outcome is acceptable.
let _ = safe_object_uri("bucket", "key\n");
}
#[test]
fn safe_object_uri_handles_null_byte_without_panic() {
let _ = safe_object_uri("bucket", "key\0bad");
}
#[test]
fn safe_object_uri_handles_unicode_without_panic() {
// RTL override, BOM, plain Japanese — none should panic.
let _ = safe_object_uri("bucket", "rtl\u{202E}override");
let _ = safe_object_uri("bucket", "\u{FEFF}bom-key");
let _ = safe_object_uri("bucket", "日本語キー");
}
#[test]
fn safe_object_uri_no_panic_for_every_byte() {
// Exhaustive byte coverage: 0x00..=0xFF as a 1-byte key.
// None of these may panic. (0x80..=0xFF are not valid UTF-8
// by themselves; we go through `String::from_utf8_lossy` so
// the helper sees a real `&str` regardless of the raw byte.)
for b in 0u8..=255 {
let s = String::from_utf8_lossy(&[b]).into_owned();
let _ = safe_object_uri("bucket", &s);
}
}
/// v0.8.1 #58: smoke test for the DEK-handling shape used by the
/// SSE-KMS branches of `put_object` and `complete_multipart_upload`.
/// Mirrors the call pattern (generate_dek → length check → copy
/// into stack `[u8; 32]` → reborrow as `&[u8; 32]` for `SseSource`)
/// without spinning up a full `S4Service`.
///
/// The real assertion this guards against is a regression where
/// the `Zeroizing` wrapper is accidentally dropped before the
/// stack copy lands (e.g. someone refactors to use
/// `let dek = kms.generate_dek(...).await?.0; drop(dek); ...`)
/// or where `&**dek` is rewritten in a way that doesn't compile.
#[tokio::test]
async fn kms_dek_lifetime_within_function_scope() {
use crate::kms::{KmsBackend, LocalKms};
use std::collections::HashMap;
use std::path::PathBuf;
use zeroize::Zeroizing;
let mut keks = HashMap::new();
keks.insert("scope".to_string(), [33u8; 32]);
let kms = LocalKms::from_keks(PathBuf::from("/tmp/kms-scope-test"), keks);
// Mirror the put_object KMS branch shape exactly.
let (dek, wrapped) = kms.generate_dek("scope").await.unwrap();
assert_eq!(dek.len(), 32);
let mut dek_arr: Zeroizing<[u8; 32]> = Zeroizing::new([0u8; 32]);
dek_arr.copy_from_slice(&dek);
// The reborrow used at the SseSource construction site —
// mirrors the call-site pattern where `let dek_ref: &[u8; 32]`
// auto-derefs from a `Zeroizing<[u8; 32]>` reference.
let dek_ref: &[u8; 32] = &dek_arr;
// Sanity: the reborrow points at the same bytes.
assert_eq!(dek_ref, &*dek_arr);
// Wrapped key id flows through unchanged.
assert_eq!(wrapped.key_id, "scope");
// At end of scope, both `dek` (Zeroizing<Vec<u8>>) and
// `dek_arr` (Zeroizing<[u8; 32]>) are dropped, wiping the
// backing memory. Cannot directly assert the wipe (would be
// UB to read freed memory), so this test instead enforces
// that the call shape compiles and executes; the wipe itself
// is exercised by the `zeroize` crate's own test suite.
}
}