tower_http/cors/
mod.rs

1//! Middleware which adds headers for [CORS][mdn].
2//!
3//! # Example
4//!
5//! ```
6//! use http::{Request, Response, Method, header};
7//! use http_body_util::Full;
8//! use bytes::Bytes;
9//! use tower::{ServiceBuilder, ServiceExt, Service};
10//! use tower_http::cors::{Any, CorsLayer};
11//! use std::convert::Infallible;
12//!
13//! async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
14//!     Ok(Response::new(Full::default()))
15//! }
16//!
17//! # #[tokio::main]
18//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
19//! let cors = CorsLayer::new()
20//!     // allow `GET` and `POST` when accessing the resource
21//!     .allow_methods([Method::GET, Method::POST])
22//!     // allow requests from any origin
23//!     .allow_origin(Any);
24//!
25//! let mut service = ServiceBuilder::new()
26//!     .layer(cors)
27//!     .service_fn(handle);
28//!
29//! let request = Request::builder()
30//!     .header(header::ORIGIN, "https://example.com")
31//!     .body(Full::default())
32//!     .unwrap();
33//!
34//! let response = service
35//!     .ready()
36//!     .await?
37//!     .call(request)
38//!     .await?;
39//!
40//! assert_eq!(
41//!     response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(),
42//!     "*",
43//! );
44//! # Ok(())
45//! # }
46//! ```
47//!
48//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
49
50#![allow(clippy::enum_variant_names)]
51
52use bytes::{BufMut, BytesMut};
53use http::{
54    header::{self, HeaderName},
55    HeaderMap, HeaderValue, Method, Request, Response,
56};
57use pin_project_lite::pin_project;
58use std::{
59    array,
60    future::Future,
61    mem,
62    pin::Pin,
63    task::{ready, Context, Poll},
64};
65use tower_layer::Layer;
66use tower_service::Service;
67
68mod allow_credentials;
69mod allow_headers;
70mod allow_methods;
71mod allow_origin;
72mod allow_private_network;
73mod expose_headers;
74mod max_age;
75mod vary;
76
77#[cfg(test)]
78mod tests;
79
80pub use self::{
81    allow_credentials::AllowCredentials, allow_headers::AllowHeaders, allow_methods::AllowMethods,
82    allow_origin::AllowOrigin, allow_private_network::AllowPrivateNetwork,
83    expose_headers::ExposeHeaders, max_age::MaxAge, vary::Vary,
84};
85
86/// Layer that applies the [`Cors`] middleware which adds headers for [CORS][mdn].
87///
88/// See the [module docs](crate::cors) for an example.
89///
90/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
91#[derive(Debug, Clone)]
92#[must_use]
93pub struct CorsLayer {
94    allow_credentials: AllowCredentials,
95    allow_headers: AllowHeaders,
96    allow_methods: AllowMethods,
97    allow_origin: AllowOrigin,
98    allow_private_network: AllowPrivateNetwork,
99    expose_headers: ExposeHeaders,
100    max_age: MaxAge,
101    vary: Vary,
102}
103
104#[allow(clippy::declare_interior_mutable_const)]
105const WILDCARD: HeaderValue = HeaderValue::from_static("*");
106
107impl CorsLayer {
108    /// Create a new `CorsLayer`.
109    ///
110    /// No headers are sent by default. Use the builder methods to customize
111    /// the behavior.
112    ///
113    /// You need to set at least an allowed origin for browsers to make
114    /// successful cross-origin requests to your service.
115    pub fn new() -> Self {
116        Self {
117            allow_credentials: Default::default(),
118            allow_headers: Default::default(),
119            allow_methods: Default::default(),
120            allow_origin: Default::default(),
121            allow_private_network: Default::default(),
122            expose_headers: Default::default(),
123            max_age: Default::default(),
124            vary: Default::default(),
125        }
126    }
127
128    /// A permissive configuration:
129    ///
130    /// - All request headers allowed.
131    /// - All methods allowed.
132    /// - All origins allowed.
133    /// - All headers exposed.
134    pub fn permissive() -> Self {
135        Self::new()
136            .allow_headers(Any)
137            .allow_methods(Any)
138            .allow_origin(Any)
139            .expose_headers(Any)
140    }
141
142    /// A very permissive configuration:
143    ///
144    /// - **Credentials allowed.**
145    /// - The method received in `Access-Control-Request-Method` is sent back
146    ///   as an allowed method.
147    /// - The origin of the preflight request is sent back as an allowed origin.
148    /// - The header names received in `Access-Control-Request-Headers` are sent
149    ///   back as allowed headers.
150    /// - No headers are currently exposed, but this may change in the future.
151    pub fn very_permissive() -> Self {
152        Self::new()
153            .allow_credentials(true)
154            .allow_headers(AllowHeaders::mirror_request())
155            .allow_methods(AllowMethods::mirror_request())
156            .allow_origin(AllowOrigin::mirror_request())
157    }
158
159    /// Set the [`Access-Control-Allow-Credentials`][mdn] header.
160    ///
161    /// ```
162    /// use tower_http::cors::CorsLayer;
163    ///
164    /// let layer = CorsLayer::new().allow_credentials(true);
165    /// ```
166    ///
167    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
168    pub fn allow_credentials<T>(mut self, allow_credentials: T) -> Self
169    where
170        T: Into<AllowCredentials>,
171    {
172        self.allow_credentials = allow_credentials.into();
173        self
174    }
175
176    /// Set the value of the [`Access-Control-Allow-Headers`][mdn] header.
177    ///
178    /// ```
179    /// use tower_http::cors::CorsLayer;
180    /// use http::header::{AUTHORIZATION, ACCEPT};
181    ///
182    /// let layer = CorsLayer::new().allow_headers([AUTHORIZATION, ACCEPT]);
183    /// ```
184    ///
185    /// All headers can be allowed with
186    ///
187    /// ```
188    /// use tower_http::cors::{Any, CorsLayer};
189    ///
190    /// let layer = CorsLayer::new().allow_headers(Any);
191    /// ```
192    ///
193    /// Note that multiple calls to this method will override any previous
194    /// calls.
195    ///
196    /// Also note that `Access-Control-Allow-Headers` is required for requests that have
197    /// `Access-Control-Request-Headers`.
198    ///
199    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
200    pub fn allow_headers<T>(mut self, headers: T) -> Self
201    where
202        T: Into<AllowHeaders>,
203    {
204        self.allow_headers = headers.into();
205        self
206    }
207
208    /// Set the value of the [`Access-Control-Max-Age`][mdn] header.
209    ///
210    /// ```
211    /// use std::time::Duration;
212    /// use tower_http::cors::CorsLayer;
213    ///
214    /// let layer = CorsLayer::new().max_age(Duration::from_secs(60) * 10);
215    /// ```
216    ///
217    /// By default the header will not be set which disables caching and will
218    /// require a preflight call for all requests.
219    ///
220    /// Note that each browser has a maximum internal value that takes
221    /// precedence when the Access-Control-Max-Age is greater. For more details
222    /// see [mdn].
223    ///
224    /// If you need more flexibility, you can use supply a function which can
225    /// dynamically decide the max-age based on the origin and other parts of
226    /// each preflight request:
227    ///
228    /// ```
229    /// # struct MyServerConfig { cors_max_age: Duration }
230    /// use std::time::Duration;
231    ///
232    /// use http::{request::Parts as RequestParts, HeaderValue};
233    /// use tower_http::cors::{CorsLayer, MaxAge};
234    ///
235    /// let layer = CorsLayer::new().max_age(MaxAge::dynamic(
236    ///     |_origin: &HeaderValue, parts: &RequestParts| -> Duration {
237    ///         // Let's say you want to be able to reload your config at
238    ///         // runtime and have another middleware that always inserts
239    ///         // the current config into the request extensions
240    ///         let config = parts.extensions.get::<MyServerConfig>().unwrap();
241    ///         config.cors_max_age
242    ///     },
243    /// ));
244    /// ```
245    ///
246    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
247    pub fn max_age<T>(mut self, max_age: T) -> Self
248    where
249        T: Into<MaxAge>,
250    {
251        self.max_age = max_age.into();
252        self
253    }
254
255    /// Set the value of the [`Access-Control-Allow-Methods`][mdn] header.
256    ///
257    /// ```
258    /// use tower_http::cors::CorsLayer;
259    /// use http::Method;
260    ///
261    /// let layer = CorsLayer::new().allow_methods([Method::GET, Method::POST]);
262    /// ```
263    ///
264    /// All methods can be allowed with
265    ///
266    /// ```
267    /// use tower_http::cors::{Any, CorsLayer};
268    ///
269    /// let layer = CorsLayer::new().allow_methods(Any);
270    /// ```
271    ///
272    /// Note that multiple calls to this method will override any previous
273    /// calls.
274    ///
275    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
276    pub fn allow_methods<T>(mut self, methods: T) -> Self
277    where
278        T: Into<AllowMethods>,
279    {
280        self.allow_methods = methods.into();
281        self
282    }
283
284    /// Set the value of the [`Access-Control-Allow-Origin`][mdn] header.
285    ///
286    /// ```
287    /// use http::HeaderValue;
288    /// use tower_http::cors::CorsLayer;
289    ///
290    /// let layer = CorsLayer::new().allow_origin(
291    ///     "http://example.com".parse::<HeaderValue>().unwrap(),
292    /// );
293    /// ```
294    ///
295    /// Multiple origins can be allowed with
296    ///
297    /// ```
298    /// use tower_http::cors::CorsLayer;
299    ///
300    /// let origins = [
301    ///     "http://example.com".parse().unwrap(),
302    ///     "http://api.example.com".parse().unwrap(),
303    /// ];
304    ///
305    /// let layer = CorsLayer::new().allow_origin(origins);
306    /// ```
307    ///
308    /// All origins can be allowed with
309    ///
310    /// ```
311    /// use tower_http::cors::{Any, CorsLayer};
312    ///
313    /// let layer = CorsLayer::new().allow_origin(Any);
314    /// ```
315    ///
316    /// You can also use a closure
317    ///
318    /// ```
319    /// use tower_http::cors::{CorsLayer, AllowOrigin};
320    /// use http::{request::Parts as RequestParts, HeaderValue};
321    ///
322    /// let layer = CorsLayer::new().allow_origin(AllowOrigin::predicate(
323    ///     |origin: &HeaderValue, _request_parts: &RequestParts| {
324    ///         origin.as_bytes().ends_with(b".rust-lang.org")
325    ///     },
326    /// ));
327    /// ```
328    ///
329    /// Note that multiple calls to this method will override any previous
330    /// calls.
331    ///
332    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
333    pub fn allow_origin<T>(mut self, origin: T) -> Self
334    where
335        T: Into<AllowOrigin>,
336    {
337        self.allow_origin = origin.into();
338        self
339    }
340
341    /// Set the value of the [`Access-Control-Expose-Headers`][mdn] header.
342    ///
343    /// ```
344    /// use tower_http::cors::CorsLayer;
345    /// use http::header::CONTENT_ENCODING;
346    ///
347    /// let layer = CorsLayer::new().expose_headers([CONTENT_ENCODING]);
348    /// ```
349    ///
350    /// All headers can be allowed with
351    ///
352    /// ```
353    /// use tower_http::cors::{Any, CorsLayer};
354    ///
355    /// let layer = CorsLayer::new().expose_headers(Any);
356    /// ```
357    ///
358    /// Note that multiple calls to this method will override any previous
359    /// calls.
360    ///
361    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
362    pub fn expose_headers<T>(mut self, headers: T) -> Self
363    where
364        T: Into<ExposeHeaders>,
365    {
366        self.expose_headers = headers.into();
367        self
368    }
369
370    /// Set the value of the [`Access-Control-Allow-Private-Network`][wicg] header.
371    ///
372    /// ```
373    /// use tower_http::cors::CorsLayer;
374    ///
375    /// let layer = CorsLayer::new().allow_private_network(true);
376    /// ```
377    ///
378    /// [wicg]: https://wicg.github.io/private-network-access/
379    pub fn allow_private_network<T>(mut self, allow_private_network: T) -> Self
380    where
381        T: Into<AllowPrivateNetwork>,
382    {
383        self.allow_private_network = allow_private_network.into();
384        self
385    }
386
387    /// Set the value(s) of the [`Vary`][mdn] header.
388    ///
389    /// In contrast to the other headers, this one has a non-empty default of
390    /// [`preflight_request_headers()`].
391    ///
392    /// You only need to set this is you want to remove some of these defaults,
393    /// or if you use a closure for one of the other headers and want to add a
394    /// vary header accordingly.
395    ///
396    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
397    pub fn vary<T>(mut self, headers: T) -> Self
398    where
399        T: Into<Vary>,
400    {
401        self.vary = headers.into();
402        self
403    }
404}
405
406/// Represents a wildcard value (`*`) used with some CORS headers such as
407/// [`CorsLayer::allow_methods`].
408#[derive(Debug, Clone, Copy)]
409#[must_use]
410pub struct Any;
411
412/// Represents a wildcard value (`*`) used with some CORS headers such as
413/// [`CorsLayer::allow_methods`].
414#[deprecated = "Use Any as a unit struct literal instead"]
415pub fn any() -> Any {
416    Any
417}
418
419fn separated_by_commas<I>(mut iter: I) -> Option<HeaderValue>
420where
421    I: Iterator<Item = HeaderValue>,
422{
423    match iter.next() {
424        Some(fst) => {
425            let mut result = BytesMut::from(fst.as_bytes());
426            for val in iter {
427                result.reserve(val.len() + 1);
428                result.put_u8(b',');
429                result.extend_from_slice(val.as_bytes());
430            }
431
432            Some(HeaderValue::from_maybe_shared(result.freeze()).unwrap())
433        }
434        None => None,
435    }
436}
437
438impl Default for CorsLayer {
439    fn default() -> Self {
440        Self::new()
441    }
442}
443
444impl<S> Layer<S> for CorsLayer {
445    type Service = Cors<S>;
446
447    fn layer(&self, inner: S) -> Self::Service {
448        ensure_usable_cors_rules(self);
449
450        Cors {
451            inner,
452            layer: self.clone(),
453        }
454    }
455}
456
457/// Middleware which adds headers for [CORS][mdn].
458///
459/// See the [module docs](crate::cors) for an example.
460///
461/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
462#[derive(Debug, Clone)]
463#[must_use]
464pub struct Cors<S> {
465    inner: S,
466    layer: CorsLayer,
467}
468
469impl<S> Cors<S> {
470    /// Create a new `Cors`.
471    ///
472    /// See [`CorsLayer::new`] for more details.
473    pub fn new(inner: S) -> Self {
474        Self {
475            inner,
476            layer: CorsLayer::new(),
477        }
478    }
479
480    /// A permissive configuration.
481    ///
482    /// See [`CorsLayer::permissive`] for more details.
483    pub fn permissive(inner: S) -> Self {
484        Self {
485            inner,
486            layer: CorsLayer::permissive(),
487        }
488    }
489
490    /// A very permissive configuration.
491    ///
492    /// See [`CorsLayer::very_permissive`] for more details.
493    pub fn very_permissive(inner: S) -> Self {
494        Self {
495            inner,
496            layer: CorsLayer::very_permissive(),
497        }
498    }
499
500    define_inner_service_accessors!();
501
502    /// Returns a new [`Layer`] that wraps services with a [`Cors`] middleware.
503    ///
504    /// [`Layer`]: tower_layer::Layer
505    pub fn layer() -> CorsLayer {
506        CorsLayer::new()
507    }
508
509    /// Set the [`Access-Control-Allow-Credentials`][mdn] header.
510    ///
511    /// See [`CorsLayer::allow_credentials`] for more details.
512    ///
513    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
514    pub fn allow_credentials<T>(self, allow_credentials: T) -> Self
515    where
516        T: Into<AllowCredentials>,
517    {
518        self.map_layer(|layer| layer.allow_credentials(allow_credentials))
519    }
520
521    /// Set the value of the [`Access-Control-Allow-Headers`][mdn] header.
522    ///
523    /// See [`CorsLayer::allow_headers`] for more details.
524    ///
525    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
526    pub fn allow_headers<T>(self, headers: T) -> Self
527    where
528        T: Into<AllowHeaders>,
529    {
530        self.map_layer(|layer| layer.allow_headers(headers))
531    }
532
533    /// Set the value of the [`Access-Control-Max-Age`][mdn] header.
534    ///
535    /// See [`CorsLayer::max_age`] for more details.
536    ///
537    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
538    pub fn max_age<T>(self, max_age: T) -> Self
539    where
540        T: Into<MaxAge>,
541    {
542        self.map_layer(|layer| layer.max_age(max_age))
543    }
544
545    /// Set the value of the [`Access-Control-Allow-Methods`][mdn] header.
546    ///
547    /// See [`CorsLayer::allow_methods`] for more details.
548    ///
549    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
550    pub fn allow_methods<T>(self, methods: T) -> Self
551    where
552        T: Into<AllowMethods>,
553    {
554        self.map_layer(|layer| layer.allow_methods(methods))
555    }
556
557    /// Set the value of the [`Access-Control-Allow-Origin`][mdn] header.
558    ///
559    /// See [`CorsLayer::allow_origin`] for more details.
560    ///
561    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
562    pub fn allow_origin<T>(self, origin: T) -> Self
563    where
564        T: Into<AllowOrigin>,
565    {
566        self.map_layer(|layer| layer.allow_origin(origin))
567    }
568
569    /// Set the value of the [`Access-Control-Expose-Headers`][mdn] header.
570    ///
571    /// See [`CorsLayer::expose_headers`] for more details.
572    ///
573    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
574    pub fn expose_headers<T>(self, headers: T) -> Self
575    where
576        T: Into<ExposeHeaders>,
577    {
578        self.map_layer(|layer| layer.expose_headers(headers))
579    }
580
581    /// Set the value of the [`Access-Control-Allow-Private-Network`][wicg] header.
582    ///
583    /// See [`CorsLayer::allow_private_network`] for more details.
584    ///
585    /// [wicg]: https://wicg.github.io/private-network-access/
586    pub fn allow_private_network<T>(self, allow_private_network: T) -> Self
587    where
588        T: Into<AllowPrivateNetwork>,
589    {
590        self.map_layer(|layer| layer.allow_private_network(allow_private_network))
591    }
592
593    fn map_layer<F>(mut self, f: F) -> Self
594    where
595        F: FnOnce(CorsLayer) -> CorsLayer,
596    {
597        self.layer = f(self.layer);
598        self
599    }
600}
601
602impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for Cors<S>
603where
604    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
605    ResBody: Default,
606{
607    type Response = S::Response;
608    type Error = S::Error;
609    type Future = ResponseFuture<S::Future>;
610
611    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
612        ensure_usable_cors_rules(&self.layer);
613        self.inner.poll_ready(cx)
614    }
615
616    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
617        let (parts, body) = req.into_parts();
618        let origin = parts.headers.get(&header::ORIGIN);
619
620        let mut headers = HeaderMap::new();
621
622        // These headers are applied to both preflight and subsequent regular CORS requests:
623        // https://fetch.spec.whatwg.org/#http-responses
624        headers.extend(self.layer.allow_origin.to_header(origin, &parts));
625        headers.extend(self.layer.allow_credentials.to_header(origin, &parts));
626        headers.extend(self.layer.allow_private_network.to_header(origin, &parts));
627        headers.extend(self.layer.vary.to_header());
628
629        // Return results immediately upon preflight request
630        if parts.method == Method::OPTIONS {
631            // These headers are applied only to preflight requests
632            headers.extend(self.layer.allow_methods.to_header(&parts));
633            headers.extend(self.layer.allow_headers.to_header(&parts));
634            headers.extend(self.layer.max_age.to_header(origin, &parts));
635
636            ResponseFuture {
637                inner: Kind::PreflightCall { headers },
638            }
639        } else {
640            // This header is applied only to non-preflight requests
641            headers.extend(self.layer.expose_headers.to_header(&parts));
642
643            let req = Request::from_parts(parts, body);
644            ResponseFuture {
645                inner: Kind::CorsCall {
646                    future: self.inner.call(req),
647                    headers,
648                },
649            }
650        }
651    }
652}
653
654pin_project! {
655    /// Response future for [`Cors`].
656    pub struct ResponseFuture<F> {
657        #[pin]
658        inner: Kind<F>,
659    }
660}
661
662pin_project! {
663    #[project = KindProj]
664    enum Kind<F> {
665        CorsCall {
666            #[pin]
667            future: F,
668            headers: HeaderMap,
669        },
670        PreflightCall {
671            headers: HeaderMap,
672        },
673    }
674}
675
676impl<F, B, E> Future for ResponseFuture<F>
677where
678    F: Future<Output = Result<Response<B>, E>>,
679    B: Default,
680{
681    type Output = Result<Response<B>, E>;
682
683    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
684        match self.project().inner.project() {
685            KindProj::CorsCall { future, headers } => {
686                let mut response: Response<B> = ready!(future.poll(cx))?;
687
688                let response_headers = response.headers_mut();
689
690                // vary header can have multiple values, don't overwrite
691                // previously-set value(s).
692                if let Some(vary) = headers.remove(header::VARY) {
693                    response_headers.append(header::VARY, vary);
694                }
695                // extend will overwrite previous headers of remaining names
696                response_headers.extend(headers.drain());
697
698                Poll::Ready(Ok(response))
699            }
700            KindProj::PreflightCall { headers } => {
701                let mut response = Response::new(B::default());
702                mem::swap(response.headers_mut(), headers);
703
704                Poll::Ready(Ok(response))
705            }
706        }
707    }
708}
709
710fn ensure_usable_cors_rules(layer: &CorsLayer) {
711    if layer.allow_credentials.is_true() {
712        assert!(
713            !layer.allow_headers.is_wildcard(),
714            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
715             with `Access-Control-Allow-Headers: *`"
716        );
717
718        assert!(
719            !layer.allow_methods.is_wildcard(),
720            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
721             with `Access-Control-Allow-Methods: *`"
722        );
723
724        assert!(
725            !layer.allow_origin.is_wildcard(),
726            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
727             with `Access-Control-Allow-Origin: *`"
728        );
729
730        assert!(
731            !layer.expose_headers.is_wildcard(),
732            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
733             with `Access-Control-Expose-Headers: *`"
734        );
735    }
736}
737
738/// Returns an iterator over the three request headers that may be involved in a CORS preflight request.
739///
740/// This is the default set of header names returned in the `vary` header
741pub fn preflight_request_headers() -> impl Iterator<Item = HeaderName> {
742    #[allow(deprecated)] // Can be changed when MSRV >= 1.53
743    array::IntoIter::new([
744        header::ORIGIN,
745        header::ACCESS_CONTROL_REQUEST_METHOD,
746        header::ACCESS_CONTROL_REQUEST_HEADERS,
747    ])
748}