sz-rust-middleware-facade 0.7.0

中间件层 facade(P3)— auth/sanctum/jwt_blacklist 等 14 个 Tower 中间件 + log 模块
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
//! CORS 中间件 — 跨域请求支持
//!
//! 对齐 PHP `app\CrossDomain`:
//! - 默认 `Access-Control-Allow-Origin: *`
//! - 若配置 `cookie.domain`,则回显请求 `Origin`(前提:Origin 命中 cookie domain)
//! - `Access-Control-Allow-Credentials: true`
//! - `Access-Control-Max-Age: 1800`
//! - `Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS`
//! - `Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since,
//!    If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With`
//!
//! 基于 `tower-http::cors`,提供:
//! - [`cors_layer`]:默认 CORS Layer(与 PHP 全局中间件等价)
//! - [`cors_layer_with_origin`]:回显 Origin 的 CORS Layer(与 PHP 配置 cookie.domain 等价)
//! - [`cors_layer_with_config`]:自定义完整 CORS 配置
//!
//! ## 用法
//!
//! ```ignore
//! use sz_rust_core::middleware::cors::cors_layer;
//! use axum::Router;
//!
//! let app: Router = Router::new()
//!     .route("/", axum::routing::get(|| async { "hello" }))
//!     .layer(cors_layer());
//! ```

use axum::http::HeaderName;
use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer};

/// 默认允许的方法(对齐 PHP `Access-Control-Allow-Methods`)
pub const DEFAULT_ALLOW_METHODS: &str = "GET, POST, PATCH, PUT, DELETE, OPTIONS";

/// 默认允许的请求头(对齐 PHP `Access-Control-Allow-Headers`)
pub const DEFAULT_ALLOW_HEADERS: &str =
    "Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With";

/// 默认预检缓存时长(秒)(对齐 PHP `Access-Control-Max-Age: 1800`)
pub const DEFAULT_MAX_AGE: u64 = 1800;

/// 默认 CORS Layer — 安全默认(不回显任意 Origin)
///
/// 安全策略(2026-07-25 修复 P1):
/// - `Allow-Origin: *`(通配,不携带凭证)
/// - **不**设置 `Allow-Credentials: true`(避免任意网站携带用户凭证发起跨域请求)
/// - `Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS`
/// - `Allow-Headers: Authorization, Content-Type, ...`
/// - `Access-Control-Max-Age: 1800`
///
/// ## 安全说明
///
/// 旧版使用 `mirror_request()` + `allow_credentials(true)` 等同于关闭 CORS 防护 —
/// 任何网站都可携带用户凭证发起跨域请求,存在 CSRF 风险。
///
/// 新版默认不携带凭证(`Allow-Origin: *` + 无 `Allow-Credentials`)。
/// 需要携带凭证(Cookie)的场景请使用 [`cors_layer_with_origin`] 显式配置可信域名。
pub fn cors_layer() -> CorsLayer {
    CorsLayer::new()
        .allow_origin(AllowOrigin::any())
        .allow_methods(parse_methods(DEFAULT_ALLOW_METHODS))
        .allow_headers(parse_headers(DEFAULT_ALLOW_HEADERS))
        .max_age(std::time::Duration::from_secs(DEFAULT_MAX_AGE))
}

/// 判断请求 Origin 是否命中 cookie_domain
///
/// ## 匹配规则(精确后缀匹配,避免子串绕过)
///
/// - `origin = "https://example.com"` + `domain = "example.com"` → 匹配
/// - `origin = "https://app.example.com"` + `domain = "example.com"` → 匹配(子域名)
/// - `origin = "https://evil-example.com"` + `domain = "example.com"` → **不匹配**(避免子串绕过)
/// - `origin = "https://example.com.evil.com"` + `domain = "example.com"` → **不匹配**
///
/// ## 实现细节
///
/// 1. 剥离 scheme(`http://` / `https://`)
/// 2. 剥离端口号(注意 IPv6 `[::1]:8080` 用 `[]` 包裹)
/// 3. 精确匹配或 `.domain` 后缀匹配
pub fn origin_matches_domain(origin: &str, domain: &str) -> bool {
    // 剥离 scheme
    let host = origin.split("://").nth(1).unwrap_or(origin);
    // 剥离端口号(区分 IPv6 与 IPv4/host)
    let host = if let Some(stripped) = host.strip_prefix('[') {
        // IPv6: [::1]:8080 → 返回 ::1(不含端口)
        stripped.split(']').next().unwrap_or(stripped)
    } else {
        // IPv4/host: example.com:8080 → example.com(rsplit_once 避免错误切分 IPv6)
        host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host)
    };
    // 精确匹配或 .domain 后缀匹配(阻止 evil-example.com / example.com.evil.com 等绕过)
    host == domain || host.ends_with(&format!(".{domain}"))
}

/// 回显请求 Origin 的 CORS Layer
///
/// 当配置了 `cookie.domain` 时使用此 Layer。若请求 `Origin` 命中 `cookie_domain`
/// 则回显 Origin,否则不设置 `Allow-Origin`(拒绝跨域)。
///
/// ## 安全实现
///
/// 使用 [`origin_matches_domain`] 做精确后缀匹配,避免 PHP 原版 `strpos` 子串匹配
/// 被 `evil-example.com` 等恶意域名绕过。
///
/// ## P1-SEC-11 修复说明
///
/// 旧版在 `cookie_domain` 为空时返回 `true`(允许所有 origin)且同时设置
/// `allow_credentials(true)`。浏览器对"反射具体 origin + credentials"的组合
/// 会放行带凭据的跨域请求,等同于对凭据请求禁用 CORS 保护。
/// 修复:空 `cookie_domain` 时不允许任何 origin(严格白名单模式),
/// 仅当 origin 命中白名单时才回显并携带 credentials。
pub fn cors_layer_with_origin(cookie_domain: &str) -> CorsLayer {
    let cookie_domain = cookie_domain.to_string();
    let allow_origin = AllowOrigin::predicate(move |origin, _| {
        // P1-SEC-11: 空 cookie_domain 不再等价于通配(防止 credentials 泄漏)
        if cookie_domain.is_empty() {
            return false; // 未配置白名单时拒绝所有跨域请求
        }
        match origin.to_str() {
            Ok(origin_str) => origin_matches_domain(origin_str, &cookie_domain),
            Err(_) => false,
        }
    });

    CorsLayer::new()
        .allow_origin(allow_origin)
        .allow_credentials(true)
        .allow_methods(parse_methods(DEFAULT_ALLOW_METHODS))
        .allow_headers(parse_headers(DEFAULT_ALLOW_HEADERS))
        .max_age(std::time::Duration::from_secs(DEFAULT_MAX_AGE))
}

/// 自定义完整 CORS 配置
///
/// 提供 `Allow-Origin: *` + 不带 credentials 的简化版本,用于不需要 cookie 的纯 API 场景。
pub fn cors_layer_with_config(
    allow_origin: AllowOrigin,
    allow_credentials: bool,
    allow_methods: &str,
    allow_headers: &str,
    max_age_secs: u64,
) -> CorsLayer {
    let mut layer = CorsLayer::new()
        .allow_origin(allow_origin)
        .allow_methods(parse_methods(allow_methods))
        .allow_headers(parse_headers(allow_headers))
        .max_age(std::time::Duration::from_secs(max_age_secs));
    if allow_credentials {
        layer = layer.allow_credentials(true);
    }
    layer
}

/// 解析方法字符串为 `AllowMethods`
fn parse_methods(methods: &str) -> AllowMethods {
    let mut list = Vec::new();
    for m in methods.split(',') {
        let m = m.trim();
        if let Ok(method) = m.parse::<axum::http::Method>() {
            list.push(method);
        }
    }
    AllowMethods::list(list)
}

/// 解析请求头字符串为 `AllowHeaders`
fn parse_headers(headers: &str) -> AllowHeaders {
    let mut list = Vec::new();
    for h in headers.split(',') {
        let h = h.trim();
        if let Ok(name) = HeaderName::from_bytes(h.as_bytes()) {
            list.push(name);
        }
    }
    AllowHeaders::list(list)
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{HeaderName, Method, Request};
    use axum::Router;
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    fn make_router(layer: CorsLayer) -> Router {
        Router::new()
            .route(
                "/api",
                axum::routing::get(|| async { "hello" }).post(|| async { "created" }),
            )
            .layer(layer)
    }

    async fn send_request(
        router: Router,
        method: &str,
        uri: &str,
        origin: Option<&str>,
    ) -> axum::response::Response {
        let mut builder = Request::builder().method(method).uri(uri);
        if let Some(o) = origin {
            builder = builder.header("origin", o);
        }
        let req = builder.body(Body::empty()).unwrap();
        router.oneshot(req).await.unwrap()
    }

    /// 发送 OPTIONS 预检请求,携带 `Access-Control-Request-Method` 和
    /// `Access-Control-Request-Headers`(对齐真实浏览器预检行为)
    async fn send_preflight(
        router: Router,
        uri: &str,
        origin: &str,
        request_method: &str,
        request_headers: &str,
    ) -> axum::response::Response {
        let req = Request::builder()
            .method("OPTIONS")
            .uri(uri)
            .header("origin", origin)
            .header("access-control-request-method", request_method)
            .header("access-control-request-headers", request_headers)
            .body(Body::empty())
            .unwrap();
        router.oneshot(req).await.unwrap()
    }

    // ====================================================================
    // cors_layer() 默认行为
    // ====================================================================

    #[tokio::test]
    async fn test_cors_layer_sets_allow_origin_wildcard() {
        let router = make_router(cors_layer());
        let resp = send_request(router, "GET", "/api", Some("https://example.com")).await;

        // 安全默认:Allow-Origin: *(通配,不携带凭证)
        let allow_origin = resp
            .headers()
            .get("access-control-allow-origin")
            .expect("missing Access-Control-Allow-Origin");
        assert_eq!(allow_origin, "*");
    }

    #[tokio::test]
    async fn test_cors_layer_no_credentials_by_default() {
        let router = make_router(cors_layer());
        let resp = send_request(router, "GET", "/api", Some("https://example.com")).await;

        // 安全默认:不设置 Allow-Credentials(避免任意网站携带用户凭证)
        assert!(
            resp.headers()
                .get("access-control-allow-credentials")
                .is_none(),
            "default cors_layer() must NOT set Allow-Credentials"
        );
    }

    #[tokio::test]
    async fn test_cors_layer_preflight_sets_methods() {
        let router = make_router(cors_layer());
        let resp = send_request(router, "OPTIONS", "/api", Some("https://example.com")).await;

        let methods = resp
            .headers()
            .get("access-control-allow-methods")
            .expect("missing Access-Control-Allow-Methods");
        let methods_str = methods.to_str().unwrap();
        assert!(methods_str.contains("GET"));
        assert!(methods_str.contains("POST"));
        assert!(methods_str.contains("PATCH"));
        assert!(methods_str.contains("PUT"));
        assert!(methods_str.contains("DELETE"));
        assert!(methods_str.contains("OPTIONS"));
    }

    #[tokio::test]
    async fn test_cors_layer_preflight_sets_headers() {
        let router = make_router(cors_layer());
        // 真实浏览器预检会带上 Access-Control-Request-Headers
        let resp = send_preflight(
            router,
            "/api",
            "https://example.com",
            "POST",
            "Authorization, Content-Type, X-Requested-With, X-CSRF-TOKEN",
        )
        .await;

        let headers = resp
            .headers()
            .get("access-control-allow-headers")
            .expect("missing Access-Control-Allow-Headers");
        // HTTP headers 大小写不敏感,统一转小写比较
        let headers_str = headers.to_str().unwrap().to_lowercase();
        assert!(headers_str.contains("authorization"));
        assert!(headers_str.contains("content-type"));
        assert!(headers_str.contains("x-requested-with"));
        assert!(headers_str.contains("x-csrf-token"));
    }

    #[tokio::test]
    async fn test_cors_layer_preflight_sets_max_age() {
        let router = make_router(cors_layer());
        let resp = send_request(router, "OPTIONS", "/api", Some("https://example.com")).await;

        let max_age = resp
            .headers()
            .get("access-control-max-age")
            .expect("missing Access-Control-Max-Age");
        assert_eq!(max_age, "1800");
    }

    #[tokio::test]
    async fn test_cors_layer_normal_request_passes_through() {
        let router = make_router(cors_layer());
        let resp = send_request(router, "GET", "/api", Some("https://example.com")).await;

        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&bytes[..], b"hello");
    }

    // ====================================================================
    // cors_layer_with_origin()
    // ====================================================================

    #[tokio::test]
    async fn test_cors_with_origin_empty_domain_allows_all() {
        // P1-SEC-11: 空字符串 cookie_domain 不再等价于通配(防止 credentials 泄漏)
        // 未配置白名单时应拒绝所有跨域请求
        let router = make_router(cors_layer_with_origin(""));
        let resp = send_request(router, "GET", "/api", Some("https://anything.com")).await;

        let allow_origin = resp.headers().get("access-control-allow-origin");
        assert!(
            allow_origin.is_none(),
            "P1-SEC-11: 空 cookie_domain 应拒绝所有 origin(不再回显)"
        );
    }

    #[tokio::test]
    async fn test_cors_with_origin_matching_domain_allows() {
        let router = make_router(cors_layer_with_origin("example.com"));
        let resp = send_request(router, "GET", "/api", Some("https://app.example.com")).await;

        let allow_origin = resp
            .headers()
            .get("access-control-allow-origin")
            .expect("missing Access-Control-Allow-Origin");
        assert_eq!(allow_origin, "https://app.example.com");
    }

    #[tokio::test]
    async fn test_cors_with_origin_non_matching_domain_blocks() {
        let router = make_router(cors_layer_with_origin("example.com"));
        let resp = send_request(router, "GET", "/api", Some("https://evil.com")).await;

        // 不匹配时不应设置 Allow-Origin
        assert!(resp.headers().get("access-control-allow-origin").is_none());
    }

    // ====================================================================
    // S-2 回归测试:origin 精确后缀匹配,阻止子串绕过
    // ====================================================================

    #[test]
    fn test_origin_matches_domain_exact() {
        assert!(origin_matches_domain("https://example.com", "example.com"));
        assert!(origin_matches_domain("http://example.com", "example.com"));
        assert!(origin_matches_domain("example.com", "example.com"));
    }

    #[test]
    fn test_origin_matches_domain_subdomain() {
        assert!(origin_matches_domain(
            "https://app.example.com",
            "example.com"
        ));
        assert!(origin_matches_domain(
            "https://a.b.example.com",
            "example.com"
        ));
    }

    #[test]
    fn test_origin_matches_domain_evil_substring_blocked() {
        // evil-example.com 不应匹配 example.com(原 PHP strpos 子串匹配会错误接受)
        assert!(!origin_matches_domain(
            "https://evil-example.com",
            "example.com"
        ));
        // example.com.evil.com 不应匹配 example.com
        assert!(!origin_matches_domain(
            "https://example.com.evil.com",
            "example.com"
        ));
        // notexample.com 不应匹配 example.com
        assert!(!origin_matches_domain(
            "https://notexample.com",
            "example.com"
        ));
    }

    #[test]
    fn test_origin_matches_domain_with_port() {
        assert!(origin_matches_domain(
            "https://example.com:8443",
            "example.com"
        ));
        assert!(origin_matches_domain(
            "https://app.example.com:8443",
            "example.com"
        ));
        // 端口不改变 host 后缀匹配规则
        assert!(!origin_matches_domain(
            "https://evil-example.com:8443",
            "example.com"
        ));
    }

    #[test]
    fn test_origin_matches_domain_ipv6() {
        // IPv6 地址用 [] 包裹,端口在 ] 之后
        assert!(origin_matches_domain("http://[::1]:8080", "::1"));
        assert!(!origin_matches_domain("http://[::2]:8080", "::1"));
    }

    #[test]
    fn test_origin_matches_domain_scheme_less() {
        // 无 scheme 的 Origin(罕见但应处理)
        assert!(origin_matches_domain("example.com", "example.com"));
        assert!(origin_matches_domain("app.example.com", "example.com"));
        assert!(!origin_matches_domain("evil-example.com", "example.com"));
    }

    #[tokio::test]
    async fn test_cors_with_origin_evil_substring_blocked() {
        // 端到端回归:evil-example.com 不应被 cors_layer_with_origin("example.com") 接受
        let router = make_router(cors_layer_with_origin("example.com"));
        let resp = send_request(router, "GET", "/api", Some("https://evil-example.com")).await;

        // 不匹配时不应设置 Allow-Origin
        assert!(
            resp.headers().get("access-control-allow-origin").is_none(),
            "evil-example.com must NOT match cookie_domain=example.com"
        );
    }

    #[tokio::test]
    async fn test_cors_with_origin_subdomain_allowed() {
        // 子域名应被允许
        let router = make_router(cors_layer_with_origin("example.com"));
        let resp = send_request(router, "GET", "/api", Some("https://app.example.com")).await;

        let allow_origin = resp
            .headers()
            .get("access-control-allow-origin")
            .expect("subdomain app.example.com should match cookie_domain=example.com");
        assert_eq!(allow_origin, "https://app.example.com");
    }

    // ====================================================================
    // cors_layer_with_config()
    // ====================================================================

    #[tokio::test]
    async fn test_cors_with_config_wildcard_no_credentials() {
        let layer =
            cors_layer_with_config(AllowOrigin::any(), false, "GET, POST", "Content-Type", 600);
        let router = make_router(layer);
        let resp = send_preflight(
            router,
            "/api",
            "https://example.com",
            "POST",
            "Content-Type",
        )
        .await;

        let allow_origin = resp
            .headers()
            .get("access-control-allow-origin")
            .expect("missing Access-Control-Allow-Origin");
        assert_eq!(allow_origin, "*");

        // 不带 credentials
        assert!(resp
            .headers()
            .get("access-control-allow-credentials")
            .is_none());

        let max_age = resp
            .headers()
            .get("access-control-max-age")
            .expect("missing Access-Control-Max-Age");
        assert_eq!(max_age, "600");
    }

    #[tokio::test]
    async fn test_cors_with_config_custom_methods_headers() {
        let layer = cors_layer_with_config(
            AllowOrigin::any(),
            false,
            "GET, POST, OPTIONS",
            "Authorization, Content-Type, X-Custom",
            3600,
        );
        let router = make_router(layer);
        let resp = send_preflight(
            router,
            "/api",
            "https://example.com",
            "POST",
            "Authorization, Content-Type, X-Custom",
        )
        .await;

        let methods = resp
            .headers()
            .get("access-control-allow-methods")
            .expect("missing methods");
        let methods_str = methods.to_str().unwrap();
        assert!(methods_str.contains("GET"));
        assert!(methods_str.contains("POST"));
        assert!(methods_str.contains("OPTIONS"));

        let headers = resp
            .headers()
            .get("access-control-allow-headers")
            .expect("missing headers");
        let headers_str = headers.to_str().unwrap().to_lowercase();
        assert!(headers_str.contains("authorization"));
        assert!(headers_str.contains("x-custom"));
    }

    // ====================================================================
    // 辅助函数测试
    // ====================================================================

    #[test]
    fn test_parse_methods_default() {
        let methods = parse_methods(DEFAULT_ALLOW_METHODS);
        // AllowMethods::list 不直接暴露内部,但通过 CorsLayer 应用到响应来验证
        // 这里仅验证不 panic
        let _ = methods;
    }

    #[test]
    fn test_parse_methods_empty() {
        let methods = parse_methods("");
        let _ = methods;
    }

    #[test]
    fn test_parse_methods_with_whitespace() {
        let methods = parse_methods("GET,  POST  , PATCH");
        let _ = methods;
    }

    #[test]
    fn test_parse_headers_default() {
        let headers = parse_headers(DEFAULT_ALLOW_HEADERS);
        let _ = headers;
    }

    #[test]
    fn test_parse_headers_empty() {
        let headers = parse_headers("");
        let _ = headers;
    }

    #[test]
    fn test_parse_headers_with_whitespace() {
        let headers = parse_headers("Authorization,  Content-Type  , X-Requested-With");
        let _ = headers;
    }

    #[test]
    fn test_default_allow_methods_constant() {
        assert!(DEFAULT_ALLOW_METHODS.contains("GET"));
        assert!(DEFAULT_ALLOW_METHODS.contains("POST"));
        assert!(DEFAULT_ALLOW_METHODS.contains("PATCH"));
        assert!(DEFAULT_ALLOW_METHODS.contains("PUT"));
        assert!(DEFAULT_ALLOW_METHODS.contains("DELETE"));
        assert!(DEFAULT_ALLOW_METHODS.contains("OPTIONS"));
    }

    #[test]
    fn test_default_allow_headers_constant() {
        assert!(DEFAULT_ALLOW_HEADERS.contains("Authorization"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("Content-Type"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("If-Match"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("If-Modified-Since"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("If-None-Match"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("If-Unmodified-Since"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("X-CSRF-TOKEN"));
        assert!(DEFAULT_ALLOW_HEADERS.contains("X-Requested-With"));
    }

    #[test]
    fn test_default_max_age_constant() {
        assert_eq!(DEFAULT_MAX_AGE, 1800);
    }

    // ====================================================================
    // 集成测试:与 PHP 行为对齐
    // ====================================================================

    #[tokio::test]
    async fn test_php_aligned_default_cors_headers() {
        // 对齐修复后的 CORS 安全配置:
        // - allow_origin: any()(允许任意来源,因为不携带凭证)
        // - allow_credentials: false(修复 P0 安全审计项:移除危险配置)
        let router = make_router(cors_layer());
        let resp = send_request(router, "OPTIONS", "/api", Some("https://example.com")).await;

        let headers = resp.headers();
        // 必须存在的 CORS 响应头
        assert!(headers.contains_key("access-control-allow-origin"));
        assert!(headers.contains_key("access-control-allow-methods"));
        assert!(headers.contains_key("access-control-allow-headers"));
        assert!(headers.contains_key("access-control-max-age"));
        // 修复后不应再返回 allow-credentials(已移除以避免任意跨域请求携带凭证)
        assert!(
            !headers.contains_key("access-control-allow-credentials"),
            "CORS 不应再返回 allow-credentials 头(安全修复)"
        );
    }

    #[tokio::test]
    async fn test_cors_layer_clonable() {
        // CorsLayer 必须 Clone + Send + Sync + 'static 才能用作 axum Layer
        let layer = cors_layer();
        let _cloned = layer.clone();
        fn assert_send_sync<T: Send + Sync + Clone + 'static>(_: T) {}
        assert_send_sync(layer);
    }

    #[tokio::test]
    async fn test_cors_no_origin_header_still_works() {
        // 无 Origin 头的请求也应正常处理
        let router = make_router(cors_layer());
        let resp = send_request(router, "GET", "/api", None).await;

        assert_eq!(resp.status(), axum::http::StatusCode::OK);
    }

    #[tokio::test]
    async fn test_cors_post_request_allowed() {
        let router = make_router(cors_layer());
        let resp = send_request(router, "POST", "/api", Some("https://example.com")).await;

        assert_eq!(resp.status(), axum::http::StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&bytes[..], b"created");
    }

    #[tokio::test]
    async fn test_cors_unknown_method_returns_405() {
        let router = make_router(cors_layer());

        // DELETE 未注册
        let builder = Request::builder()
            .method(Method::DELETE)
            .uri("/api")
            .header("origin", "https://example.com");
        let req = builder.body(Body::empty()).unwrap();
        let resp = router.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), axum::http::StatusCode::METHOD_NOT_ALLOWED);
    }

    #[test]
    fn test_header_name_constants_match_php() {
        // 验证 PHP header 名称都能解析
        let names = [
            "Access-Control-Allow-Origin",
            "Access-Control-Allow-Credentials",
            "Access-Control-Allow-Methods",
            "Access-Control-Allow-Headers",
            "Access-Control-Max-Age",
        ];
        for name in &names {
            assert!(
                HeaderName::from_bytes(name.as_bytes()).is_ok(),
                "invalid header name: {name}"
            );
        }
    }

    // ========================================================================
    // P1-SEC-11:空 cookie_domain 时不反射 origin + credentials
    // ========================================================================

    /// P1-SEC-11 回归测试:cookie_domain 为空时,任意 origin 请求不应获得
    /// Access-Control-Allow-Origin 响应头(防止 credentials 泄漏)
    #[tokio::test]
    async fn test_p1_sec_11_empty_cookie_domain_rejects_all_origins() {
        let layer = cors_layer_with_origin(""); // 空白名单
        let router = make_router(layer);

        // 恶意站点发起的跨域请求
        let resp = send_request(router, "GET", "/api", Some("https://evil.com")).await;
        let allow_origin = resp.headers().get("access-control-allow-origin");

        assert!(
            allow_origin.is_none(),
            "P1-SEC-11: 空 cookie_domain 时不应回显任何 origin(否则 credentials 可被恶意站点利用)\n\
             实际返回: {:?}",
            allow_origin
        );
    }

    /// P1-SEC-11 回归测试:cookie_domain 配置后,白名单内 origin 应通过
    #[tokio::test]
    async fn test_p1_sec_11_whitelisted_origin_allowed() {
        let layer = cors_layer_with_origin("example.com");
        let router = make_router(layer);

        let resp = send_request(router, "GET", "/api", Some("https://example.com")).await;
        let allow_origin = resp.headers().get("access-control-allow-origin");

        assert!(
            allow_origin.is_some(),
            "P1-SEC-11: 白名单内的 origin 应被允许"
        );
        assert_eq!(
            allow_origin.unwrap().to_str().unwrap(),
            "https://example.com"
        );
    }

    /// P1-SEC-11 回归测试:子域名匹配(*.example.com)应通过
    #[tokio::test]
    async fn test_p1_sec_11_subdomain_match_allowed() {
        let layer = cors_layer_with_origin("example.com");
        let router = make_router(layer);

        let resp = send_request(router, "GET", "/api", Some("https://api.example.com")).await;
        let allow_origin = resp.headers().get("access-control-allow-origin");

        assert!(allow_origin.is_some(), "子域名应匹配白名单");
        assert_eq!(
            allow_origin.unwrap().to_str().unwrap(),
            "https://api.example.com"
        );
    }

    /// P1-SEC-11 回归测试:恶意子域名绕过(evil-example.com)应被拒绝
    #[tokio::test]
    async fn test_p1_sec_11_evil_subdomain_rejected() {
        let layer = cors_layer_with_origin("example.com");
        let router = make_router(layer);

        let resp = send_request(router, "GET", "/api", Some("https://evil-example.com")).await;
        let allow_origin = resp.headers().get("access-control-allow-origin");

        assert!(
            allow_origin.is_none(),
            "P1-SEC-11: evil-example.com 不应匹配 example.com 白名单(后缀匹配防护)"
        );
    }
}