tower_http/cors/
allow_origin.rs1use 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#[derive(Clone, Default)]
17#[must_use]
18pub struct AllowOrigin(OriginInner);
19
20impl AllowOrigin {
21 pub fn any() -> Self {
27 Self(OriginInner::Const(WILDCARD))
28 }
29
30 pub fn exact(origin: HeaderValue) -> Self {
36 Self(OriginInner::Const(origin))
37 }
38
39 #[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 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 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)] 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}