rustack-s3-core 0.9.0

S3 service implementation for Rustack
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
//! CORS rule matching and response header generation.
//!
//! Provides [`CorsIndex`] for storing per-bucket CORS configurations and
//! matching incoming requests against those rules. The matching logic follows
//! the S3 CORS specification, including wildcard origin support and preflight
//! request handling.

use dashmap::DashMap;

// ---------------------------------------------------------------------------
// CorsRule
// ---------------------------------------------------------------------------

/// A single CORS configuration rule for an S3 bucket.
///
/// Each rule specifies which origins, methods, and headers are allowed, which
/// response headers may be exposed, and how long the browser may cache the
/// preflight result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorsRule {
    /// Origins that are allowed (supports `"*"` wildcard).
    pub allowed_origins: Vec<String>,
    /// HTTP methods that are allowed (e.g. `"GET"`, `"PUT"`).
    pub allowed_methods: Vec<String>,
    /// Request headers that are allowed (supports `"*"` wildcard).
    pub allowed_headers: Vec<String>,
    /// Response headers that the browser is allowed to access.
    pub expose_headers: Vec<String>,
    /// How long (in seconds) the browser may cache the preflight result.
    pub max_age_seconds: Option<i32>,
}

// ---------------------------------------------------------------------------
// CorsMatch
// ---------------------------------------------------------------------------

/// The result of a successful CORS rule match.
///
/// Contains the values that should be included in the CORS response headers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorsMatch {
    /// The allowed origin for `Access-Control-Allow-Origin`.
    pub allowed_origin: String,
    /// The allowed methods for `Access-Control-Allow-Methods`.
    pub allowed_methods: Vec<String>,
    /// The allowed headers for `Access-Control-Allow-Headers`.
    pub allowed_headers: Vec<String>,
    /// The headers to expose via `Access-Control-Expose-Headers`.
    pub expose_headers: Vec<String>,
    /// Max age for `Access-Control-Max-Age`.
    pub max_age_seconds: Option<i32>,
}

// ---------------------------------------------------------------------------
// CorsIndex
// ---------------------------------------------------------------------------

/// Thread-safe, per-bucket CORS rule index.
///
/// Uses [`DashMap`] for lock-free concurrent reads and writes.
///
/// # Examples
///
/// ```
/// use rustack_s3_core::cors::{CorsIndex, CorsRule};
///
/// let index = CorsIndex::new();
/// index.set_rules("my-bucket", vec![
///     CorsRule {
///         allowed_origins: vec!["*".to_owned()],
///         allowed_methods: vec!["GET".to_owned()],
///         allowed_headers: vec![],
///         expose_headers: vec![],
///         max_age_seconds: None,
///     },
/// ]);
///
/// let m = index.match_cors("my-bucket", "https://example.com", "GET");
/// assert!(m.is_some());
/// ```
#[derive(Debug)]
pub struct CorsIndex {
    rules: DashMap<String, Vec<CorsRule>>,
}

impl CorsIndex {
    /// Create a new empty CORS index.
    #[must_use]
    pub fn new() -> Self {
        Self {
            rules: DashMap::new(),
        }
    }

    /// Set CORS rules for a bucket, replacing any existing rules.
    pub fn set_rules(&self, bucket: &str, rules: Vec<CorsRule>) {
        self.rules.insert(bucket.to_owned(), rules);
    }

    /// Delete all CORS rules for a bucket.
    pub fn delete_rules(&self, bucket: &str) {
        self.rules.remove(bucket);
    }

    /// Get a clone of the CORS rules for a bucket.
    #[must_use]
    pub fn get_rules(&self, bucket: &str) -> Option<Vec<CorsRule>> {
        self.rules.get(bucket).map(|r| r.value().clone())
    }

    /// Match an actual (non-preflight) request against the bucket's CORS rules.
    ///
    /// Returns the first matching [`CorsMatch`] or `None` if no rule matches.
    #[must_use]
    pub fn match_cors(&self, bucket: &str, origin: &str, method: &str) -> Option<CorsMatch> {
        let rules = self.rules.get(bucket)?;
        for rule in rules.value() {
            if !rule.allowed_origins.iter().any(|p| match_origin(p, origin)) {
                continue;
            }
            if !rule
                .allowed_methods
                .iter()
                .any(|m| m.eq_ignore_ascii_case(method))
            {
                continue;
            }
            return Some(CorsMatch {
                allowed_origin: resolve_origin(&rule.allowed_origins, origin),
                allowed_methods: rule.allowed_methods.clone(),
                allowed_headers: rule.allowed_headers.clone(),
                expose_headers: rule.expose_headers.clone(),
                max_age_seconds: rule.max_age_seconds,
            });
        }
        None
    }

    /// Match a preflight (OPTIONS) request against the bucket's CORS rules.
    ///
    /// Returns the first matching [`CorsMatch`] or `None` if no rule matches.
    /// Unlike [`match_cors`](Self::match_cors), this also validates the
    /// `Access-Control-Request-Headers` against `allowed_headers`.
    #[must_use]
    pub fn match_preflight(
        &self,
        bucket: &str,
        origin: &str,
        request_method: &str,
        request_headers: &[String],
    ) -> Option<CorsMatch> {
        let rules = self.rules.get(bucket)?;
        for rule in rules.value() {
            if !rule.allowed_origins.iter().any(|p| match_origin(p, origin)) {
                continue;
            }
            if !rule
                .allowed_methods
                .iter()
                .any(|m| m.eq_ignore_ascii_case(request_method))
            {
                continue;
            }
            if !headers_allowed(&rule.allowed_headers, request_headers) {
                continue;
            }
            return Some(CorsMatch {
                allowed_origin: resolve_origin(&rule.allowed_origins, origin),
                allowed_methods: rule.allowed_methods.clone(),
                allowed_headers: rule.allowed_headers.clone(),
                expose_headers: rule.expose_headers.clone(),
                max_age_seconds: rule.max_age_seconds,
            });
        }
        None
    }
}

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

// ---------------------------------------------------------------------------
// Matching helpers
// ---------------------------------------------------------------------------

/// Match an origin pattern against an actual origin.
///
/// A pattern of `"*"` matches any origin. Otherwise the comparison is
/// case-sensitive and exact.
#[must_use]
pub fn match_origin(pattern: &str, origin: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    pattern == origin
}

/// Determine the effective `Access-Control-Allow-Origin` value.
///
/// If any allowed origin is `"*"`, the header is `"*"`. Otherwise the
/// requesting origin is echoed back.
fn resolve_origin(allowed_origins: &[String], origin: &str) -> String {
    if allowed_origins.iter().any(|o| o == "*") {
        "*".to_owned()
    } else {
        origin.to_owned()
    }
}

/// Check whether all requested headers are permitted by the rule's
/// `allowed_headers`.
fn headers_allowed(allowed: &[String], requested: &[String]) -> bool {
    if allowed.iter().any(|h| h == "*") {
        return true;
    }
    requested
        .iter()
        .all(|req| allowed.iter().any(|a| a.eq_ignore_ascii_case(req)))
}

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

    fn make_permissive_rule() -> CorsRule {
        CorsRule {
            allowed_origins: vec!["*".to_owned()],
            allowed_methods: vec!["GET".to_owned(), "PUT".to_owned(), "POST".to_owned()],
            allowed_headers: vec!["*".to_owned()],
            expose_headers: vec!["x-amz-request-id".to_owned()],
            max_age_seconds: Some(3600),
        }
    }

    fn make_strict_rule() -> CorsRule {
        CorsRule {
            allowed_origins: vec!["https://example.com".to_owned()],
            allowed_methods: vec!["GET".to_owned()],
            allowed_headers: vec!["Content-Type".to_owned()],
            expose_headers: vec![],
            max_age_seconds: None,
        }
    }

    // -----------------------------------------------------------------------
    // CorsIndex basic operations
    // -----------------------------------------------------------------------

    #[test]
    fn test_should_set_and_get_rules() {
        let index = CorsIndex::new();
        let rules = vec![make_permissive_rule()];
        index.set_rules("bucket-a", rules.clone());

        let got = index.get_rules("bucket-a");
        assert!(got.is_some());
        assert_eq!(got.expect("test get"), rules);
    }

    #[test]
    fn test_should_return_none_for_unknown_bucket() {
        let index = CorsIndex::new();
        assert!(index.get_rules("nonexistent").is_none());
    }

    #[test]
    fn test_should_delete_rules() {
        let index = CorsIndex::new();
        index.set_rules("bucket-a", vec![make_permissive_rule()]);
        index.delete_rules("bucket-a");
        assert!(index.get_rules("bucket-a").is_none());
    }

    #[test]
    fn test_should_replace_existing_rules() {
        let index = CorsIndex::new();
        index.set_rules("bucket-a", vec![make_permissive_rule()]);
        index.set_rules("bucket-a", vec![make_strict_rule()]);

        let got = index.get_rules("bucket-a").expect("test get");
        assert_eq!(got.len(), 1);
        assert_eq!(
            got[0].allowed_origins,
            vec!["https://example.com".to_owned()],
        );
    }

    // -----------------------------------------------------------------------
    // match_cors
    // -----------------------------------------------------------------------

    #[test]
    fn test_should_match_wildcard_origin() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_permissive_rule()]);

        let m = index
            .match_cors("bucket", "https://any.example.com", "GET")
            .expect("test match");
        assert_eq!(m.allowed_origin, "*");
    }

    #[test]
    fn test_should_match_specific_origin() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_strict_rule()]);

        let m = index
            .match_cors("bucket", "https://example.com", "GET")
            .expect("test match");
        assert_eq!(m.allowed_origin, "https://example.com");
    }

    #[test]
    fn test_should_not_match_wrong_origin() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_strict_rule()]);

        assert!(
            index
                .match_cors("bucket", "https://evil.com", "GET")
                .is_none()
        );
    }

    #[test]
    fn test_should_not_match_wrong_method() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_strict_rule()]);

        assert!(
            index
                .match_cors("bucket", "https://example.com", "DELETE")
                .is_none()
        );
    }

    #[test]
    fn test_should_not_match_unknown_bucket() {
        let index = CorsIndex::new();
        assert!(
            index
                .match_cors("nope", "https://example.com", "GET")
                .is_none()
        );
    }

    // -----------------------------------------------------------------------
    // match_preflight
    // -----------------------------------------------------------------------

    #[test]
    fn test_should_match_preflight_with_wildcard_headers() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_permissive_rule()]);

        let m = index
            .match_preflight(
                "bucket",
                "https://example.com",
                "PUT",
                &["X-Custom-Header".to_owned()],
            )
            .expect("test match");
        assert_eq!(m.allowed_origin, "*");
        assert!(m.max_age_seconds.is_some());
    }

    #[test]
    fn test_should_match_preflight_with_specific_headers() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_strict_rule()]);

        let m = index
            .match_preflight(
                "bucket",
                "https://example.com",
                "GET",
                &["Content-Type".to_owned()],
            )
            .expect("test match");
        assert_eq!(m.allowed_origin, "https://example.com");
    }

    #[test]
    fn test_should_not_match_preflight_with_disallowed_header() {
        let index = CorsIndex::new();
        index.set_rules("bucket", vec![make_strict_rule()]);

        assert!(
            index
                .match_preflight(
                    "bucket",
                    "https://example.com",
                    "GET",
                    &["X-Forbidden".to_owned()],
                )
                .is_none()
        );
    }

    // -----------------------------------------------------------------------
    // match_origin helper
    // -----------------------------------------------------------------------

    #[test]
    fn test_should_match_wildcard_pattern() {
        assert!(match_origin("*", "https://anything.com"));
    }

    #[test]
    fn test_should_match_exact_pattern() {
        assert!(match_origin("https://example.com", "https://example.com"));
    }

    #[test]
    fn test_should_not_match_different_pattern() {
        assert!(!match_origin("https://example.com", "https://other.com"));
    }
}