Skip to main content

hyper_cors/
config.rs

1//! Builder for the [`Cors`] middleware.
2
3use std::fmt;
4use std::time::Duration;
5
6use crate::{
7    AllowCredentials, AllowHeaders, AllowMethods, AllowOrigin, ExposeHeaders, MaxAge, Vary,
8};
9
10/// Error returned by [`CorsBuilder::try_build`] when the configuration violates a
11/// Fetch-mandated incompatibility.
12///
13/// Mirrors the panics produced by [`CorsBuilder::build`], so callers can choose to surface
14/// the message as a startup error rather than a process abort.
15///
16/// [`CorsBuilder::build`]: CorsBuilder::build
17/// [`CorsBuilder::try_build`]: CorsBuilder::try_build
18#[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        // Prefix with `Invalid CORS configuration:` to match the wording of the legacy
33        // `assert!` messages, so existing log-grep tooling keeps working.
34        write!(f, "Invalid CORS configuration: {}", self.message)
35    }
36}
37
38impl std::error::Error for ConfigError {}
39
40/// Builder for [`Cors`].
41///
42/// Construct one with [`CorsBuilder::new`] (or [`builder`](crate::builder)), chain the
43/// configuration methods, and call [`CorsBuilder::build`] to produce the middleware.
44///
45/// # Defaults
46///
47/// | Field | Default |
48/// |---|---|
49/// | `allow_origin` | empty list (no origins allowed; non-CORS requests still pass through) |
50/// | `allow_credentials` | `false` |
51/// | `allow_methods` | mirror request (`Access-Control-Request-Method`) |
52/// | `allow_headers` | mirror request (`Access-Control-Request-Headers`) |
53/// | `expose_headers` | empty |
54/// | `max_age` | not emitted |
55/// | `vary` | derived from the other knobs |
56/// | `deliver_preflight` | `false` (preflight is short-circuited) |
57/// | `deliver_non_allowed_origin` | `true` |
58/// | `deliver_non_allowed_origin_websocket_upgrade` | `false` |
59/// | `rejection_status` | `400 Bad Request` |
60///
61/// [`Cors`]: crate::Cors
62#[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            // Browsers do not enforce CORS on WebSocket handshakes, so an unchecked upgrade
94            // is a cross-site hijacking vector; reject by default.
95            deliver_non_allowed_origin_websocket_upgrade: false,
96            rejection_status: http::StatusCode::BAD_REQUEST,
97        }
98    }
99}
100
101impl CorsBuilder {
102    /// Returns a builder with default settings.
103    pub fn new() -> Self {
104        Self::default()
105    }
106
107    /// Sets the `Access-Control-Allow-Origin` policy.
108    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    /// Sets whether to send `Access-Control-Allow-Credentials`.
117    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    /// Sets the methods advertised in `Access-Control-Allow-Methods`.
126    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    /// Sets the headers advertised in `Access-Control-Allow-Headers`.
135    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    /// Sets the headers advertised in `Access-Control-Expose-Headers`.
144    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    /// Sets the `Access-Control-Max-Age` value.
153    pub fn max_age(mut self, max_age: Duration) -> Self {
154        self.max_age = MaxAge::exact(max_age);
155        self
156    }
157
158    /// Pins `Vary` to a specific list of header names, disabling automatic derivation.
159    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    /// If `false` (default), preflight requests are short-circuited and answered with a
169    /// synthetic `200 OK` carrying the CORS headers. If `true`, preflight is forwarded to
170    /// the inner service after CORS headers are added.
171    pub fn deliver_preflight(mut self, deliver: bool) -> Self {
172        self.deliver_preflight = deliver;
173        self
174    }
175
176    /// If `true` (default), requests whose `Origin` is not allowed are still passed to the
177    /// inner service (the response just won't carry CORS headers). If `false`, such requests
178    /// are rejected with [`Self::rejection_status`] directly.
179    pub fn deliver_non_allowed_origin(mut self, deliver: bool) -> Self {
180        self.deliver_non_allowed_origin = deliver;
181        self
182    }
183
184    /// If `false` (default), disallowed-origin WebSocket upgrade requests (those carrying
185    /// `Sec-WebSocket-Version`) are rejected, even when [`Self::deliver_non_allowed_origin`]
186    /// is `true`.
187    ///
188    /// Browsers do not apply CORS to WebSocket handshakes, so an unchecked upgrade is a
189    /// cross-site hijacking vector: the browser opens the socket with the user's cookies
190    /// attached.
191    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    /// Sets the status code used to reject disallowed-origin requests when
197    /// [`Self::deliver_non_allowed_origin`] is `false`.
198    ///
199    /// Defaults to `400 Bad Request`. Use `403 Forbidden` to signal the rejection as a
200    /// refusal.
201    pub fn rejection_status(mut self, status: http::StatusCode) -> Self {
202        self.rejection_status = status;
203        self
204    }
205
206    /// Builds the [`Cors`] middleware wrapping `inner`, validating the configuration.
207    ///
208    /// # Panics
209    ///
210    /// Panics if any of the Fetch-mandated incompatibilities are violated. Use
211    /// [`Self::try_build`] to receive the same diagnostics as a `Result` and translate them
212    /// into a startup error instead of a panic.
213    ///
214    /// [`Cors`]: crate::Cors
215    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    /// Builds the [`Cors`] middleware wrapping `inner`, validating the configuration.
223    ///
224    /// Use this in startup paths so misconfiguration surfaces as a regular error rather
225    /// than a process abort. [`Self::build`] panics with the same message.
226    ///
227    /// # Errors
228    ///
229    /// Returns a [`ConfigError`] when any Fetch-mandated incompatibility is violated:
230    /// `allow_credentials: true` combined with `*` in `allow_origin`, `allow_methods`,
231    /// `allow_headers`, or `expose_headers`.
232    ///
233    /// [`Cors`]: crate::Cors
234    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    /// Recompute the default `Vary` header set, unless the user pinned it via [`Self::vary`].
273    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        // `Origin` is always included: the response is always potentially origin-dependent
282        // when a CORS middleware is installed, so caches must not serve one origin's response
283        // to another.
284        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        // Pick any non-wildcard origin so credentials can be combined safely.
301        AllowOrigin::exact(http::HeaderValue::from_static("https://app.example.com"))
302    }
303
304    #[test]
305    fn try_build_succeeds_for_default_config() {
306        // Default config has credentials disabled; no incompatibilities to trip.
307        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        // `build` is the legacy panic-on-error path. Pin its behavior so a future refactor
371        // can't silently swap it to a Result-returning signature.
372        //
373        // `AssertUnwindSafe` is required because `CorsBuilder` holds an `Arc<dyn Fn(...)>`
374        // for the optional sync-predicate origin path, which is not `RefUnwindSafe`. The
375        // predicate doesn't actually mutate any captured state in this test, so opting out
376        // of the check is sound.
377        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}