1use std::fmt;
4use std::time::Duration;
5
6use crate::{
7 AllowCredentials, AllowHeaders, AllowMethods, AllowOrigin, ExposeHeaders, MaxAge, Vary,
8};
9
10#[derive(Clone, Debug, Eq, PartialEq)]
19#[must_use]
20pub struct ConfigError {
21 message: &'static str,
22}
23
24impl ConfigError {
25 fn new(message: &'static str) -> Self {
26 Self { message }
27 }
28}
29
30impl fmt::Display for ConfigError {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 write!(f, "Invalid CORS configuration: {}", self.message)
35 }
36}
37
38impl std::error::Error for ConfigError {}
39
40#[derive(Clone, Debug)]
63#[must_use]
64#[allow(clippy::struct_excessive_bools)]
65pub struct CorsBuilder {
66 pub(crate) allow_origin: AllowOrigin,
67 pub(crate) allow_credentials: AllowCredentials,
68 pub(crate) allow_methods: AllowMethods,
69 pub(crate) allow_headers: AllowHeaders,
70 pub(crate) expose_headers: ExposeHeaders,
71 pub(crate) max_age: MaxAge,
72 pub(crate) vary: Vary,
73 pub(crate) vary_pinned: bool,
74 pub(crate) deliver_preflight: bool,
75 pub(crate) deliver_non_allowed_origin: bool,
76 pub(crate) deliver_non_allowed_origin_websocket_upgrade: bool,
77 pub(crate) rejection_status: http::StatusCode,
78}
79
80impl Default for CorsBuilder {
81 fn default() -> Self {
82 Self {
83 allow_origin: AllowOrigin::default(),
84 allow_credentials: AllowCredentials::default(),
85 allow_methods: AllowMethods::default(),
86 allow_headers: AllowHeaders::default(),
87 expose_headers: ExposeHeaders::default(),
88 max_age: MaxAge::default(),
89 vary: Vary::default(),
90 vary_pinned: false,
91 deliver_preflight: false,
92 deliver_non_allowed_origin: true,
93 deliver_non_allowed_origin_websocket_upgrade: false,
96 rejection_status: http::StatusCode::BAD_REQUEST,
97 }
98 }
99}
100
101impl CorsBuilder {
102 pub fn new() -> Self {
104 Self::default()
105 }
106
107 pub fn allow_origin<T>(mut self, allow_origin: T) -> Self
109 where
110 T: Into<AllowOrigin>,
111 {
112 self.allow_origin = allow_origin.into();
113 self
114 }
115
116 pub fn allow_credentials<T>(mut self, allow_credentials: T) -> Self
118 where
119 T: Into<AllowCredentials>,
120 {
121 self.allow_credentials = allow_credentials.into();
122 self
123 }
124
125 pub fn allow_methods<T>(mut self, allow_methods: T) -> Self
127 where
128 T: Into<AllowMethods>,
129 {
130 self.allow_methods = allow_methods.into();
131 self
132 }
133
134 pub fn allow_headers<T>(mut self, allow_headers: T) -> Self
136 where
137 T: Into<AllowHeaders>,
138 {
139 self.allow_headers = allow_headers.into();
140 self
141 }
142
143 pub fn expose_headers<T>(mut self, expose_headers: T) -> Self
145 where
146 T: Into<ExposeHeaders>,
147 {
148 self.expose_headers = expose_headers.into();
149 self
150 }
151
152 pub fn max_age(mut self, max_age: Duration) -> Self {
154 self.max_age = MaxAge::exact(max_age);
155 self
156 }
157
158 pub fn vary<T>(mut self, headers: T) -> Self
160 where
161 T: Into<Vary>,
162 {
163 self.vary = headers.into();
164 self.vary_pinned = true;
165 self
166 }
167
168 pub fn deliver_preflight(mut self, deliver: bool) -> Self {
172 self.deliver_preflight = deliver;
173 self
174 }
175
176 pub fn deliver_non_allowed_origin(mut self, deliver: bool) -> Self {
180 self.deliver_non_allowed_origin = deliver;
181 self
182 }
183
184 pub fn deliver_non_allowed_origin_websocket_upgrade(mut self, deliver: bool) -> Self {
192 self.deliver_non_allowed_origin_websocket_upgrade = deliver;
193 self
194 }
195
196 pub fn rejection_status(mut self, status: http::StatusCode) -> Self {
202 self.rejection_status = status;
203 self
204 }
205
206 pub fn build<S>(self, inner: S) -> crate::Cors<S> {
216 match self.try_build(inner) {
217 Ok(cors) => cors,
218 Err(e) => panic!("{e}"),
219 }
220 }
221
222 pub fn try_build<S>(self, inner: S) -> Result<crate::Cors<S>, ConfigError> {
235 self.validate()?;
236 let mut me = self;
237 me.update_vary();
238 Ok(crate::Cors::from_parts(inner, me))
239 }
240
241 fn validate(&self) -> Result<(), ConfigError> {
242 if !self.allow_credentials.is_true() {
243 return Ok(());
244 }
245 if self.allow_origin.is_wildcard() {
246 return Err(ConfigError::new(
247 "cannot combine `Access-Control-Allow-Credentials: true` \
248 with `Access-Control-Allow-Origin: *`. Echo the request origin instead.",
249 ));
250 }
251 if self.allow_methods.is_wildcard() {
252 return Err(ConfigError::new(
253 "cannot combine `Access-Control-Allow-Credentials: true` \
254 with `Access-Control-Allow-Methods: *`.",
255 ));
256 }
257 if self.allow_headers.is_wildcard() {
258 return Err(ConfigError::new(
259 "cannot combine `Access-Control-Allow-Credentials: true` \
260 with `Access-Control-Allow-Headers: *`.",
261 ));
262 }
263 if self.expose_headers.is_wildcard() {
264 return Err(ConfigError::new(
265 "cannot combine `Access-Control-Allow-Credentials: true` \
266 with `Access-Control-Expose-Headers: *`.",
267 ));
268 }
269 Ok(())
270 }
271
272 pub(crate) fn update_vary(&mut self) {
274 if self.vary_pinned {
275 return;
276 }
277 let vary_method = self.allow_methods.varies_with_request_method();
278 let vary_headers = self.allow_headers.varies_with_request_headers();
279
280 let mut names = Vec::with_capacity(3);
281 names.push(http::header::ORIGIN);
285 if vary_method {
286 names.push(http::header::ACCESS_CONTROL_REQUEST_METHOD);
287 }
288 if vary_headers {
289 names.push(http::header::ACCESS_CONTROL_REQUEST_HEADERS);
290 }
291 self.vary = Vary::list(names);
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 fn origin() -> AllowOrigin {
300 AllowOrigin::exact(http::HeaderValue::from_static("https://app.example.com"))
302 }
303
304 #[test]
305 fn try_build_succeeds_for_default_config() {
306 let builder = CorsBuilder::new();
308 let result: Result<crate::Cors<()>, ConfigError> = builder.try_build(());
309 assert!(result.is_ok());
310 }
311
312 #[test]
313 fn try_build_succeeds_for_credentials_with_concrete_origin_and_headers() {
314 let builder = CorsBuilder::new()
315 .allow_credentials(AllowCredentials::yes())
316 .allow_origin(origin());
317 let result: Result<crate::Cors<()>, ConfigError> = builder.try_build(());
318 assert!(result.is_ok());
319 }
320
321 #[test]
322 fn try_build_rejects_credentials_with_wildcard_origin() {
323 let builder = CorsBuilder::new()
324 .allow_credentials(AllowCredentials::yes())
325 .allow_origin(crate::Any);
326 let err = builder
327 .try_build::<()>(())
328 .expect_err("wildcard origin must be rejected");
329 assert!(err.to_string().contains("Allow-Origin: *"));
330 }
331
332 #[test]
333 fn try_build_rejects_credentials_with_wildcard_methods() {
334 let builder = CorsBuilder::new()
335 .allow_credentials(AllowCredentials::yes())
336 .allow_origin(origin())
337 .allow_methods(crate::AllowMethods::any());
338 let err = builder
339 .try_build::<()>(())
340 .expect_err("wildcard methods must be rejected");
341 assert!(err.to_string().contains("Allow-Methods: *"));
342 }
343
344 #[test]
345 fn try_build_rejects_credentials_with_wildcard_headers() {
346 let builder = CorsBuilder::new()
347 .allow_credentials(AllowCredentials::yes())
348 .allow_origin(origin())
349 .allow_headers(crate::AllowHeaders::any());
350 let err = builder
351 .try_build::<()>(())
352 .expect_err("wildcard headers must be rejected");
353 assert!(err.to_string().contains("Allow-Headers: *"));
354 }
355
356 #[test]
357 fn try_build_rejects_credentials_with_wildcard_expose_headers() {
358 let builder = CorsBuilder::new()
359 .allow_credentials(AllowCredentials::yes())
360 .allow_origin(origin())
361 .expose_headers(crate::ExposeHeaders::any());
362 let err = builder
363 .try_build::<()>(())
364 .expect_err("wildcard expose-headers must be rejected");
365 assert!(err.to_string().contains("Expose-Headers: *"));
366 }
367
368 #[test]
369 fn build_still_panics_on_incompatible_config() {
370 let builder = CorsBuilder::new()
378 .allow_credentials(AllowCredentials::yes())
379 .allow_origin(crate::Any);
380 let result =
381 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| builder.build::<()>(())));
382 assert!(result.is_err(), "build must panic on wildcard origin");
383 }
384}