tower_http/cors/
allow_methods.rs

1use std::{array, fmt};
2
3use http::{
4    header::{self, HeaderName, HeaderValue},
5    request::Parts as RequestParts,
6    Method,
7};
8
9use super::{separated_by_commas, Any, WILDCARD};
10
11/// Holds configuration for how to set the [`Access-Control-Allow-Methods`][mdn] header.
12///
13/// See [`CorsLayer::allow_methods`] for more details.
14///
15/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
16/// [`CorsLayer::allow_methods`]: super::CorsLayer::allow_methods
17#[derive(Clone, Default)]
18#[must_use]
19pub struct AllowMethods(AllowMethodsInner);
20
21impl AllowMethods {
22    /// Allow any method by sending a wildcard (`*`)
23    ///
24    /// See [`CorsLayer::allow_methods`] for more details.
25    ///
26    /// [`CorsLayer::allow_methods`]: super::CorsLayer::allow_methods
27    pub fn any() -> Self {
28        Self(AllowMethodsInner::Const(Some(WILDCARD)))
29    }
30
31    /// Set a single allowed method
32    ///
33    /// See [`CorsLayer::allow_methods`] for more details.
34    ///
35    /// [`CorsLayer::allow_methods`]: super::CorsLayer::allow_methods
36    pub fn exact(method: Method) -> Self {
37        Self(AllowMethodsInner::Const(Some(
38            HeaderValue::from_str(method.as_str()).unwrap(),
39        )))
40    }
41
42    /// Set multiple allowed methods
43    ///
44    /// See [`CorsLayer::allow_methods`] for more details.
45    ///
46    /// [`CorsLayer::allow_methods`]: super::CorsLayer::allow_methods
47    pub fn list<I>(methods: I) -> Self
48    where
49        I: IntoIterator<Item = Method>,
50    {
51        Self(AllowMethodsInner::Const(separated_by_commas(
52            methods
53                .into_iter()
54                .map(|m| HeaderValue::from_str(m.as_str()).unwrap()),
55        )))
56    }
57
58    /// Allow any method, by mirroring the preflight [`Access-Control-Request-Method`][mdn]
59    /// header.
60    ///
61    /// See [`CorsLayer::allow_methods`] for more details.
62    ///
63    /// [`CorsLayer::allow_methods`]: super::CorsLayer::allow_methods
64    ///
65    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Method
66    pub fn mirror_request() -> Self {
67        Self(AllowMethodsInner::MirrorRequest)
68    }
69
70    #[allow(clippy::borrow_interior_mutable_const)]
71    pub(super) fn is_wildcard(&self) -> bool {
72        matches!(&self.0, AllowMethodsInner::Const(Some(v)) if v == WILDCARD)
73    }
74
75    pub(super) fn to_header(&self, parts: &RequestParts) -> Option<(HeaderName, HeaderValue)> {
76        let allow_methods = match &self.0 {
77            AllowMethodsInner::Const(v) => v.clone()?,
78            AllowMethodsInner::MirrorRequest => parts
79                .headers
80                .get(header::ACCESS_CONTROL_REQUEST_METHOD)?
81                .clone(),
82        };
83
84        Some((header::ACCESS_CONTROL_ALLOW_METHODS, allow_methods))
85    }
86}
87
88impl fmt::Debug for AllowMethods {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match &self.0 {
91            AllowMethodsInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
92            AllowMethodsInner::MirrorRequest => f.debug_tuple("MirrorRequest").finish(),
93        }
94    }
95}
96
97impl From<Any> for AllowMethods {
98    fn from(_: Any) -> Self {
99        Self::any()
100    }
101}
102
103impl From<Method> for AllowMethods {
104    fn from(method: Method) -> Self {
105        Self::exact(method)
106    }
107}
108
109impl<const N: usize> From<[Method; N]> for AllowMethods {
110    fn from(arr: [Method; N]) -> Self {
111        #[allow(deprecated)] // Can be changed when MSRV >= 1.53
112        Self::list(array::IntoIter::new(arr))
113    }
114}
115
116impl From<Vec<Method>> for AllowMethods {
117    fn from(vec: Vec<Method>) -> Self {
118        Self::list(vec)
119    }
120}
121
122#[derive(Clone)]
123enum AllowMethodsInner {
124    Const(Option<HeaderValue>),
125    MirrorRequest,
126}
127
128impl Default for AllowMethodsInner {
129    fn default() -> Self {
130        Self::Const(None)
131    }
132}