churust-cors 0.3.2

CORS plugin (preflight + headers) for the Churust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! Cross-Origin Resource Sharing (CORS) plugin for the [Churust] web framework.
//!
//! This crate provides a [`Cors`] plugin that intercepts every incoming HTTP
//! request and attaches the appropriate `Access-Control-*` response headers.
//! Preflight `OPTIONS` requests are short-circuited with an HTTP 204 response
//! so they never reach your route handlers.
//!
//! # Quick start
//!
//! Install the plugin via [`churust_core::Churust::server`] before calling
//! `.build()`.  Use [`Cors::permissive`] for development or use [`Cors::new`]
//! to build a precise policy for production.
//!
//! ```
//! use churust_core::{Churust, Call, TestClient};
//! use churust_cors::Cors;
//!
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let app = Churust::server()
//!     .install(Cors::allow_any_origin_insecure())
//!     .routing(|r| {
//!         r.get("/api/data", |_c: Call| async { "hello" });
//!     })
//!     .build();
//!
//! // Actual cross-origin GET: response carries the CORS header.
//! let res = TestClient::new(app)
//!     .get("/api/data")
//!     .header("origin", "https://example.com")
//!     .send()
//!     .await;
//!
//! assert_eq!(res.status().as_u16(), 200);
//! assert_eq!(res.header("access-control-allow-origin"), Some("*"));
//! # });
//! ```
//!
//! [Churust]: churust_core::Churust

#![deny(missing_docs)]

use async_trait::async_trait;
use churust_core::{AppBuilder, Call, Middleware, Next, Phase, Plugin, Response};
use http::header::{
    ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS,
    ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_MAX_AGE, ACCESS_CONTROL_REQUEST_METHOD, VARY,
};
use http::{HeaderValue, Method, StatusCode};
use std::sync::Arc;

/// Which origins are allowed.
#[derive(Debug, Clone)]
enum AllowOrigin {
    Any,
    List(Vec<String>),
}

/// CORS configuration and plugin entry point.
///
/// `Cors` holds the policy that governs which origins, HTTP methods, and
/// request headers are permitted for cross-origin requests.  It implements
/// [`Plugin`], so you pass it directly to [`AppBuilder::install`] — the plugin
/// system registers a [`Middleware`] that runs on every request.
///
/// # Choosing a constructor
///
/// | Situation | Constructor |
/// |-----------|-------------|
/// | Local development, all origins OK | [`Cors::permissive`] |
/// | Staging / production, specific origins | [`Cors::new`] + builder methods |
///
/// # Example
///
/// ```
/// use churust_core::{Churust, Call, TestClient};
/// use churust_cors::Cors;
/// use http::Method;
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let app = Churust::server()
///     .install(
///         Cors::new()
///             .allow_origin("https://app.example.com")
///             .allow_methods(vec![Method::GET, Method::POST])
///             .allow_headers(vec!["Content-Type".into(), "Authorization".into()])
///             .allow_credentials(true)
///             .max_age(3600),
///     )
///     .routing(|r| {
///         r.get("/", |_c: Call| async { "ok" });
///     })
///     .build();
///
/// let res = TestClient::new(app)
///     .get("/")
///     .header("origin", "https://app.example.com")
///     .send()
///     .await;
///
/// assert_eq!(res.status().as_u16(), 200);
/// assert_eq!(
///     res.header("access-control-allow-origin"),
///     Some("https://app.example.com")
/// );
/// # });
/// ```
#[derive(Debug, Clone)]
pub struct Cors {
    origin: AllowOrigin,
    methods: Vec<Method>,
    headers: Vec<String>,
    credentials: bool,
    max_age: Option<u64>,
}

impl Cors {
    /// Creates a permissive CORS policy suitable for development and public APIs.
    ///
    /// The policy allows **any** origin (`*`), the six most common HTTP methods
    /// (`GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`), any request header
    /// (`*`), and caches the preflight response for 24 hours (86 400 seconds).
    ///
    /// > **Note:** Per the CORS specification, `Access-Control-Allow-Origin: *`
    /// > cannot be combined with `Access-Control-Allow-Credentials: true`.
    /// > Therefore `allow_any_origin_insecure()` intentionally leaves credentials **disabled**.
    /// > If your application needs cookies or HTTP authentication on cross-origin
    /// > requests, use [`Cors::new`] with an explicit origin list and call
    /// > [`.allow_credentials(true)`](Cors::allow_credentials).
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let app = Churust::server()
    ///     .install(Cors::allow_any_origin_insecure())
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "hello" });
    ///     })
    ///     .build();
    ///
    /// let res = TestClient::new(app)
    ///     .get("/")
    ///     .header("origin", "https://any-origin.example")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(res.header("access-control-allow-origin"), Some("*"));
    /// # });
    /// ```
    #[deprecated(
        since = "0.3.0",
        note = "renamed to `allow_any_origin_insecure`, which says what it does. \
                This reflects every origin, so any site can read authenticated \
                responses from your API when credentials are not required."
    )]
    pub fn permissive() -> Self {
        Self::allow_any_origin_insecure()
    }

    /// Allow **every** origin, method and header.
    ///
    /// The name is deliberately uncomfortable. This reflects any origin, so if
    /// your API answers requests based on an ambient credential — a cookie, a
    /// bearer token a browser extension replays, an IP allowlist — any website
    /// a user visits can read those responses.
    ///
    /// It is genuinely fine for a public, unauthenticated, read-only API, and
    /// convenient in local development. It is not a default.
    pub fn allow_any_origin_insecure() -> Self {
        Self {
            origin: AllowOrigin::Any,
            methods: vec![
                Method::GET,
                Method::POST,
                Method::PUT,
                Method::DELETE,
                Method::PATCH,
                Method::OPTIONS,
            ],
            headers: vec!["*".to_string()],
            credentials: false,
            max_age: Some(86_400),
        }
    }

    /// Creates a restrictive CORS policy with safe defaults.
    ///
    /// The initial policy allows **no origins**, permits only `GET` and `POST`,
    /// exposes no extra headers, disables credentials, and sets no `max-age`.
    /// Use the builder methods to refine the policy before passing it to
    /// [`AppBuilder::install`].
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// // Without adding any allowed origins, cross-origin requests receive
    /// // no CORS headers and the browser will block the response.
    /// let app = Churust::server()
    ///     .install(Cors::new().allow_origin("https://trusted.example.com"))
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "ok" });
    ///     })
    ///     .build();
    ///
    /// // Unlisted origin → no CORS header.
    /// let res = TestClient::new(app)
    ///     .get("/")
    ///     .header("origin", "https://untrusted.example.com")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(res.header("access-control-allow-origin"), None);
    /// # });
    /// ```
    pub fn new() -> Self {
        Self {
            origin: AllowOrigin::List(Vec::new()),
            methods: vec![Method::GET, Method::POST],
            headers: Vec::new(),
            credentials: false,
            max_age: None,
        }
    }

    /// Adds a single origin that is allowed to make cross-origin requests.
    ///
    /// Call this method multiple times to whitelist several origins.  The value
    /// should be a fully-qualified origin string such as
    /// `"https://app.example.com"` (scheme + host + optional port, **no**
    /// trailing slash).
    ///
    /// If the policy was previously set to [`Cors::permissive`] (wildcard
    /// origin), calling `allow_origin` switches back to an explicit list
    /// containing only the supplied origin.
    ///
    /// # Parameters
    ///
    /// - `origin` — any type that converts to [`String`], e.g. `&str` or
    ///   `String`.  The value is compared verbatim against the `Origin` request
    ///   header.
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let app = Churust::server()
    ///     .install(
    ///         Cors::new()
    ///             .allow_origin("https://frontend.example.com")
    ///             .allow_origin("https://mobile.example.com"),
    ///     )
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "ok" });
    ///     })
    ///     .build();
    ///
    /// let res = TestClient::new(app)
    ///     .get("/")
    ///     .header("origin", "https://frontend.example.com")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(
    ///     res.header("access-control-allow-origin"),
    ///     Some("https://frontend.example.com")
    /// );
    /// # });
    /// ```
    pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
        match &mut self.origin {
            AllowOrigin::List(v) => v.push(origin.into()),
            AllowOrigin::Any => {
                self.origin = AllowOrigin::List(vec![origin.into()]);
            }
        }
        self
    }

    /// Replaces the list of HTTP methods advertised in preflight responses.
    ///
    /// The supplied `methods` are joined with `", "` and sent as the
    /// `Access-Control-Allow-Methods` header in response to `OPTIONS` preflight
    /// requests.  This call **replaces** the current list entirely — it does
    /// not append.
    ///
    /// The default (from [`Cors::new`]) is `[GET, POST]`.
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    /// use http::Method;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let app = Churust::server()
    ///     .install(
    ///         Cors::new()
    ///             .allow_origin("https://example.com")
    ///             .allow_methods(vec![Method::GET, Method::POST, Method::DELETE]),
    ///     )
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "ok" });
    ///     })
    ///     .build();
    ///
    /// // Send a preflight for DELETE.
    /// let res = TestClient::new(app)
    ///     .request(Method::OPTIONS, "/")
    ///     .header("origin", "https://example.com")
    ///     .header("access-control-request-method", "DELETE")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(res.status().as_u16(), 204);
    /// let allowed = res.header("access-control-allow-methods").unwrap_or("");
    /// assert!(allowed.contains("DELETE"));
    /// # });
    /// ```
    pub fn allow_methods(mut self, methods: Vec<Method>) -> Self {
        self.methods = methods;
        self
    }

    /// Replaces the list of request headers advertised in preflight responses.
    ///
    /// The supplied header names are joined with `", "` and sent as the
    /// `Access-Control-Allow-Headers` header in response to `OPTIONS` preflight
    /// requests.  Pass `["*"]` to allow any header (note that this is a literal
    /// wildcard string, not a glob pattern — its meaning is defined by the
    /// browser's CORS implementation).
    ///
    /// An empty list (the default from [`Cors::new`]) omits the
    /// `Access-Control-Allow-Headers` header entirely from preflight responses.
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    /// use http::Method;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let app = Churust::server()
    ///     .install(
    ///         Cors::new()
    ///             .allow_origin("https://example.com")
    ///             .allow_headers(vec!["Content-Type".into(), "X-Api-Key".into()]),
    ///     )
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "ok" });
    ///     })
    ///     .build();
    ///
    /// let res = TestClient::new(app)
    ///     .request(Method::OPTIONS, "/")
    ///     .header("origin", "https://example.com")
    ///     .header("access-control-request-method", "GET")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(res.status().as_u16(), 204);
    /// let hdrs = res.header("access-control-allow-headers").unwrap_or("");
    /// assert!(hdrs.contains("X-Api-Key"));
    /// # });
    /// ```
    pub fn allow_headers(mut self, headers: Vec<String>) -> Self {
        self.headers = headers;
        self
    }

    /// Controls whether the `Access-Control-Allow-Credentials: true` header is
    /// sent.
    ///
    /// Set this to `true` when your API relies on cookies, HTTP authentication,
    /// or TLS client certificates for cross-origin requests.  The browser only
    /// forwards credentials when **both** the server sets this header **and**
    /// the client sets `XMLHttpRequest.withCredentials = true` (or the
    /// `fetch` `credentials: "include"` option).
    ///
    /// > **CORS spec gotcha:** Credentials are incompatible with a wildcard
    /// > (`*`) `Allow-Origin`.  If you enable credentials, make sure the
    /// > policy lists explicit origins via [`allow_origin`](Cors::allow_origin)
    /// > rather than using [`Cors::permissive`].
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let app = Churust::server()
    ///     .install(
    ///         Cors::new()
    ///             .allow_origin("https://trusted.example.com")
    ///             .allow_credentials(true),
    ///     )
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "ok" });
    ///     })
    ///     .build();
    ///
    /// let res = TestClient::new(app)
    ///     .get("/")
    ///     .header("origin", "https://trusted.example.com")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(res.header("access-control-allow-credentials"), Some("true"));
    /// # });
    /// ```
    pub fn allow_credentials(mut self, yes: bool) -> Self {
        self.credentials = yes;
        self
    }

    /// Sets the `Access-Control-Max-Age` value (in seconds) for preflight caching.
    ///
    /// Browsers may cache a successful preflight response for up to `seconds`
    /// seconds, avoiding repeated `OPTIONS` round-trips for subsequent requests
    /// to the same endpoint.  The practical upper limit varies by browser (e.g.
    /// Chrome caps it at 7200 seconds; Firefox caps it at 86 400 seconds).
    ///
    /// If this method is not called (the default for [`Cors::new`]), the
    /// `Access-Control-Max-Age` header is omitted and the browser applies its
    /// own default (typically 5 seconds).
    ///
    /// # Parameters
    ///
    /// - `seconds` — cache duration as a non-negative integer.  A value of `0`
    ///   is legal and instructs browsers not to cache the preflight at all.
    ///
    /// # Example
    ///
    /// ```
    /// use churust_core::{Churust, Call, TestClient};
    /// use churust_cors::Cors;
    /// use http::Method;
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// let app = Churust::server()
    ///     .install(
    ///         Cors::new()
    ///             .allow_origin("https://example.com")
    ///             .max_age(3600),
    ///     )
    ///     .routing(|r| {
    ///         r.get("/", |_c: Call| async { "ok" });
    ///     })
    ///     .build();
    ///
    /// let res = TestClient::new(app)
    ///     .request(Method::OPTIONS, "/")
    ///     .header("origin", "https://example.com")
    ///     .header("access-control-request-method", "GET")
    ///     .send()
    ///     .await;
    ///
    /// assert_eq!(res.header("access-control-max-age"), Some("3600"));
    /// # });
    /// ```
    pub fn max_age(mut self, seconds: u64) -> Self {
        self.max_age = Some(seconds);
        self
    }

    fn origin_allowed(&self, origin: &str) -> Option<String> {
        match &self.origin {
            AllowOrigin::Any => Some("*".to_string()),
            AllowOrigin::List(list) => {
                if list.iter().any(|o| o == origin) {
                    Some(origin.to_string())
                } else {
                    None
                }
            }
        }
    }

    fn apply_common(&self, res: &mut Response, allow_origin: &str) {
        res.headers.insert(
            ACCESS_CONTROL_ALLOW_ORIGIN,
            HeaderValue::from_str(allow_origin).unwrap_or(HeaderValue::from_static("*")),
        );
        if self.credentials {
            res.headers.insert(
                ACCESS_CONTROL_ALLOW_CREDENTIALS,
                HeaderValue::from_static("true"),
            );
        }
    }
}

impl Default for Cors {
    fn default() -> Self {
        Self::new()
    }
}

/// Append `Origin` to `Vary` without disturbing what is already there.
///
/// This used to be a plain `insert` of `Vary: Origin` inside `apply_common`,
/// which threw away whatever another layer had already put in the header.
/// churust-compression merges `accept-encoding` into `Vary` as it unwinds, and
/// CORS sits outside it, so the overwrite left a gzip-encoded response keyed on
/// `Origin` alone: a shared cache would store those compressed bytes and hand
/// them to the next same-origin client that sent no `Accept-Encoding` at all,
/// which cannot decode them. The merge below is deliberately the same shape as
/// `churust_compression`'s `vary_on_accept_encoding` so the two plugins agree
/// on what a merged `Vary` looks like whichever order they are installed in:
/// split the existing values on commas, compare case-insensitively because
/// field names are case-insensitive, and leave the header alone when it is
/// already `*` (which varies on everything) or already names the origin. The
/// token is appended in lower case for the same reason — it matches the
/// spelling the compression plugin emits, so a response passing through both
/// reads as one consistent list rather than a mixture.
fn vary_on_origin(res: &mut Response) {
    let existing: Vec<String> = res
        .headers
        .get_all(VARY)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|v| v.split(','))
        .map(|v| v.trim().to_ascii_lowercase())
        .filter(|v| !v.is_empty())
        .collect();

    if existing.iter().any(|v| v == "*" || v == "origin") {
        return;
    }

    let mut merged = existing;
    merged.push("origin".to_string());
    if let Ok(value) = HeaderValue::from_str(&merged.join(", ")) {
        res.headers.insert(VARY, value);
    }
}

impl Plugin for Cors {
    fn install(self: Box<Self>, app: &mut AppBuilder) {
        app.add_middleware_in(Phase::Plugins, Arc::new(CorsMiddleware { cfg: *self }));
    }
}

struct CorsMiddleware {
    cfg: Cors,
}

#[async_trait]
impl Middleware for CorsMiddleware {
    async fn handle(&self, call: Call, next: Next) -> Response {
        let origin = call.header("origin").map(|s| s.to_string());
        let is_preflight = *call.method() == Method::OPTIONS
            && call
                .header(ACCESS_CONTROL_REQUEST_METHOD.as_str())
                .is_some();

        // Preflight: short-circuit with 204 + CORS headers.
        if is_preflight {
            let mut res = Response::new(StatusCode::NO_CONTENT);
            if let Some(o) = origin.as_deref().and_then(|o| self.cfg.origin_allowed(o)) {
                self.cfg.apply_common(&mut res, &o);
                let methods = self
                    .cfg
                    .methods
                    .iter()
                    .map(|m| m.as_str())
                    .collect::<Vec<_>>()
                    .join(", ");
                if let Ok(v) = HeaderValue::from_str(&methods) {
                    res.headers.insert(ACCESS_CONTROL_ALLOW_METHODS, v);
                }
                if !self.cfg.headers.is_empty() {
                    let hs = self.cfg.headers.join(", ");
                    if let Ok(v) = HeaderValue::from_str(&hs) {
                        res.headers.insert(ACCESS_CONTROL_ALLOW_HEADERS, v);
                    }
                }
                if let Some(age) = self.cfg.max_age {
                    if let Ok(v) = HeaderValue::from_str(&age.to_string()) {
                        res.headers.insert(ACCESS_CONTROL_MAX_AGE, v);
                    }
                }
            }
            vary_on_origin(&mut res);
            return res;
        }

        // Actual request: run the chain, then decorate the response.
        let mut res = next.run(call).await;
        if let Some(o) = origin.as_deref().and_then(|o| self.cfg.origin_allowed(o)) {
            self.cfg.apply_common(&mut res, &o);
        }
        // Every response this middleware touches is marked, not only the ones
        // that came out with an `Access-Control-Allow-Origin`. Whether that
        // header is present at all is decided by the request's `Origin`: a
        // same-origin request sends none and gets none back, a refused origin
        // gets none either, an allowed one does. Marking only the allowed case
        // left the other two freely cacheable, so a shared cache could store
        // the header-less answer and replay it to an allowed origin, whose
        // browser then blocks a response the server would have permitted.
        vary_on_origin(&mut res);
        res
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use churust_core::{App, Churust, TestClient};

    fn app() -> App {
        Churust::server()
            .install(Cors::allow_any_origin_insecure())
            .routing(|r| {
                r.get("/", |_c: Call| async { "ok" });
            })
            .build()
    }

    #[tokio::test]
    async fn actual_request_gets_allow_origin() {
        let client = TestClient::new(app());
        let res = client
            .get("/")
            .header("origin", "https://example.com")
            .send()
            .await;
        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.header("access-control-allow-origin"), Some("*"));
        // Lower case because the merge normalises what it finds and appends in
        // the same spelling churust-compression uses; `Vary` names fields, and
        // field names are case-insensitive, so this is the same header as the
        // `Origin` this test used to assert.
        assert_eq!(res.header("vary"), Some("origin"));
    }

    #[tokio::test]
    async fn preflight_returns_204_with_methods() {
        let client = TestClient::new(app());
        let res = client
            .request(Method::OPTIONS, "/")
            .header("origin", "https://example.com")
            .header("access-control-request-method", "POST")
            .send()
            .await;
        assert_eq!(res.status(), StatusCode::NO_CONTENT);
        let methods = res.header("access-control-allow-methods").unwrap();
        assert!(methods.contains("POST"));
    }

    /// The core dispatcher answers an unclaimed `OPTIONS` with `204` plus an
    /// `Allow` header. That must not shadow CORS preflight, which needs to
    /// respond with `access-control-*` headers instead.
    ///
    /// Cors sits in the `Plugins` phase and the router in `Fallback`, so
    /// preflight short-circuits first — but that is an assumption about phase
    /// ordering, and this test is what keeps it true.
    #[tokio::test]
    async fn preflight_takes_priority_over_automatic_options() {
        let client = TestClient::new(app());
        let res = client
            .request(Method::OPTIONS, "/")
            .header("origin", "https://example.com")
            .header("access-control-request-method", "GET")
            .send()
            .await;

        assert_eq!(res.status(), StatusCode::NO_CONTENT);
        assert!(
            res.header("access-control-allow-origin").is_some(),
            "CORS preflight was swallowed by the automatic OPTIONS handler"
        );
    }

    /// A `Vary` another layer already earned has to survive this one.
    /// churust-compression merges `accept-encoding` into `Vary` on its way out
    /// and the CORS middleware unwinds after it, so overwriting the header
    /// would leave a gzip response keyed on `Origin` alone — a shared cache
    /// would then hand those compressed bytes to the next client that sent no
    /// `Accept-Encoding` at all.
    #[tokio::test]
    async fn a_pre_existing_vary_survives_the_cors_layer() {
        let app = Churust::server()
            .install(Cors::allow_any_origin_insecure())
            .routing(|r| {
                r.get("/report", |_c: Call| async {
                    Response::text("ok")
                        .with_header(VARY, HeaderValue::from_static("accept-encoding"))
                });
            })
            .build();
        let res = TestClient::new(app)
            .get("/report")
            .header("origin", "https://app.example.com")
            .send()
            .await;
        assert_eq!(res.header("vary"), Some("accept-encoding, origin"));
    }

    /// Merging must not accumulate: a `Vary` that already names the origin is
    /// left exactly as it is, and stays a single header line.
    #[tokio::test]
    async fn an_origin_already_named_in_vary_is_not_repeated() {
        let app = Churust::server()
            .install(Cors::allow_any_origin_insecure())
            .routing(|r| {
                r.get("/report", |_c: Call| async {
                    Response::text("ok").with_header(VARY, HeaderValue::from_static("Origin"))
                });
            })
            .build();
        let res = TestClient::new(app)
            .get("/report")
            .header("origin", "https://app.example.com")
            .send()
            .await;
        assert_eq!(res.header("vary"), Some("Origin"));
    }

    /// The refusal is itself origin-dependent: this response has no
    /// `Access-Control-Allow-Origin` precisely because of who asked. Without
    /// `Vary: Origin` a shared cache may store the header-less answer and
    /// replay it to an allowed origin, which the browser then blocks.
    #[tokio::test]
    async fn a_response_to_a_disallowed_origin_still_varies_on_origin() {
        let app = Churust::server()
            .install(Cors::new().allow_origin("https://allowed.com"))
            .routing(|r| {
                r.get("/", |_c: Call| async { "ok" });
            })
            .build();
        let res = TestClient::new(app)
            .get("/")
            .header("origin", "https://evil.com")
            .send()
            .await;
        assert_eq!(res.header("access-control-allow-origin"), None);
        assert_eq!(res.header("vary"), Some("origin"));
    }

    /// Same-origin requests carry no `Origin` at all, so they too get an answer
    /// that differs from the cross-origin one. The cache key has to say so.
    #[tokio::test]
    async fn a_response_to_a_request_without_an_origin_still_varies_on_origin() {
        let res = TestClient::new(app()).get("/").send().await;
        assert_eq!(res.header("access-control-allow-origin"), None);
        assert_eq!(res.header("vary"), Some("origin"));
    }

    #[tokio::test]
    async fn disallowed_origin_gets_no_cors_header() {
        let app = Churust::server()
            .install(Cors::new().allow_origin("https://allowed.com"))
            .routing(|r| {
                r.get("/", |_c: Call| async { "ok" });
            })
            .build();
        let client = TestClient::new(app);
        let res = client
            .get("/")
            .header("origin", "https://evil.com")
            .send()
            .await;
        assert_eq!(res.header("access-control-allow-origin"), None);
    }
}