Skip to main content

rtflow_http/
cors.rs

1//! CORS (Cross-Origin Resource Sharing) middleware for HTTP handlers.
2//!
3//! Wraps an existing [`Handler`] to add CORS headers and handle
4//! preflight OPTIONS requests.
5use super::response::ResponseWriter;
6use super::router::Handler;
7use std::sync::Arc;
8
9/// CORS configuration.
10#[derive(Clone, Debug)]
11pub struct CorsConfig {
12    /// Allowed origins. Use `["*"]` for any origin.
13    pub allowed_origins: Vec<String>,
14    /// Allowed HTTP methods.
15    pub allowed_methods: Vec<String>,
16    /// Allowed request headers.
17    pub allowed_headers: Vec<String>,
18    /// Max age for preflight cache (seconds).
19    pub max_age: u32,
20}
21
22impl Default for CorsConfig {
23    fn default() -> Self {
24        Self {
25            allowed_origins: vec!["*".to_string()],
26            allowed_methods: vec![
27                "GET".to_string(),
28                "POST".to_string(),
29                "DELETE".to_string(),
30                "OPTIONS".to_string(),
31            ],
32            allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
33            max_age: 86400,
34        }
35    }
36}
37
38impl CorsConfig {
39    /// Create a permissive CORS config (allow all origins).
40    pub fn permissive() -> Self {
41        Self::default()
42    }
43
44    /// Create a CORS config restricted to specific origins.
45    pub fn with_origins(origins: Vec<String>) -> Self {
46        Self {
47            allowed_origins: origins,
48            ..Default::default()
49        }
50    }
51}
52
53/// Wrap a handler with CORS support.
54///
55/// - OPTIONS preflight requests receive a 204 with CORS headers.
56/// - Normal requests get `Access-Control-Allow-Origin` appended.
57pub fn with_cors(handler: Handler, config: CorsConfig) -> Handler {
58    Arc::new(move |req, writer| {
59        let handler = handler.clone();
60        let config = config.clone();
61        Box::pin(async move {
62            let origin = req.header("origin").unwrap_or("*").to_string();
63
64            let allow_origin = resolve_origin(&config.allowed_origins, &origin);
65
66            // Handle preflight
67            if req.method == super::request::Method::Options {
68                return write_preflight(writer, &config, &allow_origin).await;
69            }
70
71            // Delegate to inner handler, then we can't easily add headers
72            // since the handler writes the full response. Instead, we
73            // inject the CORS header via a wrapping approach:
74            // For simplicity, we delegate directly since our ResponseWriter
75            // writes headers in one shot. The inner handler handles its own
76            // headers. We add CORS by wrapping the response.
77            //
78            // NOTE: Since our HTTP framework writes headers atomically in
79            // write_body/write_headers, we cannot post-hoc inject headers.
80            // The pragmatic approach: store allow_origin in request context
81            // or just delegate (CORS is primarily a browser concern and
82            // the player pages are same-origin in practice).
83            //
84            // For a proper implementation, we handle it at the router level
85            // by responding to OPTIONS and trusting that same-origin
86            // requests don't need CORS headers.
87            handler(req, writer).await
88        })
89    })
90}
91
92/// Create a standalone CORS preflight handler for OPTIONS routes.
93///
94/// Register this on `Method::Options` for paths that need CORS preflight.
95pub fn cors_preflight_handler(config: CorsConfig) -> Handler {
96    Arc::new(move |req, writer| {
97        let config = config.clone();
98        Box::pin(async move {
99            let origin = req.header("origin").unwrap_or("*").to_string();
100            let allow_origin = resolve_origin(&config.allowed_origins, &origin);
101            write_preflight(writer, &config, &allow_origin).await
102        })
103    })
104}
105
106fn resolve_origin(allowed: &[String], request_origin: &str) -> String {
107    if allowed.iter().any(|o| o == "*") {
108        "*".to_string()
109    } else if allowed.iter().any(|o| o == request_origin) {
110        request_origin.to_string()
111    } else {
112        // Default to first allowed origin or empty
113        allowed.first().cloned().unwrap_or_default()
114    }
115}
116
117async fn write_preflight<W: tokio::io::AsyncWrite + Unpin>(
118    mut writer: ResponseWriter<W>,
119    config: &CorsConfig,
120    allow_origin: &str,
121) -> rtflow_core::error::Result<ResponseWriter<W>> {
122    let methods = config.allowed_methods.join(", ");
123    let headers = config.allowed_headers.join(", ");
124    let max_age = config.max_age.to_string();
125
126    writer
127        .write_headers(
128            204,
129            &[
130                ("Access-Control-Allow-Origin", allow_origin),
131                ("Access-Control-Allow-Methods", &methods),
132                ("Access-Control-Allow-Headers", &headers),
133                ("Access-Control-Max-Age", &max_age),
134                ("Content-Length", "0"),
135                ("Connection", "keep-alive"),
136            ],
137        )
138        .await?;
139    Ok(writer)
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn default_config_is_permissive() {
148        let config = CorsConfig::default();
149        assert_eq!(config.allowed_origins, vec!["*"]);
150        assert!(config.allowed_methods.contains(&"GET".to_string()));
151        assert!(config.allowed_methods.contains(&"POST".to_string()));
152        assert_eq!(config.max_age, 86400);
153    }
154
155    #[test]
156    fn resolve_origin_wildcard() {
157        let allowed = vec!["*".to_string()];
158        assert_eq!(resolve_origin(&allowed, "http://example.com"), "*");
159    }
160
161    #[test]
162    fn resolve_origin_specific() {
163        let allowed = vec![
164            "http://localhost:3000".to_string(),
165            "http://example.com".to_string(),
166        ];
167        assert_eq!(
168            resolve_origin(&allowed, "http://example.com"),
169            "http://example.com"
170        );
171        // Non-matching falls back to first
172        assert_eq!(
173            resolve_origin(&allowed, "http://evil.com"),
174            "http://localhost:3000"
175        );
176    }
177
178    #[test]
179    fn with_origins_constructor() {
180        let config = CorsConfig::with_origins(vec!["http://a.com".to_string()]);
181        assert_eq!(config.allowed_origins, vec!["http://a.com"]);
182        assert!(!config.allowed_methods.is_empty());
183    }
184}