tower_http/cors/
allow_origin.rs

1use std::{array, fmt, sync::Arc};
2
3use http::{
4    header::{self, HeaderName, HeaderValue},
5    request::Parts as RequestParts,
6};
7
8use super::{Any, WILDCARD};
9
10/// Holds configuration for how to set the [`Access-Control-Allow-Origin`][mdn] header.
11///
12/// See [`CorsLayer::allow_origin`] for more details.
13///
14/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
15/// [`CorsLayer::allow_origin`]: super::CorsLayer::allow_origin
16#[derive(Clone, Default)]
17#[must_use]
18pub struct AllowOrigin(OriginInner);
19
20impl AllowOrigin {
21    /// Allow any origin by sending a wildcard (`*`)
22    ///
23    /// See [`CorsLayer::allow_origin`] for more details.
24    ///
25    /// [`CorsLayer::allow_origin`]: super::CorsLayer::allow_origin
26    pub fn any() -> Self {
27        Self(OriginInner::Const(WILDCARD))
28    }
29
30    /// Set a single allowed origin
31    ///
32    /// See [`CorsLayer::allow_origin`] for more details.
33    ///
34    /// [`CorsLayer::allow_origin`]: super::CorsLayer::allow_origin
35    pub fn exact(origin: HeaderValue) -> Self {
36        Self(OriginInner::Const(origin))
37    }
38
39    /// Set multiple allowed origins
40    ///
41    /// See [`CorsLayer::allow_origin`] for more details.
42    ///
43    /// # Panics
44    ///
45    /// If the iterator contains a wildcard (`*`).
46    ///
47    /// [`CorsLayer::allow_origin`]: super::CorsLayer::allow_origin
48    #[allow(clippy::borrow_interior_mutable_const)]
49    pub fn list<I>(origins: I) -> Self
50    where
51        I: IntoIterator<Item = HeaderValue>,
52    {
53        let origins = origins.into_iter().collect::<Vec<_>>();
54        if origins.contains(&WILDCARD) {
55            panic!(
56                "Wildcard origin (`*`) cannot be passed to `AllowOrigin::list`. \
57                 Use `AllowOrigin::any()` instead"
58            );
59        }
60
61        Self(OriginInner::List(origins))
62    }
63
64    /// Set the allowed origins from a predicate
65    ///
66    /// See [`CorsLayer::allow_origin`] for more details.
67    ///
68    /// [`CorsLayer::allow_origin`]: super::CorsLayer::allow_origin
69    pub fn predicate<F>(f: F) -> Self
70    where
71        F: Fn(&HeaderValue, &RequestParts) -> bool + Send + Sync + 'static,
72    {
73        Self(OriginInner::Predicate(Arc::new(f)))
74    }
75
76    /// Allow any origin, by mirroring the request origin
77    ///
78    /// This is equivalent to
79    /// [`AllowOrigin::predicate(|_, _| true)`][Self::predicate].
80    ///
81    /// See [`CorsLayer::allow_origin`] for more details.
82    ///
83    /// [`CorsLayer::allow_origin`]: super::CorsLayer::allow_origin
84    pub fn mirror_request() -> Self {
85        Self::predicate(|_, _| true)
86    }
87
88    #[allow(clippy::borrow_interior_mutable_const)]
89    pub(super) fn is_wildcard(&self) -> bool {
90        matches!(&self.0, OriginInner::Const(v) if v == WILDCARD)
91    }
92
93    pub(super) fn to_header(
94        &self,
95        origin: Option<&HeaderValue>,
96        parts: &RequestParts,
97    ) -> Option<(HeaderName, HeaderValue)> {
98        let allow_origin = match &self.0 {
99            OriginInner::Const(v) => v.clone(),
100            OriginInner::List(l) => origin.filter(|o| l.contains(o))?.clone(),
101            OriginInner::Predicate(c) => origin.filter(|origin| c(origin, parts))?.clone(),
102        };
103
104        Some((header::ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin))
105    }
106}
107
108impl fmt::Debug for AllowOrigin {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match &self.0 {
111            OriginInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
112            OriginInner::List(inner) => f.debug_tuple("List").field(inner).finish(),
113            OriginInner::Predicate(_) => f.debug_tuple("Predicate").finish(),
114        }
115    }
116}
117
118impl From<Any> for AllowOrigin {
119    fn from(_: Any) -> Self {
120        Self::any()
121    }
122}
123
124impl From<HeaderValue> for AllowOrigin {
125    fn from(val: HeaderValue) -> Self {
126        Self::exact(val)
127    }
128}
129
130impl<const N: usize> From<[HeaderValue; N]> for AllowOrigin {
131    fn from(arr: [HeaderValue; N]) -> Self {
132        #[allow(deprecated)] // Can be changed when MSRV >= 1.53
133        Self::list(array::IntoIter::new(arr))
134    }
135}
136
137impl From<Vec<HeaderValue>> for AllowOrigin {
138    fn from(vec: Vec<HeaderValue>) -> Self {
139        Self::list(vec)
140    }
141}
142
143#[derive(Clone)]
144enum OriginInner {
145    Const(HeaderValue),
146    List(Vec<HeaderValue>),
147    Predicate(
148        Arc<dyn for<'a> Fn(&'a HeaderValue, &'a RequestParts) -> bool + Send + Sync + 'static>,
149    ),
150}
151
152impl Default for OriginInner {
153    fn default() -> Self {
154        Self::List(Vec::new())
155    }
156}