s3-endpoint 0.1.1

S3-compatible endpoint for upload and object-access workflows.
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
use std::{fmt, num::NonZeroU16, str::FromStr};

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;

/// Validated S3 bucket name used after request-target parsing.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct BucketName(String);

impl BucketName {
    /// Parses a bucket name from request input.
    ///
    /// Returns an error when the value is empty or contains path separators or
    /// control characters. This type intentionally keeps validation narrower
    /// than AWS bucket-creation rules because this endpoint receives existing
    /// bucket identifiers and must mainly prevent path traversal and malformed
    /// storage keys.
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        if value.is_empty() {
            return Err(DomainError::EmptyBucketName);
        }
        if value
            .bytes()
            .any(|byte| matches!(byte, b'/' | b'\\') || byte.is_ascii_control())
        {
            return Err(DomainError::InvalidBucketName);
        }
        Ok(Self(value))
    }

    /// Returns the validated bucket name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for BucketName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Validated S3 object key used after request-target parsing.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ObjectKey(String);

impl ObjectKey {
    /// Parses an object key from request input.
    ///
    /// Returns an error when the key is empty or contains control characters.
    /// Slash characters are valid object-key bytes and are preserved.
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        if value.is_empty() {
            return Err(DomainError::EmptyObjectKey);
        }
        if value.bytes().any(|byte| byte.is_ascii_control()) {
            return Err(DomainError::InvalidObjectKey);
        }
        Ok(Self(value))
    }

    /// Returns the validated object key as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ObjectKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Entity tag value returned by object and part operations.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ETag(String);

impl ETag {
    /// Parses an ETag from request or persisted metadata.
    ///
    /// Returns an error when the value is empty or contains control characters.
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        if value.is_empty() || value.bytes().any(|byte| byte.is_ascii_control()) {
            return Err(DomainError::InvalidETag);
        }
        Ok(Self(value))
    }

    /// Builds a single-part object ETag from a lowercase hexadecimal MD5 digest.
    ///
    /// The caller must pass a digest string that was produced by trusted digest
    /// code; this function only applies the S3 quote formatting.
    pub fn from_hex_md5(hex_md5: String) -> Self {
        Self(format!("\"{hex_md5}\""))
    }

    /// Builds a multipart object ETag from the multipart MD5 digest and part count.
    ///
    /// The caller must pass a digest string and part count computed from
    /// validated committed parts.
    pub fn from_multipart_md5(hex_md5: String, part_count: usize) -> Self {
        Self(format!("\"{hex_md5}-{part_count}\""))
    }

    /// Returns the formatted ETag as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ETag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Per-response request identifier surfaced in S3 XML errors and response headers.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct RequestId(String);

impl RequestId {
    /// Creates a new random request identifier.
    pub fn new() -> Self {
        Self(uuid::Uuid::new_v4().to_string())
    }

    /// Parses a request identifier from trusted external input.
    ///
    /// Returns an error when the value is empty or contains control characters.
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        if value.is_empty() || value.bytes().any(|byte| byte.is_ascii_control()) {
            return Err(DomainError::InvalidRequestId);
        }
        Ok(Self(value))
    }

    /// Returns the request identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for RequestId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for RequestId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Multipart upload identifier.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize)]
pub struct UploadId(String);

impl UploadId {
    /// Creates a new random upload ID.
    pub fn new() -> Self {
        Self(uuid::Uuid::new_v4().to_string())
    }

    /// Parses a canonical UUID upload ID.
    ///
    /// Returns an error for non-UUID values or UUID strings that are not in the
    /// canonical hyphenated lowercase form.
    pub fn parse(value: impl Into<String>) -> Result<Self, DomainError> {
        let value = value.into();
        let Ok(uuid) = uuid::Uuid::parse_str(&value) else {
            return Err(DomainError::InvalidUploadId);
        };
        if uuid.to_string() != value {
            return Err(DomainError::InvalidUploadId);
        }
        Ok(Self(value))
    }

    /// Returns the upload ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for UploadId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for UploadId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for UploadId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::parse(value).map_err(serde::de::Error::custom)
    }
}

/// Parsed HTTP Content-Length value.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ContentLength(u64);

impl ContentLength {
    /// Wraps a known-valid content length.
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the length in bytes.
    pub fn get(self) -> u64 {
        self.0
    }
}

impl fmt::Display for ContentLength {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.get())
    }
}

impl FromStr for ContentLength {
    type Err = DomainError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let value = value
            .parse::<u64>()
            .map_err(|_| DomainError::InvalidContentLength)?;
        Ok(Self::new(value))
    }
}

/// Multipart upload part number in the S3 range 1..=10000.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PartNumber(NonZeroU16);

impl PartNumber {
    /// Parses a multipart part number.
    ///
    /// Returns an error when the value is zero or greater than 10,000.
    pub fn parse(value: u16) -> Result<Self, DomainError> {
        let Some(value) = NonZeroU16::new(value) else {
            return Err(DomainError::InvalidPartNumber);
        };
        if value.get() > 10_000 {
            return Err(DomainError::InvalidPartNumber);
        }
        Ok(Self(value))
    }

    /// Returns the part number as an integer.
    pub fn get(self) -> u16 {
        self.0.get()
    }
}

impl fmt::Display for PartNumber {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.get())
    }
}

impl FromStr for PartNumber {
    type Err = DomainError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let value = value
            .parse::<u16>()
            .map_err(|_| DomainError::InvalidPartNumber)?;
        Self::parse(value)
    }
}

impl Serialize for PartNumber {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u16(self.get())
    }
}

impl<'de> Deserialize<'de> for PartNumber {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = u16::deserialize(deserializer)?;
        Self::parse(value).map_err(serde::de::Error::custom)
    }
}

/// Implemented S3 operation selected by method, target shape, and query string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum S3Operation {
    /// PutObject.
    PutObject,
    /// CreateMultipartUpload.
    CreateMultipartUpload,
    /// UploadPart.
    UploadPart {
        /// Multipart upload ID.
        upload_id: UploadId,
        /// Multipart part number.
        part_number: PartNumber,
    },
    /// CompleteMultipartUpload.
    CompleteMultipartUpload {
        /// Multipart upload ID.
        upload_id: UploadId,
    },
    /// AbortMultipartUpload.
    AbortMultipartUpload {
        /// Multipart upload ID.
        upload_id: UploadId,
    },
    /// ListParts.
    ListParts {
        /// Multipart upload ID.
        upload_id: UploadId,
    },
    /// HeadBucket.
    HeadBucket,
    /// HeadObject.
    HeadObject,
    /// GetObject.
    GetObject,
    /// DeleteObject.
    DeleteObject,
}

impl S3Operation {
    /// Returns the S3 operation name used for tracing and diagnostics.
    pub fn name(&self) -> &'static str {
        match self {
            Self::PutObject => "PutObject",
            Self::CreateMultipartUpload => "CreateMultipartUpload",
            Self::UploadPart { .. } => "UploadPart",
            Self::CompleteMultipartUpload { .. } => "CompleteMultipartUpload",
            Self::AbortMultipartUpload { .. } => "AbortMultipartUpload",
            Self::ListParts { .. } => "ListParts",
            Self::HeadBucket => "HeadBucket",
            Self::HeadObject => "HeadObject",
            Self::GetObject => "GetObject",
            Self::DeleteObject => "DeleteObject",
        }
    }

    /// Returns the IAM-style action used by authorization and tuning policies.
    pub fn action(&self) -> crate::config::S3Action {
        match self {
            Self::PutObject => crate::config::S3Action::PutObject,
            Self::CreateMultipartUpload => crate::config::S3Action::CreateMultipartUpload,
            Self::UploadPart { .. } => crate::config::S3Action::UploadPart,
            Self::CompleteMultipartUpload { .. } => {
                crate::config::S3Action::CompleteMultipartUpload
            }
            Self::AbortMultipartUpload { .. } => crate::config::S3Action::AbortMultipartUpload,
            Self::ListParts { .. } => crate::config::S3Action::ListMultipartUploadParts,
            Self::HeadBucket => crate::config::S3Action::HeadBucket,
            Self::HeadObject => crate::config::S3Action::HeadObject,
            Self::GetObject => crate::config::S3Action::GetObject,
            Self::DeleteObject => crate::config::S3Action::DeleteObject,
        }
    }
}

/// Parsed `x-amz-content-sha256` payload hash mode.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PayloadHashMode {
    /// Header is absent.
    Missing,
    /// Literal `UNSIGNED-PAYLOAD`.
    UnsignedPayload,
    /// Fixed lowercase SHA256 hex digest.
    FixedSha256 {
        /// Original lowercase hex value.
        hex: String,
        /// Decoded digest bytes.
        digest: Vec<u8>,
    },
    /// Literal `STREAMING-AWS4-HMAC-SHA256-PAYLOAD`.
    StreamingSignedPayload,
    /// Literal `STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER`.
    StreamingSignedPayloadTrailer,
    /// Literal `STREAMING-UNSIGNED-PAYLOAD-TRAILER`.
    StreamingUnsignedPayloadTrailer,
}

impl PayloadHashMode {
    /// Parses a payload hash header value.
    ///
    /// Returns an error when the value is not one of the S3 payload hash modes
    /// implemented by this endpoint.
    pub fn parse(value: Option<&str>) -> Result<Self, DomainError> {
        let Some(value) = value else {
            return Ok(Self::Missing);
        };
        match value {
            "UNSIGNED-PAYLOAD" => Ok(Self::UnsignedPayload),
            "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" => Ok(Self::StreamingSignedPayload),
            "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER" => Ok(Self::StreamingSignedPayloadTrailer),
            "STREAMING-UNSIGNED-PAYLOAD-TRAILER" => Ok(Self::StreamingUnsignedPayloadTrailer),
            _ if is_lowercase_sha256_hex(value) => {
                let digest = hex::decode(value).map_err(|_| DomainError::InvalidPayloadHashMode)?;
                Ok(Self::FixedSha256 {
                    hex: value.to_owned(),
                    digest,
                })
            }
            _ => Err(DomainError::InvalidPayloadHashMode),
        }
    }

    /// Returns the literal value used in SigV4 canonical requests, if present.
    pub fn canonical_value(&self) -> Option<&str> {
        match self {
            Self::Missing => None,
            Self::UnsignedPayload => Some("UNSIGNED-PAYLOAD"),
            Self::FixedSha256 { hex, .. } => Some(hex),
            Self::StreamingSignedPayload => Some("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"),
            Self::StreamingSignedPayloadTrailer => {
                Some("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER")
            }
            Self::StreamingUnsignedPayloadTrailer => Some("STREAMING-UNSIGNED-PAYLOAD-TRAILER"),
        }
    }
}

fn is_lowercase_sha256_hex(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

/// Resolved object request target.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct S3Target {
    /// Bucket component of the target.
    pub bucket: BucketName,
    /// Object-key component of the target.
    pub key: ObjectKey,
    /// Whether the target was resolved from virtual-hosted-style addressing.
    pub virtual_hosted: bool,
}

/// Error returned when parsing S3 domain newtypes fails.
#[derive(Debug, Error)]
pub enum DomainError {
    /// Bucket name was empty.
    #[error("bucket name must not be empty")]
    EmptyBucketName,

    /// Bucket name contained path separators or control characters.
    #[error("bucket name contains invalid characters")]
    InvalidBucketName,

    /// Object key was empty.
    #[error("object key must not be empty")]
    EmptyObjectKey,

    /// Object key contained control characters.
    #[error("object key contains invalid characters")]
    InvalidObjectKey,

    /// Part number was outside the S3 range 1..=10000.
    #[error("part number must be in the range 1..=10000")]
    InvalidPartNumber,

    /// Content length was not an unsigned decimal integer.
    #[error("content length must be an integer")]
    InvalidContentLength,

    /// ETag was empty or contained control characters.
    #[error("ETag contains invalid characters")]
    InvalidETag,

    /// Request ID was empty or contained control characters.
    #[error("request ID contains invalid characters")]
    InvalidRequestId,

    /// Upload ID was not a canonical lowercase UUID.
    #[error("upload ID must be a canonical lowercase UUID")]
    InvalidUploadId,

    /// Payload hash mode was not supported.
    #[error("payload hash mode is invalid")]
    InvalidPayloadHashMode,
}

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

    #[test]
    fn bucket_name_rejects_path_separators_and_control_characters() {
        assert!(BucketName::parse("test-bucket").is_ok());
        assert!(matches!(
            BucketName::parse("bad/bucket"),
            Err(DomainError::InvalidBucketName)
        ));
        assert!(matches!(
            BucketName::parse("bad\\bucket"),
            Err(DomainError::InvalidBucketName)
        ));
        assert!(matches!(
            BucketName::parse("bad\nbucket"),
            Err(DomainError::InvalidBucketName)
        ));
    }

    #[test]
    fn object_key_preserves_slashes_but_rejects_control_characters() {
        assert_eq!(
            ObjectKey::parse("a//b.txt").expect("key").as_str(),
            "a//b.txt"
        );
        assert!(matches!(
            ObjectKey::parse("bad\nkey"),
            Err(DomainError::InvalidObjectKey)
        ));
    }

    #[test]
    fn request_id_rejects_empty_and_control_characters() {
        assert!(RequestId::parse("request-123").is_ok());
        assert!(matches!(
            RequestId::parse(""),
            Err(DomainError::InvalidRequestId)
        ));
        assert!(matches!(
            RequestId::parse("bad\nrequest"),
            Err(DomainError::InvalidRequestId)
        ));
    }

    #[test]
    fn upload_id_accepts_canonical_uuid() {
        let upload_id = UploadId::new();

        assert_eq!(
            UploadId::parse(upload_id.as_str()).expect("upload id"),
            upload_id
        );
    }

    #[test]
    fn upload_id_rejects_non_uuid_or_non_canonical_values() {
        assert!(matches!(
            UploadId::parse("../outside"),
            Err(DomainError::InvalidUploadId)
        ));
        assert!(matches!(
            UploadId::parse("550E8400-E29B-41D4-A716-446655440000"),
            Err(DomainError::InvalidUploadId)
        ));
    }

    #[test]
    fn upload_id_deserialization_uses_same_validation() {
        let result = serde_json::from_str::<UploadId>(r#""../outside""#);

        assert!(result.is_err());
    }

    #[test]
    fn etag_rejects_empty_and_control_characters() {
        assert_eq!(ETag::parse("\"abc\"").expect("etag").as_str(), "\"abc\"");
        assert!(matches!(ETag::parse(""), Err(DomainError::InvalidETag)));
        assert!(matches!(
            ETag::parse("bad\netag"),
            Err(DomainError::InvalidETag)
        ));
    }

    #[test]
    fn content_length_parses_unsigned_decimal_values() {
        assert_eq!(ContentLength::from_str("0").expect("length").get(), 0);
        assert_eq!(ContentLength::from_str("42").expect("length").get(), 42);
        assert!(matches!(
            ContentLength::from_str("-1"),
            Err(DomainError::InvalidContentLength)
        ));
        assert!(matches!(
            ContentLength::from_str("not-an-int"),
            Err(DomainError::InvalidContentLength)
        ));
    }

    #[test]
    fn payload_hash_mode_parses_supported_values() {
        let digest = "0".repeat(64);
        assert!(matches!(
            PayloadHashMode::parse(None).expect("missing"),
            PayloadHashMode::Missing
        ));
        assert!(matches!(
            PayloadHashMode::parse(Some("UNSIGNED-PAYLOAD")).expect("unsigned"),
            PayloadHashMode::UnsignedPayload
        ));
        assert!(matches!(
            PayloadHashMode::parse(Some(&digest)).expect("fixed"),
            PayloadHashMode::FixedSha256 { .. }
        ));
        assert!(matches!(
            PayloadHashMode::parse(Some("STREAMING-AWS4-HMAC-SHA256-PAYLOAD")).expect("streaming"),
            PayloadHashMode::StreamingSignedPayload
        ));
        assert!(matches!(
            PayloadHashMode::parse(Some("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"))
                .expect("streaming trailer"),
            PayloadHashMode::StreamingSignedPayloadTrailer
        ));
        assert!(matches!(
            PayloadHashMode::parse(Some("STREAMING-UNSIGNED-PAYLOAD-TRAILER"))
                .expect("unsigned trailer"),
            PayloadHashMode::StreamingUnsignedPayloadTrailer
        ));
    }

    #[test]
    fn payload_hash_mode_rejects_unsupported_or_non_lowercase_values() {
        assert!(matches!(
            PayloadHashMode::parse(Some(&"A".repeat(64))),
            Err(DomainError::InvalidPayloadHashMode)
        ));
        assert!(matches!(
            PayloadHashMode::parse(Some("not-supported")),
            Err(DomainError::InvalidPayloadHashMode)
        ));
    }
}