1use std::{future::Future, pin::Pin, sync::Arc};
4
5use http::{
6 header::{self, HeaderName, HeaderValue},
7 request::Parts as RequestParts,
8};
9use pin_project_lite::pin_project;
10
11use crate::headers::WILDCARD;
12
13#[derive(Debug, Clone, Copy)]
15#[must_use]
16pub struct Any;
17
18#[derive(Clone, Default)]
20#[must_use]
21pub struct AllowOrigin(OriginInner);
22
23impl AllowOrigin {
24 pub fn any() -> Self {
26 Self(OriginInner::Const(WILDCARD))
27 }
28
29 pub fn exact(origin: HeaderValue) -> Self {
35 assert_ne!(
36 origin, WILDCARD,
37 "wildcard origin must be configured via AllowOrigin::any(), not AllowOrigin::exact()"
38 );
39 Self(OriginInner::Const(origin))
40 }
41
42 pub fn list<I>(origins: I) -> Self
49 where
50 I: IntoIterator<Item = HeaderValue>,
51 {
52 let origins: Vec<HeaderValue> = origins.into_iter().collect();
53 assert!(
54 !origins.contains(&WILDCARD),
55 "wildcard origin must be configured via AllowOrigin::any(), not AllowOrigin::list()"
56 );
57 Self(OriginInner::List(origins))
58 }
59
60 pub fn predicate<F>(f: F) -> Self
64 where
65 F: Fn(&HeaderValue, &RequestParts) -> bool + Send + Sync + 'static,
66 {
67 Self(OriginInner::Predicate(Arc::new(f)))
68 }
69
70 pub fn async_predicate<F, Fut>(f: F) -> Self
76 where
77 F: Fn(HeaderValue, RequestParts) -> Fut + Send + Sync + 'static,
78 Fut: Future<Output = bool> + Send + 'static,
79 {
80 Self(OriginInner::AsyncPredicate(Arc::new(move |v, p| {
81 Box::pin(f(v, p))
82 })))
83 }
84
85 pub fn mirror_request() -> Self {
88 Self::predicate(|_, _| true)
89 }
90
91 pub(crate) fn is_wildcard(&self) -> bool {
94 matches!(&self.0, OriginInner::Const(v) if *v == WILDCARD)
95 }
96
97 pub(crate) fn to_future(
109 &self,
110 origin: Option<&HeaderValue>,
111 parts: &RequestParts,
112 ) -> AllowOriginFuture {
113 let name = header::ACCESS_CONTROL_ALLOW_ORIGIN;
114 let has_origin = origin.is_some();
115 match &self.0 {
116 OriginInner::Const(v) => AllowOriginFuture::ready(has_origin, Some((name, v.clone()))),
117 OriginInner::List(l) => AllowOriginFuture::ready(
118 has_origin,
119 origin
120 .filter(|o| origin_list_matches(l, o))
121 .map(|o| (name, o.clone())),
122 ),
123 OriginInner::Predicate(f) => AllowOriginFuture::ready(
124 has_origin,
125 origin.filter(|o| f(o, parts)).map(|o| (name, o.clone())),
126 ),
127 OriginInner::AsyncPredicate(f) => origin.cloned().map_or_else(
128 || AllowOriginFuture::ready(has_origin, None),
129 |origin| {
130 let parts = parts.clone();
131 let fut = f(origin.clone(), parts);
132 AllowOriginFuture::pending(
133 has_origin,
134 Box::pin(async move { fut.await.then_some((name, origin)) }),
135 )
136 },
137 ),
138 }
139 }
140}
141
142fn origin_list_matches(allowed: &[HeaderValue], origin: &HeaderValue) -> bool {
148 let mut saw_token = false;
149 for token in origin.as_bytes().split(|&b| b == b' ') {
150 let token = token.trim_ascii();
151 if token.is_empty() {
152 continue;
153 }
154 saw_token = true;
155 if !allowed.iter().any(|a| a.as_bytes() == token) {
156 return false;
157 }
158 }
159 saw_token
160}
161
162impl std::fmt::Debug for AllowOrigin {
163 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164 match &self.0 {
165 OriginInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
166 OriginInner::List(inner) => f.debug_tuple("List").field(inner).finish(),
167 OriginInner::Predicate(_) => f.debug_tuple("Predicate").finish(),
168 OriginInner::AsyncPredicate(_) => f.debug_tuple("AsyncPredicate").finish(),
169 }
170 }
171}
172
173impl From<Any> for AllowOrigin {
174 fn from(_: Any) -> Self {
175 Self::any()
176 }
177}
178
179impl From<HeaderValue> for AllowOrigin {
180 fn from(v: HeaderValue) -> Self {
181 Self::exact(v)
182 }
183}
184
185impl<const N: usize> From<[HeaderValue; N]> for AllowOrigin {
186 fn from(arr: [HeaderValue; N]) -> Self {
187 Self::list(arr)
188 }
189}
190
191impl From<Vec<HeaderValue>> for AllowOrigin {
192 fn from(vec: Vec<HeaderValue>) -> Self {
193 Self::list(vec)
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 fn hv(s: &str) -> HeaderValue {
202 HeaderValue::from_str(s).unwrap()
203 }
204
205 #[test]
206 fn single_origin_matches() {
207 let allowed = [hv("https://a.example")];
208 assert!(origin_list_matches(&allowed, &hv("https://a.example")));
209 assert!(!origin_list_matches(&allowed, &hv("https://b.example")));
210 }
211
212 #[test]
213 fn space_separated_all_allowed_matches() {
214 let allowed = [hv("https://a.example"), hv("https://b.example")];
215 assert!(origin_list_matches(
216 &allowed,
217 &hv("https://a.example https://b.example")
218 ));
219 }
220
221 #[test]
222 fn space_separated_partially_allowed_is_rejected() {
223 let allowed = [hv("https://a.example")];
224 assert!(!origin_list_matches(
225 &allowed,
226 &hv("https://a.example https://evil.example")
227 ));
228 }
229
230 #[test]
231 fn empty_or_whitespace_origin_does_not_match() {
232 let allowed = [hv("https://a.example")];
233 assert!(!origin_list_matches(&allowed, &hv("")));
234 assert!(!origin_list_matches(&allowed, &hv(" ")));
235 }
236
237 #[test]
238 fn empty_allow_list_matches_nothing() {
239 assert!(!origin_list_matches(&[], &hv("https://a.example")));
240 }
241}
242
243#[derive(Clone)]
244#[allow(clippy::type_complexity)]
245enum OriginInner {
246 Const(HeaderValue),
247 List(Vec<HeaderValue>),
248 Predicate(Arc<dyn for<'a> Fn(&'a HeaderValue, &'a RequestParts) -> bool + Send + Sync>),
249 AsyncPredicate(
250 Arc<
251 dyn Fn(HeaderValue, RequestParts) -> Pin<Box<dyn Future<Output = bool> + Send>>
252 + Send
253 + Sync,
254 >,
255 ),
256}
257
258impl Default for OriginInner {
259 fn default() -> Self {
260 Self::List(Vec::new())
261 }
262}
263
264pin_project! {
265 #[project = AllowOriginFutureProj]
270 #[allow(clippy::type_complexity)]
271 pub(crate) struct AllowOriginFuture {
272 has_origin: bool,
273 #[pin]
274 state: AllowOriginFutureState,
275 }
276}
277
278pin_project! {
279 #[project = AllowOriginFutureStateProj]
280 enum AllowOriginFutureState {
281 Ready { res: Option<(HeaderName, HeaderValue)> },
282 Pending { #[pin] fut: Pin<Box<dyn Future<Output = Option<(HeaderName, HeaderValue)>> + Send>> },
283 }
284}
285
286impl AllowOriginFuture {
287 fn ready(has_origin: bool, res: Option<(HeaderName, HeaderValue)>) -> Self {
288 Self {
289 has_origin,
290 state: AllowOriginFutureState::Ready { res },
291 }
292 }
293
294 #[allow(clippy::type_complexity)]
295 fn pending(
296 has_origin: bool,
297 fut: Pin<Box<dyn Future<Output = Option<(HeaderName, HeaderValue)>> + Send>>,
298 ) -> Self {
299 Self {
300 has_origin,
301 state: AllowOriginFutureState::Pending { fut },
302 }
303 }
304
305 pub(crate) fn has_origin(&self) -> bool {
307 self.has_origin
308 }
309}
310
311impl Future for AllowOriginFuture {
312 type Output = Option<(HeaderName, HeaderValue)>;
313
314 fn poll(
315 self: Pin<&mut Self>,
316 cx: &mut std::task::Context<'_>,
317 ) -> std::task::Poll<Self::Output> {
318 match self.project().state.project() {
319 AllowOriginFutureStateProj::Ready { res } => std::task::Poll::Ready(res.take()),
320 AllowOriginFutureStateProj::Pending { fut } => fut.poll(cx),
321 }
322 }
323}