rs3gw 0.2.1

High-Performance AI/HPC Object Storage Gateway powered by scirs2-io
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
//! Protocol correctness tests for rs3gw
//!
//! Tests covering:
//! - Conditional GET headers (If-Match, If-None-Match, If-Modified-Since, If-Unmodified-Since)
//! - Range requests (basic, suffix, single-byte, invalid, beyond-size)
//! - User metadata persistence (PUT → GET/HEAD parity)
//! - CopyObject with metadata directives (COPY/REPLACE) and cross-bucket
//! - Special object keys (URL-encoded spaces, plus, deep prefix, trailing slash)

mod common;

use common::setup_test_server;

// ─── Conditional Headers ─────────────────────────────────────────────────────

/// PUT an object, then GET with If-Match=<correct etag> → 200
#[tokio::test]
async fn test_conditional_get_if_match_hit() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cond-if-match-hit";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello".to_vec().into())
        .send()
        .await
        .expect("put object");

    let head = client
        .head_object()
        .bucket(bucket)
        .key("obj.txt")
        .send()
        .await
        .expect("head object");
    let etag = head.e_tag().expect("etag present").to_string();

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("If-Match", &etag)
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        200,
        "If-Match with correct ETag should return 200"
    );
}

/// GET with If-Match=wrong_etag → 412 PreconditionFailed
#[tokio::test]
async fn test_conditional_get_if_match_miss() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cond-if-match-miss";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello".to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("If-Match", "\"this-etag-will-never-match\"")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        412,
        "If-Match with wrong ETag should return 412"
    );
}

/// GET with If-None-Match=<correct etag> (etag matches → not modified) → 304
#[tokio::test]
async fn test_conditional_get_if_none_match_hit() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cond-if-none-match-hit";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello".to_vec().into())
        .send()
        .await
        .expect("put object");

    let head = client
        .head_object()
        .bucket(bucket)
        .key("obj.txt")
        .send()
        .await
        .expect("head object");
    let etag = head.e_tag().expect("etag present").to_string();

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("If-None-Match", &etag)
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        304,
        "If-None-Match with matching ETag should return 304"
    );
}

/// GET with If-None-Match=wrong_etag → 200 (etag differs → proceed)
#[tokio::test]
async fn test_conditional_get_if_none_match_miss() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cond-if-none-match-miss";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello".to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("If-None-Match", "\"totally-different-etag\"")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        200,
        "If-None-Match with non-matching ETag should return 200"
    );
}

/// GET with If-Modified-Since set to a far-future date → 304 (not modified since then)
#[tokio::test]
async fn test_conditional_get_if_modified_since_hit() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cond-if-modified-since-hit";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello".to_vec().into())
        .send()
        .await
        .expect("put object");

    // Object was created now; a far-future timestamp means "not modified since then"
    // → server should return 304
    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("If-Modified-Since", "Thu, 01 Jan 2099 00:00:00 GMT")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        304,
        "If-Modified-Since with far-future timestamp: object not modified → 304"
    );
}

/// GET with If-Unmodified-Since set to an old timestamp → 412 (object was modified after)
#[tokio::test]
async fn test_conditional_get_if_unmodified_since_miss() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cond-if-unmod-since-miss";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello".to_vec().into())
        .send()
        .await
        .expect("put object");

    // Object was created now (2026); an old 2020 date means object was modified after that
    // → If-Unmodified-Since fails → 412
    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("If-Unmodified-Since", "Wed, 01 Jan 2020 00:00:00 GMT")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        412,
        "If-Unmodified-Since with old timestamp: object was modified since then → 412"
    );
}

// ─── Range Requests ───────────────────────────────────────────────────────────

/// PUT 1000-byte object, GET with Range: bytes=0-99 → 206, body is 100 bytes
#[tokio::test]
async fn test_range_basic() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "range-basic";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    // Build a 1000-byte body with predictable content
    let content: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
    client
        .put_object()
        .bucket(bucket)
        .key("large.bin")
        .body(content.clone().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/large.bin", server.addr, bucket))
        .header("Range", "bytes=0-99")
        .send()
        .await
        .expect("send request");

    assert_eq!(resp.status(), 206, "Range request should return 206");
    let body = resp.bytes().await.expect("read body");
    assert_eq!(body.len(), 100, "Should return exactly 100 bytes");
    assert_eq!(
        &body[..],
        &content[0..100],
        "Range content should match source"
    );
}

/// GET with Range: bytes=-100 → 206, last 100 bytes
#[tokio::test]
async fn test_range_suffix() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "range-suffix";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
    client
        .put_object()
        .bucket(bucket)
        .key("large.bin")
        .body(content.clone().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/large.bin", server.addr, bucket))
        .header("Range", "bytes=-100")
        .send()
        .await
        .expect("send request");

    assert_eq!(resp.status(), 206, "Suffix range should return 206");
    let body = resp.bytes().await.expect("read body");
    assert_eq!(body.len(), 100, "Should return exactly 100 bytes");
    assert_eq!(
        &body[..],
        &content[900..1000],
        "Suffix range should return last 100 bytes"
    );
}

/// GET with Range: bytes=0-0 → 206, exactly 1 byte
#[tokio::test]
async fn test_range_single_byte() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "range-single-byte";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"ABCDEFGHIJ";
    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("Range", "bytes=0-0")
        .send()
        .await
        .expect("send request");

    assert_eq!(resp.status(), 206, "Single-byte range should return 206");
    let body = resp.bytes().await.expect("read body");
    assert_eq!(body.len(), 1, "Should return exactly 1 byte");
    assert_eq!(body[0], b'A', "Should return the first byte");
}

/// GET with Range: bytes=abc-def → 416 InvalidRange
#[tokio::test]
async fn test_range_invalid() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "range-invalid";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("obj.txt")
        .body(b"hello world".to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.txt", server.addr, bucket))
        .header("Range", "bytes=abc-def")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        416,
        "Invalid range header should return 416 Range Not Satisfiable"
    );
}

/// GET with Range: bytes=0-9999 on 100-byte object → 206, clamped to full content
#[tokio::test]
async fn test_range_beyond_size() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "range-beyond-size";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content: Vec<u8> = (b'A'..=b'Z').cycle().take(100).collect();
    client
        .put_object()
        .bucket(bucket)
        .key("obj.bin")
        .body(content.clone().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/obj.bin", server.addr, bucket))
        .header("Range", "bytes=0-9999")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        206,
        "Range beyond object size should clamp and return 206"
    );
    let body = resp.bytes().await.expect("read body");
    // Clamped to entire 100-byte object
    assert_eq!(
        body.len(),
        100,
        "Body should be clamped to full 100-byte content"
    );
    assert_eq!(&body[..], &content[..], "Content should match full object");
}

// ─── User Metadata Persistence ────────────────────────────────────────────────

/// PUT with x-amz-meta-foo/baz → GET and HEAD both return those headers
#[tokio::test]
async fn test_user_metadata_persistence() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "user-meta-persist";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("meta.txt")
        .content_type("text/plain")
        .metadata("foo", "bar")
        .metadata("baz", "qux")
        .body(b"metadata test".to_vec().into())
        .send()
        .await
        .expect("put object with metadata");

    // Verify via HEAD
    let head = client
        .head_object()
        .bucket(bucket)
        .key("meta.txt")
        .send()
        .await
        .expect("head object");
    let meta = head.metadata().expect("metadata present");
    assert_eq!(
        meta.get("foo"),
        Some(&"bar".to_string()),
        "HEAD: x-amz-meta-foo should be 'bar'"
    );
    assert_eq!(
        meta.get("baz"),
        Some(&"qux".to_string()),
        "HEAD: x-amz-meta-baz should be 'qux'"
    );

    // Verify via raw GET (check response headers)
    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/meta.txt", server.addr, bucket))
        .send()
        .await
        .expect("send GET");
    assert_eq!(resp.status(), 200);
    let headers = resp.headers();
    assert_eq!(
        headers.get("x-amz-meta-foo").and_then(|v| v.to_str().ok()),
        Some("bar"),
        "GET: x-amz-meta-foo should be 'bar'"
    );
    assert_eq!(
        headers.get("x-amz-meta-baz").and_then(|v| v.to_str().ok()),
        Some("qux"),
        "GET: x-amz-meta-baz should be 'qux'"
    );
}

/// PUT object → GET and HEAD should return identical ETag, Content-Type, Content-Length, metadata
#[tokio::test]
async fn test_head_get_parity() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "head-get-parity";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"parity test content";
    client
        .put_object()
        .bucket(bucket)
        .key("parity.txt")
        .content_type("text/plain")
        .metadata("version", "42")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();

    // HEAD request
    let head_resp = http
        .head(format!("http://{}/{}/parity.txt", server.addr, bucket))
        .send()
        .await
        .expect("HEAD request");
    assert_eq!(head_resp.status(), 200);
    let head_etag = head_resp
        .headers()
        .get("etag")
        .and_then(|v| v.to_str().ok())
        .expect("HEAD ETag")
        .to_string();
    let head_ct = head_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .expect("HEAD Content-Type")
        .to_string();
    let head_cl = head_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("HEAD Content-Length")
        .to_string();
    let head_meta = head_resp
        .headers()
        .get("x-amz-meta-version")
        .and_then(|v| v.to_str().ok())
        .expect("HEAD x-amz-meta-version")
        .to_string();

    // GET request
    let get_resp = http
        .get(format!("http://{}/{}/parity.txt", server.addr, bucket))
        .send()
        .await
        .expect("GET request");
    assert_eq!(get_resp.status(), 200);
    let get_etag = get_resp
        .headers()
        .get("etag")
        .and_then(|v| v.to_str().ok())
        .expect("GET ETag")
        .to_string();
    let get_ct = get_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .expect("GET Content-Type")
        .to_string();
    let get_cl = get_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("GET Content-Length")
        .to_string();
    let get_meta = get_resp
        .headers()
        .get("x-amz-meta-version")
        .and_then(|v| v.to_str().ok())
        .expect("GET x-amz-meta-version")
        .to_string();

    assert_eq!(
        head_etag, get_etag,
        "ETag must be identical in HEAD and GET"
    );
    assert_eq!(
        head_ct, get_ct,
        "Content-Type must be identical in HEAD and GET"
    );
    assert_eq!(
        head_cl, get_cl,
        "Content-Length must be identical in HEAD and GET"
    );
    assert_eq!(
        head_meta, get_meta,
        "x-amz-meta-version must be identical in HEAD and GET"
    );
}

// ─── CopyObject ───────────────────────────────────────────────────────────────

/// CopyObject without metadata-directive (defaults to COPY) → dst has same metadata
#[tokio::test]
async fn test_copy_object_metadata_directive_copy() {
    let (client, _temp_dir, _server) = setup_test_server().await;
    let bucket = "copy-meta-copy";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("src.txt")
        .content_type("text/plain")
        .metadata("original", "yes")
        .metadata("version", "1")
        .body(b"source content".to_vec().into())
        .send()
        .await
        .expect("put source");

    // Copy without specifying metadata-directive (should default to COPY)
    let copy_result = client
        .copy_object()
        .bucket(bucket)
        .key("dst.txt")
        .copy_source(format!("{}/src.txt", bucket))
        .send()
        .await;
    assert!(
        copy_result.is_ok(),
        "CopyObject should succeed: {:?}",
        copy_result.err()
    );

    let head = client
        .head_object()
        .bucket(bucket)
        .key("dst.txt")
        .send()
        .await
        .expect("head dst");
    let meta = head.metadata().expect("metadata present");
    assert_eq!(
        meta.get("original"),
        Some(&"yes".to_string()),
        "Metadata 'original' should be copied"
    );
    assert_eq!(
        meta.get("version"),
        Some(&"1".to_string()),
        "Metadata 'version' should be copied"
    );
    assert_eq!(
        head.content_type(),
        Some("text/plain"),
        "Content-Type should be copied"
    );
}

/// CopyObject with x-amz-metadata-directive: REPLACE and new metadata → dst has new metadata only
#[tokio::test]
async fn test_copy_object_metadata_directive_replace() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "copy-meta-replace";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("src.txt")
        .content_type("text/plain")
        .metadata("original", "yes")
        .metadata("version", "1")
        .body(b"source content".to_vec().into())
        .send()
        .await
        .expect("put source");

    // Copy with REPLACE directive and new metadata
    let http = reqwest::Client::new();
    let resp = http
        .put(format!("http://{}/{}/dst.txt", server.addr, bucket))
        .header("x-amz-copy-source", format!("{}/src.txt", bucket).as_str())
        .header("x-amz-metadata-directive", "REPLACE")
        .header("x-amz-meta-newkey", "newvalue")
        .header("Content-Type", "application/octet-stream")
        .send()
        .await
        .expect("copy with REPLACE");
    assert_eq!(resp.status(), 200, "CopyObject with REPLACE should succeed");

    let head = client
        .head_object()
        .bucket(bucket)
        .key("dst.txt")
        .send()
        .await
        .expect("head dst");
    let meta = head.metadata().expect("metadata present");
    assert_eq!(
        meta.get("newkey"),
        Some(&"newvalue".to_string()),
        "New metadata 'newkey' should be present"
    );
    assert_eq!(
        meta.get("original"),
        None,
        "Old metadata 'original' should NOT be present after REPLACE"
    );
    assert_eq!(
        meta.get("version"),
        None,
        "Old metadata 'version' should NOT be present after REPLACE"
    );
}

/// Cross-bucket copy: PUT in bucket1, CopyObject to bucket2/key → GET from bucket2 succeeds
#[tokio::test]
async fn test_copy_object_cross_bucket() {
    let (client, _temp_dir, _server) = setup_test_server().await;

    client
        .create_bucket()
        .bucket("cross-src")
        .send()
        .await
        .expect("create src bucket");
    client
        .create_bucket()
        .bucket("cross-dst")
        .send()
        .await
        .expect("create dst bucket");

    let content = b"cross-bucket content";
    client
        .put_object()
        .bucket("cross-src")
        .key("src.txt")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put into src bucket");

    let copy_result = client
        .copy_object()
        .bucket("cross-dst")
        .key("copied.txt")
        .copy_source("cross-src/src.txt")
        .send()
        .await;
    assert!(
        copy_result.is_ok(),
        "Cross-bucket copy should succeed: {:?}",
        copy_result.err()
    );

    let get_result = client
        .get_object()
        .bucket("cross-dst")
        .key("copied.txt")
        .send()
        .await
        .expect("get from dst bucket");
    let body = get_result
        .body
        .collect()
        .await
        .expect("collect body")
        .into_bytes();
    assert_eq!(
        &body[..],
        content,
        "Cross-bucket copied content should match"
    );
}

// ─── Special Keys ─────────────────────────────────────────────────────────────

/// PUT/GET/DELETE with URL-encoded key containing spaces (foo%20bar)
#[tokio::test]
async fn test_key_with_spaces() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "special-keys-spaces";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"content for key with spaces";

    // PUT via AWS SDK (key with literal space)
    client
        .put_object()
        .bucket(bucket)
        .key("foo bar")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object with space in key");

    // GET via raw HTTP with URL-encoded space
    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/foo%20bar", server.addr, bucket))
        .send()
        .await
        .expect("GET with %20");
    assert_eq!(resp.status(), 200, "GET with %20 should return 200");
    let body = resp.bytes().await.expect("read body");
    assert_eq!(&body[..], content, "Content should match");

    // DELETE via raw HTTP with URL-encoded space
    let resp = http
        .delete(format!("http://{}/{}/foo%20bar", server.addr, bucket))
        .send()
        .await
        .expect("DELETE with %20");
    assert_eq!(resp.status(), 204, "DELETE with %20 should return 204");

    // Verify gone
    let resp = http
        .get(format!("http://{}/{}/foo%20bar", server.addr, bucket))
        .send()
        .await
        .expect("GET after delete");
    assert_eq!(
        resp.status(),
        404,
        "Object should be deleted after DELETE with %20"
    );
}

/// PUT/GET key foo%2Bbar (literal plus in key name)
#[tokio::test]
async fn test_key_with_plus() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "special-keys-plus";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"content for key with plus sign";

    // PUT via AWS SDK with literal '+' in key
    client
        .put_object()
        .bucket(bucket)
        .key("foo+bar")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object with plus in key");

    // GET via raw HTTP — %2B should decode to '+' and fetch the correct object
    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/foo%2Bbar", server.addr, bucket))
        .send()
        .await
        .expect("GET with %2B");
    assert_eq!(resp.status(), 200, "GET with %2B should return 200");
    let body = resp.bytes().await.expect("read body");
    assert_eq!(&body[..], content, "Content should match");
}

/// PUT/GET/DELETE a/b/c/d/e/key (deep prefix)
#[tokio::test]
async fn test_deep_prefix_key() {
    let (client, _temp_dir, _server) = setup_test_server().await;
    let bucket = "deep-prefix";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let deep_key = "a/b/c/d/e/key.txt";
    let content = b"deeply nested content";

    client
        .put_object()
        .bucket(bucket)
        .key(deep_key)
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put deep prefix object");

    let get = client
        .get_object()
        .bucket(bucket)
        .key(deep_key)
        .send()
        .await
        .expect("get deep prefix object");
    let body = get.body.collect().await.expect("collect body").into_bytes();
    assert_eq!(&body[..], content, "Deep prefix content should match");

    client
        .delete_object()
        .bucket(bucket)
        .key(deep_key)
        .send()
        .await
        .expect("delete deep prefix object");

    let not_found = client
        .get_object()
        .bucket(bucket)
        .key(deep_key)
        .send()
        .await;
    assert!(not_found.is_err(), "Deep prefix object should be deleted");
}

/// PUT/GET object with key ending in /
#[tokio::test]
async fn test_trailing_slash_key() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "trailing-slash";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"trailing slash key content";

    // PUT via AWS SDK with trailing slash in key (simulates directory-like object)
    client
        .put_object()
        .bucket(bucket)
        .key("folder/")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object with trailing slash");

    // GET via raw HTTP
    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/folder/", server.addr, bucket))
        .send()
        .await
        .expect("GET trailing slash key");
    assert_eq!(
        resp.status(),
        200,
        "GET trailing slash key should return 200"
    );
    let body = resp.bytes().await.expect("read body");
    assert_eq!(
        &body[..],
        content,
        "Trailing slash key content should match"
    );
}

// === Malformed XML rejection ===

/// PUT /{bucket} with an unclosed-tag body — should return 400
#[tokio::test]
async fn test_create_bucket_malformed_xml() {
    let (_client, _temp_dir, server) = setup_test_server().await;
    let bucket = "malformed-xml-bucket";

    let http = reqwest::Client::new();
    // Send a body with unclosed tags to PUT /{bucket} (CreateBucket)
    let resp = http
        .put(format!("http://{}/{}", server.addr, bucket))
        .header("Content-Type", "application/xml")
        .body("<CreateBucketConfiguration><LocationConstraint>us-west-2</LocationConstraint")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        400,
        "CreateBucket with malformed XML body should return 400"
    );
}

/// POST /{bucket}/{key}?uploadId=test-upload-id with garbage body — should return 400
#[tokio::test]
async fn test_complete_multipart_upload_invalid_xml() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "complete-mpu-bad-xml";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let http = reqwest::Client::new();
    // POST with garbage XML body — CompleteMultipartUpload parses <Part> elements
    // and will return MalformedXML when none are found
    let resp = http
        .post(format!(
            "http://{}/{}/mykey?uploadId=nonexistent-upload-id",
            server.addr, bucket
        ))
        .header("Content-Type", "application/xml")
        .body("!!garbage!not-xml!!")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        400,
        "CompleteMultipartUpload with garbage body should return 400"
    );
}

/// PUT /{bucket}?tagging with partial/invalid XML — should return 400
#[tokio::test]
async fn test_put_bucket_tagging_malformed_xml() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "tagging-malformed-xml";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let http = reqwest::Client::new();
    // Send partial/invalid XML (no <TagSet> element)
    let resp = http
        .put(format!("http://{}/{}?tagging", server.addr, bucket))
        .header("Content-Type", "application/xml")
        .body("<Tagging><unclosed_tag")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        400,
        "PutBucketTagging with malformed XML should return 400"
    );
}

/// POST /{bucket}?delete with empty body — should return 400
#[tokio::test]
async fn test_delete_objects_empty_body() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "delete-objects-empty";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let http = reqwest::Client::new();
    // POST with empty body to ?delete — DeleteObjects expects an XML list of objects
    let resp = http
        .post(format!("http://{}/{}?delete", server.addr, bucket))
        .header("Content-Type", "application/xml")
        .body("")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        400,
        "DeleteObjects with empty body should return 400"
    );
}

// === Query Parsing Hardening ===

/// PUT /{bucket}/{key}?partNumber=abc&uploadId=xyz — non-numeric partNumber should return 400
#[tokio::test]
async fn test_invalid_part_number_query_param() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "invalid-part-number";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let http = reqwest::Client::new();
    // partNumber=abc is not a valid u32 — Axum's Query extractor will reject it with 400
    let resp = http
        .put(format!(
            "http://{}/{}/mykey?partNumber=abc&uploadId=some-upload-id",
            server.addr, bucket
        ))
        .body("part data")
        .send()
        .await
        .expect("send request");

    assert_eq!(
        resp.status(),
        400,
        "PUT with non-numeric partNumber should return 400"
    );
}

// === Content-Length on list responses ===

/// ListBuckets response must include a numeric Content-Length header
#[tokio::test]
async fn test_list_buckets_response_has_content_length() {
    let (_client, _temp_dir, server) = setup_test_server().await;

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/", server.addr))
        .send()
        .await
        .expect("send ListBuckets request");

    assert_eq!(resp.status(), 200, "ListBuckets should return 200");
    let cl_header = resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("ListBuckets response must have content-length header");
    let cl_value: u64 = cl_header
        .parse()
        .expect("content-length must be a numeric value");
    assert!(
        cl_value > 0,
        "ListBuckets content-length should be non-zero (XML body)"
    );
}

/// ListObjectsV1 response must include a numeric Content-Length header
#[tokio::test]
async fn test_list_objects_response_has_content_length() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "list-cl-check";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    // Put one object so the response body is non-trivial
    client
        .put_object()
        .bucket(bucket)
        .key("test.txt")
        .body(b"content".to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}", server.addr, bucket))
        .send()
        .await
        .expect("send ListObjectsV1 request");

    assert_eq!(resp.status(), 200, "ListObjectsV1 should return 200");
    let cl_header = resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("ListObjectsV1 response must have content-length header");
    let _cl_value: u64 = cl_header
        .parse()
        .expect("content-length must be a numeric value");
}

// ─── Content-Length Audit / Verification ──────────────────────────────────────

/// PUT a known-size object, GET it, verify Content-Length header equals actual body length
#[tokio::test]
async fn test_get_content_length_matches_body() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cl-get-body-match";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"The quick brown fox jumps over the lazy dog.";
    client
        .put_object()
        .bucket(bucket)
        .key("cl-test.txt")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/cl-test.txt", server.addr, bucket))
        .send()
        .await
        .expect("GET request");

    assert_eq!(resp.status(), 200);
    let cl_header: u64 = resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("Content-Length header must be present")
        .parse()
        .expect("Content-Length must be numeric");

    let body = resp.bytes().await.expect("read body");
    assert_eq!(
        cl_header,
        body.len() as u64,
        "Content-Length header must equal actual body length"
    );
    assert_eq!(
        cl_header,
        content.len() as u64,
        "Content-Length must match the original object size"
    );
}

/// PUT object, do both HEAD and GET, verify Content-Length headers match
#[tokio::test]
async fn test_head_content_length_matches_get() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cl-head-get-match";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content = b"content-length parity check between HEAD and GET";
    client
        .put_object()
        .bucket(bucket)
        .key("parity-cl.txt")
        .body(content.to_vec().into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();

    // HEAD request
    let head_resp = http
        .head(format!("http://{}/{}/parity-cl.txt", server.addr, bucket))
        .send()
        .await
        .expect("HEAD request");
    assert_eq!(head_resp.status(), 200);
    let head_cl: u64 = head_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("HEAD Content-Length must be present")
        .parse()
        .expect("HEAD Content-Length must be numeric");

    // GET request
    let get_resp = http
        .get(format!("http://{}/{}/parity-cl.txt", server.addr, bucket))
        .send()
        .await
        .expect("GET request");
    assert_eq!(get_resp.status(), 200);
    let get_cl: u64 = get_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("GET Content-Length must be present")
        .parse()
        .expect("GET Content-Length must be numeric");

    assert_eq!(
        head_cl, get_cl,
        "HEAD and GET Content-Length must be identical"
    );
    assert_eq!(
        head_cl,
        content.len() as u64,
        "Content-Length must match the original object size"
    );
}

/// PUT a 1000-byte object, GET with Range: bytes=100-199, verify Content-Length is 100
#[tokio::test]
async fn test_range_content_length_correct() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cl-range-check";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    let content: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
    client
        .put_object()
        .bucket(bucket)
        .key("range-cl.bin")
        .body(content.into())
        .send()
        .await
        .expect("put object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/range-cl.bin", server.addr, bucket))
        .header("Range", "bytes=100-199")
        .send()
        .await
        .expect("range GET request");

    assert_eq!(resp.status(), 206, "Range request should return 206");
    let cl_header: u64 = resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("Content-Length header must be present on range response")
        .parse()
        .expect("Content-Length must be numeric");

    assert_eq!(
        cl_header, 100,
        "Content-Length for bytes=100-199 must be 100"
    );

    let body = resp.bytes().await.expect("read body");
    assert_eq!(
        body.len() as u64,
        cl_header,
        "Actual body length must match Content-Length header"
    );
}

/// PUT empty object, GET it, verify Content-Length is 0
#[tokio::test]
async fn test_zero_byte_object_content_length() {
    let (client, _temp_dir, server) = setup_test_server().await;
    let bucket = "cl-zero-byte";
    client
        .create_bucket()
        .bucket(bucket)
        .send()
        .await
        .expect("create bucket");

    client
        .put_object()
        .bucket(bucket)
        .key("empty.txt")
        .body(Vec::new().into())
        .send()
        .await
        .expect("put empty object");

    let http = reqwest::Client::new();
    let resp = http
        .get(format!("http://{}/{}/empty.txt", server.addr, bucket))
        .send()
        .await
        .expect("GET empty object");

    assert_eq!(resp.status(), 200);
    let cl_header: u64 = resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .expect("Content-Length header must be present for empty object")
        .parse()
        .expect("Content-Length must be numeric");

    assert_eq!(
        cl_header, 0,
        "Content-Length for a zero-byte object must be 0"
    );

    let body = resp.bytes().await.expect("read body");
    assert_eq!(body.len(), 0, "Body of empty object must be empty");
}