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

//! annotation 模块测试,仅在启用 `web-axum` feature 时编译。

use super::mock::{MockDao, MockInterface};
use super::*;
use crate::context::tenant::with_default_tenant;
use crate::dao::GarrisonDao;
use crate::error::GarrisonError;
use crate::manager::GarrisonManager;
use crate::stp::{with_current_token, GarrisonInterface, GarrisonUtil};
use axum::body::Body;
use axum::extract::FromRequestParts;
use axum::http::Request;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use serial_test::serial;
use std::sync::Arc;

// 测试用 marker 类型

struct AdminRole;
impl RoleName for AdminRole {
    const NAME: &'static str = "admin";
}

struct UserRead;
impl PermissionName for UserRead {
    const NAME: &'static str = "user:read";
}

// 辅助函数

/// 创建测试配置(throw_on_not_login 可配置)。
fn make_config(throw_on_not_login: bool) -> crate::config::GarrisonConfig {
    let mut config = crate::config::GarrisonConfig::default_config();
    config.timeout = 3600;
    config.active_timeout = -1;
    config.throw_on_not_login = throw_on_not_login;
    config
}

/// 初始化 GarrisonManager(带权限/角色数据)。
async fn init_manager(
    throw_on_not_login: bool,
    permissions: &[(&str, &[&str])],
    roles: &[(&str, &[&str])],
) {
    GarrisonManager::reset_for_test();
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let config = Arc::new(make_config(throw_on_not_login));
    let mut interface = MockInterface::new();
    for (id, perms) in permissions {
        interface = interface.with_permission(id, perms);
    }
    for (id, roles) in roles {
        interface = interface.with_role(id, roles);
    }
    let interface: Arc<dyn GarrisonInterface> = Arc::new(interface);
    GarrisonManager::builder()
        .dao(dao)
        .config(config)
        .interface(interface)
        .build()
        .await
        .unwrap();
}

/// 构建空的 axum Parts(无 header)。
fn make_parts() -> axum::http::request::Parts {
    let req = Request::builder()
        .method("GET")
        .uri("/protected")
        .body(Body::empty())
        .unwrap();
    req.into_parts().0
}

/// 构建带 Authorization: Bearer header 的 axum Parts。
fn make_parts_with_bearer(token: &str) -> axum::http::request::Parts {
    let req = Request::builder()
        .method("GET")
        .uri("/protected")
        .header("authorization", format!("Bearer {}", token))
        .body(Body::empty())
        .unwrap();
    req.into_parts().0
}

/// 构建带 garrison_token header 的 axum Parts。
fn make_parts_with_garrison_header(token: &str) -> axum::http::request::Parts {
    let req = Request::builder()
        .method("GET")
        .uri("/protected")
        .header("garrison_token", token)
        .body(Body::empty())
        .unwrap();
    req.into_parts().0
}

/// 构建带 Cookie: <token cookie 解析名>=<token> 的 axum Parts(含额外 cookie 测试循环分支)。
///
/// cookie 名经 `token_cookie_name` 解析(production + Secure 上下文为 `__Host-` 前缀名),
/// 与写侧构建点保持写读同名。
fn make_parts_with_cookie_token(token: &str) -> axum::http::request::Parts {
    let config = crate::config::GarrisonConfig::default_config();
    let cookie_name = crate::context::token_cookie_name(&config);
    let req = Request::builder()
        .method("GET")
        .uri("/protected")
        .header(
            "cookie",
            format!("other=val; {}={}; foo=bar", cookie_name, token),
        )
        .body(Body::empty())
        .unwrap();
    req.into_parts().0
}

// CheckLogin 测试

/// 已登录时 CheckLogin 返回 Ok。
#[tokio::test]
#[serial]
async fn check_login_logged_in_returns_ok() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts();
    let result = with_current_token(token, async {
        CheckLogin::from_request_parts(&mut parts, &()).await
    })
    .await;
    assert!(result.is_ok(), "已登录应返回 Ok");

    GarrisonManager::reset_for_test();
}

/// 未登录且 throw_on_not_login=false 时 CheckLogin 返回 Err(NotLogin)。
#[tokio::test]
#[serial]
async fn check_login_not_logged_in_returns_not_login() {
    init_manager(false, &[], &[]).await;
    let mut parts = make_parts();
    let result = CheckLogin::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "未登录且 throw_on_not_login=false 应返回 Err(NotLogin)"
    );

    GarrisonManager::reset_for_test();
}

/// 未登录且 throw_on_not_login=true 时 CheckLogin 返回 Err(Session)。
#[tokio::test]
#[serial]
async fn check_login_not_logged_in_returns_session() {
    init_manager(true, &[], &[]).await;
    let mut parts = make_parts();
    let result = CheckLogin::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::Session(_))),
        "未登录且 throw_on_not_login=true 应返回 Err(Session)"
    );

    GarrisonManager::reset_for_test();
}

// CheckRole<R> 测试

/// 持有角色时 CheckRole<AdminRole> 返回 Ok。
#[tokio::test]
#[serial]
async fn check_role_held_returns_ok() {
    init_manager(true, &[], &[("1001", &["admin"])]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts();
    let result = with_current_token(
        token,
        with_default_tenant(async {
            CheckRole::<AdminRole>::from_request_parts(&mut parts, &()).await
        }),
    )
    .await;
    assert!(result.is_ok(), "持有角色应返回 Ok");

    GarrisonManager::reset_for_test();
}

/// 未持有角色时 CheckRole<AdminRole> 返回 Err(NotRole)。
#[tokio::test]
#[serial]
async fn check_role_not_held_returns_not_role() {
    init_manager(true, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts();
    let result = with_current_token(
        token,
        with_default_tenant(async {
            CheckRole::<AdminRole>::from_request_parts(&mut parts, &()).await
        }),
    )
    .await;
    assert!(
        matches!(result, Err(GarrisonError::NotRole(_))),
        "未持有角色应返回 Err(NotRole)"
    );

    GarrisonManager::reset_for_test();
}

// CheckPermission<P> 测试

/// 持有权限时 CheckPermission<UserRead> 返回 Ok。
#[tokio::test]
#[serial]
async fn check_permission_held_returns_ok() {
    init_manager(true, &[("1001", &["user:read"])], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts();
    let result = with_current_token(token, async {
        with_default_tenant(async {
            CheckPermission::<UserRead>::from_request_parts(&mut parts, &()).await
        })
        .await
    })
    .await;
    assert!(result.is_ok(), "持有权限应返回 Ok");

    GarrisonManager::reset_for_test();
}

/// 未持有权限时 CheckPermission<UserRead> 返回 Err(NotPermission)。
#[tokio::test]
#[serial]
async fn check_permission_not_held_returns_not_permission() {
    init_manager(true, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts();
    let result = with_current_token(token, async {
        with_default_tenant(async {
            CheckPermission::<UserRead>::from_request_parts(&mut parts, &()).await
        })
        .await
    })
    .await;
    assert!(
        matches!(result, Err(GarrisonError::NotPermission(_))),
        "未持有权限应返回 Err(NotPermission)"
    );

    GarrisonManager::reset_for_test();
}

// Ignore 测试

/// Ignore 总是返回 Ok(不校验)。
#[tokio::test]
#[serial]
async fn ignore_always_returns_ok() {
    init_manager(false, &[], &[]).await;
    let mut parts = make_parts();
    let result = Ignore::from_request_parts(&mut parts, &()).await;
    assert!(result.is_ok(), "Ignore 应总是返回 Ok");

    GarrisonManager::reset_for_test();
}

// Mode<M> 测试

/// Mode<Strict> 未登录时抛 NotLogin。
#[tokio::test]
#[serial]
async fn mode_strict_not_logged_in_throws_not_login() {
    init_manager(false, &[], &[]).await;
    let mut parts = make_parts();
    let result = Mode::<Strict>::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "Mode<Strict> 未登录应抛 Err(NotLogin)"
    );

    GarrisonManager::reset_for_test();
}

/// Mode<Loose> 未登录时返回 Ok(宽松模式)。
#[tokio::test]
#[serial]
async fn mode_loose_not_logged_in_returns_ok() {
    init_manager(false, &[], &[]).await;
    let mut parts = make_parts();
    let result = Mode::<Loose>::from_request_parts(&mut parts, &()).await;
    assert!(result.is_ok(), "Mode<Loose> 未登录应返回 Ok");

    GarrisonManager::reset_for_test();
}

// IntoResponse for GarrisonError 测试

/// NotLogin 映射为 401。
#[test]
fn not_login_returns_401() {
    let err = GarrisonError::NotLogin("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

/// InvalidToken 映射为 401。
#[test]
fn invalid_token_returns_401() {
    let err = GarrisonError::InvalidToken("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

/// ExpiredToken 映射为 401。
#[test]
fn expired_token_returns_401() {
    let err = GarrisonError::ExpiredToken("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

/// NotPermission 映射为 403。
#[test]
fn not_permission_returns_403() {
    let err = GarrisonError::NotPermission("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
}

/// NotRole 映射为 403。
#[test]
fn not_role_returns_403() {
    let err = GarrisonError::NotRole("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::FORBIDDEN);
}

/// 其他错误映射为 500。
#[test]
fn internal_error_returns_500() {
    let err = GarrisonError::Internal("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

/// Session 错误映射为 500。
#[test]
fn session_error_returns_500() {
    let err = GarrisonError::Session("test".to_string());
    let response = err.into_response();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

// Annotation::name 测试

/// Annotation::name 返回注解变体名称(16 个变体)。
///
/// 验收标准:CheckApiKey 与 Mode 变体的 name() 返回正确字符串。
/// CheckAccessToken / CheckClientToken name() 返回正确字符串。
#[test]
fn annotation_name_returns_variant_string() {
    assert_eq!(Annotation::CheckLogin.name(), "CheckLogin");
    assert_eq!(
        Annotation::CheckPermission("p".to_string()).name(),
        "CheckPermission"
    );
    assert_eq!(Annotation::CheckRole("r".to_string()).name(), "CheckRole");
    assert_eq!(Annotation::CheckSafe.name(), "CheckSafe");
    assert_eq!(Annotation::CheckDisable.name(), "CheckDisable");
    assert_eq!(Annotation::CheckOr.name(), "CheckOr");
    assert_eq!(Annotation::CheckAnd.name(), "CheckAnd");
    assert_eq!(Annotation::CheckNot.name(), "CheckNot");
    assert_eq!(Annotation::Ignore.name(), "Ignore");
    assert_eq!(Annotation::CheckBasicAuth.name(), "CheckBasicAuth");
    assert_eq!(Annotation::CheckDigestAuth.name(), "CheckDigestAuth");
    assert_eq!(Annotation::CheckSign.name(), "CheckSign");
    assert_eq!(
        Annotation::CheckApiKey { namespace: None }.name(),
        "CheckApiKey"
    );
    assert_eq!(
        Annotation::CheckApiKey {
            namespace: Some("ns1".to_string())
        }
        .name(),
        "CheckApiKey"
    );
    assert_eq!(Annotation::Mode(AnnotationMode::And).name(), "Mode");
    assert_eq!(Annotation::Mode(AnnotationMode::Or).name(), "Mode");
    assert_eq!(Annotation::CheckAccessToken.name(), "CheckAccessToken");
    assert_eq!(Annotation::CheckClientToken.name(), "CheckClientToken");
}

// AnnotationMode Display / Debug / Clone / PartialEq 测试

/// AnnotationMode::And 的 Display 输出 "AND",AnnotationMode::Or 输出 "OR"。
#[test]
fn annotation_mode_display_outputs_uppercase() {
    assert_eq!(format!("{}", AnnotationMode::And), "AND");
    assert_eq!(format!("{}", AnnotationMode::Or), "OR");
}

/// AnnotationMode 实现 Copy,可在 match 表达式中按值使用而无需 clone。
#[test]
fn annotation_mode_copy_semantics() {
    let mode = AnnotationMode::And;
    let copied = mode;
    assert_eq!(mode, AnnotationMode::And);
    assert_eq!(copied, AnnotationMode::And);
}

/// AnnotationMode::Mode(AnnotationMode::And) 与 .Or 在 Annotation 枚举层级可比较相等性。
#[test]
fn annotation_mode_equality_within_annotation() {
    assert_eq!(
        Annotation::Mode(AnnotationMode::And),
        Annotation::Mode(AnnotationMode::And)
    );
    assert_ne!(
        Annotation::Mode(AnnotationMode::And),
        Annotation::Mode(AnnotationMode::Or)
    );
}

/// CheckApiKey 变体 namespace 字段 None 与 Some 不影响 name(),但影响 PartialEq。
#[test]
fn check_api_key_namespace_equality() {
    assert_eq!(
        Annotation::CheckApiKey { namespace: None },
        Annotation::CheckApiKey { namespace: None }
    );
    assert_ne!(
        Annotation::CheckApiKey { namespace: None },
        Annotation::CheckApiKey {
            namespace: Some("ns1".to_string())
        }
    );
    assert_ne!(
        Annotation::CheckApiKey {
            namespace: Some("ns1".to_string())
        },
        Annotation::CheckApiKey {
            namespace: Some("ns2".to_string())
        }
    );
}

// Display / FromStr 测试

/// CheckAccessToken Display 格式化为 "CheckAccessToken"。
#[test]
fn check_access_token_display_formats_correctly() {
    assert_eq!(
        format!("{}", Annotation::CheckAccessToken),
        "CheckAccessToken"
    );
}

/// CheckClientToken Display 格式化为 "CheckClientToken"。
#[test]
fn check_client_token_display_formats_correctly() {
    assert_eq!(
        format!("{}", Annotation::CheckClientToken),
        "CheckClientToken"
    );
}

/// from_str("CheckAccessToken") 返回 Ok(CheckAccessToken)。
#[test]
fn check_access_token_from_str_returns_ok() {
    let result: Result<Annotation, _> = "CheckAccessToken".parse();
    assert!(result.is_ok(), "from_str 应返回 Ok");
    assert_eq!(result.unwrap(), Annotation::CheckAccessToken);
}

/// from_str("CheckClientToken") 返回 Ok(CheckClientToken)。
#[test]
fn check_client_token_from_str_returns_ok() {
    let result: Result<Annotation, _> = "CheckClientToken".parse();
    assert!(result.is_ok(), "from_str 应返回 Ok");
    assert_eq!(result.unwrap(), Annotation::CheckClientToken);
}

/// from_str 对未知字符串返回 Err(InvalidParam)。
#[test]
fn annotation_from_str_unknown_returns_err() {
    let result: Result<Annotation, _> = "UnknownAnnotation".parse();
    assert!(
        matches!(result, Err(GarrisonError::InvalidParam(_))),
        "未知注解应返回 Err(InvalidParam),实际: {:?}",
        result
    );
}

/// from_str 对含数据变体(如 "CheckPermission")返回 Err。
#[test]
fn annotation_from_str_data_variant_returns_err() {
    let result: Result<Annotation, _> = "CheckPermission".parse();
    assert!(
        result.is_err(),
        "含数据变体应返回 Err(无法仅从名称解析),实际: {:?}",
        result
    );
}

/// Display 对所有 unit 变体输出与 name() 一致的字符串。
#[serial]
#[test]
fn display_matches_name_for_all_unit_variants() {
    let unit_variants = [
        Annotation::CheckLogin,
        Annotation::CheckSafe,
        Annotation::CheckDisable,
        Annotation::CheckOr,
        Annotation::CheckAnd,
        Annotation::CheckNot,
        Annotation::Ignore,
        Annotation::CheckBasicAuth,
        Annotation::CheckDigestAuth,
        Annotation::CheckSign,
        Annotation::CheckAccessToken,
        Annotation::CheckClientToken,
    ];
    for ann in &unit_variants {
        assert_eq!(
            format!("{}", ann),
            ann.name(),
            "Display 输出应与 name() 一致"
        );
    }
}

// token 提取(header / cookie)分支测试

/// CheckLogin 从 Authorization: Bearer header 提取 token 并校验通过。
#[tokio::test]
#[serial]
async fn check_login_extracts_token_from_bearer_header() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_bearer(&token);
    let result = CheckLogin::from_request_parts(&mut parts, &()).await;
    assert!(result.is_ok(), "Bearer header 提取 token 后校验应通过");

    GarrisonManager::reset_for_test();
}

/// CheckLogin 从 garrison_token header 提取 token 并校验通过。
#[tokio::test]
#[serial]
async fn check_login_extracts_token_from_garrison_header() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_garrison_header(&token);
    let result = CheckLogin::from_request_parts(&mut parts, &()).await;
    assert!(
        result.is_ok(),
        "garrison_token header 提取 token 后校验应通过"
    );

    GarrisonManager::reset_for_test();
}

/// CheckLogin 从 Cookie: garrison_token=<token> 提取 token 并校验通过。
#[tokio::test]
#[serial]
async fn check_login_extracts_token_from_cookie() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_cookie_token(&token);
    let result = CheckLogin::from_request_parts(&mut parts, &()).await;
    assert!(result.is_ok(), "Cookie 提取 token 后校验应通过");

    GarrisonManager::reset_for_test();
}

/// production 构建下 CheckLogin 命中 `__Host-` 前缀 token cookie(写读同名)。
///
/// 回归:提取器须经 `token_cookie_name` 统一入口解析 cookie 名,production + Secure
/// 上下文下写侧产出 `__Host-` 前缀名,读侧直查裸名会导致纯 cookie 会话永远 NotLogin。
#[cfg(feature = "production")]
#[tokio::test]
#[serial]
async fn check_login_extracts_token_from_host_prefixed_cookie() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let config = GarrisonUtil::config().unwrap();
    let cookie_name = crate::context::token_cookie_name(&config);
    assert!(
        cookie_name.starts_with("__Host-"),
        "production 默认 Secure 上下文应为 __Host- 前缀名,实际: {}",
        cookie_name
    );

    let req = Request::builder()
        .method("GET")
        .uri("/protected")
        .header("cookie", format!("{}={}", cookie_name, token))
        .body(Body::empty())
        .unwrap();
    let mut parts = req.into_parts().0;
    let result = CheckLogin::from_request_parts(&mut parts, &()).await;
    assert!(
        result.is_ok(),
        "__Host- 前缀 cookie 提取 token 后校验应通过"
    );

    GarrisonManager::reset_for_test();
}

// extractor 通过 header 提取 token 的 if-let-Some 分支测试

/// CheckRole<AdminRole> 从 Bearer header 提取 token 并校验角色通过。
#[tokio::test]
#[serial]
async fn check_role_extracts_token_from_header() {
    init_manager(true, &[], &[("1001", &["admin"])]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_bearer(&token);
    let result = with_default_tenant(async {
        CheckRole::<AdminRole>::from_request_parts(&mut parts, &()).await
    })
    .await;
    assert!(result.is_ok(), "持有角色时通过 header token 校验应通过");

    GarrisonManager::reset_for_test();
}

/// CheckPermission<UserRead> 从 Bearer header 提取 token 并校验权限通过。
#[tokio::test]
#[serial]
async fn check_permission_extracts_token_from_header() {
    init_manager(true, &[("1001", &["user:read"])], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_bearer(&token);
    let result = with_default_tenant(async {
        CheckPermission::<UserRead>::from_request_parts(&mut parts, &()).await
    })
    .await;
    assert!(result.is_ok(), "持有权限时通过 header token 校验应通过");

    GarrisonManager::reset_for_test();
}

/// Mode<Strict> 从 Bearer header 提取 token,已登录时校验通过。
#[tokio::test]
#[serial]
async fn mode_strict_extracts_token_from_header() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_bearer(&token);
    let result = Mode::<Strict>::from_request_parts(&mut parts, &()).await;
    assert!(
        result.is_ok(),
        "Mode<Strict> 已登录时通过 header token 校验应通过"
    );

    GarrisonManager::reset_for_test();
}

/// Mode<Loose> 从 Bearer header 提取 token,已登录时校验通过(宽松模式不抛错)。
#[tokio::test]
#[serial]
async fn mode_loose_logged_in_with_header() {
    init_manager(false, &[], &[]).await;
    let token = GarrisonUtil::login_simple("1001").await.unwrap();

    let mut parts = make_parts_with_bearer(&token);
    let result = Mode::<Loose>::from_request_parts(&mut parts, &()).await;
    assert!(result.is_ok(), "Mode<Loose> 已登录时应返回 Ok");

    GarrisonManager::reset_for_test();
}

// GarrisonPrincipal extractor 测试(携带 login_id)

/// `GarrisonPrincipal::from_request_parts` 从 Bearer header 解析出 `login_id`(与 actix/warp 提取器一致)。
#[tokio::test]
#[serial]
async fn garrison_principal_extracts_login_id_from_bearer_header() {
    init_manager(false, &[], &[]).await;
    let login_id = "1001";
    let token = GarrisonUtil::login_simple(login_id).await.unwrap();

    let mut parts = make_parts_with_bearer(&token);
    let principal = crate::context::GarrisonPrincipal::from_request_parts(&mut parts, &())
        .await
        .expect("有效 token 应解析出 GarrisonPrincipal");

    assert_eq!(principal.login_id, login_id);

    GarrisonManager::reset_for_test();
}

/// `GarrisonPrincipal::from_request_parts` 在无 token 时返回 `Err(NotLogin)`(与 actix/warp 提取器一致)。
#[tokio::test]
#[serial]
async fn garrison_principal_returns_err_without_token() {
    init_manager(false, &[], &[]).await;

    let mut parts = make_parts();
    let result = crate::context::GarrisonPrincipal::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "无 token 时应返回 Err(NotLogin),实际 = {:?}",
        result
    );

    GarrisonManager::reset_for_test();
}

/// `GarrisonPrincipal::from_request_parts` 在无效 token 时返回 `Err(NotLogin)`(与 actix/warp 提取器一致)。
#[tokio::test]
#[serial]
async fn garrison_principal_returns_err_with_invalid_token() {
    init_manager(false, &[], &[]).await;

    let mut parts = make_parts_with_bearer("invalid_token_xyz");
    let result = crate::context::GarrisonPrincipal::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "无效 token 时应返回 Err(NotLogin),实际 = {:?}",
        result
    );

    GarrisonManager::reset_for_test();
}

/// `GarrisonPrincipal::from_request_parts` 在 token 曾有效但已 logout 时返回 `Err(NotLogin)`;
/// 覆盖 `get_login_id_by_token` 返回 `Ok(None)` 的路径(token 存在过但 session 已销毁)。
#[tokio::test]
#[serial]
async fn garrison_principal_returns_err_when_token_logout() {
    init_manager(false, &[], &[]).await;
    let login_id = "1001";
    let token = GarrisonUtil::login_simple(login_id).await.unwrap();

    with_current_token(token.clone(), async {
        GarrisonUtil::logout().await.unwrap();
    })
    .await;

    let mut parts = make_parts_with_bearer(&token);
    let result = crate::context::GarrisonPrincipal::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "token 已注销时应返回 Err(NotLogin),实际 = {:?}",
        result
    );

    GarrisonManager::reset_for_test();
}

// TenantContext extractor 测试(cfg tenant-isolation)

/// `TenantContext::from_request_parts` 从 `X-Tenant-Id` header 解析出 `tenant_id`(与 actix/warp 提取器一致)。
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn tenant_context_extracts_tenant_id_from_header() {
    let req = Request::builder()
        .method("GET")
        .uri("/api/test")
        .header("x-tenant-id", "42")
        .body(Body::empty())
        .unwrap();
    let mut parts = req.into_parts().0;

    let ctx = crate::context::tenant::TenantContext::from_request_parts(&mut parts, &())
        .await
        .expect("有效 X-Tenant-Id 应解析出 TenantContext");

    assert_eq!(ctx.tenant_id, 42);
    assert!(
        matches!(
            ctx.resolved_from,
            crate::context::tenant::TenantSource::Header
        ),
        "resolved_from 应为 Header,实际 = {:?}",
        ctx.resolved_from
    );
}

/// `TenantContext::from_request_parts` 在缺失 `X-Tenant-Id` header 时返回 `Err(Config)`(与 actix/warp 提取器一致)。
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn tenant_context_returns_err_without_x_tenant_id_header() {
    let mut parts = make_parts();
    let result = crate::context::tenant::TenantContext::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::Config(_))),
        "缺失 X-Tenant-Id 时应返回 Err(Config),实际 = {:?}",
        result
    );
}

/// `TenantContext::from_request_parts` 在非数字 `X-Tenant-Id` 时返回 `Err(Config)`(与 actix/warp 提取器一致)。
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
#[serial]
async fn tenant_context_returns_err_with_non_numeric_x_tenant_id() {
    let req = Request::builder()
        .method("GET")
        .uri("/api/test")
        .header("x-tenant-id", "not-a-number")
        .body(Body::empty())
        .unwrap();
    let mut parts = req.into_parts().0;

    let result = crate::context::tenant::TenantContext::from_request_parts(&mut parts, &()).await;
    assert!(
        matches!(result, Err(GarrisonError::Config(_))),
        "非数字 X-Tenant-Id 时应返回 Err(Config),实际 = {:?}",
        result
    );
}

/// 调用 MockInterface 的默认委托方法以覆盖 async_trait wrapper。
#[tokio::test]
async fn mock_interface_default_methods_with_type_coverage() {
    let iface = MockInterface::new();
    let _ = iface
        .get_permission_list_with_type("u1", "default")
        .await
        .unwrap();
    let _ = iface
        .get_role_list_with_type("u1", "default")
        .await
        .unwrap();
}