Skip to main content

rama_http_headers/common/
access_control_allow_credentials.rs

1use rama_http_types::{HeaderName, HeaderValue};
2
3use crate::{Error, HeaderDecode, HeaderEncode, TypedHeader};
4
5/// `Access-Control-Allow-Credentials` header, as defined on
6/// [mdn](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Credentials).
7///
8/// > The Access-Control-Allow-Credentials HTTP response header indicates whether the
9/// > response to request can be exposed when the credentials flag is true. When part
10/// > of the response to an preflight request it indicates that the actual request can
11/// > be made with credentials. The Access-Control-Allow-Credentials HTTP header must
12/// > match the following ABNF:
13///
14/// # ABNF
15///
16/// ```text
17/// Access-Control-Allow-Credentials: "Access-Control-Allow-Credentials" ":" "true"
18/// ```
19///
20/// Since there is only one acceptable field value, the header struct does not accept
21/// any values at all. Setting an empty `AccessControlAllowCredentials` header is
22/// sufficient. See the examples below.
23///
24/// # Example values
25/// * "true"
26///
27/// # Examples
28///
29/// ```
30/// use rama_http_headers::AccessControlAllowCredentials;
31///
32/// let allow_creds = AccessControlAllowCredentials::new();
33/// ```
34#[derive(Default, Clone, PartialEq, Eq, Debug)]
35#[non_exhaustive]
36pub struct AccessControlAllowCredentials;
37
38impl AccessControlAllowCredentials {
39    #[must_use]
40    pub fn new() -> Self {
41        Self
42    }
43}
44
45impl TypedHeader for AccessControlAllowCredentials {
46    fn name() -> &'static HeaderName {
47        &::rama_http_types::header::ACCESS_CONTROL_ALLOW_CREDENTIALS
48    }
49}
50
51impl HeaderDecode for AccessControlAllowCredentials {
52    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
53        values
54            .next()
55            .and_then(|value| if value == "true" { Some(Self) } else { None })
56            .ok_or_else(Error::invalid)
57    }
58}
59
60impl HeaderEncode for AccessControlAllowCredentials {
61    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
62        values.extend(::std::iter::once(HeaderValue::from_static("true")));
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::super::test_decode;
69    use super::*;
70
71    #[test]
72    fn allow_credentials_is_case_sensitive() {
73        let allow_header = test_decode::<AccessControlAllowCredentials>(&["true"]);
74        assert!(allow_header.is_some());
75
76        let allow_header = test_decode::<AccessControlAllowCredentials>(&["True"]);
77        assert!(allow_header.is_none());
78    }
79}