Skip to main content

hyper_cors/
allow_credentials.rs

1//! Configuration for the `Access-Control-Allow-Credentials` response header.
2
3use std::sync::Arc;
4
5use http::{
6    header::{self, HeaderName, HeaderValue},
7    request::Parts as RequestParts,
8};
9
10use crate::headers::ALLOW_CREDENTIALS_TRUE;
11
12/// Configuration for the `Access-Control-Allow-Credentials` header.
13#[derive(Clone, Default)]
14#[must_use]
15pub struct AllowCredentials(AllowCredentialsInner);
16
17impl AllowCredentials {
18    /// Allows credentials for every cross-origin request.
19    pub fn yes() -> Self {
20        Self(AllowCredentialsInner::Yes)
21    }
22
23    /// Allows credentials per request, based on a synchronous predicate. The predicate
24    /// receives the request's `Origin` header (if any) and the request
25    /// [`Parts`](http::request::Parts).
26    pub fn predicate<F>(f: F) -> Self
27    where
28        F: Fn(&HeaderValue, &RequestParts) -> bool + Send + Sync + 'static,
29    {
30        Self(AllowCredentialsInner::Predicate(Arc::new(f)))
31    }
32
33    /// Returns `true` if credentials are unconditionally allowed. Used to enforce the Fetch
34    /// spec's incompatibility with wildcard origin / method / header / expose-headers values
35    /// at configuration time.
36    pub(crate) fn is_true(&self) -> bool {
37        matches!(&self.0, AllowCredentialsInner::Yes)
38    }
39
40    /// Returns the header pair to set, or `None` if credentials are not allowed for this
41    /// request. When the `Origin` header is absent (no CORS request), credentials are never
42    /// emitted.
43    pub(crate) fn to_header(
44        &self,
45        origin: Option<&HeaderValue>,
46        parts: &RequestParts,
47    ) -> Option<(HeaderName, HeaderValue)> {
48        let allow_creds = match &self.0 {
49            AllowCredentialsInner::Yes => true,
50            AllowCredentialsInner::No => false,
51            AllowCredentialsInner::Predicate(f) => origin.is_some() && f(origin?, parts),
52        };
53        allow_creds.then_some((
54            header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
55            ALLOW_CREDENTIALS_TRUE,
56        ))
57    }
58}
59
60impl std::fmt::Debug for AllowCredentials {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match &self.0 {
63            AllowCredentialsInner::Yes => f.debug_tuple("Yes").finish(),
64            AllowCredentialsInner::No => f.debug_tuple("No").finish(),
65            AllowCredentialsInner::Predicate(_) => f.debug_tuple("Predicate").finish(),
66        }
67    }
68}
69
70impl From<bool> for AllowCredentials {
71    fn from(v: bool) -> Self {
72        if v {
73            Self::yes()
74        } else {
75            Self(AllowCredentialsInner::No)
76        }
77    }
78}
79
80#[derive(Clone, Default)]
81enum AllowCredentialsInner {
82    Yes,
83    #[default]
84    No,
85    #[allow(clippy::type_complexity)]
86    Predicate(Arc<dyn for<'a> Fn(&'a HeaderValue, &'a RequestParts) -> bool + Send + Sync>),
87}