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

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

// WarpRequest:持有 path + method + HeaderMap(owned)

/// warp 请求适配器,持有 owned 的 path / method / HeaderMap。
///
/// 与 `ActixRequest`(持引用)不同:warp 的 Filter 体系通常在中间件层已提取出 HeaderMap。
pub struct WarpRequest {
    path: String,
    method: String,
    headers: HeaderMap,
    /// 预读的 body 字节(`is_read_body=true` 时从 JSON 提取 token);默认空 `Vec`,此时 body 分支跳过。
    ///
    /// body 读取是 async 操作而 `get_token` 是 sync 方法,故由调用方在 async 上下文中预读后经 `with_body` 注入。
    body_bytes: Vec<u8>,
}

impl WarpRequest {
    /// 创建新的 WarpRequest(body 为空,不读取 body)。
    pub fn new(path: String, method: String, headers: HeaderMap) -> Self {
        Self {
            path,
            method,
            headers,
            body_bytes: Vec::new(),
        }
    }

    /// 创建带预读 body 的 WarpRequest(`is_read_body=true` 场景,body 由调用方在 async 上下文读取)。
    pub fn with_body(
        path: String,
        method: String,
        headers: HeaderMap,
        body_bytes: Vec<u8>,
    ) -> Self {
        Self {
            path,
            method,
            headers,
            body_bytes,
        }
    }
}

impl GarrisonRequest for WarpRequest {
    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),
        )
    }
}

// WarpResponse:持有 HeaderMap + StatusCode

/// warp 响应适配器,持有 HeaderMap 与 StatusCode。
pub struct WarpResponse {
    headers: HeaderMap,
    status: StatusCode,
}

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

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

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

// WarpStorage:HashMap<String, String>

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

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

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

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

// WarpContext:组合 Request + Response + Storage

/// warp 上下文适配器,组合 owned 的 `WarpRequest` + `WarpResponse` + `WarpStorage`:
/// 经 `raw_response_mut()` 写入 status / headers / cookies,经 `raw_storage_mut()` 写入请求级临时数据。
///
/// # body 单一存储
///
/// `body_bytes` 仅存于 `request_data: WarpRequest`(单一事实来源),`WarpContext` 不另存外层副本:
/// `with_body()` 直接注入 `WarpRequest::with_body`,`request()` 从 `request_data` 读取并传递,
/// 消除双存储互不一致的脆弱性。
pub struct WarpContext {
    request_data: WarpRequest,
    response: WarpResponse,
    storage: WarpStorage,
}

impl WarpContext {
    /// 创建新的 WarpContext(body 为空,不读取 body)。
    pub fn new(path: String, method: String, headers: HeaderMap) -> Self {
        Self {
            request_data: WarpRequest::new(path, method, headers),
            response: WarpResponse::new(),
            storage: WarpStorage::new(),
        }
    }

    /// 创建带预读 body 的 WarpContext(`is_read_body=true` 场景);body 存于 `request_data` 内(单一事实来源)。
    pub fn with_body(
        path: String,
        method: String,
        headers: HeaderMap,
        body_bytes: Vec<u8>,
    ) -> Self {
        Self {
            request_data: WarpRequest::with_body(path, method, headers, body_bytes),
            response: WarpResponse::new(),
            storage: WarpStorage::new(),
        }
    }

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

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

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

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

impl GarrisonContext for WarpContext {
    fn request(&self) -> GarrisonResult<Box<dyn GarrisonRequest>> {
        // WarpRequest 已 owned:克隆数据构造新实例,body_bytes 从 request_data(单一事实来源)传递
        Ok(Box::new(WarpRequest::with_body(
            self.request_data.path.clone(),
            self.request_data.method.clone(),
            self.request_data.headers.clone(),
            self.request_data.body_bytes.clone(),
        )))
    }
}

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

    /// 构建测试用 HeaderMap。
    fn make_headers(headers: &[(&str, &str)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in headers {
            map.insert(
                name.parse::<HeaderName>().unwrap(),
                value.parse::<HeaderValue>().unwrap(),
            );
        }
        map
    }

    /// 构建测试用 WarpRequest。
    fn make_warp_request(path: &str, method: &str, headers: &[(&str, &str)]) -> WarpRequest {
        WarpRequest::new(path.to_string(), method.to_string(), make_headers(headers))
    }

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

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

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

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

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

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

    /// 验证 header() 在 header name 非法时返回 Context 错误。
    #[test]
    fn warp_request_header_invalid_name_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let req = make_warp_request("/", "GET", &[]);
        let result = 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 warp_request_get_token_from_header() {
        let req = make_warp_request("/", "GET", &[("Authorization", "Bearer my_token_123")]);
        let config = GarrisonConfig::default_config();
        let token = req.get_token(&config).unwrap();
        assert_eq!(token, Some("my_token_123".to_string()));
    }

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

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

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

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

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

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

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

    /// 验证 set_header 设置响应头。
    #[test]
    fn warp_response_set_header() {
        let mut resp = WarpResponse::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 warp_response_set_cookie_writes_header() {
        let mut resp = WarpResponse::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 warp_response_set_cookie_with_config_dev() {
        let mut resp = WarpResponse::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 warp_response_set_cookie_none_insecure_downgrades_to_lax() {
        let mut resp = WarpResponse::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 warp_response_set_status_invalid_code_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let mut resp = WarpResponse::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 warp_response_set_header_invalid_value_errors() {
        // 钉住 locale:断言依赖中文模板文案(guard 随测试作用域恢复)
        let _locale_guard = crate::i18n::set_locale(crate::i18n::GarrisonLocale::Zh);
        let mut resp = WarpResponse::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 warp_response_set_header_invalid_name_errors() {
        let mut resp = WarpResponse::new();
        let result = resp.set_header("invalid header", "value");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), GarrisonError::Context(_)));
    }

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

    // WarpStorage 测试
    /// 验证 set/get/delete 存储数据。
    #[test]
    fn warp_storage_set_get_delete() {
        let mut storage = WarpStorage::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 warp_storage_request_isolation() {
        let mut storage_a = WarpStorage::new();
        storage_a.set("trace_id", "A").unwrap();

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

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

    // WarpContext 测试
    /// 验证 GarrisonContext::request() 返回 Box<dyn GarrisonRequest>。
    #[test]
    fn warp_context_request_returns_box() {
        let ctx = WarpContext::new(
            "/api/test".to_string(),
            "GET".to_string(),
            make_headers(&[("Authorization", "Bearer abc")]),
        );

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

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

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

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

    /// 验证 WarpContext::request() 返回的 wrapper 从 cookie 提取 token。
    #[test]
    fn warp_context_wrapper_get_token_from_cookie() {
        let ctx = WarpContext::new(
            "/".to_string(),
            "GET".to_string(),
            make_headers(&[("Cookie", "garrison_token=cookie_tok")]),
        );
        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 warp_context_raw_response_mut_writable() {
        let mut ctx = WarpContext::new("/".to_string(), "GET".to_string(), make_headers(&[]));
        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 warp_context_raw_storage_mut_writable() {
        let mut ctx = WarpContext::new("/".to_string(), "GET".to_string(), make_headers(&[]));
        ctx.raw_storage_mut().set("key", "value").unwrap();
        assert_eq!(
            ctx.raw_storage().get("key").unwrap(),
            Some("value".to_string())
        );
    }

    // 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 = WarpRequest::with_body(
            "/".to_string(),
            "POST".to_string(),
            make_headers(&[("Content-Type", "application/json")]),
            br#"{"garrison_token":"body_token_456"}"#.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 = req.get_token(&config).unwrap();
        assert_eq!(token, Some("body_token_456".to_string()));
    }

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

    // C7: body token 提取方法限制测试(防 body 注入攻击)
    /// C7: GET 方法 + body 含 token 应跳过 body 提取:GET 携带 body token 可被恶意链接
    /// (如 `<img src="https://victim.com/api?token=attacker_token">`)在用户不知情时注入(CSRF 变种)。
    #[test]
    fn c7_warp_request_get_method_skips_body_token() {
        let req = WarpRequest::with_body(
            "/".to_string(),
            "GET".to_string(),
            make_headers(&[("Content-Type", "application/json")]),
            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 = req.get_token(&config).unwrap();
        assert_eq!(
            token, None,
            "C7: GET 方法不应从 body 提取 token(防 body 注入攻击)"
        );
    }

    /// C7: POST/PUT/PATCH 三个方法均应允许从 body 提取 token。
    #[test]
    fn c7_warp_request_post_put_patch_methods_allow_body_token() {
        for method in &["POST", "PUT", "PATCH"] {
            let body_bytes = format!(r#"{{"garrison_token":"tok_{}"}}"#, method).into_bytes();
            let req = WarpRequest::with_body(
                "/".to_string(),
                method.to_string(),
                make_headers(&[("Content-Type", "application/json")]),
                body_bytes,
            );
            let mut config = GarrisonConfig::default_config();
            config.is_read_header = false;
            config.is_read_cookie = false;
            config.is_read_body = true;
            let token = req.get_token(&config).unwrap();
            assert_eq!(
                token,
                Some(format!("tok_{}", method)),
                "C7: {} 方法应允许从 body 提取 token",
                method
            );
        }
    }

    /// C7: 经 WarpContext(Wrapper 路径)的 GET 方法也应跳过 body 提取。
    #[test]
    fn c7_warp_context_get_method_skips_body_token_via_wrapper() {
        let ctx = WarpContext::with_body(
            "/".to_string(),
            "GET".to_string(),
            make_headers(&[("Content-Type", "application/json")]),
            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: 通过 WarpContext 的 GET 方法不应从 body 提取 token"
        );
    }
}