Skip to main content

hyper_cors/
allow_methods.rs

1//! Configuration for the `Access-Control-Allow-Methods` response header.
2
3use http::{
4    header::{self, HeaderName, HeaderValue, ACCESS_CONTROL_REQUEST_METHOD},
5    request::Parts as RequestParts,
6    Method,
7};
8
9use crate::{
10    headers::WILDCARD,
11    util::{is_valid_token, separated_by_commas},
12};
13
14/// Configuration for the `Access-Control-Allow-Methods` header.
15#[derive(Clone, Default)]
16#[must_use]
17pub struct AllowMethods(AllowMethodsInner);
18
19impl AllowMethods {
20    /// Responds with `*`. Incompatible with credentials; see [`CorsBuilder::build`].
21    ///
22    /// [`CorsBuilder::build`]: crate::CorsBuilder::build
23    pub fn any() -> Self {
24        Self(AllowMethodsInner::Const(Some(WILDCARD)))
25    }
26
27    /// Responds with a fixed set of methods.
28    pub fn list<I>(methods: I) -> Self
29    where
30        I: IntoIterator<Item = Method>,
31    {
32        Self(AllowMethodsInner::Const(separated_by_commas(
33            methods.into_iter().map(|m| method_to_value(&m)),
34        )))
35    }
36
37    /// Echoes the request's `Access-Control-Request-Method` header.
38    ///
39    /// The reflected value is validated as an HTTP token; non-token values are dropped so a
40    /// malformed request header cannot inject control characters into the response.
41    pub fn mirror_request() -> Self {
42        Self(AllowMethodsInner::MirrorRequest)
43    }
44
45    /// Returns `true` if the configured value is the literal `*` (incompatible with
46    /// credentials).
47    pub(crate) fn is_wildcard(&self) -> bool {
48        matches!(&self.0, AllowMethodsInner::Const(Some(v)) if *v == WILDCARD)
49    }
50
51    /// Returns `true` if the value depends on the request's `Access-Control-Request-Method`
52    /// (so `Vary: Access-Control-Request-Method` is required).
53    pub(crate) fn varies_with_request_method(&self) -> bool {
54        matches!(&self.0, AllowMethodsInner::MirrorRequest)
55    }
56
57    pub(crate) fn to_header(&self, parts: &RequestParts) -> Option<(HeaderName, HeaderValue)> {
58        let value = match &self.0 {
59            AllowMethodsInner::Const(v) => v.clone()?,
60            AllowMethodsInner::MirrorRequest => {
61                let raw = parts.headers.get(ACCESS_CONTROL_REQUEST_METHOD)?;
62                if !is_valid_token(raw.as_bytes()) {
63                    return None;
64                }
65                raw.clone()
66            }
67        };
68        Some((header::ACCESS_CONTROL_ALLOW_METHODS, value))
69    }
70}
71
72impl std::fmt::Debug for AllowMethods {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match &self.0 {
75            AllowMethodsInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
76            AllowMethodsInner::MirrorRequest => f.debug_tuple("MirrorRequest").finish(),
77        }
78    }
79}
80
81impl<const N: usize> From<[Method; N]> for AllowMethods {
82    fn from(arr: [Method; N]) -> Self {
83        Self::list(arr)
84    }
85}
86
87impl From<Vec<Method>> for AllowMethods {
88    fn from(vec: Vec<Method>) -> Self {
89        Self::list(vec)
90    }
91}
92
93fn method_to_value(m: &Method) -> HeaderValue {
94    // Every `Method` is a valid HTTP token, so `as_str()` always yields bytes that satisfy
95    // `HeaderValue::from_bytes`.
96    HeaderValue::from_bytes(m.as_str().as_bytes()).expect("Method is always a valid HeaderValue")
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use http::Request;
103
104    fn parts_with_request_method(value: &str) -> RequestParts {
105        let req = Request::builder()
106            .method(Method::OPTIONS)
107            .uri("/")
108            .header(ACCESS_CONTROL_REQUEST_METHOD, value)
109            .body(())
110            .unwrap();
111        req.into_parts().0
112    }
113
114    #[test]
115    fn mirror_request_echoes_valid_token() {
116        let am = AllowMethods::mirror_request();
117        let parts = parts_with_request_method("DELETE");
118        let (_, value) = am.to_header(&parts).expect("ACAM present");
119        assert_eq!(value, "DELETE");
120    }
121
122    #[test]
123    fn mirror_request_drops_non_token_value() {
124        let am = AllowMethods::mirror_request();
125        let parts = parts_with_request_method("bad method"); // contains space
126        assert!(am.to_header(&parts).is_none());
127    }
128
129    #[test]
130    fn const_value_does_not_depend_on_parts() {
131        let am = AllowMethods::list([Method::GET, Method::POST]);
132        let req = Request::builder()
133            .method(Method::OPTIONS)
134            .uri("/")
135            .body(())
136            .unwrap();
137        let parts = req.into_parts().0;
138        let (_, value) = am.to_header(&parts).expect("ACAM present");
139        assert_eq!(value, "GET,POST");
140    }
141}
142
143#[derive(Clone, Default)]
144enum AllowMethodsInner {
145    Const(Option<HeaderValue>),
146    #[default]
147    MirrorRequest,
148}