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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! actix-web 适配器模块。
//!
//! 实现 `GarrisonContext` / `GarrisonRequest` / `GarrisonResponse` / `GarrisonStorage` trait,
//! 将 Garrison 鉴权逻辑与 actix-web 4 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 actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};
use actix_web::http::StatusCode;
use actix_web::HttpRequest;
use std::collections::HashMap;

// ActixRequest:包装 &HttpRequest

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

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

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

impl<'a> GarrisonRequest for ActixRequest<'a> {
    fn path(&self) -> GarrisonResult<String> {
        Ok(self.request.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("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),
        )
    }
}

// ActixResponse:持有 HeaderMap + StatusCode

/// actix-web 响应适配器,持有 HeaderMap 与 StatusCode。
pub struct ActixResponse {
    headers: HeaderMap,
    status: StatusCode,
}

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

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

impl GarrisonResponse for ActixResponse {
    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(())
    }
}

// ActixStorage:HashMap<String, String>

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

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

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

impl GarrisonStorage for ActixStorage {
    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(())
    }
}

// ActixContext:组合 Request + Response + Storage

/// actix-web 上下文适配器,组合 `&HttpRequest` + `ActixResponse` + `ActixStorage`:
/// 经 `raw_response_mut()` 写入 status / headers / cookies,经 `raw_storage_mut()` 写入请求级临时数据。
pub struct ActixContext<'a> {
    request: &'a HttpRequest,
    response: ActixResponse,
    storage: ActixStorage,
    /// 预读的 body 字节(`is_read_body=true` 时从 JSON 提取 token);默认空 `Vec`,此时 body 分支跳过。
    body_bytes: Vec<u8>,
}

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

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

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

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

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

    /// 获取底层存储的不可变引用。
    pub fn raw_storage(&self) -> &ActixStorage {
        &self.storage
    }

    /// 获取底层存储的可变引用(用于 set / delete)。
    pub fn raw_storage_mut(&mut self) -> &mut ActixStorage {
        &mut self.storage
    }
}

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

/// ActixRequest 包装器(绕过 `Box<dyn>` 的生命周期问题):克隆 path / method / headers 等必要数据。
struct ActixRequestWrapper {
    path: String,
    method: String,
    headers: HeaderMap,
    /// 预读的 body 字节(`is_read_body=true` 时从 JSON 提取 token)。
    body_bytes: Vec<u8>,
}

impl ActixRequestWrapper {
    fn with_body(req: &HttpRequest, body_bytes: Vec<u8>) -> Self {
        Self {
            path: req.path().to_string(),
            method: req.method().as_str().to_string(),
            headers: req.headers().clone(),
            body_bytes,
        }
    }
}

impl GarrisonRequest for ActixRequestWrapper {
    fn path(&self) -> GarrisonResult<String> {
        Ok(self.path.clone())
    }

    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("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 actix_web::test::TestRequest;

    /// 构建测试用 HttpRequest。
    fn make_request(uri: &str, method: &str, headers: &[(&str, &str)]) -> HttpRequest {
        let mut req = TestRequest::default()
            .uri(uri)
            .method(method.parse().unwrap());
        for (name, value) in headers {
            req = req.insert_header((*name, *value));
        }
        req.to_http_request()
    }

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

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

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

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

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

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

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

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

    /// 验证 Bearer 前缀大小写不敏感。
    #[test]
    fn actix_request_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 actix_req = ActixRequest::new(&req);
            let token = actix_req.get_token(&config).unwrap();
            assert_eq!(
                token,
                Some(format!("tok_{}", prefix)),
                "前缀 '{}' 应能提取 token(大小写不敏感)",
                prefix
            );
        }
    }

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

    /// 验证从 cookie 提取 token。
    #[test]
    fn actix_request_get_token_from_cookie() {
        let req = make_request("/", "GET", &[("Cookie", "garrison_token=cookie_token_789")]);
        let actix_req = ActixRequest::new(&req);
        let config = GarrisonConfig::default_config();
        let token = actix_req.get_token(&config).unwrap();
        assert_eq!(token, Some("cookie_token_789".to_string()));
    }

    /// 验证 header 优先级高于 cookie。
    #[test]
    fn actix_request_get_token_header_priority_over_cookie() {
        let req = make_request(
            "/",
            "GET",
            &[
                ("Authorization", "Bearer header_token"),
                ("Cookie", "garrison_token=cookie_token"),
            ],
        );
        let actix_req = ActixRequest::new(&req);
        let config = GarrisonConfig::default_config();
        let token = actix_req.get_token(&config).unwrap();
        assert_eq!(token, Some("header_token".to_string()));
    }

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

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

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

    /// 验证 set_header 设置响应头。
    #[test]
    fn actix_response_set_header() {
        let mut resp = ActixResponse::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 actix_response_set_cookie_writes_header() {
        let mut resp = ActixResponse::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=/"));
    }

    /// 验证 set_cookie_with_config 依据 config 调整 Secure/SameSite(dev 场景关闭 Secure)。
    #[test]
    fn actix_response_set_cookie_with_config_dev() {
        let mut resp = ActixResponse::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 actix_response_set_cookie_none_insecure_downgrades_to_lax() {
        let mut resp = ActixResponse::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);
    }

    /// 验证 set_status 在状态码非法(> 999)时返回 Context 错误。
    #[test]
    fn actix_response_set_status_invalid_code_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let mut resp = ActixResponse::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("非法状态码"));
    }

    /// 验证 set_header 在 header value 非法时返回 Context 错误。
    #[test]
    fn actix_response_set_header_invalid_value_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let mut resp = ActixResponse::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 值"));
    }

    /// 验证 set_header 在 header name 非法时返回 Context 错误。
    #[test]
    fn actix_response_set_header_invalid_name_errors() {
        let mut resp = ActixResponse::new();
        let result = resp.set_header("invalid header", "value");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), GarrisonError::Context(_)));
    }

    /// 验证 Default 实现等价于 new()。
    #[test]
    fn actix_response_default_impl() {
        let resp = ActixResponse::default();
        assert_eq!(resp.status, StatusCode::OK);
        assert!(resp.headers.is_empty());
    }

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

    /// 验证请求间隔离。
    #[test]
    fn actix_storage_request_isolation() {
        let mut storage_a = ActixStorage::new();
        storage_a.set("trace_id", "A").unwrap();

        let mut storage_b = ActixStorage::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 actix_storage_missing_key_returns_none() {
        let storage = ActixStorage::new();
        assert_eq!(storage.get("missing").unwrap(), None);
    }

    /// 验证 Default 实现等价于 new()。
    #[test]
    fn actix_storage_default_impl() {
        let storage = ActixStorage::default();
        assert_eq!(storage.get("any").unwrap(), None);
    }

    // ActixContext 测试
    /// 验证 GarrisonContext::request() 返回 Box<dyn GarrisonRequest>。
    #[test]
    fn actix_context_request_returns_box() {
        let req = make_request("/api/test", "GET", &[("Authorization", "Bearer abc")]);
        let ctx = ActixContext::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()));
    }

    /// 验证 ActixContext::request() 返回的 wrapper 正确提取 path。
    #[test]
    fn actix_context_wrapper_path() {
        let req = make_request("/api/v1/users", "GET", &[]);
        let ctx = ActixContext::new(&req);
        let request = ctx.request().unwrap();
        assert_eq!(request.path().unwrap(), "/api/v1/users");
    }

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

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

    /// 验证 ActixContext::request() 返回的 wrapper 从 cookie 提取 token。
    #[test]
    fn actix_context_wrapper_get_token_from_cookie() {
        let req = make_request("/", "GET", &[("Cookie", "garrison_token=cookie_tok")]);
        let ctx = ActixContext::new(&req);
        let request = ctx.request().unwrap();
        let mut config = GarrisonConfig::default_config();
        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()));
    }

    /// 验证 raw_response_mut() 返回可写的内部 response 引用。
    #[test]
    fn actix_context_raw_response_mut_writable() {
        let req = make_request("/", "GET", &[]);
        let mut ctx = ActixContext::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);
    }

    /// 验证 raw_storage_mut() 返回可写的内部 storage 引用。
    #[test]
    fn actix_context_raw_storage_mut_writable() {
        let req = make_request("/", "GET", &[]);
        let mut ctx = ActixContext::new(&req);
        ctx.raw_storage_mut().set("key", "value").unwrap();
        assert_eq!(
            ctx.raw_storage().get("key").unwrap(),
            Some("value".to_string())
        );
    }

    /// 验证 raw_request() 返回底层请求引用。
    #[test]
    fn actix_context_raw_request() {
        let req = make_request("/api/test", "GET", &[]);
        let ctx = ActixContext::new(&req);
        assert_eq!(ctx.raw_request().path(), "/api/test");
    }

    // get_token body 读取测试
    /// 验证 is_read_body=true 时从 JSON body 的 token_name 字段提取 token。
    #[test]
    fn extract_token_from_body_when_is_read_body_true() {
        let req = make_request("/", "POST", &[("Content-Type", "application/json")]);
        let actix_req =
            ActixRequest::with_body(&req, br#"{"garrison_token":"body_token_123"}"#.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 = actix_req.get_token(&config).unwrap();
        assert_eq!(token, Some("body_token_123".to_string()));
    }

    // Context 层 body 读取测试
    /// 验证 `ActixContext::with_body()` 经 `request()` 传递 `body_bytes`,使 `get_token()` 能从 JSON body 提取 token。
    #[test]
    fn actix_context_with_body_extracts_token_from_body() {
        let req = make_request("/", "POST", &[("Content-Type", "application/json")]);
        let ctx = ActixContext::with_body(&req, br#"{"garrison_token":"ctx_body_token"}"#.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("ctx_body_token".to_string()),
            "ActixContext::with_body 应通过 request() 传递 body_bytes,使 get_token 能从 body 提取 token"
        );
    }

    // C7: body token 提取方法限制测试(防 body 注入攻击)
    /// C7: GET 方法 + body 含 token 应跳过 body 提取(否则攻击者可经 `<img src="...?token=...">` 注入)。
    #[test]
    fn c7_actix_request_get_method_skips_body_token() {
        let req = make_request("/", "GET", &[("Content-Type", "application/json")]);
        let actix_req = ActixRequest::with_body(
            &req,
            br#"{"garrison_token":"body_token_should_be_skipped"}"#.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 = actix_req.get_token(&config).unwrap();
        assert_eq!(
            token, None,
            "C7: GET 方法不应从 body 提取 token(防 body 注入攻击)"
        );
    }

    /// C7: POST 方法 + body 含 token 应正常提取。
    #[test]
    fn c7_actix_request_post_method_allows_body_token() {
        let req = make_request("/", "POST", &[("Content-Type", "application/json")]);
        let actix_req =
            ActixRequest::with_body(&req, br#"{"garrison_token":"body_token_ok"}"#.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 = actix_req.get_token(&config).unwrap();
        assert_eq!(
            token,
            Some("body_token_ok".to_string()),
            "C7: POST 方法应允许从 body 提取 token"
        );
    }

    /// C7: GET 方法应跳过 body 提取(经 ActixContext + request() 验证 Wrapper 路径同样受方法限制)。
    #[test]
    fn c7_actix_context_get_method_skips_body_token_via_wrapper() {
        let req = make_request("/", "GET", &[("Content-Type", "application/json")]);
        let ctx =
            ActixContext::with_body(&req, br#"{"garrison_token":"wrapper_skipped"}"#.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: 通过 ActixContext 的 GET 方法不应从 body 提取 token"
        );
    }

    /// C7: PUT/PATCH 方法应允许从 body 提取 token(经 ActixContext + request())。
    #[test]
    fn c7_actix_context_put_patch_methods_allow_body_token_via_wrapper() {
        for method in &["PUT", "PATCH"] {
            let req = make_request("/", method, &[("Content-Type", "application/json")]);
            let body_bytes = format!(r#"{{"garrison_token":"tok_{}"}}"#, method).into_bytes();
            let ctx = ActixContext::with_body(&req, body_bytes);
            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
            );
        }
    }
}