1use super::response::ResponseWriter;
6use super::router::Handler;
7use std::sync::Arc;
8
9#[derive(Clone, Debug)]
11pub struct CorsConfig {
12 pub allowed_origins: Vec<String>,
14 pub allowed_methods: Vec<String>,
16 pub allowed_headers: Vec<String>,
18 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 pub fn permissive() -> Self {
41 Self::default()
42 }
43
44 pub fn with_origins(origins: Vec<String>) -> Self {
46 Self {
47 allowed_origins: origins,
48 ..Default::default()
49 }
50 }
51}
52
53pub 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 if req.method == super::request::Method::Options {
68 return write_preflight(writer, &config, &allow_origin).await;
69 }
70
71 handler(req, writer).await
88 })
89 })
90}
91
92pub 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 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 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}