salvo-cors 1.1.0

CORS support for salvo web server 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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
#![cfg_attr(test, allow(clippy::unwrap_used))]
//! CORS (Cross-Origin Resource Sharing) protection for Salvo web framework.
//!
//! # Important
//!
//! The CORS handler must be added to [`Service`](salvo_core::Service) via `.hoop()`,
//! **not** to [`Router`](salvo_core::Router). This is because browsers send
//! `OPTIONS` preflight requests that don't match any route, and only
//! `Service`-level middleware can intercept them.
//!
//! ```no_run
//! use salvo_core::http::Method;
//! use salvo_core::prelude::*;
//! use salvo_cors::Cors;
//!
//! #[handler]
//! async fn hello() -> &'static str {
//!     "Hello World"
//! }
//!
//! fn main() {
//!     let cors = Cors::new()
//!         .allow_origin("http://localhost:3000")
//!         .allow_methods([Method::GET, Method::POST, Method::DELETE])
//!         .allow_headers("authorization")
//!         .into_handler();
//!
//!     let router = Router::new().get(hello);
//!     // CORS must be on Service, NOT on Router
//!     let _service = Service::new(router).hoop(cors);
//! }
//! ```
//!
//! [CORS]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
#![doc(html_favicon_url = "https://salvo.rs/favicon-32x32.png")]
#![doc(html_logo_url = "https://salvo.rs/images/logo.svg")]
#![cfg_attr(docsrs, feature(doc_cfg))]

use bytes::{BufMut, BytesMut};
use salvo_core::http::header::{self, HeaderMap, HeaderName, HeaderValue};
use salvo_core::http::{Method, Request, Response, StatusCode};
use salvo_core::{Depot, FlowCtrl, Handler, async_trait};

mod allow_credentials;
mod allow_headers;
mod allow_methods;
mod allow_origin;
mod allow_private_network;
mod expose_headers;
mod inner;
mod max_age;
mod vary;

pub use self::allow_credentials::AllowCredentials;
pub use self::allow_headers::AllowHeaders;
pub use self::allow_methods::AllowMethods;
pub use self::allow_origin::AllowOrigin;
pub use self::allow_private_network::AllowPrivateNetwork;
pub use self::expose_headers::ExposeHeaders;
pub use self::max_age::MaxAge;
pub use self::vary::Vary;

static WILDCARD: HeaderValue = HeaderValue::from_static("*");

/// Represents a wildcard value (`*`) used with some CORS headers such as
/// [`Cors::allow_methods`].
#[derive(Debug, Clone, Copy)]
#[must_use]
pub struct Any;

fn separated_by_commas<I>(iter: I) -> Option<HeaderValue>
where
    I: Iterator<Item = HeaderValue>,
{
    // Materialise the iterator so we can size the output buffer in one
    // shot. The previous implementation grew the `BytesMut` per entry via
    // `reserve(val.len() + 1)`, which produced O(N) reallocations when
    // joining many header values (e.g. a long `allow_headers` list).
    let values: Vec<HeaderValue> = iter.collect();
    let (first, rest) = values.split_first()?;

    let total = first.len()
        + rest
            .iter()
            .map(|v| v.len() + 1) // +1 for the leading comma
            .sum::<usize>();

    let mut result = BytesMut::with_capacity(total);
    result.extend_from_slice(first.as_bytes());
    for val in rest {
        result.put_u8(b',');
        result.extend_from_slice(val.as_bytes());
    }

    HeaderValue::from_maybe_shared(result.freeze()).ok()
}

/// [`Cors`] middleware which adds headers for [CORS][mdn].
///
/// After building, call [`.into_handler()`](Cors::into_handler) and add the
/// resulting handler to [`Service`](salvo_core::Service) via `.hoop()`.
/// Do **not** add it to `Router` — preflight `OPTIONS` requests won't reach
/// router-level middleware.
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
#[derive(Clone, Debug)]
pub struct Cors {
    allow_credentials: AllowCredentials,
    allow_headers: AllowHeaders,
    allow_methods: AllowMethods,
    allow_origin: AllowOrigin,
    allow_private_network: AllowPrivateNetwork,
    expose_headers: ExposeHeaders,
    max_age: MaxAge,
    vary: Vary,
}
impl Default for Cors {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Cors {
    /// Creates a new `Cors`.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self {
            allow_credentials: Default::default(),
            allow_headers: Default::default(),
            allow_methods: Default::default(),
            allow_origin: Default::default(),
            allow_private_network: Default::default(),
            expose_headers: Default::default(),
            max_age: Default::default(),
            vary: Default::default(),
        }
    }

    /// A permissive configuration:
    ///
    /// - All request headers allowed.
    /// - All methods allowed.
    /// - All origins allowed.
    /// - All headers exposed.
    ///
    /// # Security Warning
    ///
    /// **This configuration allows any website to make requests to your API.**
    /// Only use this for:
    /// - Public APIs that don't require authentication
    /// - Development/testing environments
    ///
    /// For production APIs that require authentication, configure CORS explicitly
    /// with specific allowed origins.
    #[must_use]
    pub fn permissive() -> Self {
        Self::new()
            .allow_headers(Any)
            .allow_methods(Any)
            .allow_origin(Any)
            .expose_headers(Any)
    }

    /// A very permissive configuration:
    ///
    /// - **Credentials allowed.**
    /// - The method received in `Access-Control-Request-Method` is sent back as an allowed method.
    /// - The origin of the preflight request is sent back as an allowed origin.
    /// - The header names received in `Access-Control-Request-Headers` are sent back as allowed
    ///   headers.
    /// - No headers are currently exposed, but this may change in the future.
    ///
    /// # Security Warning
    ///
    /// **⚠️ DANGER: This configuration essentially disables CORS protection!**
    ///
    /// By enabling credentials AND mirroring the request origin, you are allowing
    /// ANY website to:
    /// - Make authenticated requests to your API
    /// - Read response data including sensitive information
    /// - Perform actions on behalf of logged-in users (CSRF attacks)
    ///
    /// **This should NEVER be used in production with authentication.**
    /// Runtime wildcard guards do not make this pattern safe for authenticated
    /// endpoints, because this configuration reflects each request's `Origin`
    /// as a concrete allowed origin while also allowing credentials. Browsers
    /// then treat the calling site as explicitly trusted for that response.
    ///
    /// Only use this for:
    /// - Local development where security is not a concern
    /// - Internal tools on trusted networks
    ///
    /// For production, always configure explicit allowed origins:
    /// ```ignore
    /// Cors::new()
    ///     .allow_origin("https://your-frontend.com")
    ///     .allow_credentials(true)
    /// ```
    #[must_use]
    pub fn very_permissive() -> Self {
        tracing::warn!(
            "Using Cors::very_permissive() - this disables CORS security and should not be used in production!"
        );
        Self::new()
            .allow_credentials(true)
            .allow_headers(AllowHeaders::mirror_request())
            .allow_methods(AllowMethods::mirror_request())
            .allow_origin(AllowOrigin::mirror_request())
    }

    /// Sets whether to add the `Access-Control-Allow-Credentials` header.
    #[inline]
    #[must_use]
    pub fn allow_credentials(mut self, allow_credentials: impl Into<AllowCredentials>) -> Self {
        self.allow_credentials = allow_credentials.into();
        self
    }

    /// Adds multiple headers to the list of allowed request headers.
    ///
    /// **Note**: These should match the values the browser sends via
    /// `Access-Control-Request-Headers`, e.g.`content-type`.
    ///
    /// # Panics
    ///
    /// Panics if any of the headers are not a valid `http::header::HeaderName`.
    #[inline]
    #[must_use]
    pub fn allow_headers(mut self, headers: impl Into<AllowHeaders>) -> Self {
        self.allow_headers = headers.into();
        self
    }

    /// Sets the `Access-Control-Max-Age` header.
    ///
    /// # Example
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use salvo_core::prelude::*;
    /// use salvo_cors::Cors;
    ///
    /// let cors = Cors::new().max_age(30); // 30 seconds
    /// let cors = Cors::new().max_age(Duration::from_secs(30)); // or a Duration
    /// ```
    #[inline]
    #[must_use]
    pub fn max_age(mut self, max_age: impl Into<MaxAge>) -> Self {
        self.max_age = max_age.into();
        self
    }

    /// Adds multiple methods to the existing list of allowed request methods.
    ///
    /// # Panics
    ///
    /// Panics if the provided argument is not a valid `http::Method`.
    #[inline]
    #[must_use]
    pub fn allow_methods<I>(mut self, methods: I) -> Self
    where
        I: Into<AllowMethods>,
    {
        self.allow_methods = methods.into();
        self
    }

    /// Set the value of the [`Access-Control-Allow-Origin`][mdn] header.
    /// ```
    /// use salvo_core::http::HeaderValue;
    /// use salvo_cors::Cors;
    ///
    /// let cors = Cors::new().allow_origin("http://example.com".parse::<HeaderValue>().unwrap());
    /// ```
    ///
    /// Multiple origins can be allowed with
    ///
    /// ```
    /// use salvo_cors::Cors;
    ///
    /// let origins = ["http://example.com", "http://api.example.com"];
    ///
    /// let cors = Cors::new().allow_origin(origins);
    /// ```
    ///
    /// All origins can be allowed with
    ///
    /// ```
    /// use salvo_cors::{Any, Cors};
    ///
    /// let cors = Cors::new().allow_origin(Any);
    /// ```
    ///
    /// You can also use a closure
    ///
    /// ```
    /// use salvo_core::http::HeaderValue;
    /// use salvo_core::{Depot, Request};
    /// use salvo_cors::{AllowOrigin, Cors};
    ///
    /// let cors = Cors::new().allow_origin(AllowOrigin::dynamic(
    ///     |origin: Option<&HeaderValue>, _req: &Request, _depot: &Depot| {
    ///         if origin?.as_bytes().ends_with(b".rust-lang.org") {
    ///             origin.cloned()
    ///         } else {
    ///             None
    ///         }
    ///     },
    /// ));
    /// ```
    ///
    /// You can also use an async closure, make sure all the values are owned
    /// before passing into the future:
    ///
    /// ```
    /// # #[derive(Clone)]
    /// # struct Client;
    /// # fn get_api_client() -> Client {
    /// #     Client
    /// # }
    /// # impl Client {
    /// #     async fn fetch_allowed_origins(&self) -> Vec<HeaderValue> {
    /// #         vec![HeaderValue::from_static("http://example.com")]
    /// #     }
    /// #     async fn fetch_allowed_origins_for_path(&self, _path: String) -> Vec<HeaderValue> {
    /// #         vec![HeaderValue::from_static("http://example.com")]
    /// #     }
    /// # }
    /// use salvo_core::http::header::HeaderValue;
    /// use salvo_core::{Depot, Request};
    /// use salvo_cors::{AllowOrigin, Cors};
    ///
    /// let cors = Cors::new().allow_origin(AllowOrigin::dynamic_async(
    ///     |origin: Option<&HeaderValue>, _req: &Request, _depot: &Depot| {
    ///         let origin = origin.cloned();
    ///         async move {
    ///             let client = get_api_client();
    ///             // fetch list of origins that are allowed
    ///             let origins = client.fetch_allowed_origins().await;
    ///             if origins.contains(origin.as_ref()?) {
    ///                 origin
    ///             } else {
    ///                 None
    ///             }
    ///         }
    ///     },
    /// ));
    /// ```
    ///
    /// **Note** that multiple calls to this method will override any previous
    /// calls.
    ///
    /// **Note** origin must contain http or https protocol name.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
    #[inline]
    #[must_use]
    pub fn allow_origin(mut self, origin: impl Into<AllowOrigin>) -> Self {
        self.allow_origin = origin.into();
        self
    }

    /// Set the value of the [`Access-Control-Expose-Headers`][mdn] header.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
    #[inline]
    #[must_use]
    pub fn expose_headers(mut self, headers: impl Into<ExposeHeaders>) -> Self {
        self.expose_headers = headers.into();
        self
    }

    /// Set the value of the [`Access-Control-Allow-Private-Network`][wicg] header.
    ///
    /// ```
    /// use salvo_cors::Cors;
    ///
    /// let cors = Cors::new().allow_private_network(true);
    /// ```
    ///
    /// [wicg]: https://wicg.github.io/private-network-access/
    #[must_use]
    pub fn allow_private_network<T>(mut self, allow_private_network: T) -> Self
    where
        T: Into<AllowPrivateNetwork>,
    {
        self.allow_private_network = allow_private_network.into();
        self
    }

    /// Set the value(s) of the [`Vary`][mdn] header.
    ///
    /// In contrast to the other headers, this one has a non-empty default of
    /// [`preflight_request_headers()`].
    ///
    /// You only need to set this is you want to remove some of these defaults,
    /// or if you use a closure for one of the other headers and want to add a
    /// vary header accordingly.
    ///
    /// ```
    /// use salvo_core::http::header;
    /// use salvo_cors::{Cors, Vary};
    ///
    /// let _cors = Cors::new().vary([header::ORIGIN, header::ACCEPT_LANGUAGE]);
    /// let _cors = Cors::new().vary(vec![header::ORIGIN]);
    /// let _cors = Cors::new().vary(Vary::default());
    /// ```
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
    #[must_use]
    pub fn vary(mut self, headers: impl Into<Vary>) -> Self {
        self.vary = headers.into();
        self
    }

    /// Returns a new `CorsHandler` using current cors settings.
    pub fn into_handler(self) -> CorsHandler {
        self.ensure_usable_cors_rules();
        CorsHandler::new(self, CallNext::default())
    }

    fn ensure_usable_cors_rules(&self) {
        if self.allow_credentials.is_true() {
            assert!(
                !self.allow_headers.is_wildcard(),
                "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
                 with `Access-Control-Allow-Headers: *`"
            );

            assert!(
                !self.allow_methods.is_wildcard(),
                "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
                 with `Access-Control-Allow-Methods: *`"
            );

            assert!(
                !self.allow_origin.is_wildcard(),
                "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
                 with `Access-Control-Allow-Origin: *`"
            );

            assert!(
                !self.expose_headers.is_wildcard(),
                "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
                 with `Access-Control-Expose-Headers: *`"
            );
        }
    }
}

/// Controls when [`CorsHandler`] runs the rest of the middleware/handler chain
/// relative to writing the CORS headers.
#[non_exhaustive]
#[derive(Default, Clone, Copy, Eq, PartialEq, Debug)]
pub enum CallNext {
    /// Run the remaining handlers **before** [`CorsHandler`] writes the CORS
    /// headers onto the response. This is the default and the right choice for
    /// most setups: downstream handlers see the request unmodified, and CORS
    /// headers are appended last.
    #[default]
    Before,
    /// Run the remaining handlers **after** [`CorsHandler`] has written the CORS
    /// headers. Use this when downstream handlers need to inspect or augment the
    /// CORS headers — note that they may also overwrite them.
    After,
}

/// CorsHandler
#[derive(Clone, Debug)]
pub struct CorsHandler {
    cors: Cors,
    call_next: CallNext,
}
impl CorsHandler {
    /// Create a new `CorsHandler`.
    pub fn new(cors: Cors, call_next: CallNext) -> Self {
        Self { cors, call_next }
    }
}

#[async_trait]
impl Handler for CorsHandler {
    async fn handle(
        &self,
        req: &mut Request,
        depot: &mut Depot,
        res: &mut Response,
        ctrl: &mut FlowCtrl,
    ) {
        if self.call_next == CallNext::Before {
            ctrl.call_next(req, depot, res).await;
        }

        let origin = req.headers().get(&header::ORIGIN);
        let is_preflight = req.method() == Method::OPTIONS
            && origin.is_some()
            && req
                .headers()
                .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD);
        let mut headers = HeaderMap::new();

        // These headers are applied to both preflight and subsequent regular CORS requests:
        // https://fetch.spec.whatwg.org/#http-responses
        headers.extend(self.cors.allow_origin.to_header(origin, req, depot).await);
        headers.extend(
            self.cors
                .allow_credentials
                .to_header(origin, req, depot)
                .await,
        );
        headers.extend(
            self.cors
                .allow_private_network
                .to_header(origin, req, depot)
                .await,
        );

        // Keep cache selectors set by other middleware or the endpoint. HeaderMap::extend
        // replaces all existing values, so Vary must be merged separately.
        for value in self.cors.vary.values() {
            let already_varies = res.headers().get_all(header::VARY).iter().any(|existing| {
                existing
                    .as_bytes()
                    .split(|byte| *byte == b',')
                    .any(|token| {
                        let token = token.trim_ascii();
                        token == b"*" || token.eq_ignore_ascii_case(value.as_bytes())
                    })
            });
            if !already_varies {
                res.headers_mut().append(header::VARY, value);
            }
        }

        // Only a CORS preflight gets a generated response. Ordinary OPTIONS
        // requests must keep the status and body produced by their handlers.
        if is_preflight {
            // These headers are applied only to preflight requests
            headers.extend(self.cors.allow_methods.to_header(origin, req, depot).await);
            headers.extend(self.cors.allow_headers.to_header(origin, req, depot).await);
            headers.extend(self.cors.max_age.to_header(origin, req, depot).await);
            res.status_code = Some(StatusCode::NO_CONTENT);
        } else {
            // This header is applied only to non-preflight requests
            headers.extend(self.cors.expose_headers.to_header(origin, req, depot).await);
        }

        res.headers_mut().extend(headers);

        if self.call_next == CallNext::After {
            ctrl.call_next(req, depot, res).await;
        }

        // Run the wildcard/credentials guard last, after every `call_next` point,
        // so it always sees the truly final response regardless of whether the
        // downstream chain ran before or after this handler. A genuine CORS
        // preflight is an OPTIONS request carrying Origin and Access-Control-
        // Request-Method; ordinary OPTIONS requests use the actual-response rules.
        enforce_credentials_safety(res, is_preflight);
    }
}

/// Defense in depth: when credentials are allowed, none of the *applicable* CORS
/// response headers may be the wildcard `*`. `ensure_usable_cors_rules` asserts
/// this at build time, but only for statically configured credentials
/// (`AllowCredentials::Yes`); a dynamic credentials policy — or a downstream
/// handler that sets its own CORS headers — can otherwise produce this invalid,
/// unsafe combination at runtime.
///
/// Each header is only checked where it is meaningful, so a non-applicable
/// wildcard (e.g. a global middleware that always emits `Access-Control-Allow-
/// Methods: *`) does not strip credentials from a valid response:
/// - `Access-Control-Allow-Origin` — every response (the security-critical case);
/// - `Access-Control-Allow-Methods` / `-Allow-Headers` — preflight responses only;
/// - `Access-Control-Expose-Headers` — non-preflight (actual) responses only.
fn enforce_credentials_safety(res: &mut Response, is_preflight: bool) {
    let credentials = res
        .headers()
        .get_all(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
        .iter()
        .any(|v| v == "true");
    if !credentials {
        return;
    }

    // CORS list headers (methods/headers/expose) may be comma-separated, so a
    // wildcard can appear as a token within a list such as `*, authorization`.
    // Split on commas and compare per token rather than the whole value.
    let has_wildcard_token = |name: &HeaderName| {
        res.headers().get_all(name).iter().any(|v| {
            v.to_str()
                .is_ok_and(|s| s.split(',').any(|token| token.trim() == "*"))
        })
    };

    let mut candidates = vec![header::ACCESS_CONTROL_ALLOW_ORIGIN];
    if is_preflight {
        candidates.push(header::ACCESS_CONTROL_ALLOW_METHODS);
        candidates.push(header::ACCESS_CONTROL_ALLOW_HEADERS);
    } else {
        candidates.push(header::ACCESS_CONTROL_EXPOSE_HEADERS);
    }

    if let Some(name) = candidates.into_iter().find(|name| has_wildcard_token(name)) {
        tracing::error!(
            "CORS misconfiguration: `Access-Control-Allow-Credentials: true` cannot be combined \
             with `{name}: *`; dropping the credentials header"
        );
        res.headers_mut()
            .remove(header::ACCESS_CONTROL_ALLOW_CREDENTIALS);
    }
}

/// Iterator over the three request headers that may be involved in a CORS preflight request.
///
/// This is the default set of header names returned in the `vary` header
pub fn preflight_request_headers() -> impl Iterator<Item = HeaderName> {
    [
        header::ORIGIN,
        header::ACCESS_CONTROL_REQUEST_METHOD,
        header::ACCESS_CONTROL_REQUEST_HEADERS,
    ]
    .into_iter()
}

#[cfg(test)]
mod tests {
    use salvo_core::http::header::*;
    use salvo_core::prelude::*;
    use salvo_core::test::{ResponseExt, TestClient};

    use super::*;

    #[tokio::test]
    async fn test_cors_preserves_downstream_vary() {
        #[handler]
        async fn varies(res: &mut Response) {
            res.headers_mut()
                .append(VARY, HeaderValue::from_static("Accept-Encoding, Origin"));
            res.headers_mut()
                .append(VARY, HeaderValue::from_static("Accept-Language"));
            res.render("hello");
        }

        let service = Service::new(Router::new().goal(varies)).hoop(Cors::new().into_handler());
        let res = TestClient::get("http://localhost/").send(&service).await;
        let tokens: Vec<_> = res
            .headers()
            .get_all(VARY)
            .iter()
            .flat_map(|value| {
                value
                    .to_str()
                    .unwrap()
                    .split(',')
                    .map(|token| token.trim().to_ascii_lowercase())
            })
            .collect();
        assert_eq!(
            tokens,
            [
                "accept-encoding",
                "origin",
                "accept-language",
                "access-control-request-method",
                "access-control-request-headers"
            ]
        );
    }

    #[tokio::test]
    async fn test_cors_merges_existing_vary_in_both_call_next_modes() {
        #[handler]
        async fn existing_vary(req: &mut Request, res: &mut Response) {
            let value = if req.uri().path() == "/wildcard" {
                "*"
            } else {
                "Accept-Language, ORIGIN"
            };
            res.headers_mut()
                .insert(VARY, HeaderValue::from_static(value));
        }
        #[handler]
        async fn hello() -> &'static str {
            "hello"
        }

        for mode in [CallNext::Before, CallNext::After] {
            let service = Service::new(Router::new().goal(hello))
                .hoop(existing_vary)
                .hoop(CorsHandler::new(Cors::new(), mode));
            for path in ["/", "/wildcard"] {
                let res = TestClient::get(format!("http://localhost{path}"))
                    .send(&service)
                    .await;
                let values: Vec<_> = res
                    .headers()
                    .get_all(VARY)
                    .iter()
                    .map(|value| value.to_str().unwrap())
                    .collect();
                if path == "/wildcard" {
                    assert_eq!(values, ["*"]);
                } else {
                    assert_eq!(
                        values,
                        [
                            "Accept-Language, ORIGIN",
                            "access-control-request-method",
                            "access-control-request-headers"
                        ]
                    );
                }
            }
        }
    }

    #[tokio::test]
    async fn test_cors_drops_credentials_with_wildcard_origin() {
        // A dynamic credentials policy bypasses the build-time assertions, so the
        // runtime guard must drop `Allow-Credentials: true` when the resolved
        // `Allow-Origin` is `*`.
        let cors_handler = Cors::new()
            .allow_origin(AllowOrigin::any())
            .allow_credentials(AllowCredentials::dynamic(|_, _, _| true))
            .allow_methods(vec![Method::GET, Method::OPTIONS])
            .into_handler();

        #[handler]
        async fn hello() -> &'static str {
            "hello"
        }
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(hello));
        let service = Service::new(router);

        let res = TestClient::get("http://127.0.0.1/hello")
            .add_header("Origin", "https://evil.example.com", true)
            .send(&service)
            .await;

        assert_eq!(res.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(), "*");
        assert!(
            res.headers()
                .get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .is_none(),
            "credentials header must be dropped when origin is `*`"
        );
    }

    #[tokio::test]
    async fn test_cors_drops_credentials_when_handler_sets_wildcard_origin() {
        // With the default `CallNext::Before`, the downstream handler runs first
        // and may set its own `Access-Control-Allow-Origin: *`. The guard must
        // inspect the final merged response, not just the headers it built.
        #[handler]
        async fn sets_wildcard(res: &mut Response) {
            res.headers_mut()
                .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
            res.render("ok");
        }

        let cors_handler = Cors::new()
            .allow_credentials(AllowCredentials::dynamic(|_, _, _| true))
            .into_handler();
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(sets_wildcard));
        let service = Service::new(router);

        let res = TestClient::get("http://127.0.0.1/hello")
            .add_header("Origin", "https://app.example.com", true)
            .send(&service)
            .await;

        assert!(
            res.headers()
                .get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .is_none(),
            "credentials must be dropped when the handler set a wildcard origin"
        );
    }

    #[tokio::test]
    async fn test_cors_drops_credentials_in_after_mode_with_handler_wildcard() {
        // In `CallNext::After` mode the downstream chain runs after this handler,
        // so a handler that sets a wildcard CORS header must still be caught by
        // the guard, which runs after every `call_next` point.
        #[handler]
        async fn sets_wildcard(res: &mut Response) {
            res.headers_mut()
                .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
            res.render("ok");
        }

        let cors = Cors::new().allow_credentials(AllowCredentials::dynamic(|_, _, _| true));
        let cors_handler = CorsHandler::new(cors, CallNext::After);
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(sets_wildcard));
        let service = Service::new(router);

        let res = TestClient::get("http://127.0.0.1/hello")
            .add_header("Origin", "https://app.example.com", true)
            .send(&service)
            .await;

        assert!(
            res.headers()
                .get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .is_none(),
            "credentials must be dropped even in After mode when the handler sets a wildcard"
        );
    }

    #[tokio::test]
    async fn test_cors_drops_credentials_with_wildcard_token_in_list() {
        // A wildcard can appear as a token inside a comma-separated list header
        // (e.g. `Access-Control-Allow-Headers: *, authorization`); it must still
        // be detected. `Allow-Headers` is preflight-only, so use an OPTIONS
        // request.
        // A handler sets a comma-separated `Allow-Headers` containing a `*` token.
        #[handler]
        async fn sets_list_wildcard(res: &mut Response) {
            res.headers_mut().insert(
                ACCESS_CONTROL_ALLOW_HEADERS,
                HeaderValue::from_static("*, authorization"),
            );
        }
        let cors_handler = Cors::new()
            .allow_origin("https://app.example.com")
            .allow_credentials(AllowCredentials::dynamic(|_, _, _| true))
            .into_handler();
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(sets_list_wildcard));
        let service = Service::new(router);

        let res = TestClient::options("http://127.0.0.1/hello")
            .add_header("Origin", "https://app.example.com", true)
            .add_header(ACCESS_CONTROL_REQUEST_METHOD, "GET", true)
            .send(&service)
            .await;

        assert!(
            res.headers()
                .get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .is_none(),
            "credentials must be dropped when a list header contains a `*` token"
        );
    }

    #[tokio::test]
    async fn test_cors_keeps_credentials_on_options_without_request_method() {
        // An OPTIONS request without `Access-Control-Request-Method` is an actual
        // request, not a preflight, so a wildcard `Allow-Methods` must not strip
        // credentials.
        #[handler]
        async fn sets_wildcard_methods(res: &mut Response) {
            res.headers_mut()
                .insert(ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("*"));
        }

        let cors_handler = Cors::new()
            .allow_origin("https://app.example.com")
            .allow_credentials(AllowCredentials::dynamic(|_, _, _| true))
            .into_handler();
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(sets_wildcard_methods));
        let service = Service::new(router);

        let res = TestClient::options("http://127.0.0.1/hello")
            .add_header("Origin", "https://app.example.com", true)
            .send(&service)
            .await;

        assert_eq!(
            res.headers().get(ACCESS_CONTROL_ALLOW_CREDENTIALS).unwrap(),
            "true",
            "credentials must be kept for a non-preflight OPTIONS (no Request-Method)"
        );
    }

    #[tokio::test]
    async fn test_cors_keeps_credentials_on_actual_request_with_wildcard_methods() {
        // `Allow-Methods` is only meaningful on a preflight response. A wildcard
        // value on a normal (non-OPTIONS) response is ignored by the browser, so
        // the guard must NOT strip credentials in that case (the actual
        // credentialed CORS check uses the specific origin + credentials).
        #[handler]
        async fn sets_wildcard_methods(res: &mut Response) {
            res.headers_mut()
                .insert(ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("*"));
            res.render("ok");
        }

        let cors_handler = Cors::new()
            .allow_origin("https://app.example.com")
            .allow_credentials(AllowCredentials::dynamic(|_, _, _| true))
            .into_handler();
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(sets_wildcard_methods));
        let service = Service::new(router);

        let res = TestClient::get("http://127.0.0.1/hello")
            .add_header("Origin", "https://app.example.com", true)
            .send(&service)
            .await;

        assert_eq!(
            res.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(),
            "https://app.example.com"
        );
        assert_eq!(
            res.headers().get(ACCESS_CONTROL_ALLOW_CREDENTIALS).unwrap(),
            "true",
            "credentials must be kept: wildcard methods is preflight-only and ignored here"
        );
    }

    #[tokio::test]
    async fn test_cors_drops_credentials_with_wildcard_methods() {
        // Origin is an exact (reflected) value, but `Allow-Methods` is `*`;
        // credentials must still be dropped because `*` and credentials are
        // incompatible for any of the CORS response headers.
        let cors_handler = Cors::new()
            .allow_origin("https://app.example.com")
            .allow_methods(Any)
            .allow_credentials(AllowCredentials::dynamic(|_, _, _| true))
            .into_handler();

        #[handler]
        async fn hello() -> &'static str {
            "hello"
        }
        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(hello));
        let service = Service::new(router);

        let res = TestClient::options("http://127.0.0.1/hello")
            .add_header("Origin", "https://app.example.com", true)
            .add_header(ACCESS_CONTROL_REQUEST_METHOD, "GET", true)
            .send(&service)
            .await;

        assert_eq!(
            res.headers().get(ACCESS_CONTROL_ALLOW_METHODS).unwrap(),
            "*"
        );
        assert_eq!(
            res.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).unwrap(),
            "https://app.example.com"
        );
        assert!(
            res.headers()
                .get(ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .is_none(),
            "credentials must be dropped when any CORS header is `*`"
        );
    }

    #[tokio::test]
    async fn test_cors() {
        let cors_handler = Cors::new()
            .allow_origin("https://salvo.rs")
            .allow_methods(vec![Method::GET, Method::POST, Method::OPTIONS])
            .allow_headers(vec![
                "CONTENT-TYPE",
                "Access-Control-Request-Method",
                "Access-Control-Allow-Origin",
                "Access-Control-Allow-Headers",
                "Access-Control-Max-Age",
            ])
            .into_handler();

        #[handler]
        async fn hello() -> &'static str {
            "hello"
        }

        let router = Router::new()
            .hoop(cors_handler)
            .push(Router::with_path("hello").goal(hello));
        let service = Service::new(router);

        async fn options_access(service: &Service, origin: &str) -> Response {
            TestClient::options("http://127.0.0.1:5801/hello")
                .add_header("Origin", origin, true)
                .add_header("Access-Control-Request-Method", "POST", true)
                .add_header("Access-Control-Request-Headers", "Content-Type", true)
                .send(service)
                .await
        }

        let res = TestClient::options("https://salvo.rs").send(&service).await;
        assert!(res.headers().get(ACCESS_CONTROL_ALLOW_METHODS).is_none());

        let res = options_access(&service, "https://salvo.rs").await;
        let headers = res.headers();
        assert!(headers.get(ACCESS_CONTROL_ALLOW_METHODS).is_some());
        assert!(headers.get(ACCESS_CONTROL_ALLOW_HEADERS).is_some());

        let res = TestClient::options("https://google.com")
            .send(&service)
            .await;
        let headers = res.headers();
        assert!(
            headers.get(ACCESS_CONTROL_ALLOW_METHODS).is_none(),
            "POST, GET, DELETE, OPTIONS"
        );
        assert!(headers.get(ACCESS_CONTROL_ALLOW_HEADERS).is_none());
    }

    #[tokio::test]
    async fn test_cors_preserves_ordinary_options_responses() {
        #[handler]
        async fn options(req: &mut Request, res: &mut Response) {
            res.status_code = Some(if req.uri().path() == "/denied" {
                StatusCode::UNAUTHORIZED
            } else {
                StatusCode::OK
            });
            res.render("options response");
        }

        for mode in [CallNext::Before, CallNext::After] {
            let cors = Cors::new()
                .allow_origin("https://app.example.com")
                .allow_methods([Method::GET])
                .allow_headers([CONTENT_TYPE])
                .expose_headers([ETAG])
                .max_age(60);
            let router = Router::new()
                .options(options)
                .push(Router::with_path("denied").options(options));
            let service = Service::new(router).hoop(CorsHandler::new(cors, mode));
            for (path, expected) in [("/", StatusCode::OK), ("/denied", StatusCode::UNAUTHORIZED)] {
                // Neither header, Origin only, and Request-Method only are all
                // ordinary OPTIONS requests, rather than CORS preflights.
                for (origin, method) in [(false, false), (true, false), (false, true)] {
                    let mut request = TestClient::options(format!("http://localhost{path}"));
                    if origin {
                        request = request.add_header(ORIGIN, "https://app.example.com", true);
                    }
                    if method {
                        request = request.add_header(ACCESS_CONTROL_REQUEST_METHOD, "GET", true);
                    }
                    let mut res = request.send(&service).await;
                    assert_eq!(
                        res.status_code,
                        Some(expected),
                        "mode={mode:?}, origin={origin}, method={method}"
                    );
                    assert_eq!(res.take_string().await.unwrap(), "options response");
                    assert!(!res.headers().contains_key(ACCESS_CONTROL_ALLOW_METHODS));
                    assert!(!res.headers().contains_key(ACCESS_CONTROL_ALLOW_HEADERS));
                    assert!(!res.headers().contains_key(ACCESS_CONTROL_MAX_AGE));
                    if origin {
                        assert_eq!(res.headers()[ACCESS_CONTROL_EXPOSE_HEADERS], "etag");
                    }
                }
            }
        }
    }

    #[tokio::test]
    async fn test_cors_preflight_without_options_route_in_both_modes() {
        #[handler]
        async fn hello() -> &'static str {
            "hello"
        }

        for mode in [CallNext::Before, CallNext::After] {
            let cors = Cors::new()
                .allow_origin("https://app.example.com")
                .allow_methods([Method::GET])
                .allow_headers([CONTENT_TYPE])
                .expose_headers([ETAG])
                .max_age(60);
            let service = Service::new(Router::new().get(hello)).hoop(CorsHandler::new(cors, mode));
            let res = TestClient::options("http://localhost/")
                .add_header(ORIGIN, "https://app.example.com", true)
                .add_header(ACCESS_CONTROL_REQUEST_METHOD, "GET", true)
                .send(&service)
                .await;
            assert_eq!(res.status_code, Some(StatusCode::NO_CONTENT));
            assert_eq!(res.headers()[ACCESS_CONTROL_ALLOW_METHODS], "GET");
            assert_eq!(res.headers()[ACCESS_CONTROL_ALLOW_HEADERS], "content-type");
            assert_eq!(res.headers()[ACCESS_CONTROL_MAX_AGE], "60");
            assert!(!res.headers().contains_key(ACCESS_CONTROL_EXPOSE_HEADERS));
        }
    }

    #[test]
    fn test_separated_by_commas_empty_iter_returns_none() {
        let result = super::separated_by_commas(std::iter::empty::<HeaderValue>());
        assert!(result.is_none());
    }

    #[test]
    fn test_separated_by_commas_joins_values() {
        let values = vec![
            HeaderValue::from_static("content-type"),
            HeaderValue::from_static("authorization"),
            HeaderValue::from_static("x-requested-with"),
        ];

        let joined = super::separated_by_commas(values.into_iter()).expect("non-empty");
        assert_eq!(joined, "content-type,authorization,x-requested-with");
    }
}