multistore 0.4.0

Runtime-agnostic core library for the S3 proxy gateway
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
//! S3 XML response serialization.

use quick_xml::se::to_string as xml_to_string;
use serde::Serialize;

use crate::error::ProxyError;
pub use crate::types::BucketOwner;

/// S3 Error response XML.
#[derive(Debug, Serialize)]
#[serde(rename = "Error")]
pub struct ErrorResponse {
    #[serde(rename = "Code")]
    pub code: String,
    #[serde(rename = "Message")]
    pub message: String,
    #[serde(rename = "Resource")]
    pub resource: String,
    #[serde(rename = "RequestId")]
    pub request_id: String,
}

impl ErrorResponse {
    /// Build an S3-compatible error response.
    ///
    /// When `debug` is `true`, the full internal error message is included
    /// (useful during development). When `false`, server-side errors (500)
    /// use a generic message to avoid leaking backend details.
    pub fn from_proxy_error(
        err: &ProxyError,
        resource: &str,
        request_id: &str,
        debug: bool,
    ) -> Self {
        let message = if debug {
            err.to_string()
        } else {
            err.safe_message()
        };
        Self {
            code: err.s3_error_code().to_string(),
            message,
            resource: resource.to_string(),
            request_id: request_id.to_string(),
        }
    }

    /// Build an S3 `SlowDown` error for rate-limited requests.
    pub fn slow_down(request_id: &str) -> Self {
        Self {
            code: "SlowDown".to_string(),
            message: "Please reduce your request rate.".to_string(),
            resource: String::new(),
            request_id: request_id.to_string(),
        }
    }

    /// Serialize this error response to an S3-compatible XML string.
    pub fn to_xml(&self) -> String {
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
            xml_to_string(self)
                .unwrap_or_else(|_| "<Error><Code>InternalError</Code></Error>".to_string())
        )
    }
}

/// InitiateMultipartUpload response.
#[derive(Debug, Serialize)]
#[serde(rename = "InitiateMultipartUploadResult")]
pub struct InitiateMultipartUploadResult {
    #[serde(rename = "Bucket")]
    pub bucket: String,
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "UploadId")]
    pub upload_id: String,
}

impl InitiateMultipartUploadResult {
    /// Serialize this result to an S3-compatible XML string.
    pub fn to_xml(&self) -> String {
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
            xml_to_string(self).unwrap_or_default()
        )
    }
}

/// CompleteMultipartUpload response.
#[derive(Debug, Serialize)]
#[serde(rename = "CompleteMultipartUploadResult")]
pub struct CompleteMultipartUploadResult {
    #[serde(rename = "Location")]
    pub location: String,
    #[serde(rename = "Bucket")]
    pub bucket: String,
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "ETag")]
    pub etag: String,
}

impl CompleteMultipartUploadResult {
    /// Serialize this result to an S3-compatible XML string.
    pub fn to_xml(&self) -> String {
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
            xml_to_string(self).unwrap_or_default()
        )
    }
}

/// Deserialized XML body of a CompleteMultipartUpload request.
#[derive(Debug, serde::Deserialize)]
#[serde(rename = "CompleteMultipartUpload")]
pub struct CompleteMultipartUploadRequest {
    #[serde(rename = "Part")]
    pub parts: Vec<CompletePart>,
}

/// A single part entry in a CompleteMultipartUpload request.
#[derive(Debug, serde::Deserialize)]
pub struct CompletePart {
    /// The part number assigned during UploadPart.
    #[serde(rename = "PartNumber")]
    pub part_number: u32,
    /// The ETag returned by the backend for this part.
    #[serde(rename = "ETag")]
    pub etag: String,
}

/// ListAllMyBucketsResult response (for `GET /`).
#[derive(Debug, Serialize)]
#[serde(rename = "ListAllMyBucketsResult")]
pub struct ListAllMyBucketsResult {
    #[serde(rename = "Owner")]
    pub owner: BucketOwner,
    #[serde(rename = "Buckets")]
    pub buckets: BucketList,
}

/// Wrapper for the `<Buckets>` element in a ListAllMyBucketsResult response.
#[derive(Debug, Serialize)]
pub struct BucketList {
    #[serde(rename = "Bucket")]
    pub buckets: Vec<BucketEntry>,
}

/// A single bucket entry in a ListAllMyBucketsResult response.
#[derive(Debug, Serialize)]
pub struct BucketEntry {
    /// The virtual bucket name.
    #[serde(rename = "Name")]
    pub name: String,
    /// ISO 8601 creation timestamp.
    #[serde(rename = "CreationDate")]
    pub creation_date: String,
}

impl ListAllMyBucketsResult {
    /// Serialize this result to an S3-compatible XML string.
    pub fn to_xml(&self) -> String {
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
            xml_to_string(self).unwrap_or_default()
        )
    }
}

/// S3 ListObjectsV2 response.
#[derive(Debug, Serialize)]
#[serde(rename = "ListBucketResult")]
pub struct ListBucketResult {
    /// XML namespace URI for the S3 ListBucketResult schema.
    #[serde(rename = "@xmlns")]
    pub xmlns: &'static str,
    /// The bucket name.
    #[serde(rename = "Name")]
    pub name: String,
    /// The key prefix used to filter results.
    #[serde(rename = "Prefix")]
    pub prefix: String,
    /// The delimiter used to group common prefixes.
    #[serde(rename = "Delimiter", skip_serializing_if = "String::is_empty")]
    pub delimiter: String,
    /// Encoding type applied to keys and prefixes in this response.
    #[serde(rename = "EncodingType", skip_serializing_if = "Option::is_none")]
    pub encoding_type: Option<String>,
    /// Maximum number of keys returned per page.
    #[serde(rename = "MaxKeys")]
    pub max_keys: usize,
    /// Whether additional pages of results are available.
    #[serde(rename = "IsTruncated")]
    pub is_truncated: bool,
    /// Number of keys returned in this response (contents + common prefixes).
    #[serde(rename = "KeyCount")]
    pub key_count: usize,
    /// The `start-after` value from the request, if provided.
    #[serde(rename = "StartAfter", skip_serializing_if = "Option::is_none")]
    pub start_after: Option<String>,
    /// The continuation token from the request, echoed back.
    #[serde(rename = "ContinuationToken", skip_serializing_if = "Option::is_none")]
    pub continuation_token: Option<String>,
    /// Token to pass in the next request to fetch the next page.
    #[serde(
        rename = "NextContinuationToken",
        skip_serializing_if = "Option::is_none"
    )]
    pub next_continuation_token: Option<String>,
    /// The object entries matching the list request.
    #[serde(rename = "Contents", default)]
    pub contents: Vec<ListContents>,
    /// Common prefix entries when a delimiter is used.
    #[serde(rename = "CommonPrefixes", default)]
    pub common_prefixes: Vec<ListCommonPrefix>,
}

/// A single object entry in a ListObjectsV2 response.
#[derive(Debug, Clone, Serialize)]
pub struct ListContents {
    /// The object key.
    #[serde(rename = "Key")]
    pub key: String,
    /// ISO 8601 timestamp of the last modification.
    #[serde(rename = "LastModified")]
    pub last_modified: String,
    /// The entity tag (ETag) for the object.
    #[serde(rename = "ETag")]
    pub etag: String,
    /// Object size in bytes.
    #[serde(rename = "Size")]
    pub size: u64,
    /// Storage class of the object (always "STANDARD" in this proxy).
    #[serde(rename = "StorageClass")]
    pub storage_class: &'static str,
}

/// A common prefix entry in a ListObjectsV2 response (delimiter-based grouping).
#[derive(Debug, Serialize)]
pub struct ListCommonPrefix {
    /// The shared prefix for grouped keys.
    #[serde(rename = "Prefix")]
    pub prefix: String,
}

impl ListBucketResult {
    /// Serialize this result to an S3-compatible XML string.
    pub fn to_xml(&self) -> String {
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
            xml_to_string(self).unwrap_or_default()
        )
    }
}

/// S3 ListObjectsV1 response.
#[derive(Debug, Serialize)]
#[serde(rename = "ListBucketResult")]
pub struct ListBucketResultV1 {
    /// XML namespace URI for the S3 ListBucketResult schema.
    #[serde(rename = "@xmlns")]
    pub xmlns: &'static str,
    /// The bucket name.
    #[serde(rename = "Name")]
    pub name: String,
    /// The key prefix used to filter results.
    #[serde(rename = "Prefix")]
    pub prefix: String,
    /// The delimiter used to group common prefixes.
    #[serde(rename = "Delimiter", skip_serializing_if = "String::is_empty")]
    pub delimiter: String,
    /// Encoding type applied to keys and prefixes in this response.
    #[serde(rename = "EncodingType", skip_serializing_if = "Option::is_none")]
    pub encoding_type: Option<String>,
    /// Maximum number of keys returned per page.
    #[serde(rename = "MaxKeys")]
    pub max_keys: usize,
    /// Whether additional pages of results are available.
    #[serde(rename = "IsTruncated")]
    pub is_truncated: bool,
    /// The marker from the request, echoed back.
    #[serde(rename = "Marker")]
    pub marker: String,
    /// When `IsTruncated` is true, the key to use as `marker` in the next request.
    #[serde(rename = "NextMarker", skip_serializing_if = "Option::is_none")]
    pub next_marker: Option<String>,
    /// The object entries matching the list request.
    #[serde(rename = "Contents", default)]
    pub contents: Vec<ListContents>,
    /// Common prefix entries when a delimiter is used.
    #[serde(rename = "CommonPrefixes", default)]
    pub common_prefixes: Vec<ListCommonPrefix>,
}

impl ListBucketResultV1 {
    /// Serialize this result to an S3-compatible XML string.
    pub fn to_xml(&self) -> String {
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}",
            xml_to_string(self).unwrap_or_default()
        )
    }
}

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

    #[test]
    fn test_list_bucket_result_xml() {
        let result = ListBucketResult {
            xmlns: "http://s3.amazonaws.com/doc/2006-03-01/",
            name: "my-bucket".to_string(),
            prefix: "photos/".to_string(),
            delimiter: "/".to_string(),
            encoding_type: None,
            max_keys: 1000,
            is_truncated: false,
            key_count: 1,
            start_after: None,
            continuation_token: None,
            next_continuation_token: None,
            contents: vec![ListContents {
                key: "photos/image.jpg".to_string(),
                last_modified: "2024-01-01T00:00:00.000Z".to_string(),
                etag: "\"abc123\"".to_string(),
                size: 1024,
                storage_class: "STANDARD",
            }],
            common_prefixes: vec![ListCommonPrefix {
                prefix: "photos/thumbs/".to_string(),
            }],
        };

        let xml = result.to_xml();
        assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
        assert!(
            xml.contains("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">")
        );
        assert!(xml.contains("<Name>my-bucket</Name>"));
        assert!(xml.contains("<Key>photos/image.jpg</Key>"));
        assert!(xml.contains("<Size>1024</Size>"));
        assert!(xml.contains("<CommonPrefixes><Prefix>photos/thumbs/</Prefix></CommonPrefixes>"));
    }

    #[test]
    fn test_list_bucket_result_empty() {
        let result = ListBucketResult {
            xmlns: "http://s3.amazonaws.com/doc/2006-03-01/",
            name: "bucket".to_string(),
            prefix: String::new(),
            delimiter: "/".to_string(),
            encoding_type: None,
            max_keys: 1000,
            is_truncated: false,
            key_count: 0,
            start_after: None,
            continuation_token: None,
            next_continuation_token: None,
            contents: vec![],
            common_prefixes: vec![],
        };

        let xml = result.to_xml();
        assert!(xml.contains("<KeyCount>0</KeyCount>"));
        assert!(!xml.contains("<Contents>"));
        assert!(!xml.contains("<CommonPrefixes>"));
    }

    #[test]
    fn test_list_bucket_result_v1_xml() {
        let result = ListBucketResultV1 {
            xmlns: "http://s3.amazonaws.com/doc/2006-03-01/",
            name: "my-bucket".to_string(),
            prefix: "photos/".to_string(),
            delimiter: "/".to_string(),
            encoding_type: None,
            max_keys: 1000,
            is_truncated: true,
            marker: "photos/a.jpg".to_string(),
            next_marker: Some("photos/z.jpg".to_string()),
            contents: vec![ListContents {
                key: "photos/image.jpg".to_string(),
                last_modified: "2024-01-01T00:00:00.000Z".to_string(),
                etag: "\"abc123\"".to_string(),
                size: 1024,
                storage_class: "STANDARD",
            }],
            common_prefixes: vec![ListCommonPrefix {
                prefix: "photos/thumbs/".to_string(),
            }],
        };

        let xml = result.to_xml();
        assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
        assert!(xml.contains("<Marker>photos/a.jpg</Marker>"));
        assert!(xml.contains("<NextMarker>photos/z.jpg</NextMarker>"));
        assert!(xml.contains("<Name>my-bucket</Name>"));
        assert!(xml.contains("<Key>photos/image.jpg</Key>"));

        // V2-only elements must be absent
        assert!(!xml.contains("<KeyCount>"), "V1 must not have KeyCount");
        assert!(!xml.contains("<StartAfter>"), "V1 must not have StartAfter");
        assert!(
            !xml.contains("<ContinuationToken>"),
            "V1 must not have ContinuationToken"
        );
    }
}