Skip to main content

hyper_cors/
max_age.rs

1//! Configuration for the `Access-Control-Max-Age` response header.
2
3use std::time::Duration;
4
5use http::{
6    header::{self, HeaderName, HeaderValue},
7    request::Parts as RequestParts,
8};
9
10/// Configuration for the `Access-Control-Max-Age` header.
11#[derive(Clone, Default)]
12#[must_use]
13pub struct MaxAge(MaxAgeInner);
14
15impl MaxAge {
16    /// Sets a fixed max-age value.
17    pub fn exact(max_age: Duration) -> Self {
18        Self(MaxAgeInner::Exact(seconds_to_header_value(
19            max_age.as_secs(),
20        )))
21    }
22
23    /// Omits `Access-Control-Max-Age` from responses, so browsers re-preflight every time.
24    pub fn none() -> Self {
25        Self(MaxAgeInner::Exact(None))
26    }
27
28    pub(crate) fn to_header(
29        &self,
30        _origin: Option<&HeaderValue>,
31        _parts: &RequestParts,
32    ) -> Option<(HeaderName, HeaderValue)> {
33        match &self.0 {
34            MaxAgeInner::Exact(v) => v.clone().map(|v| (header::ACCESS_CONTROL_MAX_AGE, v)),
35        }
36    }
37}
38
39impl std::fmt::Debug for MaxAge {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        match &self.0 {
42            MaxAgeInner::Exact(inner) => f.debug_tuple("Exact").field(inner).finish(),
43        }
44    }
45}
46
47impl From<Duration> for MaxAge {
48    fn from(d: Duration) -> Self {
49        Self::exact(d)
50    }
51}
52
53#[derive(Clone)]
54enum MaxAgeInner {
55    Exact(Option<HeaderValue>),
56}
57
58impl Default for MaxAgeInner {
59    fn default() -> Self {
60        Self::Exact(None)
61    }
62}
63
64fn seconds_to_header_value(seconds: u64) -> Option<HeaderValue> {
65    HeaderValue::from_str(itoa::Buffer::new().format(seconds)).ok()
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use http::Request;
72
73    #[test]
74    fn formats_known_values() {
75        assert_eq!(seconds_to_header_value(0).unwrap(), "0");
76        assert_eq!(seconds_to_header_value(60).unwrap(), "60");
77        assert_eq!(seconds_to_header_value(600).unwrap(), "600");
78        assert_eq!(
79            seconds_to_header_value(u64::MAX).unwrap(),
80            u64::MAX.to_string()
81        );
82    }
83
84    #[test]
85    fn none_emits_no_header() {
86        let ma = MaxAge::none();
87        let req = Request::builder()
88            .method(http::Method::OPTIONS)
89            .uri("/")
90            .header(http::header::ORIGIN, "https://x.example")
91            .header(http::header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
92            .body(())
93            .unwrap();
94        let parts = req.into_parts().0;
95        let origin = parts.headers.get(http::header::ORIGIN).cloned();
96        assert!(ma.to_header(origin.as_ref(), &parts).is_none());
97    }
98
99    #[test]
100    fn default_equals_none() {
101        // `Default` and `none()` produce the same "no header" configuration.
102        assert!(MaxAge::default().to_header(None, &empty_parts()).is_none());
103        assert!(MaxAge::none().to_header(None, &empty_parts()).is_none());
104    }
105
106    fn empty_parts() -> http::request::Parts {
107        Request::builder()
108            .method(http::Method::GET)
109            .uri("/")
110            .body(())
111            .unwrap()
112            .into_parts()
113            .0
114    }
115}