Skip to main content

tower_http/cors/
allow_methods.rs

1use std::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 varies_with_request_method(&self) -> bool {
76        !matches!(&self.0, AllowMethodsInner::Const(_))
77    }
78
79    pub(super) fn to_header(&self, parts: &RequestParts) -> Option<(HeaderName, HeaderValue)> {
80        let allow_methods = match &self.0 {
81            AllowMethodsInner::Const(v) => v.clone()?,
82            AllowMethodsInner::MirrorRequest => parts
83                .headers
84                .get(header::ACCESS_CONTROL_REQUEST_METHOD)?
85                .clone(),
86        };
87
88        Some((header::ACCESS_CONTROL_ALLOW_METHODS, allow_methods))
89    }
90}
91
92impl fmt::Debug for AllowMethods {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match &self.0 {
95            AllowMethodsInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
96            AllowMethodsInner::MirrorRequest => f.debug_tuple("MirrorRequest").finish(),
97        }
98    }
99}
100
101impl From<Any> for AllowMethods {
102    fn from(_: Any) -> Self {
103        Self::any()
104    }
105}
106
107impl From<Method> for AllowMethods {
108    fn from(method: Method) -> Self {
109        Self::exact(method)
110    }
111}
112
113impl<const N: usize> From<[Method; N]> for AllowMethods {
114    fn from(arr: [Method; N]) -> Self {
115        Self::list(arr)
116    }
117}
118
119impl From<Vec<Method>> for AllowMethods {
120    fn from(vec: Vec<Method>) -> Self {
121        Self::list(vec)
122    }
123}
124
125#[derive(Clone)]
126enum AllowMethodsInner {
127    Const(Option<HeaderValue>),
128    MirrorRequest,
129}
130
131impl Default for AllowMethodsInner {
132    fn default() -> Self {
133        Self::Const(None)
134    }
135}