rustango 0.57.11

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! CORS middleware — Cross-Origin Resource Sharing for axum routers.
//!
//! Adds the standard CORS response headers and handles `OPTIONS` preflight
//! requests automatically.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::cors::CorsLayer;
//! use axum::Router;
//!
//! let app = Router::new()
//!     .route("/api/posts", axum::routing::get(list_posts))
//!     .layer(CorsLayer::permissive()); // allow any origin (dev only)
//! ```
//!
//! ## Production config
//!
//! ```ignore
//! use rustango::cors::CorsLayer;
//! use std::time::Duration;
//!
//! let cors = CorsLayer::new()
//!     .allow_origins(vec!["https://app.example.com", "https://admin.example.com"])
//!     .allow_methods(vec!["GET", "POST", "PUT", "PATCH", "DELETE", "QUERY"])
//!     .allow_headers(vec!["content-type", "authorization"])
//!     .allow_credentials(true)
//!     .max_age(Duration::from_secs(3600));
//!
//! let app = Router::new()
//!     .route("/api/posts", axum::routing::post(create_post))
//!     .layer(cors);
//! ```

use std::sync::Arc;
use std::time::Duration;

use axum::body::Body;
use axum::http::header::{
    HeaderName, HeaderValue, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
    ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS,
    ACCESS_CONTROL_MAX_AGE, ACCESS_CONTROL_REQUEST_HEADERS, ORIGIN, VARY,
};
use axum::http::{Method, Request, Response, StatusCode};
use axum::middleware::Next;
use axum::Router;

/// Origin matching policy.
#[derive(Clone, Debug)]
pub enum AllowOrigin {
    /// Accept any origin. Sends `Access-Control-Allow-Origin: *`.
    Any,
    /// Allow only origins in this list (case-insensitive exact match).
    List(Arc<Vec<String>>),
}

/// Builder for the CORS axum layer.
#[derive(Clone)]
pub struct CorsLayer {
    allow_origin: AllowOrigin,
    allow_methods: Vec<String>,
    allow_headers: Vec<String>,
    expose_headers: Vec<String>,
    allow_credentials: bool,
    max_age: Option<Duration>,
}

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

impl CorsLayer {
    /// Empty layer: no origin is allowed. Add some with
    /// `allow_origins` or `allow_any_origin`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            allow_origin: AllowOrigin::List(Arc::new(Vec::new())),
            allow_methods: Vec::new(),
            allow_headers: Vec::new(),
            expose_headers: Vec::new(),
            allow_credentials: false,
            max_age: None,
        }
    }

    /// Development config: any origin, plus the common methods and
    /// headers. **Do not use it in production.**
    #[must_use]
    pub fn permissive() -> Self {
        Self {
            allow_origin: AllowOrigin::Any,
            allow_methods: vec![
                "GET".into(),
                "POST".into(),
                "PUT".into(),
                "PATCH".into(),
                "DELETE".into(),
                "HEAD".into(),
                "OPTIONS".into(),
                // QUERY is never CORS-safelisted, so it always needs a
                // preflight and must be listed here.
                "QUERY".into(),
            ],
            allow_headers: vec!["*".into()],
            expose_headers: Vec::new(),
            allow_credentials: false,
            max_age: Some(Duration::from_secs(3600)),
        }
    }

    /// Allow these origins (case-insensitive exact match).
    #[must_use]
    pub fn allow_origins<I, S>(mut self, origins: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allow_origin =
            AllowOrigin::List(Arc::new(origins.into_iter().map(Into::into).collect()));
        self
    }

    /// Allow any origin.
    ///
    /// This warns if credentials are already on. Browsers reject `*`
    /// together with credentials. For credentialed CORS, list the
    /// origins with `.allow_origins([...])` instead.
    #[must_use]
    pub fn allow_any_origin(mut self) -> Self {
        self.allow_origin = AllowOrigin::Any;
        if self.allow_credentials {
            tracing::warn!(
                target: "rustango::cors",
                "CorsLayer.allow_any_origin() called with allow_credentials=true — \
                 use .allow_origins([...]) with an explicit allowlist for credentialed CORS"
            );
        }
        self
    }

    /// Build the layer from a [`crate::config::SecuritySettings`]
    /// section:
    ///
    /// - `cors_allowed_origins` empty gives `None`. CORS is opt-in,
    ///   so an empty list means "do not mount the layer", which is
    ///   not the same as "allow no origin".
    /// - A list holding `"*"` gives [`Self::permissive`].
    /// - Named origins give an allowlist plus the methods and
    ///   headers most APIs need. For tighter control, build the
    ///   layer yourself.
    ///
    /// ```ignore
    /// let cfg = rustango::config::Settings::load_from_env()?;
    /// if let Some(layer) = CorsLayer::from_settings(&cfg.security) {
    ///     app = app.layer(layer.into_layer());
    /// }
    /// ```
    #[cfg(feature = "config")]
    #[must_use]
    pub fn from_settings(s: &crate::config::SecuritySettings) -> Option<Self> {
        if s.cors_allowed_origins.is_empty() {
            return None;
        }
        if s.cors_allowed_origins.iter().any(|o| o == "*") {
            return Some(Self::permissive());
        }
        Some(
            Self::new()
                .allow_origins(s.cors_allowed_origins.iter().cloned())
                .allow_methods([
                    "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "QUERY",
                ])
                .allow_headers(["Content-Type", "Authorization"])
                .max_age(Duration::from_secs(3600)),
        )
    }

    /// Allowed methods sent in preflight responses.
    #[must_use]
    pub fn allow_methods<I, S>(mut self, methods: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allow_methods = methods.into_iter().map(Into::into).collect();
        self
    }

    /// Allowed request headers sent in preflight responses.
    #[must_use]
    pub fn allow_headers<I, S>(mut self, headers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allow_headers = headers.into_iter().map(Into::into).collect();
        self
    }

    /// Response headers exposed to the browser.
    #[must_use]
    pub fn expose_headers<I, S>(mut self, headers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.expose_headers = headers.into_iter().map(Into::into).collect();
        self
    }

    /// Set `Access-Control-Allow-Credentials: true`.
    ///
    /// **Do not combine this with `allow_any_origin()`.** Browsers
    /// reject `*` together with credentials, so those requests fail.
    /// List your origins instead. This method warns at build time if
    /// the layer already allows any origin, so the mistake shows up
    /// in the logs and not only as a broken preflight.
    #[must_use]
    pub fn allow_credentials(mut self, yes: bool) -> Self {
        self.allow_credentials = yes;
        if yes && matches!(self.allow_origin, AllowOrigin::Any) {
            tracing::warn!(
                target: "rustango::cors",
                "CorsLayer.allow_credentials(true) combined with allow_any_origin() — \
                 the framework echoes the request Origin back per request, but preflights \
                 that omit `Origin` will fail in browsers. Use .allow_origins([...]) with \
                 an explicit allowlist for credentialed CORS."
            );
        }
        self
    }

    /// Browser preflight cache duration.
    #[must_use]
    pub fn max_age(mut self, dur: Duration) -> Self {
        self.max_age = Some(dur);
        self
    }

    /// Resolve the `Access-Control-Allow-Origin` value for a given request `Origin`.
    /// Returns `None` when the origin should be rejected.
    fn resolve_origin(&self, request_origin: Option<&str>) -> Option<String> {
        match (&self.allow_origin, request_origin) {
            // Never echo a concrete origin while credentials are on.
            //
            // A browser refuses `Access-Control-Allow-Origin: *` with
            // credentials, but it accepts an echoed concrete origin.
            // So echoing here would turn "any origin" into "every
            // origin, with cookies", readable by any site the victim
            // visits. Answer `*` and let the browser block it.
            (AllowOrigin::Any, _) if self.allow_credentials => Some("*".to_owned()),
            (AllowOrigin::Any, Some(o)) => Some(o.to_owned()),
            (AllowOrigin::Any, None) => Some("*".to_owned()),
            (AllowOrigin::List(list), Some(o)) => {
                let lower = o.to_ascii_lowercase();
                if list
                    .iter()
                    .any(|allowed| allowed.eq_ignore_ascii_case(&lower))
                {
                    Some(o.to_owned())
                } else {
                    None
                }
            }
            (AllowOrigin::List(_), None) => None,
        }
    }
}

/// Extension trait that adds `.layer(CorsLayer)` ergonomics to `Router`.
pub trait CorsRouterExt {
    /// Apply this CORS configuration to all routes in this router.
    #[must_use]
    fn cors(self, layer: CorsLayer) -> Self;
}

impl<S: Clone + Send + Sync + 'static> CorsRouterExt for Router<S> {
    fn cors(self, layer: CorsLayer) -> Self {
        let cfg = Arc::new(layer);
        self.layer(axum::middleware::from_fn(
            move |req: Request<Body>, next: Next| {
                let cfg = cfg.clone();
                async move { handle(cfg, req, next).await }
            },
        ))
    }
}

async fn handle(cfg: Arc<CorsLayer>, req: Request<Body>, next: Next) -> Response<Body> {
    let req_origin = req
        .headers()
        .get(ORIGIN)
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);

    // Preflight: short-circuit and return CORS headers
    if req.method() == Method::OPTIONS && req.headers().get(ORIGIN).is_some() {
        let mut response = Response::builder()
            .status(StatusCode::NO_CONTENT)
            .body(Body::empty())
            .unwrap();
        // Echo requested headers back if a list isn't configured.
        let request_headers = req
            .headers()
            .get(ACCESS_CONTROL_REQUEST_HEADERS)
            .and_then(|v| v.to_str().ok())
            .map(str::to_owned);
        attach_cors_headers(
            &cfg,
            req_origin.as_deref(),
            request_headers.as_deref(),
            &mut response,
        );
        return response;
    }

    // Pass through to the inner handler, then attach CORS to its response.
    let mut response = next.run(req).await;
    attach_cors_headers(&cfg, req_origin.as_deref(), None, &mut response);
    response
}

fn attach_cors_headers(
    cfg: &CorsLayer,
    request_origin: Option<&str>,
    request_headers: Option<&str>,
    response: &mut Response<Body>,
) {
    let Some(allow_origin) = cfg.resolve_origin(request_origin) else {
        return;
    };
    let headers = response.headers_mut();
    if let Ok(v) = HeaderValue::from_str(&allow_origin) {
        headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, v);
    }
    // Vary: Origin so caches don't serve a wrong-origin response
    if matches!(cfg.allow_origin, AllowOrigin::List(_)) {
        headers.append(VARY, HeaderValue::from_static("origin"));
    }

    if !cfg.allow_methods.is_empty() {
        if let Ok(v) = HeaderValue::from_str(&cfg.allow_methods.join(", ")) {
            headers.insert(ACCESS_CONTROL_ALLOW_METHODS, v);
        }
    }

    let allow_headers = if cfg.allow_headers.is_empty() {
        request_headers.map(str::to_owned)
    } else {
        Some(cfg.allow_headers.join(", "))
    };
    if let Some(h) = allow_headers {
        if let Ok(v) = HeaderValue::from_str(&h) {
            headers.insert(ACCESS_CONTROL_ALLOW_HEADERS, v);
        }
    }

    if !cfg.expose_headers.is_empty() {
        if let Ok(v) = HeaderValue::from_str(&cfg.expose_headers.join(", ")) {
            headers.insert(ACCESS_CONTROL_EXPOSE_HEADERS, v);
        }
    }

    // Never send credentials next to a wildcard: no browser honours
    // that pair. The build-time warning tells the operator instead.
    if cfg.allow_credentials && allow_origin != "*" {
        headers.insert(
            ACCESS_CONTROL_ALLOW_CREDENTIALS,
            HeaderValue::from_static("true"),
        );
    }

    if let Some(age) = cfg.max_age {
        if let Ok(v) = HeaderValue::from_str(&age.as_secs().to_string()) {
            headers.insert(ACCESS_CONTROL_MAX_AGE, v);
        }
    }
    let _ = (HeaderName::from_static("vary"),); // silence unused import in some configs
}

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

    #[test]
    fn resolve_any_with_origin() {
        let l = CorsLayer::new().allow_any_origin();
        assert_eq!(
            l.resolve_origin(Some("https://x.com")).as_deref(),
            Some("https://x.com")
        );
    }

    #[test]
    fn resolve_any_without_origin_returns_wildcard() {
        let l = CorsLayer::new().allow_any_origin();
        assert_eq!(l.resolve_origin(None).as_deref(), Some("*"));
    }

    /// The credentialed wildcard hole. Echoing the request origin is
    /// safe without credentials, and lets any site read any response
    /// with them, because browsers reject `*` plus credentials but
    /// accept an echoed concrete origin. Both halves are pinned here.
    #[test]
    fn any_origin_never_echoes_while_credentials_are_on() {
        let evil = "https://evil.example";

        let safe = CorsLayer::new().allow_any_origin();
        assert_eq!(
            safe.resolve_origin(Some(evil)).as_deref(),
            Some(evil),
            "without credentials, echoing is fine and stays"
        );

        let holed = CorsLayer::new().allow_any_origin().allow_credentials(true);
        assert_eq!(
            holed.resolve_origin(Some(evil)).as_deref(),
            Some("*"),
            "with credentials the origin must NOT be echoed — a reflected \
             concrete origin is what browsers accept, and is the hole"
        );
    }

    /// The other half: `*` and `Access-Control-Allow-Credentials: true` must
    /// never ship together, whatever the origin resolved to.
    #[test]
    fn wildcard_response_carries_no_credentials_header() {
        let cfg = CorsLayer::new().allow_any_origin().allow_credentials(true);
        let mut res = Response::new(Body::empty());
        attach_cors_headers(&cfg, Some("https://evil.example"), None, &mut res);

        let h = res.headers();
        assert_eq!(
            h.get(ACCESS_CONTROL_ALLOW_ORIGIN)
                .map(|v| v.to_str().unwrap()),
            Some("*")
        );
        assert!(
            h.get(ACCESS_CONTROL_ALLOW_CREDENTIALS).is_none(),
            "a wildcard response must not claim credentials: got {:?}",
            h.get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
        );
    }

    /// An allowlist is the supported way to do credentialed CORS, so
    /// it must keep working.
    #[test]
    fn allowlisted_origin_still_gets_credentials() {
        let cfg = CorsLayer::new()
            .allow_origins(vec!["https://app.example.com"])
            .allow_credentials(true);
        let mut res = Response::new(Body::empty());
        attach_cors_headers(&cfg, Some("https://app.example.com"), None, &mut res);

        let h = res.headers();
        assert_eq!(
            h.get(ACCESS_CONTROL_ALLOW_ORIGIN)
                .map(|v| v.to_str().unwrap()),
            Some("https://app.example.com")
        );
        assert_eq!(
            h.get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .map(|v| v.to_str().unwrap()),
            Some("true")
        );
    }

    #[test]
    fn resolve_list_match() {
        let l = CorsLayer::new().allow_origins(vec!["https://app.example.com"]);
        assert_eq!(
            l.resolve_origin(Some("https://app.example.com")).as_deref(),
            Some("https://app.example.com")
        );
    }

    #[test]
    fn resolve_list_case_insensitive() {
        let l = CorsLayer::new().allow_origins(vec!["https://APP.example.com"]);
        assert_eq!(
            l.resolve_origin(Some("https://app.example.com")).as_deref(),
            Some("https://app.example.com")
        );
    }

    #[test]
    fn resolve_list_miss_returns_none() {
        let l = CorsLayer::new().allow_origins(vec!["https://other.com"]);
        assert_eq!(l.resolve_origin(Some("https://x.com")), None);
    }

    #[test]
    fn resolve_empty_list_rejects_all() {
        let l = CorsLayer::new();
        assert_eq!(l.resolve_origin(Some("https://x.com")), None);
    }

    #[test]
    fn permissive_allows_any() {
        let l = CorsLayer::permissive();
        assert!(l.resolve_origin(Some("https://anywhere.test")).is_some());
    }

    #[test]
    fn permissive_advertises_query_method() {
        // QUERY always needs a preflight, so it must appear in
        // Access-Control-Allow-Methods.
        let l = CorsLayer::permissive();
        assert!(
            l.allow_methods.iter().any(|m| m == "QUERY"),
            "permissive CORS must allow QUERY: {:?}",
            l.allow_methods
        );
    }

    // ---- from_settings ----

    /// An empty `cors_allowed_origins` gives `None`, so the layer is
    /// not mounted. That differs from "allow no origin", which would
    /// reject every preflight.
    #[cfg(feature = "config")]
    #[test]
    fn from_settings_empty_returns_none() {
        let s = crate::config::SecuritySettings::default();
        assert!(CorsLayer::from_settings(&s).is_none());
    }

    /// Wildcard `"*"` maps to the permissive preset.
    #[cfg(feature = "config")]
    #[test]
    fn from_settings_wildcard_returns_permissive() {
        let mut s = crate::config::SecuritySettings::default();
        s.cors_allowed_origins = vec!["*".into()];
        let layer = CorsLayer::from_settings(&s).expect("Some");
        assert!(layer.resolve_origin(Some("https://random.test")).is_some());
    }

    /// Named origins build an allowlist and anything else is
    /// rejected. Methods, headers and max-age get useful defaults.
    #[cfg(feature = "config")]
    #[test]
    fn from_settings_specific_origins_build_allowlist() {
        let mut s = crate::config::SecuritySettings::default();
        s.cors_allowed_origins = vec!["https://app.example.com".into()];
        let layer = CorsLayer::from_settings(&s).expect("Some");
        assert!(layer
            .resolve_origin(Some("https://app.example.com"))
            .is_some());
        assert!(layer
            .resolve_origin(Some("https://other.example.com"))
            .is_none());
    }
}