garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! axum 适配器模块。
//!
//! 实现 `GarrisonContext` / `GarrisonRequest` / `GarrisonResponse` / `GarrisonStorage` trait,
//! 将 Garrison 鉴权逻辑与 axum Web 框架解耦。

use crate::config::GarrisonConfig;
use crate::context::token_extract::{extract_token_from_request_parts, parse_cookie_value};
use crate::context::{GarrisonContext, GarrisonRequest, GarrisonResponse, GarrisonStorage};
use crate::error::{GarrisonError, GarrisonResult};
use axum::body::Body;
use axum::http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode};
use std::collections::HashMap;

// AxumRequest:包装 &http::Request<Body>

/// axum 请求适配器,包装 `&http::Request<Body>`。
pub struct AxumRequest<'a> {
    request: &'a Request<Body>,
    /// 预读的 body 字节(`is_read_body=true` 时从 JSON 提取 token);默认空 `Vec`,此时 body 分支跳过。
    ///
    /// body 读取是 async 操作而 `get_token` 是 sync 方法,故由调用方在 async 上下文中预读后经 `with_body` 注入。
    body_bytes: Vec<u8>,
}

impl<'a> AxumRequest<'a> {
    /// 创建新的 AxumRequest(body 为空,不读取 body)。
    pub fn new(request: &'a Request<Body>) -> Self {
        Self::with_body(request, Vec::new())
    }

    /// 创建带预读 body 的 AxumRequest(`is_read_body=true` 场景,body 由调用方在 async 上下文读取)。
    pub fn with_body(request: &'a Request<Body>, body_bytes: Vec<u8>) -> Self {
        Self {
            request,
            body_bytes,
        }
    }
}

impl<'a> GarrisonRequest for AxumRequest<'a> {
    fn path(&self) -> GarrisonResult<String> {
        Ok(self.request.uri().path().to_string())
    }

    fn method(&self) -> GarrisonResult<String> {
        Ok(self.request.method().as_str().to_string())
    }

    fn header(&self, name: &str) -> GarrisonResult<Option<String>> {
        let header_name: HeaderName = name.parse().map_err(|e| {
            GarrisonError::Context(format!("ctx-invalid-header-name::{}::{}", name, e))
        })?;
        Ok(self
            .request
            .headers()
            .get(header_name)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string()))
    }

    fn cookie(&self, name: &str) -> GarrisonResult<Option<String>> {
        let cookie_header = self
            .request
            .headers()
            .get(axum::http::header::COOKIE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        Ok(parse_cookie_value(cookie_header, name))
    }

    fn get_token(&self, config: &GarrisonConfig) -> GarrisonResult<Option<String>> {
        extract_token_from_request_parts(
            config,
            &self.body_bytes,
            self.request.method().as_str(),
            |name| self.header(name),
            |name| self.cookie(name),
        )
    }
}

// AxumResponse:持有 HeaderMap + StatusCode

/// axum 响应适配器,持有 HeaderMap 与 StatusCode,`to_response()` 转换为 axum Response。
pub struct AxumResponse {
    headers: HeaderMap,
    status: StatusCode,
}

impl AxumResponse {
    /// 创建新的 AxumResponse(默认 200 OK)。
    pub fn new() -> Self {
        Self {
            headers: HeaderMap::new(),
            status: StatusCode::OK,
        }
    }
}

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

impl AxumResponse {
    /// 转换为 axum Response(空 body,携带当前 `HeaderMap` 与 `StatusCode`)。
    pub fn to_response(self) -> axum::response::Response {
        let mut response = axum::response::Response::new(Body::empty());
        *response.status_mut() = self.status;
        *response.headers_mut() = self.headers;
        response
    }
}

impl GarrisonResponse for AxumResponse {
    fn set_status(&mut self, code: u16) -> GarrisonResult<()> {
        self.status = StatusCode::from_u16(code).map_err(|e| {
            GarrisonError::Context(format!("ctx-invalid-status-code::{}::{}", code, e))
        })?;
        Ok(())
    }

    fn set_header(&mut self, name: &str, value: &str) -> GarrisonResult<()> {
        let header_name: HeaderName = name.parse().map_err(|e| {
            GarrisonError::Context(format!("ctx-invalid-header-name::{}::{}", name, e))
        })?;
        let header_value = HeaderValue::from_str(value).map_err(|e| {
            GarrisonError::Context(format!("ctx-invalid-header-value::{}::{}", value, e))
        })?;
        self.headers.insert(header_name, header_value);
        Ok(())
    }
}

// AxumStorage:HashMap<String, String>

/// axum 存储适配器,用 HashMap 实现请求级临时存储。
pub struct AxumStorage {
    map: HashMap<String, String>,
}

impl AxumStorage {
    /// 创建新的 AxumStorage。
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }
}

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

impl GarrisonStorage for AxumStorage {
    fn set(&mut self, key: &str, value: &str) -> GarrisonResult<()> {
        self.map.insert(key.to_string(), value.to_string());
        Ok(())
    }

    fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
        Ok(self.map.get(key).cloned())
    }

    fn delete(&mut self, key: &str) -> GarrisonResult<()> {
        self.map.remove(key);
        Ok(())
    }
}

// AxumContext:组合 Request + Response

/// axum 上下文适配器,组合 Request 引用 + Response:仅持有 `&Request<Body>` 与 `AxumResponse`,
/// 经 `into_response()` 消费 context 生成 axum Response。
///
/// 不提供 `response()` / `storage()` trait 方法(返回新实例违反 trait 契约)。
pub struct AxumContext<'a> {
    request: &'a Request<Body>,
    response: AxumResponse,
    /// 预读的 body 字节(`is_read_body=true` 时从 JSON 提取 token)。
    body_bytes: Vec<u8>,
}

impl<'a> AxumContext<'a> {
    /// 创建新的 AxumContext,绑定到指定请求(body 为空,不读取 body)。
    pub fn new(request: &'a Request<Body>) -> Self {
        Self {
            request,
            response: AxumResponse::new(),
            body_bytes: Vec::new(),
        }
    }

    /// 创建带预读 body 的 AxumContext(`is_read_body=true` 场景,body 由调用方在 async 上下文读取)。
    pub fn with_body(request: &'a Request<Body>, body_bytes: Vec<u8>) -> Self {
        Self {
            request,
            response: AxumResponse::new(),
            body_bytes,
        }
    }

    /// 获取底层请求引用,用于直接访问 axum 原生请求字段。
    pub fn raw_request(&self) -> &Request<Body> {
        self.request
    }

    /// 获取底层响应的不可变引用(用于读取已设置的 headers / status)。
    pub fn raw_response(&self) -> &AxumResponse {
        &self.response
    }

    /// 获取底层响应的可变引用(用于设置 status / headers / cookies)。
    pub fn raw_response_mut(&mut self) -> &mut AxumResponse {
        &mut self.response
    }

    /// 消费 context,生成 axum Response(携带已设置的 status 与 headers)。
    pub fn into_response(self) -> axum::response::Response {
        self.response.to_response()
    }
}

impl<'a> GarrisonContext for AxumContext<'a> {
    fn request(&self) -> GarrisonResult<Box<dyn GarrisonRequest>> {
        // Box<dyn GarrisonRequest> 不能带生命周期参数,故克隆必要数据
        Ok(Box::new(AxumRequestWrapper::with_body(
            self.request,
            self.body_bytes.clone(),
        )))
    }
}

/// AxumRequest 包装器(绕过 `Box<dyn>` 的生命周期问题):持有 HeaderMap + Method + Uri 的克隆。
///
/// 不持有 `Request<Body>`,因 Body 不可克隆。
struct AxumRequestWrapper {
    headers: HeaderMap,
    method: String,
    uri: String,
    /// 预读的 body 字节(用于 `is_read_body=true` 时从 JSON 提取 token)。
    body_bytes: Vec<u8>,
}

impl AxumRequestWrapper {
    fn with_body(req: &Request<Body>, body_bytes: Vec<u8>) -> Self {
        Self {
            headers: req.headers().clone(),
            method: req.method().as_str().to_string(),
            uri: req.uri().to_string(),
            body_bytes,
        }
    }
}

impl GarrisonRequest for AxumRequestWrapper {
    fn path(&self) -> GarrisonResult<String> {
        Ok(self.uri.split('?').next().unwrap_or(&self.uri).to_string())
    }

    fn method(&self) -> GarrisonResult<String> {
        Ok(self.method.clone())
    }

    fn header(&self, name: &str) -> GarrisonResult<Option<String>> {
        let header_name: HeaderName = name.parse().map_err(|e| {
            GarrisonError::Context(format!("ctx-invalid-header-name::{}::{}", name, e))
        })?;
        Ok(self
            .headers
            .get(header_name)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string()))
    }

    fn cookie(&self, name: &str) -> GarrisonResult<Option<String>> {
        let cookie_header = self
            .headers
            .get(axum::http::header::COOKIE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        Ok(parse_cookie_value(cookie_header, name))
    }

    fn get_token(&self, config: &GarrisonConfig) -> GarrisonResult<Option<String>> {
        extract_token_from_request_parts(
            config,
            &self.body_bytes,
            &self.method,
            |name| self.header(name),
            |name| self.cookie(name),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::Request;

    /// 构建测试用 Request<Body>(空 body)。
    fn make_request(uri: &str, method: &str, headers: &[(&str, &str)]) -> Request<Body> {
        let mut builder = Request::builder().method(method).uri(uri);
        for (name, value) in headers {
            builder = builder.header(*name, *value);
        }
        builder.body(Body::empty()).unwrap()
    }

    /// 构建带 body 的 Request<Body>(用于 body 读取测试)。
    fn make_request_with_body(
        uri: &str,
        method: &str,
        headers: &[(&str, &str)],
        body: &str,
    ) -> Request<Body> {
        let mut builder = Request::builder().method(method).uri(uri);
        for (name, value) in headers {
            builder = builder.header(*name, *value);
        }
        builder.body(Body::from(body.to_string())).unwrap()
    }

    // AxumRequest 测试
    /// 验证 path() 返回请求路径。
    #[test]
    fn axum_request_path() {
        let req = make_request("/api/users?id=1", "GET", &[]);
        let axum_req = AxumRequest::new(&req);
        assert_eq!(axum_req.path().unwrap(), "/api/users");
    }

    /// 验证 method() 返回请求方法。
    #[test]
    fn axum_request_method() {
        let req = make_request("/", "POST", &[]);
        let axum_req = AxumRequest::new(&req);
        assert_eq!(axum_req.method().unwrap(), "POST");
    }

    /// 验证 header() 返回请求头。
    #[test]
    fn axum_request_header() {
        let req = make_request("/", "GET", &[("X-Token", "abc123")]);
        let axum_req = AxumRequest::new(&req);
        assert_eq!(
            axum_req.header("X-Token").unwrap(),
            Some("abc123".to_string())
        );
        assert_eq!(axum_req.header("Not-Exist").unwrap(), None);
    }

    /// 验证 cookie() 解析 Cookie header。
    #[test]
    fn axum_request_cookie() {
        let req = make_request(
            "/",
            "GET",
            &[("Cookie", "garrison_token=tok123; other=val")],
        );
        let axum_req = AxumRequest::new(&req);
        assert_eq!(
            axum_req.cookie("garrison_token").unwrap(),
            Some("tok123".to_string())
        );
        assert_eq!(axum_req.cookie("other").unwrap(), Some("val".to_string()));
        assert_eq!(axum_req.cookie("missing").unwrap(), None);
    }

    // get_token 测试(GarrisonRequest)
    /// 验证从 Authorization: Bearer 提取 token。
    #[test]
    fn get_token_from_bearer_header() {
        let req = make_request("/", "GET", &[("Authorization", "Bearer my_token_123")]);
        let axum_req = AxumRequest::new(&req);
        let config = GarrisonConfig::default_config();
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(token, Some("my_token_123".to_string()));
    }

    /// Bearer 前缀大小写不敏感(RFC 7235):`bearer` / `BEARER` / `BeArEr` 均应能提取 token。
    #[test]
    fn bearer_prefix_case_insensitive() {
        let config = GarrisonConfig::default_config();
        for prefix in &["Bearer", "bearer", "BEARER", "BeArEr"] {
            let auth_value = format!("{} tok_{}", prefix, prefix);
            let req = make_request("/", "GET", &[("Authorization", auth_value.as_str())]);
            let axum_req = AxumRequest::new(&req);
            let token = axum_req.get_token(&config).unwrap();
            assert_eq!(
                token,
                Some(format!("tok_{}", prefix)),
                "前缀 '{}' 应能提取 token(大小写不敏感)",
                prefix
            );
        }
    }

    /// 验证从自定义 header 提取 token。
    #[test]
    fn get_token_from_custom_header() {
        let req = make_request("/", "GET", &[("garrison_token", "header_token_456")]);
        let axum_req = AxumRequest::new(&req);
        let config = GarrisonConfig::default_config();
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(token, Some("header_token_456".to_string()));
    }

    /// 验证从 cookie 提取 token。
    #[test]
    fn get_token_from_cookie() {
        let config = GarrisonConfig::default_config();
        let cookie_value = format!(
            "{}=cookie_token_789",
            crate::context::token_cookie_name(&config)
        );
        let req = make_request("/", "GET", &[("Cookie", cookie_value.as_str())]);
        let axum_req = AxumRequest::new(&req);
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(token, Some("cookie_token_789".to_string()));
    }

    /// 验证 header 优先级高于 cookie。
    #[test]
    fn get_token_header_priority_over_cookie() {
        let config = GarrisonConfig::default_config();
        let cookie_value = format!(
            "{}=cookie_token",
            crate::context::token_cookie_name(&config)
        );
        let req = make_request(
            "/",
            "GET",
            &[
                ("Authorization", "Bearer header_token"),
                ("Cookie", cookie_value.as_str()),
            ],
        );
        let axum_req = AxumRequest::new(&req);
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(token, Some("header_token".to_string()));
    }

    /// 验证无 token 时返回 None。
    #[test]
    fn get_token_returns_none_when_missing() {
        let req = make_request("/", "GET", &[]);
        let axum_req = AxumRequest::new(&req);
        let config = GarrisonConfig::default_config();
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(token, None);
    }

    /// 验证 is_read_header=false 时不从 header 提取。
    #[test]
    fn get_token_skips_header_when_disabled() {
        let req = make_request("/", "GET", &[("Authorization", "Bearer header_token")]);
        let axum_req = AxumRequest::new(&req);
        let mut config = GarrisonConfig::default_config();
        config.is_read_header = false;
        config.is_read_cookie = false;
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(token, None);
    }

    // AxumResponse 测试(GarrisonResponse)
    /// 验证 set_status 设置状态码。
    #[test]
    fn response_set_status() {
        let mut resp = AxumResponse::new();
        resp.set_status(401).unwrap();
        assert_eq!(resp.status, StatusCode::UNAUTHORIZED);
    }

    /// 验证 set_header 设置响应头。
    #[test]
    fn response_set_header() {
        let mut resp = AxumResponse::new();
        resp.set_header("Authorization", "my_token").unwrap();
        assert_eq!(
            resp.headers
                .get("Authorization")
                .and_then(|v| v.to_str().ok()),
            Some("my_token")
        );
    }

    /// 验证 set_cookie 设置安全属性(HttpOnly + Secure + SameSite=Lax + Path=/)。
    #[test]
    fn response_set_cookie() {
        let mut resp = AxumResponse::new();
        resp.set_cookie("garrison_token", "cookie_value").unwrap();
        let set_cookie = resp
            .headers
            .get("Set-Cookie")
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert!(set_cookie.contains("garrison_token=cookie_value"));
        assert!(set_cookie.contains("HttpOnly"));
        assert!(set_cookie.contains("Secure"));
        assert!(set_cookie.contains("SameSite=Lax"));
        assert!(set_cookie.contains("Path=/"));
    }

    /// 含 `;`、控制字符等非法字符的 cookie name/value 必须被拒绝,不得拼入 Set-Cookie 头(防属性注入)。
    #[test]
    fn response_set_cookie_rejects_injection() {
        let mut resp = AxumResponse::new();
        let result = resp.set_cookie("token", "abc; Domain=evil.com");
        assert!(
            matches!(result, Err(GarrisonError::Context(_))),
            "value 含 ';' 应返回错误,实际: {:?}",
            result.map(|_| ())
        );
        let result = resp.set_cookie("to;ken", "v");
        assert!(matches!(result, Err(GarrisonError::Context(_))));
        let result = resp.set_cookie("token", "bad\nvalue");
        assert!(matches!(result, Err(GarrisonError::Context(_))));
        // 空格与逗号
        let result = resp.set_cookie("token", "a b");
        assert!(matches!(result, Err(GarrisonError::Context(_))));
        let result = resp.set_cookie("token", "a,b");
        assert!(matches!(result, Err(GarrisonError::Context(_))));
        // 被拒绝的调用不得写入任何 Set-Cookie 头
        assert!(
            resp.headers.get("Set-Cookie").is_none(),
            "校验失败时不应产生 Set-Cookie 头"
        );
        // 合法值不受影响
        let mut resp2 = AxumResponse::new();
        assert!(resp2.set_cookie("token", "abc123_def-.~").is_ok());
    }

    /// 验证 set_cookie_with_config 依据 config 调整 Secure/SameSite(dev 场景关闭 Secure)。
    #[test]
    fn response_set_cookie_with_config_dev() {
        let mut resp = AxumResponse::new();
        let mut config = GarrisonConfig::default_config();
        config.cookie_secure = false;
        config.cookie_same_site = "Strict".to_string();
        resp.set_cookie_with_config("token", "v", &config).unwrap();
        let set_cookie = resp
            .headers
            .get("Set-Cookie")
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert!(set_cookie.contains("HttpOnly"));
        assert!(!set_cookie.contains("Secure"));
        assert!(set_cookie.contains("SameSite=Strict"));
    }

    /// set_cookie_with_config 在 SameSite=None + 非 Secure 上下文下降级为 Lax(浏览器拒收不带 Secure 的 None)。
    #[test]
    fn response_set_cookie_none_insecure_downgrades_to_lax() {
        let mut resp = AxumResponse::new();
        let mut config = GarrisonConfig::default_config();
        config.cookie_secure = false;
        config.cookie_same_site = "None".to_string();
        resp.set_cookie_with_config("token", "v", &config).unwrap();
        let set_cookie = resp
            .headers
            .get("Set-Cookie")
            .and_then(|v| v.to_str().ok())
            .unwrap();
        assert!(
            set_cookie.contains("SameSite=Lax"),
            "应降级为 SameSite=Lax,实际: {}",
            set_cookie
        );
        assert!(
            !set_cookie.contains("SameSite=None"),
            "不得输出 SameSite=None,实际: {}",
            set_cookie
        );
        assert!(!set_cookie.contains("Secure"), "实际: {}", set_cookie);
        assert!(
            !set_cookie.contains("__Host-") && !set_cookie.contains("__Secure-"),
            "http 降级无前缀,实际: {}",
            set_cookie
        );
    }

    /// 验证 to_response 转换为 axum Response。
    #[test]
    fn response_to_axum_response() {
        let mut resp = AxumResponse::new();
        resp.set_status(403).unwrap();
        resp.set_header("X-Custom", "test").unwrap();
        let axum_resp = resp.to_response();
        assert_eq!(axum_resp.status(), StatusCode::FORBIDDEN);
        assert_eq!(
            axum_resp
                .headers()
                .get("X-Custom")
                .and_then(|v| v.to_str().ok()),
            Some("test")
        );
    }

    /// 验证非法状态码抛错。
    #[test]
    fn response_invalid_status_errors() {
        let mut resp = AxumResponse::new();
        // from_u16 接受任意 u16(含非标准状态码),此处仅验证合法值不抛错
        assert!(resp.set_status(200).is_ok());
        assert!(resp.set_status(500).is_ok());
    }

    /// 验证非法 header name 抛错。
    #[test]
    fn response_invalid_header_name_errors() {
        let mut resp = AxumResponse::new();
        // header name 不能包含空格
        let result = resp.set_header("invalid header", "value");
        assert!(
            matches!(result, Err(GarrisonError::Context(_))),
            "无效 header name 应返回 Context 错误,实际: {:?}",
            result
        );
    }

    // AxumStorage 测试(GarrisonStorage)
    /// 验证 set/get 存储数据。
    #[test]
    fn storage_set_get() {
        let mut storage = AxumStorage::new();
        storage.set("trace_id", "abc-123").unwrap();
        assert_eq!(
            storage.get("trace_id").unwrap(),
            Some("abc-123".to_string())
        );
    }

    /// 验证 delete 删除存储数据。
    #[test]
    fn storage_delete() {
        let mut storage = AxumStorage::new();
        storage.set("key1", "value1").unwrap();
        storage.delete("key1").unwrap();
        assert_eq!(storage.get("key1").unwrap(), None);
    }

    /// 验证请求间隔离:两个独立 storage 互不影响。
    #[test]
    fn storage_request_isolation() {
        let mut storage_a = AxumStorage::new();
        storage_a.set("trace_id", "A").unwrap();

        let mut storage_b = AxumStorage::new();
        storage_b.set("trace_id", "B").unwrap();

        assert_eq!(storage_a.get("trace_id").unwrap(), Some("A".to_string()));
        assert_eq!(storage_b.get("trace_id").unwrap(), Some("B".to_string()));
    }

    /// 验证不存在的 key 返回 None。
    #[test]
    fn storage_missing_key_returns_none() {
        let storage = AxumStorage::new();
        assert_eq!(storage.get("missing").unwrap(), None);
    }

    // AxumContext 测试
    /// 验证 AxumContext 创建并访问 request/response/storage。
    #[test]
    fn context_creation() {
        let req = make_request("/api/test", "GET", &[("X-Test", "value")]);
        let ctx = AxumContext::new(&req);
        assert_eq!(ctx.raw_request().uri().path(), "/api/test");
    }

    /// 验证 GarrisonContext trait 实现。
    #[test]
    fn context_trait_impl() {
        let req = make_request("/", "GET", &[("Authorization", "Bearer abc")]);
        let ctx = AxumContext::new(&req);

        let request = ctx.request().unwrap();
        let config = GarrisonConfig::default_config();
        let token = request.get_token(&config).unwrap();
        assert_eq!(token, Some("abc".to_string()));

        let mut ctx = ctx;
        ctx.raw_response_mut().set_status(403).unwrap();
        ctx.raw_response_mut().set_header("X-Trace", "v").unwrap();
        let resp = ctx.into_response();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    // AxumRequest 错误分支与边界测试
    /// 验证 AxumRequest::header() 在 header name 非法时返回 Context 错误。
    #[test]
    fn axum_request_header_invalid_name_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let req = make_request("/", "GET", &[]);
        let axum_req = AxumRequest::new(&req);
        let result = axum_req.header("invalid header");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, GarrisonError::Context(_)));
        assert!(err.to_string().contains("非法 header 名称"));
    }

    /// 验证 AxumRequest::cookie() 在没有 Cookie header 时返回 None(空 header 分支)。
    #[test]
    fn axum_request_cookie_empty_header_returns_none() {
        let req = make_request("/", "GET", &[]);
        let axum_req = AxumRequest::new(&req);
        assert_eq!(axum_req.cookie("any").unwrap(), None);
    }

    /// 验证 AxumRequest::cookie() 跳过没有 '=' 的 cookie 项。
    #[test]
    fn axum_request_cookie_skips_pair_without_equals() {
        let req = make_request("/", "GET", &[("Cookie", "invalidpair; valid=val")]);
        let axum_req = AxumRequest::new(&req);
        assert_eq!(axum_req.cookie("valid").unwrap(), Some("val".to_string()));
        assert_eq!(axum_req.cookie("invalidpair").unwrap(), None);
    }

    // AxumResponse 错误分支与 Default 实现测试
    /// 验证 AxumResponse::set_status() 在状态码非法(> 999)时返回 Context 错误。
    #[test]
    fn axum_response_set_status_invalid_code_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let mut resp = AxumResponse::new();
        let result = resp.set_status(1000);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, GarrisonError::Context(_)));
        assert!(err.to_string().contains("非法状态码"));
    }

    /// 验证 AxumResponse::set_header() 在 header value 非法时返回 Context 错误。
    #[test]
    fn axum_response_set_header_invalid_value_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let mut resp = AxumResponse::new();
        let result = resp.set_header("X-Test", "bad\0value");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, GarrisonError::Context(_)));
        assert!(err.to_string().contains("非法 header 值"));
    }

    /// 验证 AxumResponse::default() 等价于 new(),状态码为 200 OK 且 headers 为空。
    #[test]
    fn axum_response_default_impl() {
        let resp = AxumResponse::default();
        assert_eq!(resp.status, StatusCode::OK);
        assert!(resp.headers.is_empty());
    }

    /// 验证 AxumStorage::default() 等价于 new(),返回空 storage。
    #[test]
    fn axum_storage_default_impl() {
        let storage = AxumStorage::default();
        assert_eq!(storage.get("any").unwrap(), None);
    }

    // AxumRequestWrapper 测试(通过 AxumContext::request() 访问)
    /// 验证 AxumContext::request() 返回的 wrapper 正确提取 path(去掉 query string)。
    #[test]
    fn axum_context_wrapper_path_strips_query() {
        let req = make_request("/api/v1/users?page=2&size=10", "GET", &[]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(request.path().unwrap(), "/api/v1/users");
    }

    /// 验证 AxumContext::request() 返回的 wrapper 正确返回 method。
    #[test]
    fn axum_context_wrapper_method() {
        let req = make_request("/", "PUT", &[]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(request.method().unwrap(), "PUT");
    }

    /// 验证 AxumContext::request() 返回的 wrapper 正确读取 header(命中与未命中)。
    #[test]
    fn axum_context_wrapper_header() {
        let req = make_request("/", "GET", &[("X-Custom", "hello"), ("X-Other", "world")]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(
            request.header("X-Custom").unwrap(),
            Some("hello".to_string())
        );
        assert_eq!(
            request.header("X-Other").unwrap(),
            Some("world".to_string())
        );
        assert_eq!(request.header("Missing").unwrap(), None);
    }

    /// 验证 AxumContext::request() 返回的 wrapper 在 header name 非法时返回 Context 错误。
    #[test]
    fn axum_context_wrapper_header_invalid_name_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let req = make_request("/", "GET", &[]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        let result = request.header("bad name");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, GarrisonError::Context(_)));
        assert!(err.to_string().contains("非法 header 名称"));
    }

    /// 验证 AxumContext::request() 返回的 wrapper 在没有 Cookie header 时返回 None。
    #[test]
    fn axum_context_wrapper_cookie_no_header_returns_none() {
        let req = make_request("/", "GET", &[]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(request.cookie("any").unwrap(), None);
    }

    /// 验证 AxumContext::request() 返回的 wrapper 解析 Cookie header(命中与未命中)。
    #[test]
    fn axum_context_wrapper_cookie_found() {
        let req = make_request("/", "GET", &[("Cookie", "session=abc; user=xyz")]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(request.cookie("session").unwrap(), Some("abc".to_string()));
        assert_eq!(request.cookie("user").unwrap(), Some("xyz".to_string()));
        assert_eq!(request.cookie("missing").unwrap(), None);
    }

    /// 验证 AxumContext::request() 返回的 wrapper 跳过没有 '=' 的 cookie 项。
    #[test]
    fn axum_context_wrapper_cookie_skips_pair_without_equals() {
        let req = make_request("/", "GET", &[("Cookie", "invalidpair; valid=val")]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(request.cookie("valid").unwrap(), Some("val".to_string()));
        assert_eq!(request.cookie("invalidpair").unwrap(), None);
    }

    /// 验证 AxumContext::request() 返回的 wrapper 从 cookie 提取 token。
    #[test]
    fn axum_context_wrapper_get_token_from_cookie() {
        let mut config = GarrisonConfig::default_config();
        let cookie_value = format!("{}=cookie_tok", crate::context::token_cookie_name(&config));
        let req = make_request("/", "GET", &[("Cookie", cookie_value.as_str())]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        // 关闭 header 读取,强制走 cookie 路径以覆盖 wrapper 的 cookie 分支
        config.is_read_header = false;
        config.is_read_cookie = true;
        let token = request.get_token(&config).unwrap();
        assert_eq!(token, Some("cookie_tok".to_string()));
    }

    /// 验证 AxumContext::request() 返回的 wrapper 在无 token 时返回 None。
    #[test]
    fn axum_context_wrapper_get_token_returns_none() {
        let req = make_request("/", "GET", &[]);
        let ctx = AxumContext::new(&req);
        let request = ctx.request().unwrap();
        let config = GarrisonConfig::default_config();
        let token = request.get_token(&config).unwrap();
        assert_eq!(token, None);
    }

    /// wrapper 从 Authorization: Bearer 提取 token 时大小写不敏感(RFC 7235)。
    #[test]
    fn axum_context_wrapper_bearer_case_insensitive() {
        let config = GarrisonConfig::default_config();
        for prefix in ["Bearer", "bearer", "BEARER", "BeArEr"] {
            let header_value = format!("{} my_token_123", prefix);
            let req = make_request("/", "GET", &[("Authorization", &header_value)]);
            let ctx = AxumContext::new(&req);
            let request = ctx.request().unwrap();
            let token = request.get_token(&config).unwrap();
            assert_eq!(
                token,
                Some("my_token_123".to_string()),
                "prefix '{}' should extract token (RFC 7235 case-insensitive)",
                prefix
            );
        }
    }

    // AxumContext::raw_response_mut() / into_response() 测试
    /// 验证 AxumContext::raw_response_mut() 返回可写的内部 response 引用。
    #[test]
    fn axum_context_raw_response_mut_writable() {
        let req = make_request("/", "GET", &[]);
        let mut ctx = AxumContext::new(&req);
        ctx.raw_response_mut().set_status(404).unwrap();
        ctx.raw_response_mut()
            .set_header("X-Trace", "trace-123")
            .unwrap();
        assert_eq!(ctx.raw_response().status, StatusCode::NOT_FOUND);
        let resp = ctx.into_response();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            resp.headers().get("X-Trace").and_then(|v| v.to_str().ok()),
            Some("trace-123")
        );
    }

    /// 验证 AxumContext::into_response() 转换为 axum Response(默认 200 OK)。
    #[test]
    fn axum_context_into_response_default() {
        let req = make_request("/", "GET", &[]);
        let ctx = AxumContext::new(&req);
        let response = ctx.into_response();
        assert_eq!(response.status(), StatusCode::OK);
    }

    // body 读取分支测试(is_read_body=true)
    /// `is_read_body=true` 且 header/cookie 无 token 时从 body JSON(`{"token": "abc123"}`)提取 token。
    ///
    /// 优先级:header > cookie > body。
    #[test]
    fn extract_token_from_body_when_is_read_body_true() {
        let body_str = r#"{"token": "abc123"}"#;
        let req = make_request_with_body(
            "/",
            "POST",
            &[("Content-Type", "application/json")],
            body_str,
        );
        let ctx = AxumContext::with_body(&req, body_str.as_bytes().to_vec());
        let request = ctx.request().unwrap();
        let mut config = GarrisonConfig::default_config();
        config.is_read_body = true;
        config.token_name = "token".to_string();
        let token = request.get_token(&config).unwrap();
        assert_eq!(
            token,
            Some("abc123".to_string()),
            "is_read_body=true 且 body 含 token 字段时应提取到 token"
        );
    }

    /// `is_read_body=true` 但 body 无 token 字段时回退到 header 读取(优先级:header > cookie > body)。
    #[test]
    fn extract_token_fallback_to_header_when_body_empty() {
        let body_str = r#"{"other": "value"}"#;
        let req = make_request_with_body(
            "/",
            "POST",
            &[
                ("Content-Type", "application/json"),
                ("Authorization", "Bearer header_tok_456"),
            ],
            body_str,
        );
        let ctx = AxumContext::with_body(&req, body_str.as_bytes().to_vec());
        let request = ctx.request().unwrap();
        let mut config = GarrisonConfig::default_config();
        config.is_read_body = true;
        config.token_name = "token".to_string();
        let token = request.get_token(&config).unwrap();
        assert_eq!(
            token,
            Some("header_tok_456".to_string()),
            "body 无 token 字段时应回退到 header 读取"
        );
    }

    // C7: body token 提取方法限制测试(防 body 注入攻击)
    /// C7: GET 方法 + body 含 token 应跳过 body 提取(否则攻击者可经 `<img src="...?token=...">` 注入)。
    #[test]
    fn c7_axum_request_get_method_skips_body_token() {
        let body_str = r#"{"garrison_token":"body_token_should_be_skipped"}"#;
        let req = make_request_with_body(
            "/",
            "GET",
            &[("Content-Type", "application/json")],
            body_str,
        );
        let axum_req = AxumRequest::with_body(&req, body_str.as_bytes().to_vec());
        let mut config = GarrisonConfig::default_config();
        config.is_read_header = false;
        config.is_read_cookie = false;
        config.is_read_body = true;
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(
            token, None,
            "C7: GET 方法不应从 body 提取 token(防 body 注入攻击)"
        );
    }

    /// C7: POST 方法 + body 含 token 应正常提取。
    #[test]
    fn c7_axum_request_post_method_allows_body_token() {
        let body_str = r#"{"garrison_token":"body_token_ok"}"#;
        let req = make_request_with_body(
            "/",
            "POST",
            &[("Content-Type", "application/json")],
            body_str,
        );
        let axum_req = AxumRequest::with_body(&req, body_str.as_bytes().to_vec());
        let mut config = GarrisonConfig::default_config();
        config.is_read_header = false;
        config.is_read_cookie = false;
        config.is_read_body = true;
        let token = axum_req.get_token(&config).unwrap();
        assert_eq!(
            token,
            Some("body_token_ok".to_string()),
            "C7: POST 方法应允许从 body 提取 token"
        );
    }

    /// C7: GET 方法应跳过 body 提取(经 AxumContext + request() 验证 Wrapper 路径同样受方法限制)。
    #[test]
    fn c7_axum_context_get_method_skips_body_token_via_wrapper() {
        let body_str = r#"{"garrison_token":"wrapper_skipped"}"#;
        let req = make_request_with_body(
            "/",
            "GET",
            &[("Content-Type", "application/json")],
            body_str,
        );
        let ctx = AxumContext::with_body(&req, body_str.as_bytes().to_vec());
        let request = ctx.request().unwrap();
        let mut config = GarrisonConfig::default_config();
        config.is_read_header = false;
        config.is_read_cookie = false;
        config.is_read_body = true;
        let token = request.get_token(&config).unwrap();
        assert_eq!(
            token, None,
            "C7: 通过 AxumContext 的 GET 方法不应从 body 提取 token"
        );
    }

    /// C7: PUT/PATCH 方法应允许从 body 提取 token(经 AxumContext + request())。
    #[test]
    fn c7_axum_context_put_patch_methods_allow_body_token_via_wrapper() {
        for method in &["PUT", "PATCH"] {
            let body_str = format!(r#"{{"garrison_token":"tok_{}"}}"#, method);
            let req = make_request_with_body(
                "/",
                method,
                &[("Content-Type", "application/json")],
                &body_str,
            );
            let ctx = AxumContext::with_body(&req, body_str.as_bytes().to_vec());
            let request = ctx.request().unwrap();
            let mut config = GarrisonConfig::default_config();
            config.is_read_header = false;
            config.is_read_cookie = false;
            config.is_read_body = true;
            let token = request.get_token(&config).unwrap();
            assert_eq!(
                token,
                Some(format!("tok_{}", method)),
                "C7: {} 方法应允许从 body 提取 token",
                method
            );
        }
    }
}