use super::response::ResponseWriter;
use super::router::Handler;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct CorsConfig {
pub allowed_origins: Vec<String>,
pub allowed_methods: Vec<String>,
pub allowed_headers: Vec<String>,
pub max_age: u32,
}
impl Default for CorsConfig {
fn default() -> Self {
Self {
allowed_origins: vec!["*".to_string()],
allowed_methods: vec![
"GET".to_string(),
"POST".to_string(),
"DELETE".to_string(),
"OPTIONS".to_string(),
],
allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
max_age: 86400,
}
}
}
impl CorsConfig {
pub fn permissive() -> Self {
Self::default()
}
pub fn with_origins(origins: Vec<String>) -> Self {
Self {
allowed_origins: origins,
..Default::default()
}
}
}
pub fn with_cors(handler: Handler, config: CorsConfig) -> Handler {
Arc::new(move |req, writer| {
let handler = handler.clone();
let config = config.clone();
Box::pin(async move {
let origin = req.header("origin").unwrap_or("*").to_string();
let allow_origin = resolve_origin(&config.allowed_origins, &origin);
if req.method == super::request::Method::Options {
return write_preflight(writer, &config, &allow_origin).await;
}
handler(req, writer).await
})
})
}
pub fn cors_preflight_handler(config: CorsConfig) -> Handler {
Arc::new(move |req, writer| {
let config = config.clone();
Box::pin(async move {
let origin = req.header("origin").unwrap_or("*").to_string();
let allow_origin = resolve_origin(&config.allowed_origins, &origin);
write_preflight(writer, &config, &allow_origin).await
})
})
}
fn resolve_origin(allowed: &[String], request_origin: &str) -> String {
if allowed.iter().any(|o| o == "*") {
"*".to_string()
} else if allowed.iter().any(|o| o == request_origin) {
request_origin.to_string()
} else {
allowed.first().cloned().unwrap_or_default()
}
}
async fn write_preflight<W: tokio::io::AsyncWrite + Unpin>(
mut writer: ResponseWriter<W>,
config: &CorsConfig,
allow_origin: &str,
) -> rtflow_core::error::Result<ResponseWriter<W>> {
let methods = config.allowed_methods.join(", ");
let headers = config.allowed_headers.join(", ");
let max_age = config.max_age.to_string();
writer
.write_headers(
204,
&[
("Access-Control-Allow-Origin", allow_origin),
("Access-Control-Allow-Methods", &methods),
("Access-Control-Allow-Headers", &headers),
("Access-Control-Max-Age", &max_age),
("Content-Length", "0"),
("Connection", "keep-alive"),
],
)
.await?;
Ok(writer)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_config_is_permissive() {
let config = CorsConfig::default();
assert_eq!(config.allowed_origins, vec!["*"]);
assert!(config.allowed_methods.contains(&"GET".to_string()));
assert!(config.allowed_methods.contains(&"POST".to_string()));
assert_eq!(config.max_age, 86400);
}
#[test]
fn resolve_origin_wildcard() {
let allowed = vec!["*".to_string()];
assert_eq!(resolve_origin(&allowed, "http://example.com"), "*");
}
#[test]
fn resolve_origin_specific() {
let allowed = vec![
"http://localhost:3000".to_string(),
"http://example.com".to_string(),
];
assert_eq!(
resolve_origin(&allowed, "http://example.com"),
"http://example.com"
);
assert_eq!(
resolve_origin(&allowed, "http://evil.com"),
"http://localhost:3000"
);
}
#[test]
fn with_origins_constructor() {
let config = CorsConfig::with_origins(vec!["http://a.com".to_string()]);
assert_eq!(config.allowed_origins, vec!["http://a.com"]);
assert!(!config.allowed_methods.is_empty());
}
}