s3 0.1.34

A lean, modern, unofficial S3-compatible client for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use http::{
    HeaderMap, HeaderValue, StatusCode,
    header::{HeaderName, IntoHeaderName},
};

#[cfg(feature = "multipart")]
use crate::types::CompletedPart;
use crate::{
    error::{Error, Result},
    types::{DeleteObjectIdentifier, MAX_DELETE_OBJECTS_PER_REQUEST},
};

pub(crate) const MAX_LIST_OBJECTS_KEYS: u32 = 1_000;
#[cfg(feature = "multipart")]
pub(crate) const MAX_LIST_PARTS: u32 = 1_000;
#[cfg(feature = "multipart")]
pub(crate) const MAX_UPLOAD_PART_NUMBER: u32 = 10_000;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ByteRange {
    start: u64,
    end_inclusive: u64,
}

impl ByteRange {
    pub(crate) fn new(start: u64, end_inclusive: u64) -> Result<Self> {
        if start > end_inclusive {
            return Err(Error::invalid_config(
                "byte range start must be <= end_inclusive",
            ));
        }

        Ok(Self {
            start,
            end_inclusive,
        })
    }

    pub(crate) fn header_value(self, invalid_message: &'static str) -> Result<HeaderValue> {
        header_value(
            format!("bytes={}-{}", self.start, self.end_inclusive),
            invalid_message,
        )
    }
}

pub(crate) fn header_value(
    value: impl AsRef<str>,
    invalid_message: &'static str,
) -> Result<HeaderValue> {
    HeaderValue::from_str(value.as_ref()).map_err(|_| Error::invalid_config(invalid_message))
}

pub(crate) fn validate_header_value(value: &str, invalid_message: &'static str) -> Result<()> {
    if value.is_empty() || value.trim() != value {
        return Err(Error::invalid_config(invalid_message));
    }
    header_value(value, invalid_message)?;
    Ok(())
}

fn validate_metadata_value(value: &str) -> Result<()> {
    if value.trim() != value {
        return Err(Error::invalid_config(
            "metadata values must not include leading or trailing whitespace",
        ));
    }
    header_value(value, "invalid metadata header value")?;
    Ok(())
}

pub(crate) fn insert_header<K>(
    headers: &mut HeaderMap,
    name: K,
    value: impl AsRef<str>,
    invalid_message: &'static str,
) -> Result<()>
where
    K: IntoHeaderName,
{
    headers.insert(name, header_value(value, invalid_message)?);
    Ok(())
}

pub(crate) fn insert_optional_header(
    headers: &mut HeaderMap,
    name: HeaderName,
    value: Option<String>,
    invalid_message: &'static str,
) -> Result<()> {
    if let Some(value) = value {
        validate_header_value(&value, invalid_message)?;
        insert_header(headers, name, value, invalid_message)?;
    }
    Ok(())
}

pub(crate) fn xml_body_headers(body: &[u8]) -> Result<HeaderMap> {
    let mut headers = HeaderMap::new();
    headers.insert(
        http::header::CONTENT_TYPE,
        HeaderValue::from_static("application/xml"),
    );
    headers.insert(
        HeaderName::from_static("content-md5"),
        crate::util::md5::content_md5_header_value(body)?,
    );
    Ok(headers)
}

pub(crate) fn require_configured<T>(value: Option<T>, message: &'static str) -> Result<T> {
    value.ok_or_else(|| Error::invalid_config(message))
}

pub(crate) fn validate_content_length_matches_body(
    configured: Option<u64>,
    body_len: usize,
    context: &'static str,
) -> Result<u64> {
    let body_len = u64::try_from(body_len)
        .map_err(|_| Error::invalid_config(format!("{context} body length exceeds u64")))?;
    if let Some(configured) = configured
        && configured != body_len
    {
        return Err(Error::invalid_config(format!(
            "{context} content_length must match the byte body length"
        )));
    }
    Ok(body_len)
}

pub(crate) fn parse_xml_or_service_error<T>(
    status: StatusCode,
    headers: &HeaderMap,
    body: &str,
    parse: impl FnOnce(&str) -> Result<T>,
) -> Result<T> {
    match parse(body) {
        Ok(value) => Ok(value),
        Err(parse_error) => {
            if crate::util::xml::parse_error_xml(body).is_some() {
                return Err(crate::transport::response_error_from_status(
                    status, headers, body,
                ));
            }
            Err(parse_error)
        }
    }
}

#[cfg(feature = "async")]
pub(crate) fn parse_async_xml_response<T>(
    resp: crate::transport::async_transport::AsyncResponse,
    parse: impl FnOnce(&str) -> Result<T>,
) -> Result<T> {
    let (status, headers, body) = resp.into_parts();
    let body = crate::util::text::decode_utf8_response_body(body.as_ref())?;
    parse_xml_or_service_error(status, &headers, &body, parse)
}

pub(crate) fn create_bucket_location_constraint(
    explicit: Option<String>,
    client_region: &str,
) -> Result<Option<String>> {
    match explicit {
        Some(region) => {
            crate::auth::Region::new(region.as_str())?;
            Ok(Some(region))
        }
        None => {
            crate::auth::Region::new(client_region)?;
            if client_region == "us-east-1" {
                Ok(None)
            } else {
                Ok(Some(client_region.to_string()))
            }
        }
    }
}

pub(crate) fn validate_max_keys(max_keys: u32) -> Result<()> {
    if max_keys == 0 || max_keys > MAX_LIST_OBJECTS_KEYS {
        return Err(Error::invalid_config(
            "max_keys must be in the range 1..=1000",
        ));
    }
    Ok(())
}

pub(crate) fn next_list_v2_continuation_token(
    current: Option<&str>,
    next: Option<&str>,
    is_truncated: bool,
) -> Result<Option<String>> {
    if !is_truncated {
        return Ok(None);
    }

    let next = next.ok_or_else(|| {
        Error::decode(
            "ListObjectsV2 response is truncated but missing NextContinuationToken",
            None,
        )
    })?;
    validate_query_token("next_continuation_token", next).map_err(|_| {
        Error::decode(
            "ListObjectsV2 response contains an invalid NextContinuationToken",
            None,
        )
    })?;

    if current.is_some_and(|current| current == next) {
        return Err(Error::decode(
            "ListObjectsV2 response repeated the current continuation token",
            None,
        ));
    }

    Ok(Some(next.to_string()))
}

#[cfg(feature = "multipart")]
pub(crate) fn validate_max_parts(max_parts: u32) -> Result<()> {
    if max_parts == 0 || max_parts > MAX_LIST_PARTS {
        return Err(Error::invalid_config(
            "max_parts must be in the range 1..=1000",
        ));
    }
    Ok(())
}

#[cfg(feature = "multipart")]
pub(crate) fn validate_part_number_marker(part_number_marker: u32) -> Result<()> {
    if part_number_marker == 0 || part_number_marker > MAX_UPLOAD_PART_NUMBER {
        return Err(Error::invalid_config(
            "part_number_marker must be in the range 1..=10000",
        ));
    }
    Ok(())
}

#[cfg(feature = "multipart")]
pub(crate) fn validate_upload_part_number(part_number: u32) -> Result<()> {
    if part_number == 0 || part_number > MAX_UPLOAD_PART_NUMBER {
        return Err(Error::invalid_config(
            "part_number must be in the range 1..=10000",
        ));
    }
    Ok(())
}

#[cfg(feature = "multipart")]
pub(crate) fn validate_upload_id(upload_id: &str) -> Result<()> {
    validate_query_token("upload_id", upload_id)
}

pub(crate) fn validate_query_token(name: &'static str, value: &str) -> Result<()> {
    if value.is_empty() {
        return Err(Error::invalid_config(format!("{name} must not be empty")));
    }
    if value.trim() != value {
        return Err(Error::invalid_config(format!(
            "{name} must not include leading or trailing whitespace"
        )));
    }
    if value
        .bytes()
        .any(|b| b.is_ascii_control() || b.is_ascii_whitespace())
    {
        return Err(Error::invalid_config(format!(
            "{name} must not contain ASCII control or whitespace characters"
        )));
    }
    Ok(())
}

pub(crate) fn validate_query_value(name: &'static str, value: &str) -> Result<()> {
    if value.is_empty() {
        return Err(Error::invalid_config(format!("{name} must not be empty")));
    }
    if value.bytes().any(|b| b.is_ascii_control()) {
        return Err(Error::invalid_config(format!(
            "{name} must not contain ASCII control characters"
        )));
    }
    Ok(())
}

pub(crate) fn push_delete_object(
    objects: &mut Vec<DeleteObjectIdentifier>,
    object: DeleteObjectIdentifier,
) -> Result<()> {
    if objects.len() >= MAX_DELETE_OBJECTS_PER_REQUEST {
        return Err(Error::invalid_config(
            "delete_objects supports at most 1000 objects per request",
        ));
    }
    objects.push(object);
    Ok(())
}

#[cfg(feature = "multipart")]
pub(crate) fn push_completed_part(
    parts: &mut Vec<CompletedPart>,
    part: CompletedPart,
) -> Result<()> {
    if parts.len() >= MAX_UPLOAD_PART_NUMBER as usize {
        return Err(Error::invalid_config(
            "complete_multipart_upload supports at most 10000 completed parts",
        ));
    }
    if parts
        .iter()
        .any(|existing| existing.part_number() == part.part_number())
    {
        return Err(Error::invalid_config(
            "completed part numbers must be unique",
        ));
    }
    parts.push(part);
    Ok(())
}

#[cfg(feature = "multipart")]
pub(crate) fn prepare_completed_parts(mut parts: Vec<CompletedPart>) -> Result<Vec<CompletedPart>> {
    if parts.is_empty() {
        return Err(Error::invalid_config(
            "complete_multipart_upload requires at least one completed part",
        ));
    }
    if parts.len() > MAX_UPLOAD_PART_NUMBER as usize {
        return Err(Error::invalid_config(
            "complete_multipart_upload supports at most 10000 completed parts",
        ));
    }

    parts.sort_by_key(|part| part.part_number());
    if parts
        .windows(2)
        .any(|pair| pair[0].part_number() == pair[1].part_number())
    {
        return Err(Error::invalid_config(
            "completed part numbers must be unique",
        ));
    }

    Ok(parts)
}

pub(crate) fn validate_subresource(subresource: &str) -> Result<()> {
    if subresource.is_empty() {
        return Err(Error::invalid_config("subresource must not be empty"));
    }
    if subresource.trim() != subresource {
        return Err(Error::invalid_config(
            "subresource must not include leading or trailing whitespace",
        ));
    }
    if subresource
        .bytes()
        .any(|b| b.is_ascii_control() || b.is_ascii_whitespace())
    {
        return Err(Error::invalid_config(
            "subresource must not contain ASCII control or whitespace characters",
        ));
    }
    Ok(())
}

pub(crate) fn apply_metadata_headers(
    headers: &mut HeaderMap,
    metadata: Vec<(String, String)>,
) -> Result<()> {
    let mut pending = Vec::with_capacity(metadata.len());
    for (name, value) in metadata {
        let header_name = crate::util::redact::metadata_header_name(&name)?;
        if headers.contains_key(&header_name)
            || pending
                .iter()
                .any(|(existing, _): &(HeaderName, String)| existing == header_name)
        {
            return Err(Error::invalid_config("metadata keys must be unique"));
        }
        validate_metadata_value(&value)?;
        pending.push((header_name, value));
    }

    for (name, value) in pending {
        insert_header(headers, name, value, "invalid metadata header value")?;
    }
    Ok(())
}

pub(crate) fn push_metadata(
    metadata: &mut Vec<(String, String)>,
    key: impl Into<String>,
    value: impl Into<String>,
) -> Result<()> {
    let key = key.into();
    let value = value.into();
    let header_name = crate::util::redact::metadata_header_name(&key)?;
    validate_metadata_value(&value)?;

    if metadata.iter().any(|(existing, _)| {
        crate::util::redact::metadata_header_name(existing)
            .is_ok_and(|existing_header| existing_header == header_name)
    }) {
        return Err(Error::invalid_config("metadata keys must be unique"));
    }

    metadata.push((key, value));
    Ok(())
}

pub(crate) fn apply_copy_metadata_headers(
    headers: &mut HeaderMap,
    explicit_replace: bool,
    content_type: Option<String>,
    metadata: Vec<(String, String)>,
) -> Result<()> {
    let should_replace = explicit_replace || content_type.is_some() || !metadata.is_empty();
    if should_replace {
        headers.insert(
            "x-amz-metadata-directive",
            HeaderValue::from_static("REPLACE"),
        );
    }

    insert_optional_header(
        headers,
        http::header::CONTENT_TYPE,
        content_type,
        "invalid Content-Type header",
    )?;
    apply_metadata_headers(headers, metadata)
}

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

    #[test]
    fn create_bucket_location_constraint_defaults_to_client_region() {
        assert_eq!(
            create_bucket_location_constraint(None, "ap-southeast-1").unwrap(),
            Some("ap-southeast-1".to_string())
        );
    }

    #[test]
    fn create_bucket_location_constraint_skips_us_east_1_by_default() {
        assert_eq!(
            create_bucket_location_constraint(None, "us-east-1").unwrap(),
            None
        );
        assert!(create_bucket_location_constraint(None, "US-EAST-1").is_err());
    }

    #[test]
    fn create_bucket_location_constraint_respects_explicit_value() {
        assert_eq!(
            create_bucket_location_constraint(Some("eu-west-1".to_string()), "us-east-1").unwrap(),
            Some("eu-west-1".to_string())
        );
    }

    #[test]
    fn create_bucket_location_constraint_rejects_invalid_explicit_value() {
        let err = create_bucket_location_constraint(Some("eu west 1".to_string()), "us-east-1")
            .expect_err("invalid explicit location constraint must be rejected");
        match err {
            Error::InvalidConfig { message } => assert!(message.contains("region")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[test]
    fn validate_content_length_matches_byte_body() {
        assert_eq!(
            validate_content_length_matches_body(None, 3, "put_object").unwrap(),
            3
        );
        assert_eq!(
            validate_content_length_matches_body(Some(3), 3, "put_object").unwrap(),
            3
        );
        let err = validate_content_length_matches_body(Some(4), 3, "put_object")
            .expect_err("mismatched content length must be rejected");
        match err {
            Error::InvalidConfig { message } => assert!(message.contains("content_length")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[test]
    fn validate_max_keys_accepts_range_and_rejects_out_of_range() {
        assert!(validate_max_keys(1).is_ok());
        assert!(validate_max_keys(1_000).is_ok());
        assert!(validate_max_keys(0).is_err());
        assert!(validate_max_keys(1_001).is_err());
    }

    #[test]
    fn next_list_v2_continuation_token_rejects_invalid_truncated_pages() {
        assert_eq!(
            next_list_v2_continuation_token(None, None, false).unwrap(),
            None
        );
        assert_eq!(
            next_list_v2_continuation_token(None, Some("token-2"), true).unwrap(),
            Some("token-2".to_string())
        );
        assert!(next_list_v2_continuation_token(None, None, true).is_err());
        assert!(next_list_v2_continuation_token(Some("same"), Some("same"), true).is_err());
        assert!(next_list_v2_continuation_token(None, Some(" bad"), true).is_err());
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn validate_max_parts_accepts_range_and_rejects_out_of_range() {
        assert!(validate_max_parts(1).is_ok());
        assert!(validate_max_parts(1_000).is_ok());
        assert!(validate_max_parts(0).is_err());
        assert!(validate_max_parts(1_001).is_err());
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn validate_part_number_marker_accepts_range_and_rejects_out_of_range() {
        assert!(validate_part_number_marker(1).is_ok());
        assert!(validate_part_number_marker(10_000).is_ok());
        assert!(validate_part_number_marker(0).is_err());
        assert!(validate_part_number_marker(10_001).is_err());
    }

    #[test]
    fn byte_range_rejects_reversed_bounds() {
        let err = ByteRange::new(10, 9).expect_err("reversed byte range should be rejected");

        match err {
            Error::InvalidConfig { message } => assert!(message.contains("byte range")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[test]
    fn byte_range_formats_http_header_value() {
        let value = ByteRange::new(3, 9)
            .expect("range should be valid")
            .header_value("invalid Range header")
            .expect("range should be valid");
        assert_eq!(value.to_str().ok(), Some("bytes=3-9"));
    }

    #[test]
    fn insert_optional_header_rejects_empty_or_outer_whitespace() {
        for value in ["", " text/plain", "text/plain "] {
            let mut headers = HeaderMap::new();
            let err = insert_optional_header(
                &mut headers,
                http::header::CONTENT_TYPE,
                Some(value.to_string()),
                "invalid Content-Type header",
            )
            .expect_err("ambiguous header values must be rejected");

            match err {
                Error::InvalidConfig { message } => {
                    assert!(message.contains("Content-Type"));
                    assert!(headers.is_empty());
                }
                other => panic!("expected InvalidConfig, got {other:?}"),
            }
        }
    }

    #[test]
    fn xml_body_headers_include_content_type_and_md5() {
        let headers = xml_body_headers(b"<Tagging/>").expect("headers should be valid");

        assert_eq!(
            headers
                .get(http::header::CONTENT_TYPE)
                .and_then(|value| value.to_str().ok()),
            Some("application/xml")
        );
        assert_eq!(
            headers
                .get("content-md5")
                .and_then(|value| value.to_str().ok()),
            Some("5MKq9Afjj8VFAV5vB64atA==")
        );
    }

    #[test]
    fn push_delete_object_rejects_oversized_batches() {
        let mut objects = Vec::new();
        for idx in 0..MAX_DELETE_OBJECTS_PER_REQUEST {
            push_delete_object(
                &mut objects,
                DeleteObjectIdentifier::new(format!("key-{idx}")).unwrap(),
            )
            .unwrap();
        }

        let err = push_delete_object(
            &mut objects,
            DeleteObjectIdentifier::new("one-too-many").unwrap(),
        )
        .expect_err("oversized delete batch must be rejected before send");

        match err {
            Error::InvalidConfig { message } => assert!(message.contains("at most 1000")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
        assert_eq!(objects.len(), MAX_DELETE_OBJECTS_PER_REQUEST);
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn prepare_completed_parts_sorts_valid_parts() {
        let parts = prepare_completed_parts(vec![
            CompletedPart::new(2, "\"etag-2\"").unwrap(),
            CompletedPart::new(1, "\"etag-1\"").unwrap(),
        ])
        .expect("parts should be valid");

        assert_eq!(parts[0].part_number(), 1);
        assert_eq!(parts[1].part_number(), 2);
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn completed_part_rejects_invalid_values() {
        assert!(CompletedPart::new(0, "etag").is_err());
        assert!(CompletedPart::new(1, " ").is_err());
        assert!(CompletedPart::new(1, " etag").is_err());
        assert!(CompletedPart::new(1, "etag").is_err());
        assert!(CompletedPart::new(1, "\"et ag\"").is_err());
        assert!(CompletedPart::new(1, "\"\"").is_err());
        assert!(CompletedPart::new(1, "\"bad\"etag\"").is_err());
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn prepare_completed_parts_rejects_empty_or_duplicate_parts() {
        assert!(prepare_completed_parts(Vec::new()).is_err());
        assert!(
            prepare_completed_parts(vec![
                CompletedPart::new(1, "\"etag-1\"").unwrap(),
                CompletedPart::new(1, "\"etag-duplicate\"").unwrap(),
            ])
            .is_err()
        );
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn push_completed_part_rejects_duplicate_and_oversized_batches() {
        let mut parts = Vec::new();
        push_completed_part(&mut parts, CompletedPart::new(1, "\"etag-1\"").unwrap()).unwrap();
        let err = push_completed_part(
            &mut parts,
            CompletedPart::new(1, "\"etag-duplicate\"").unwrap(),
        )
        .expect_err("duplicate completed part must be rejected before send");
        match err {
            Error::InvalidConfig { message } => assert!(message.contains("unique")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }

        let mut parts = Vec::new();
        for part_number in 1..=MAX_UPLOAD_PART_NUMBER {
            push_completed_part(
                &mut parts,
                CompletedPart::new(part_number, format!("\"etag-{part_number}\"")).unwrap(),
            )
            .unwrap();
        }
        let err = push_completed_part(
            &mut parts,
            CompletedPart::new(MAX_UPLOAD_PART_NUMBER, "\"duplicate\"").unwrap(),
        )
        .expect_err("oversized completed part batch must be rejected before send");
        match err {
            Error::InvalidConfig { message } => assert!(message.contains("at most 10000")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
        assert_eq!(parts.len(), MAX_UPLOAD_PART_NUMBER as usize);
    }

    #[cfg(feature = "multipart")]
    #[test]
    fn validate_upload_id_rejects_outer_whitespace() {
        assert!(validate_upload_id("").is_err());
        assert!(validate_upload_id(" upload-id").is_err());
        assert!(validate_upload_id("upload-id ").is_err());
        assert!(validate_upload_id("upload id").is_err());
        assert!(validate_upload_id("upload\nid").is_err());
        assert!(validate_upload_id("upload-id").is_ok());
    }

    #[test]
    fn validate_query_token_rejects_ambiguous_values() {
        assert!(validate_query_token("continuation_token", "").is_err());
        assert!(validate_query_token("continuation_token", " token").is_err());
        assert!(validate_query_token("continuation_token", "token ").is_err());
        assert!(validate_query_token("continuation_token", "tok en").is_err());
        assert!(validate_query_token("continuation_token", "tok\nen").is_err());
        assert!(validate_query_token("continuation_token", "opaque/token+id=").is_ok());
    }

    #[test]
    fn validate_query_value_rejects_ambiguous_values() {
        validate_query_value("prefix", "photos/2026 ").unwrap();

        for value in ["", "line\nbreak", "bad\u{7f}"] {
            let err = validate_query_value("prefix", value).expect_err("expected invalid query");
            match err {
                Error::InvalidConfig { .. } => {}
                other => panic!("expected InvalidConfig, got {other:?}"),
            }
        }
    }

    #[test]
    fn validate_subresource_rejects_blank_values() {
        assert!(validate_subresource("versioning").is_ok());
        assert!(validate_subresource("").is_err());
        assert!(validate_subresource("   ").is_err());
        assert!(validate_subresource(" versioning").is_err());
        assert!(validate_subresource("versioning ").is_err());
        assert!(validate_subresource("bucket versioning").is_err());
        assert!(validate_subresource("versioning\n").is_err());
    }

    #[test]
    fn apply_metadata_headers_writes_expected_headers() {
        let mut headers = HeaderMap::new();
        apply_metadata_headers(
            &mut headers,
            vec![
                ("owner".to_string(), "alice".to_string()),
                ("trace-id".to_string(), "abc-123".to_string()),
            ],
        )
        .expect("metadata should map to headers");

        assert_eq!(
            headers
                .get("x-amz-meta-owner")
                .and_then(|v| v.to_str().ok()),
            Some("alice")
        );
        assert_eq!(
            headers
                .get("x-amz-meta-trace-id")
                .and_then(|v| v.to_str().ok()),
            Some("abc-123")
        );
    }

    #[test]
    fn apply_metadata_headers_rejects_duplicate_keys_after_normalization() {
        let mut headers = HeaderMap::new();
        let err = apply_metadata_headers(
            &mut headers,
            vec![
                ("Owner".to_string(), "alice".to_string()),
                ("owner".to_string(), "bob".to_string()),
            ],
        )
        .expect_err("metadata keys normalize to the same header");

        match err {
            Error::InvalidConfig { message } => assert!(message.contains("unique")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
        assert!(headers.is_empty());
    }

    #[test]
    fn metadata_values_reject_outer_whitespace_but_allow_empty() {
        let mut metadata = Vec::new();
        push_metadata(&mut metadata, "empty", "").expect("empty metadata values are valid");
        assert_eq!(metadata, vec![("empty".to_string(), String::new())]);

        let err = push_metadata(&mut metadata, "bad", " value")
            .expect_err("metadata value with outer whitespace must be rejected");
        match err {
            Error::InvalidConfig { message } => assert!(message.contains("metadata values")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[test]
    fn apply_metadata_headers_rejects_existing_header_collision() {
        let mut headers = HeaderMap::new();
        headers.insert("x-amz-meta-owner", HeaderValue::from_static("alice"));
        let err =
            apply_metadata_headers(&mut headers, vec![("owner".to_string(), "bob".to_string())])
                .expect_err("metadata must not overwrite existing headers");

        match err {
            Error::InvalidConfig { message } => assert!(message.contains("unique")),
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[test]
    fn copy_metadata_headers_only_replace_when_requested_or_overridden() {
        let mut headers = HeaderMap::new();
        apply_copy_metadata_headers(&mut headers, false, None, Vec::new())
            .expect("empty copy metadata should be valid");
        assert!(!headers.contains_key("x-amz-metadata-directive"));

        let mut headers = HeaderMap::new();
        apply_copy_metadata_headers(&mut headers, true, None, Vec::new())
            .expect("explicit metadata replacement should be valid");
        assert_eq!(
            headers
                .get("x-amz-metadata-directive")
                .and_then(|v| v.to_str().ok()),
            Some("REPLACE")
        );

        let mut headers = HeaderMap::new();
        apply_copy_metadata_headers(
            &mut headers,
            false,
            Some("text/plain".to_string()),
            Vec::new(),
        )
        .expect("content type override should be valid");
        assert_eq!(
            headers
                .get("x-amz-metadata-directive")
                .and_then(|v| v.to_str().ok()),
            Some("REPLACE")
        );

        let mut headers = HeaderMap::new();
        apply_copy_metadata_headers(
            &mut headers,
            false,
            None,
            vec![("color".to_string(), "blue".to_string())],
        )
        .expect("metadata override should be valid");
        assert_eq!(
            headers
                .get("x-amz-metadata-directive")
                .and_then(|v| v.to_str().ok()),
            Some("REPLACE")
        );
    }

    #[test]
    fn parse_xml_or_service_error_maps_request_id_only_error_payload() {
        let body = "<Error><RequestId>req-only</RequestId></Error>";
        let err = parse_xml_or_service_error::<()>(
            http::StatusCode::BAD_REQUEST,
            &http::HeaderMap::new(),
            body,
            |_| Err(Error::decode("failed to parse expected xml", None)),
        )
        .expect_err("request-id-only payload should map to API error");

        match err {
            Error::Api {
                status, request_id, ..
            } => {
                assert_eq!(status, http::StatusCode::BAD_REQUEST);
                assert_eq!(request_id.as_deref(), Some("req-only"));
            }
            other => panic!("expected Api error, got {other:?}"),
        }
    }
}