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
//! 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"])
//! .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 {
/// Echo back any incoming `Origin` (sets `Access-Control-Allow-Origin: *`
/// when no specific origin is sent — request-aware reflection).
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 CORS layer — no origins allowed by default. Configure with
/// `allow_origins` / `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,
}
}
/// Wide-open development config: any origin, common methods, common
/// headers. **Do not use 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(),
],
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 (echoes the incoming Origin back).
///
/// v0.30.12 (security audit) — emits a `tracing::warn!` if
/// credentials are already enabled. Browsers reject `*` with
/// credentials, and while the framework works around this by
/// echoing the Origin per-request, preflights without an
/// Origin header fail. Build with an explicit allowlist
/// (`.allow_origins([...])`) for credentialed CORS.
#[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 loaded
/// [`crate::config::SecuritySettings`] section (#87 wiring,
/// v0.29). Three branches:
///
/// - `cors_allowed_origins` empty → returns `None`. CORS is
/// opt-in; an empty list means "don't mount the layer at
/// all" (different from "allow zero origins").
/// - List contains `"*"` → returns
/// `Some(Self::permissive())`. Wildcard is the canonical way
/// to write "any origin" in TOML; it maps to the existing
/// permissive preset.
/// - Specific origins → returns `Some` with allowlist + the
/// common methods/headers most APIs need. Callers that want
/// tighter control build their own layer.
///
/// ```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"])
.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`. Note: when `true`
/// you cannot use `allow_any_origin()` — browsers reject `*` with
/// credentials, and the framework works around this by echoing
/// the request's `Origin` back instead of `*` (only on requests
/// that carry an `Origin` header). Preflight requests that omit
/// `Origin` will still get `*` in the response, which the
/// browser rejects with credentials.
///
/// v0.30.12 (security audit) — this method emits a
/// `tracing::warn!` at construction time when `yes = true`
/// and the layer is configured with `allow_any_origin()`, so
/// the misconfig surfaces in logs instead of silently failing
/// preflights for some clients.
#[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) {
(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);
}
}
if cfg.allow_credentials {
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("*"));
}
#[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());
}
// ---- #87 wiring: from_settings ----
/// Empty `cors_allowed_origins` returns `None` so callers don't
/// mount the layer at all — different from "allow zero origins"
/// (which would 403 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());
}
/// Specific origins build an allowlist; non-matching origins
/// reject. Methods + headers + max-age get sensible defaults so
/// the resulting layer is immediately usable.
#[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());
}
}