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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! `strategy` 模块的 inline tests:覆盖权限校验、角色层级、权限缓存、插件钩子、防火墙安全钩子等场景。
//!
//! 注意:引用 `GarrisonFirewallCheckHook` / `LoginContext` 的测试需 cfg 门控(依赖 limiteron / firewall-* / oauth2-server feature)。

use super::mock::MockCacheDao;
use super::*;
use crate::error::GarrisonError;
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
use crate::strategy::hooks::{
    GarrisonFirewallCheckHook, GarrisonFirewallCheckHookDefault, LoginContext,
};
use std::collections::HashMap;

// MockInterface:模拟业务方实现 GarrisonInterface 回调

/// 测试用 GarrisonInterface mock,基于 HashMap 存储 login_id → 权限/角色列表。
struct MockInterface {
    permissions: HashMap<String, Vec<String>>,
    roles: HashMap<String, Vec<String>>,
}

impl MockInterface {
    fn new() -> Self {
        Self {
            permissions: HashMap::new(),
            roles: HashMap::new(),
        }
    }

    /// 设置指定 login_id 的权限列表。
    fn set_permissions(&mut self, login_id: &str, perms: &[&str]) {
        self.permissions.insert(
            login_id.to_string(),
            perms.iter().map(|s| s.to_string()).collect(),
        );
    }

    /// 设置指定 login_id 的角色列表。
    fn set_roles(&mut self, login_id: &str, roles: &[&str]) {
        self.roles.insert(
            login_id.to_string(),
            roles.iter().map(|s| s.to_string()).collect(),
        );
    }
}

#[async_trait]
impl GarrisonInterface for MockInterface {
    async fn get_permission_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.permissions.get(login_id).cloned().unwrap_or_default())
    }

    async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.roles.get(login_id).cloned().unwrap_or_default())
    }
}

/// 辅助函数:创建 GarrisonPermissionStrategyDefault 实例。
fn make_firewall(interface: MockInterface) -> GarrisonPermissionStrategyDefault {
    GarrisonPermissionStrategyDefault::new(Arc::new(interface))
}

// 持有权限返回 true / 未持有返回 false

/// 验证主体持有指定权限时 check_permission 返回 true。
#[tokio::test]
async fn check_permission_held_returns_true() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read", "user:write"]);
    let fw = make_firewall(iface);

    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "持有权限应返回 true"
    );
}

/// 验证主体未持有指定权限时 check_permission 返回 false。
#[tokio::test]
async fn check_permission_not_held_returns_false() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read"]);
    let fw = make_firewall(iface);

    assert!(
        !fw.check_permission("1001", "user:delete").await.unwrap(),
        "未持有权限应返回 false"
    );
}

/// 空字符串抛 InvalidParam。
#[tokio::test]
async fn check_permission_empty_string_errors() {
    let iface = MockInterface::new();
    let fw = make_firewall(iface);

    let result = fw.check_permission("1001", "").await;
    assert!(
        matches!(result, Err(GarrisonError::InvalidParam(_))),
        "空权限字符串应抛 InvalidParam"
    );
}

/// 验证主体无任何权限记录时 check_permission 返回 false(不抛错)。
#[tokio::test]
async fn check_permission_no_record_returns_false() {
    let iface = MockInterface::new();
    let fw = make_firewall(iface);

    assert!(
        !fw.check_permission("9999", "user:read").await.unwrap(),
        "无权限记录的 login_id 应返回 false"
    );
}

// 持有角色返回 true / 未持有返回 false

/// 验证主体持有指定角色时 check_role 返回 true。
#[tokio::test]
async fn check_role_held_returns_true() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin", "user"]);
    let fw = make_firewall(iface);

    assert!(
        fw.check_role("1001", "admin").await.unwrap(),
        "持有角色应返回 true"
    );
}

/// 验证主体未持有指定角色时 check_role 返回 false。
#[tokio::test]
async fn check_role_not_held_returns_false() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["user"]);
    let fw = make_firewall(iface);

    assert!(
        !fw.check_role("1001", "admin").await.unwrap(),
        "未持有角色应返回 false"
    );
}

/// 验证空角色字符串返回 Err(与 `check_permission_empty_string_errors` 对称,抛 `InvalidParam`)。
#[tokio::test]
async fn check_role_empty_string_errors() {
    let iface = MockInterface::new();
    let fw = make_firewall(iface);

    let result = fw.check_role("1001", "").await;
    assert!(
        matches!(result, Err(GarrisonError::InvalidParam(_))),
        "空角色字符串应抛 InvalidParam"
    );
}

// 多角色任一匹配 / 全部匹配

/// 验证 check_role_any:主体持有 roles 中任意一个即返回 true。
#[tokio::test]
async fn check_role_any_match_returns_true() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    let fw = make_firewall(iface);

    assert!(
        fw.check_role_any("1001", &["admin", "superadmin"])
            .await
            .unwrap(),
        "持有任一角色应返回 true"
    );
}

/// 验证 check_role_any:主体不持有 roles 中任何一个则返回 false。
#[tokio::test]
async fn check_role_any_no_match_returns_false() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["user"]);
    let fw = make_firewall(iface);

    assert!(
        !fw.check_role_any("1001", &["admin", "superadmin"])
            .await
            .unwrap(),
        "不持有任一角色应返回 false"
    );
}

/// 验证 check_role_all:主体持有 roles 中所有角色才返回 true。
#[tokio::test]
async fn check_role_all_all_held_returns_true() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin", "user"]);
    let fw = make_firewall(iface);

    assert!(
        fw.check_role_all("1001", &["admin", "user"]).await.unwrap(),
        "持有所有角色应返回 true"
    );
}

/// 主体仅持有部分角色时返回 false。
#[tokio::test]
async fn check_role_all_partial_held_returns_false() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    let fw = make_firewall(iface);

    assert!(
        !fw.check_role_all("1001", &["admin", "user"]).await.unwrap(),
        "仅持有部分角色应返回 false"
    );
}

/// 验证 check_role_all:空 roles 切片返回 true(空集平凡满足)。
#[tokio::test]
async fn check_role_all_empty_roles_returns_true() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    let fw = make_firewall(iface);

    assert!(
        fw.check_role_all("1001", &[]).await.unwrap(),
        "空 roles 切片应平凡返回 true"
    );
}

// get_permission_list / get_role_list 回调委托验证

/// 验证 get_permission_list 委托 GarrisonInterface 回调。
#[tokio::test]
async fn get_permission_list_delegates_to_interface() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read", "user:write"]);
    let fw = make_firewall(iface);

    let perms = fw.get_permission_list("1001").await.unwrap();
    assert_eq!(perms, vec!["user:read", "user:write"]);
}

/// 验证 get_role_list 委托 GarrisonInterface 回调。
#[tokio::test]
async fn get_role_list_delegates_to_interface() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin", "user"]);
    let fw = make_firewall(iface);

    let roles = fw.get_role_list("1001").await.unwrap();
    assert_eq!(roles, vec!["admin", "user"]);
}

/// 验证未配置权限的 login_id 返回空列表(不抛错)。
#[tokio::test]
async fn get_permission_list_unknown_login_id_returns_empty() {
    let iface = MockInterface::new();
    let fw = make_firewall(iface);

    let perms = fw.get_permission_list("9999").await.unwrap();
    assert!(perms.is_empty(), "未配置权限的 login_id 应返回空列表");
}

// PermissionChecker 集成测试

/// 可配置的 MockPermissionChecker,返回预设的权限/角色校验结果。
struct MockPermissionChecker {
    perm_result: bool,
}

#[async_trait]
impl PermissionChecker for MockPermissionChecker {
    async fn has_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<bool> {
        Ok(self.perm_result)
    }
    async fn has_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
        Ok(false)
    }
    async fn check_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn has_any_permission(&self, _login_id: &str, _perms: &[&str]) -> bool {
        false
    }
    async fn has_all_permissions(&self, _login_id: &str, _perms: &[&str]) -> bool {
        false
    }
}

/// 验证注入 PermissionChecker 后 check_permission 委托到它。
#[tokio::test]
async fn check_permission_delegates_to_permission_checker() {
    let iface = MockInterface::new();
    let pc = Arc::new(MockPermissionChecker { perm_result: true });
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_permission_checker(pc);

    // PermissionChecker 返回 true,即使 interface 中无权限记录
    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "注入 PermissionChecker 后应委托校验,返回 true"
    );
}

/// 验证 PermissionChecker 返回 false 时 check_permission 返回 false。
#[tokio::test]
async fn check_permission_delegates_returns_false() {
    let iface = MockInterface::new();
    let pc = Arc::new(MockPermissionChecker { perm_result: false });
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_permission_checker(pc);

    assert!(
        !fw.check_permission("1001", "user:read").await.unwrap(),
        "PermissionChecker 返回 false 时应返回 false"
    );
}

/// 验证未注入 PermissionChecker 时回退到 默认行为(直接查 interface)。
#[tokio::test]
async fn check_permission_without_checker_falls_back_to_interface() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read"]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));

    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "未注入 PermissionChecker 时应回退到 interface 查询"
    );
}

// 层级角色测试

/// 辅助函数:创建带角色层级的 firewall。
fn make_firewall_with_hierarchy(
    interface: MockInterface,
    hierarchy: HashMap<String, Vec<String>>,
) -> GarrisonPermissionStrategyDefault {
    GarrisonPermissionStrategyDefault::new(Arc::new(interface)).with_role_hierarchy(hierarchy)
}

/// 验证层级角色:admin 隐含持有 user。
#[tokio::test]
async fn check_role_hierarchy_admin_implies_user() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    let mut hierarchy = HashMap::new();
    hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
    let fw = make_firewall_with_hierarchy(iface, hierarchy);

    assert!(
        fw.check_role("1001", "user").await.unwrap(),
        "admin 应隐含持有 user"
    );
    assert!(
        !fw.check_role("1001", "superadmin").await.unwrap(),
        "admin 不隐含 superadmin"
    );
}

/// 验证层级角色多层传递:superadmin → admin → user。
#[tokio::test]
async fn check_role_hierarchy_transitive() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["superadmin"]);
    let mut hierarchy = HashMap::new();
    hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
    hierarchy.insert("superadmin".to_string(), vec!["admin".to_string()]);
    let fw = make_firewall_with_hierarchy(iface, hierarchy);

    assert!(
        fw.check_role("1001", "user").await.unwrap(),
        "superadmin 应多层传递隐含 user"
    );
    assert!(
        fw.check_role("1001", "admin").await.unwrap(),
        "superadmin 应隐含 admin"
    );
}

/// 验证未配置 role_hierarchy 时保持 默认行为。
#[tokio::test]
async fn check_role_without_hierarchy_uses_flat_matching() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    let fw = make_firewall(iface); // 无 hierarchy

    assert!(
        !fw.check_role("1001", "user").await.unwrap(),
        "未配置 hierarchy 时 admin 不隐含 user(0.1.0 行为)"
    );
}

/// 验证 check_role_any / check_role_all 在层级角色下的行为。
#[tokio::test]
async fn check_role_any_all_with_hierarchy() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    let mut hierarchy = HashMap::new();
    hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
    let fw = make_firewall_with_hierarchy(iface, hierarchy);

    // admin 隐含 user,所以 check_role_any(["user", "guest"]) 应返回 true
    assert!(
        fw.check_role_any("1001", &["user", "guest"]).await.unwrap(),
        "层级展开后应持有 user,check_role_any 应返回 true"
    );
    // admin 隐含 user,但不含 superadmin,check_role_all 应返回 false
    assert!(
        !fw.check_role_all("1001", &["user", "superadmin"])
            .await
            .unwrap(),
        "层级展开后不含 superadmin,check_role_all 应返回 false"
    );
}

// 插件钩子测试

/// 验证注入 PluginManager 后 check_permission 触发插件钩子。
#[tokio::test]
async fn check_permission_triggers_plugin_hook() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read"]);
    // GarrisonPluginManager::new() 收集所有 inventory 注册的插件
    let pm = Arc::new(GarrisonPluginManager::new());
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_plugin_manager(pm);

    // 插件钩子不应中断主流程,校验结果应正常返回
    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "插件钩子不应影响校验结果"
    );
}

/// 验证插件失败不中断 check_permission 主流程(当前实现为 Err → warn 不中断,不实现 spec 的 Override 机制)。
#[tokio::test]
async fn check_permission_plugin_failure_does_not_interrupt() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read"]);
    // PluginManager 包含 ErrPlugin(on_permission_check 返回 Err),
    // 但主流程不应被中断
    let pm = Arc::new(GarrisonPluginManager::new());
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_plugin_manager(pm);

    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "插件失败不应中断主流程,校验结果应正常返回 true"
    );
}

// 权限缓存测试

/// 验证 cache_permission 写入 DAO,后续 get_cached_permission 返回缓存值。
#[tokio::test]
async fn cache_permission_writes_and_reads_back() {
    let dao = Arc::new(MockCacheDao::new());
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    fw.cache_permission("1001", "user:read", true, 300)
        .await
        .unwrap();

    let cached = fw.get_cached_permission("1001", "user:read").await.unwrap();
    assert_eq!(cached, Some(true), "缓存应命中并返回 true");

    // 验证 key 格式:`garrison:perm:cache:v{version}:{tenant}:{enc(login)}:{enc(perm)}`——tenant 未设置时用占位符 `_`,
    // login/permission 经歧义消除编码(`:` → `%3A`),版本未失效时为 v0。
    let key = "garrison:perm:cache:v0:_:1001:user%3Aread";
    assert_eq!(
        dao.get(key).await.unwrap(),
        Some("true".to_string()),
        "DAO 中应存储 key {}",
        key
    );
}

/// 验证 get_cached_permission 未命中时返回 None。
#[tokio::test]
async fn get_cached_permission_miss_returns_none() {
    let dao = Arc::new(MockCacheDao::new());
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);

    let cached = fw
        .get_cached_permission("1001", "user:delete")
        .await
        .unwrap();
    assert!(cached.is_none(), "未缓存的权限应返回 None");
}

/// 验证缓存覆盖:相同 key 的第二次写入覆盖第一次。
#[tokio::test]
async fn cache_permission_overwrite() {
    let dao = Arc::new(MockCacheDao::new());
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);

    fw.cache_permission("1001", "user:read", true, 300)
        .await
        .unwrap();
    assert_eq!(
        fw.get_cached_permission("1001", "user:read").await.unwrap(),
        Some(true)
    );

    fw.cache_permission("1001", "user:read", false, 300)
        .await
        .unwrap();
    assert_eq!(
        fw.get_cached_permission("1001", "user:read").await.unwrap(),
        Some(false),
        "覆盖后应返回 false"
    );
}

/// 验证租户隔离:不同 tenant 相同 login_id 的权限缓存互不污染。
#[tokio::test]
async fn cache_permission_isolated_by_tenant() {
    let dao = Arc::new(MockCacheDao::new());
    let iface_a = MockInterface::new();
    let iface_b = MockInterface::new();

    let fw_tenant_a = GarrisonPermissionStrategyDefault::new(Arc::new(iface_a))
        .with_dao(dao.clone())
        .with_tenant_id(1);
    let fw_tenant_b = GarrisonPermissionStrategyDefault::new(Arc::new(iface_b))
        .with_dao(dao.clone())
        .with_tenant_id(2);

    // 租户 A 缓存 user:read = true
    fw_tenant_a
        .cache_permission("1001", "user:read", true, 300)
        .await
        .unwrap();

    // 租户 B 读取相同 login_id + permission 应未命中(互不污染)
    let b = fw_tenant_b
        .get_cached_permission("1001", "user:read")
        .await
        .unwrap();
    assert!(b.is_none(), "租户 B 不应读到租户 A 的缓存");

    // 各自键空间独立
    assert_eq!(
        dao.get("garrison:perm:cache:v0:1:1001:user%3Aread")
            .await
            .unwrap(),
        Some("true".to_string())
    );
    assert_eq!(
        dao.get("garrison:perm:cache:v0:2:1001:user%3Aread")
            .await
            .unwrap(),
        None
    );
}

/// 验证 invalidate_permission_cache 使权限回收立即生效,而非等 300s TTL。
#[tokio::test]
async fn invalidate_permission_cache_reflects_revocation_immediately() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &[]); // interface 实际无 user:read
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    // 预先写入矛盾缓存 true
    fw.cache_permission("1001", "user:read", true, 300)
        .await
        .unwrap();
    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "应命中缓存返回 true"
    );

    // 回收:失效该用户全部权限缓存
    fw.invalidate_permission_cache("1001").await.unwrap();

    // 失效后立即回源查询 interface(无 user:read),返回 false,不等 TTL
    assert!(
        !fw.check_permission("1001", "user:read").await.unwrap(),
        "失效后应立即回源返回 false,而非读取已回收的缓存"
    );
}

/// trait 方法 invalidate_login_cache(logout/kickout 联动入口)同样使权限回收立即生效——钉住登出联动失效路径,防 trait 默认 no-op 回归。
#[tokio::test]
async fn invalidate_login_cache_reflects_revocation_immediately() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &[]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    // 预先写入矛盾缓存 true
    fw.cache_permission("1001", "user:read", true, 300)
        .await
        .unwrap();
    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "应命中缓存返回 true"
    );

    // logout/kickout 联动入口:trait 方法失效缓存
    fw.invalidate_login_cache("1001").await.unwrap();

    assert!(
        !fw.check_permission("1001", "user:read").await.unwrap(),
        "invalidate_login_cache 后应立即回源返回 false"
    );
}

/// 验证 check_permission 优先读取缓存(短路优化)。
#[tokio::test]
async fn check_permission_uses_cache_short_circuit() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    // interface 中无 user:read 权限
    iface.set_permissions("1001", &[]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    // 预先写入缓存 true(与 interface 实际权限矛盾)
    fw.cache_permission("1001", "user:read", true, 300)
        .await
        .unwrap();

    // check_permission 应短路返回缓存值 true,不查询 interface
    assert!(
        fw.check_permission("1001", "user:read").await.unwrap(),
        "应优先返回缓存结果 true,而非查询 interface"
    );
}

// 权限缓存键歧义消除与跨租户失效回归(渗透-租户隔离-缓存键歧义-1 / 渗透-租户隔离-缓存失效-1)

/// 键碰撞回归:不同 (login_id, permission) 组合编码后必不同键。
///
/// 旧版裸冒号拼接下 (login="a:b", perm="c") 与 (login="a", perm="b:c") 同得 `garrison:perm:cache:_:a:b:c`(缓存投毒),编码后两组键必须互不命中。
#[tokio::test]
async fn perm_cache_key_components_do_not_collide_after_encoding() {
    let dao = Arc::new(MockCacheDao::new());
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    // 组合 1:login="a:b" + perm="c" 缓存 Allow
    fw.cache_permission("a:b", "c", true, 300).await.unwrap();
    assert_eq!(
        fw.get_cached_permission("a:b", "c").await.unwrap(),
        Some(true)
    );

    // 组合 2(旧版同键):login="a" + perm="b:c" 必须未命中(不得读到组合 1 的 Allow)
    assert_eq!(
        fw.get_cached_permission("a", "b:c").await.unwrap(),
        None,
        "编码后 (a:b, c) 与 (a, b:c) 不得共享缓存键"
    );

    // 组合 2 未命中 → 回源(interface 空)→ 判定 false 并写入自己的键
    let fw2 = GarrisonPermissionStrategyDefault::new(Arc::new(MockInterface::new()))
        .with_dao(dao.clone());
    assert!(
        !fw2.check_permission("a", "b:c").await.unwrap(),
        "组合 2 回源应为 false,不得被组合 1 的缓存污染"
    );
}

/// 编码后与旧版裸拼接键不冲突:旧版本写入的 `garrison:perm:cache:<t>:<login>:<perm>` 与新键
/// `garrison:perm:cache:v{ver}:<t>:<enc(login)>:<enc(perm)>` 键空间不相交(新键第 4 段恒为 `v<数字>`,旧键该段为租户,纯数字或 `_`),
/// 旧键残留既不会被读到(防投毒),也不与新键碰撞。
#[tokio::test]
async fn perm_cache_key_encoded_format_never_hits_legacy_key() {
    let dao = Arc::new(MockCacheDao::new());
    // 手工写入旧版裸拼接键(模拟升级前残留)
    dao.set("garrison:perm:cache:1:1001:user:read", "true", 300)
        .await
        .unwrap();

    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &[]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
        .with_dao(dao)
        .with_tenant_id(1);

    // 新键未命中:旧键残留不得命中(返回 None),回源判定 false
    assert_eq!(
        fw.get_cached_permission("1001", "user:read").await.unwrap(),
        None,
        "旧版裸拼接键残留不得被新版编码键读到"
    );
    assert!(
        !fw.check_permission("1001", "user:read").await.unwrap(),
        "回源判定应为 false(旧键 Allow 不得越权)"
    );
}

/// 跨租户失效回归(渗透-租户隔离-缓存失效-1 场景 A):多租户装配(builder 不设租户)下,
/// 请求级租户段写入的 Allow 经 invalidate_login_cache(logout/kickout 联动)必须立即清除。
#[tokio::test]
async fn invalidate_login_cache_clears_request_tenant_segments() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    iface.set_permissions("u1", &[]); // 回收后回源应 false
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    // 租户 7 请求级租户段预先写入 Allow(模拟回收前的判定缓存)
    fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
        .await
        .unwrap();
    assert!(
        fw.check_permission_in_tenant(7, "u1", "doc:read")
            .await
            .unwrap(),
        "预置条件:回收前缓存命中 Allow"
    );

    // 管理员回收权限 + kickout(invalidate_login_cache 无租户参数)
    fw.invalidate_login_cache("u1").await.unwrap();

    // 旧 Allow 不得存续:租户 7 段立即回源返回 false
    assert_eq!(
        fw.get_cached_permission_with(Some(7), "u1", "doc:read")
            .await
            .unwrap(),
        None,
        "失效后其他租户段的旧 Allow 必须清除"
    );
    assert!(
        !fw.check_permission_in_tenant(7, "u1", "doc:read")
            .await
            .unwrap(),
        "失效后应立即回源返回 false,而非读取已回收的缓存"
    );
}

/// 跨租户失效回归(渗透-租户隔离-缓存失效-1 场景 C):builder 配置租户(1)与请求级租户(7)错位时,失效端仍须清掉 7 段。
#[tokio::test]
async fn invalidate_permission_cache_clears_all_tenant_segments() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    iface.set_permissions("u1", &[]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
        .with_dao(dao)
        .with_tenant_id(1);

    // 请求级租户 7 写入 Allow(与 builder 租户 1 错位)
    fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
        .await
        .unwrap();
    assert_eq!(
        fw.get_cached_permission_with(Some(7), "u1", "doc:read")
            .await
            .unwrap(),
        Some(true)
    );

    // invalidate_permission_cache(业务方权限变更监听器调用点)无租户参数
    fw.invalidate_permission_cache("u1").await.unwrap();

    assert_eq!(
        fw.get_cached_permission_with(Some(7), "u1", "doc:read")
            .await
            .unwrap(),
        None,
        "失效端必须跨租户清除,而非只清 builder 配置租户段"
    );
}

/// 失效版本号隔离:失效只影响目标 login_id,不误伤其他主体。
#[tokio::test]
async fn invalidate_permission_cache_scopes_to_target_login_id() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    iface.set_permissions("u1", &[]);
    iface.set_permissions("u2", &["doc:read"]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);

    fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
        .await
        .unwrap();
    fw.cache_permission_with(Some(7), "u2", "doc:read", true, 300)
        .await
        .unwrap();

    fw.invalidate_permission_cache("u1").await.unwrap();

    assert_eq!(
        fw.get_cached_permission_with(Some(7), "u1", "doc:read")
            .await
            .unwrap(),
        None,
        "目标 login_id 的缓存应失效"
    );
    assert_eq!(
        fw.get_cached_permission_with(Some(7), "u2", "doc:read")
            .await
            .unwrap(),
        Some(true),
        "其他主体的缓存不得被误伤"
    );
}

/// 失效纪元唯一性回归:每次失效写入全新随机 UUID 标签。
///
/// 计数器方案在纪元键过期后计数重走,与上一纪元同值的旧 Allow 键仍存活时可被再次命中(复活窗口);随机标签使新旧纪元标签结构性不相等,
/// 本测试钉死「标签为非计数 UUID 且逐次互异 + 旧键物理在场亦不可达」。
#[tokio::test]
async fn invalidation_epoch_is_fresh_uuid_per_call_and_old_keys_unreachable() {
    let dao = Arc::new(MockCacheDao::new());
    let mut iface = MockInterface::new();
    iface.set_permissions("u1", &[]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    // 哨兵纪元(v0)写入 Allow
    fw.cache_permission_with(Some(7), "u1", "doc:read", true, 300)
        .await
        .unwrap();
    let v0_key = "garrison:perm:cache:v0:7:u1:doc%3Aread";
    assert_eq!(dao.get(v0_key).await.unwrap().as_deref(), Some("true"));

    // 两次失效 → 纪元标签互异且为 32 位 hex(UUID simple),非计数重用
    fw.invalidate_permission_cache("u1").await.unwrap();
    let epoch_a = dao
        .get("garrison:decision:ver:u1")
        .await
        .unwrap()
        .expect("首次失效后纪元键应存在");
    fw.invalidate_permission_cache("u1").await.unwrap();
    let epoch_b = dao
        .get("garrison:decision:ver:u1")
        .await
        .unwrap()
        .expect("二次失效后纪元键应存在");
    assert_ne!(epoch_a, epoch_b, "每次失效必须生成全新纪元标签");
    for epoch in [&epoch_a, &epoch_b] {
        assert_eq!(epoch.len(), 32, "纪元标签应为 UUID simple(32 hex)");
        assert!(
            epoch.bytes().all(|b| b.is_ascii_hexdigit()),
            "纪元标签应为 hex:{epoch}"
        );
    }

    // 旧哨兵纪元键仍物理在场,但当前纪元已迁移 → 读取必须不可达
    assert_eq!(
        dao.get(v0_key).await.unwrap().as_deref(),
        Some("true"),
        "旧纪元键残留为存储垃圾(TTL 兜底),属预期"
    );
    assert_eq!(
        fw.get_cached_permission_with(Some(7), "u1", "doc:read")
            .await
            .unwrap(),
        None,
        "旧纪元 Allow 键物理在场时也必须不可达(失效结构性生效)"
    );
}

// 租户感知数据源(渗透-RBAC-租户维度-1)回归

/// 租户感知 interface mock:按 (tenant_id, login_id) 返回角色/权限,覆写 `get_*_list_in_tenant` 模拟业务方租户隔离数据源。
struct TenantAwareMockInterface {
    roles: HashMap<(i64, String), Vec<String>>,
    permissions: HashMap<(i64, String), Vec<String>>,
    global_roles: HashMap<String, Vec<String>>,
}

#[async_trait]
impl GarrisonInterface for TenantAwareMockInterface {
    async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(Vec::new())
    }

    async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
        Ok(self.global_roles.get(login_id).cloned().unwrap_or_default())
    }

    async fn get_role_list_in_tenant(
        &self,
        tenant_id: i64,
        login_id: &str,
    ) -> GarrisonResult<Vec<String>> {
        Ok(self
            .roles
            .get(&(tenant_id, login_id.to_string()))
            .cloned()
            .unwrap_or_default())
    }

    async fn get_permission_list_in_tenant(
        &self,
        tenant_id: i64,
        login_id: &str,
    ) -> GarrisonResult<Vec<String>> {
        Ok(self
            .permissions
            .get(&(tenant_id, login_id.to_string()))
            .cloned()
            .unwrap_or_default())
    }
}

/// check_role_in_tenant 必须消费租户参数(租户感知数据源已实现时):跨租户重名 login_id 的角色不得互染(渗透-RBAC-租户维度-1 回归)。
#[tokio::test]
async fn check_role_in_tenant_queries_tenant_scoped_data_source() {
    let mut iface = TenantAwareMockInterface {
        roles: HashMap::new(),
        permissions: HashMap::new(),
        global_roles: HashMap::new(),
    };
    // 两个租户各有一个重名 login_id "admin":租户 1 授予 tenant-a-root
    iface
        .roles
        .insert((1, "admin".to_string()), vec!["tenant-a-root".to_string()]);
    // 租户 2 的 "admin" 无任何角色
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));

    assert!(
        fw.check_role_in_tenant(1, "admin", "tenant-a-root")
            .await
            .unwrap(),
        "租户 1 的 admin 应持有租户 1 授予的角色"
    );
    assert!(
        !fw.check_role_in_tenant(2, "admin", "tenant-a-root")
            .await
            .unwrap(),
        "租户 2 的重名 admin 不得继承租户 1 的角色(互染回归)"
    );
}

// check_role_scoped 判定缓存(注入 DAO 的路径)回归

/// check_role_in_tenant 注入 DAO 时回填判定缓存:true / false 两种结果都落 `garrison:role:cache:` 键(租户段 + 纪元哨兵)。
#[tokio::test]
async fn check_role_in_tenant_fills_decision_cache() {
    let mut iface = MockInterface::new();
    iface.set_roles("u-cache", &["admin"]);
    let dao = Arc::new(MockCacheDao::new());
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao.clone());

    assert!(
        fw.check_role_in_tenant(1, "u-cache", "admin")
            .await
            .unwrap(),
        "数据源持有角色应判定 true"
    );
    assert_eq!(
        dao.get("garrison:role:cache:v0:1:u-cache:admin")
            .await
            .unwrap(),
        Some("true".to_string()),
        "true 判定应回填缓存键"
    );

    assert!(
        !fw.check_role_in_tenant(1, "u-cache", "auditor")
            .await
            .unwrap(),
        "数据源未持有角色应判定 false"
    );
    assert_eq!(
        dao.get("garrison:role:cache:v0:1:u-cache:auditor")
            .await
            .unwrap(),
        Some("false".to_string()),
        "false 判定同样回填缓存键"
    );
}

/// check_role_in_tenant 命中缓存直接返回缓存值:数据源无该角色时也以缓存为准(证明未回源判定)。
#[tokio::test]
async fn check_role_in_tenant_serves_cached_decision() {
    let iface = MockInterface::new();
    let dao = Arc::new(MockCacheDao::new());
    dao.set("garrison:role:cache:v0:1:u-hit:admin", "true", 300)
        .await
        .unwrap();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(dao);

    assert!(
        fw.check_role_in_tenant(1, "u-hit", "admin").await.unwrap(),
        "缓存命中应返回缓存值 true(数据源为空)"
    );
    assert!(
        !fw.check_role_in_tenant(1, "u-hit", "auditor")
            .await
            .unwrap(),
        "缓存未命中且数据源为空应判定 false"
    );
}

/// 空角色名显性报错(不做静默放行)。
#[tokio::test]
async fn check_role_in_tenant_empty_role_errors() {
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));

    assert!(
        matches!(
            fw.check_role_in_tenant(1, "1001", "").await,
            Err(GarrisonError::InvalidParam(_))
        ),
        "空角色名应抛 InvalidParam"
    );
}

/// 角色层级展开与判定缓存共存:admin 隐含 user,回源展开后按层级判定 true。
#[tokio::test]
async fn check_role_in_tenant_hierarchy_with_cache_dao() {
    let mut iface = MockInterface::new();
    iface.set_roles("u-hier", &["admin"]);
    let mut hierarchy = HashMap::new();
    hierarchy.insert("admin".to_string(), vec!["user".to_string()]);
    let dao = Arc::new(MockCacheDao::new());
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
        .with_dao(dao)
        .with_role_hierarchy(hierarchy);

    assert!(
        fw.check_role_in_tenant(1, "u-hier", "user").await.unwrap(),
        "admin 应隐含 user(层级展开生效)"
    );
}

/// check_permission_in_tenant 在租户感知数据源已实现时按租户过滤权限。
#[tokio::test]
async fn check_permission_in_tenant_queries_tenant_scoped_data_source() {
    let mut iface = TenantAwareMockInterface {
        roles: HashMap::new(),
        permissions: HashMap::new(),
        global_roles: HashMap::new(),
    };
    iface
        .permissions
        .insert((1, "admin".to_string()), vec!["doc:delete".to_string()]);
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface));

    assert!(
        fw.check_permission_in_tenant(1, "admin", "doc:delete")
            .await
            .unwrap(),
        "租户 1 的 admin 应持有租户 1 授予的权限"
    );
    assert!(
        !fw.check_permission_in_tenant(2, "admin", "doc:delete")
            .await
            .unwrap(),
        "租户 2 的重名 admin 不得继承租户 1 的权限(互染回归)"
    );
}

/// GarrisonInterface 租户感知默认方法委托全局方法(无行为破坏契约):未覆写 `get_role_list_in_tenant` 的既有实现,in_tenant 路径数据与全局一致。
#[tokio::test]
async fn interface_tenant_aware_defaults_delegate_to_global() {
    let mut iface = MockInterface::new();
    iface.set_roles("1001", &["admin"]);
    iface.set_permissions("1001", &["user:read"]);

    let roles = iface.get_role_list_in_tenant(7, "1001").await.unwrap();
    assert_eq!(
        roles,
        vec!["admin"],
        "默认实现应委托 get_role_list(忽略租户)"
    );
    let perms = iface
        .get_permission_list_in_tenant(7, "1001")
        .await
        .unwrap();
    assert_eq!(
        perms,
        vec!["user:read"],
        "默认实现应委托 get_permission_list(忽略租户)"
    );
}

// 防火墙安全钩子集成测试

/// 验证未注入 firewall_hook 时 check_login_hooks 为 no-op(无防火墙检查直接放行)。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_noop_without_hook() {
    let iface = MockInterface::new();
    let fw = make_firewall(iface);
    let ctx = LoginContext::new("1001");

    // 未注入 hook,应直接返回 Ok
    assert!(
        fw.check_login_hooks("1001", &ctx).await.is_ok(),
        "未注入 firewall_hook 时 check_login_hooks 应为 no-op"
    );
}

/// 验证注入 hook 且所有检查通过时 check_login_hooks 返回 Ok。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_passes_with_hook() {
    let iface = MockInterface::new();
    let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook);
    let ctx = LoginContext::new("1001");

    // hook 计数器为空,所有检查应通过
    assert!(
        fw.check_login_hooks("1001", &ctx).await.is_ok(),
        "注入 hook 且无失败记录时 check_login_hooks 应返回 Ok"
    );
}

/// 验证 hook 在登录频率超限时阻断 check_login_hooks。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_blocks_on_frequency_exceeded() {
    let iface = MockInterface::new();
    let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
    let fw =
        GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook.clone());
    let ctx = LoginContext::new("1001").with_ip("1.2.3.4");

    // 记录 10 次失败(达到阈值)
    for _ in 0..10 {
        hook.record_failure(&ctx).await.unwrap();
    }

    // check_login_hooks 应被 login_frequency hook 阻断
    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "登录频率超限时应被 check_login_hooks 阻断");
    assert!(
        matches!(result.unwrap_err(), GarrisonError::Session(_)),
        "阻断错误应为 Session 类型"
    );
}

/// 验证 hook 在暴力破解超限时阻断 check_login_hooks。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_blocks_on_brute_force_exceeded() {
    let iface = MockInterface::new();
    let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
    let fw =
        GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook.clone());
    let ctx = LoginContext::new("1001"); // 无 IP,仅触发暴力破解检测

    // 记录 5 次失败(达到阈值)
    for _ in 0..5 {
        hook.record_failure(&ctx).await.unwrap();
    }

    // check_login_hooks 应被 brute_force hook 阻断
    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "暴力破解超限时应被 check_login_hooks 阻断");
}

/// 验证 with_firewall_hook builder 方法正确注入 hook。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn with_firewall_hook_injects_hook() {
    let iface = MockInterface::new();
    let hook = Arc::new(GarrisonFirewallCheckHookDefault::new());
    let fw =
        GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook.clone());

    // 注入后,记录失败并触发检测应能阻断
    let ctx = LoginContext::new("1001").with_ip("9.9.9.9");
    for _ in 0..10 {
        hook.record_failure(&ctx).await.unwrap();
    }
    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "注入 hook 后应能检测到频率超限并阻断");
}

/// 验证 check_login_hooks 按 5 个 hook 顺序调用(login_frequency 先于 brute_force);IP 维度先达阈值时应优先返回 login_frequency 错误。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_calls_in_order() {
    use std::sync::atomic::{AtomicU8, Ordering};

    /// 记录调用顺序的测试 hook。
    struct OrderTrackingHook {
        order: Arc<AtomicU8>,
    }

    #[async_trait]
    impl GarrisonFirewallCheckHook for OrderTrackingHook {
        async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.order.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
        async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.order.fetch_add(2, Ordering::SeqCst);
            Ok(())
        }
        async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.order.fetch_add(4, Ordering::SeqCst);
            Ok(())
        }
        async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.order.fetch_add(8, Ordering::SeqCst);
            Ok(())
        }
        async fn check_device_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.order.fetch_add(16, Ordering::SeqCst);
            Ok(())
        }
    }

    let order = Arc::new(AtomicU8::new(0));
    let hook = Arc::new(OrderTrackingHook {
        order: order.clone(),
    });
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook);
    let ctx = LoginContext::new("1001");

    fw.check_login_hooks("1001", &ctx).await.unwrap();

    // 5 个 hook 按序调用:1 + 2 + 4 + 8 + 16 = 31
    assert_eq!(order.load(Ordering::SeqCst), 31, "5 个 hook 应全部按序调用");
}

/// 验证 check_login_hooks 任一 hook Err 立即阻断后续 hook。
#[cfg(any(
    feature = "sms-rate-limit",
    feature = "firewall-ratelimit",
    feature = "firewall-bruteforce",
    feature = "firewall-ddos",
    feature = "firewall",
    feature = "oauth2-server"
))]
#[tokio::test]
async fn check_login_hooks_short_circuits_on_err() {
    use std::sync::atomic::{AtomicU8, Ordering};

    struct ShortCircuitHook {
        called: Arc<AtomicU8>,
    }

    #[async_trait]
    impl GarrisonFirewallCheckHook for ShortCircuitHook {
        async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.called.fetch_add(1, Ordering::SeqCst);
            Err(GarrisonError::Session("frequency blocked".to_string()))
        }
        async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.called.fetch_add(2, Ordering::SeqCst);
            Ok(())
        }
        async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.called.fetch_add(4, Ordering::SeqCst);
            Ok(())
        }
        async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.called.fetch_add(8, Ordering::SeqCst);
            Ok(())
        }
        async fn check_device_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            self.called.fetch_add(16, Ordering::SeqCst);
            Ok(())
        }
    }

    let called = Arc::new(AtomicU8::new(0));
    let hook = Arc::new(ShortCircuitHook {
        called: called.clone(),
    });
    let iface = MockInterface::new();
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_firewall_hook(hook);
    let ctx = LoginContext::new("1001");

    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "应在第一个 hook Err 时阻断");

    // 仅第一个 hook 被调用(值为 1),后续 4 个未调用
    assert_eq!(
        called.load(Ordering::SeqCst),
        1,
        "第一个 hook Err 后应短路,后续 hook 不应被调用"
    );
}

// 覆盖率补充:with_listener_manager、缓存写入失败、多 hook 失败

/// `with_listener_manager` 注入后 listener_manager 字段为 Some。
#[cfg(feature = "listener")]
#[test]
fn with_listener_manager_sets_field() {
    use crate::listener::GarrisonListenerManager;
    let lm = Arc::new(GarrisonListenerManager::new());
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(MockInterface::new()))
        .with_listener_manager(lm);
    assert!(
        fw.listener_manager.is_some(),
        "with_listener_manager 后 listener_manager 应为 Some"
    );
}

/// `check_permission` 缓存写入失败时仅 warn 不中断,仍返回正确结果(用 FailingDao(set 返回 Err)触发缓存写入失败)。
#[tokio::test]
async fn check_permission_cache_write_failure_warns_but_returns_result() {
    /// 所有写操作都失败的 DAO
    struct FailingDao;
    #[async_trait]
    impl crate::dao::GarrisonDao for FailingDao {
        async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
            Ok(None)
        }
        async fn set(&self, _key: &str, _value: &str, _ttl: u64) -> GarrisonResult<()> {
            Err(GarrisonError::Dao("simulated set failure".to_string()))
        }
        async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
            Err(GarrisonError::Dao("simulated update failure".to_string()))
        }
        async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
            Err(GarrisonError::Dao("simulated expire failure".to_string()))
        }
        async fn delete(&self, _key: &str) -> GarrisonResult<()> {
            Ok(())
        }

        crate::atomic_test_fallback!();
    }

    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read"]);
    // atomic + 默认 trait 方法覆盖(在 Arc 包装前调用)
    {
        let d = FailingDao;
        let _ = d.set_if_absent("a", "v", 60).await;
        let _ = d.get_and_delete("a").await;
        let _ = d.incr("c", 60).await;
        let _ = d.decr("c").await;
        let _ = d.rename("a", "b").await;
        let _ = d.compare_and_swap("b", None, "v", 60).await;
        let _ = d.set_permanent("p", "v").await;
        let _ = d.get_timeout("k").await;
        let _ = d.get_with_ttl("k").await;
        let _ = d.keys("*").await;
        let _ = d.find_social_binding(0, "w", "o").await;
        let _ = d.insert_social_binding(0, "u", "w", "o", None, 0).await;
        let _ = d.compare_and_update_if_greater("k", 1, 60).await;
        let _ = d.eval_lua("r", vec![], vec![]).await;
        #[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
        {
            let _ = d.insert_credit_consumption(0, "r", 1, 1, 1, 0).await;
            let _ = d.query_credit_consumption(0, 0, 0).await;
            let _ = d.query_role_hierarchy_edges(0).await;
            let _ = d.insert_role_hierarchy_edge(0, "c", "p").await;
            let _ = d.delete_role_hierarchy_edge(0, "c", "p").await;
        }
    }
    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface)).with_dao(Arc::new(FailingDao));
    // 缓存写入失败但 check_permission 仍应返回 true(持有权限)
    let result = fw.check_permission("1001", "user:read").await;
    assert!(
        result.is_ok(),
        "缓存写入失败不应中断 check_permission,实际: {:?}",
        result
    );
    assert!(
        result.unwrap(),
        "持有权限应返回 true(缓存写入失败不影响结果)"
    );
}

/// `check_login_hooks` 第 3 个 hook(check_geo_anomaly)失败时广播 FirewallBlock 并阻断。
///
/// 需 listener + firewall/oauth2 双重 cfg 门控(仅 listener 门控在 listener + 无 firewall 时会编译失败)。
#[cfg(all(
    feature = "listener",
    any(
        feature = "sms-rate-limit",
        feature = "firewall-ratelimit",
        feature = "firewall-bruteforce",
        feature = "firewall-ddos",
        feature = "firewall",
        feature = "oauth2-server"
    )
))]
#[tokio::test]
async fn check_login_hooks_geo_anomaly_failure_broadcasts_firewall_block() {
    use crate::listener::GarrisonListenerManager;
    let iface = MockInterface::new();
    let lm = Arc::new(GarrisonListenerManager::new());

    struct GeoFailHook;
    #[async_trait]
    impl crate::strategy::GarrisonFirewallCheckHook for GeoFailHook {
        async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Err(GarrisonError::Session("geo blocked".to_string()))
        }
    }

    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
        .with_firewall_hook(Arc::new(GeoFailHook))
        .with_listener_manager(lm);
    let ctx = LoginContext::new("1001");
    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "geo_anomaly 失败应阻断");
    assert!(
        matches!(result.unwrap_err(), GarrisonError::Session(_)),
        "应返回 Session 错误"
    );
}

/// `check_login_hooks` 第 4 个 hook(check_token_reuse)失败时广播并阻断(双重 cfg 门控同上)。
#[cfg(all(
    feature = "listener",
    any(
        feature = "sms-rate-limit",
        feature = "firewall-ratelimit",
        feature = "firewall-bruteforce",
        feature = "firewall-ddos",
        feature = "firewall",
        feature = "oauth2-server"
    )
))]
#[tokio::test]
async fn check_login_hooks_token_reuse_failure_broadcasts() {
    use crate::listener::GarrisonListenerManager;
    let iface = MockInterface::new();
    let lm = Arc::new(GarrisonListenerManager::new());

    struct TokenReuseFailHook;
    #[async_trait]
    impl crate::strategy::GarrisonFirewallCheckHook for TokenReuseFailHook {
        async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Err(GarrisonError::Session("token reuse blocked".to_string()))
        }
    }

    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
        .with_firewall_hook(Arc::new(TokenReuseFailHook))
        .with_listener_manager(lm);
    let ctx = LoginContext::new("1001");
    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "token_reuse 失败应阻断");
}

/// `check_login_hooks` 第 5 个 hook(check_device_anomaly)失败时广播并阻断(双重 cfg 门控同上)。
#[cfg(all(
    feature = "listener",
    any(
        feature = "sms-rate-limit",
        feature = "firewall-ratelimit",
        feature = "firewall-bruteforce",
        feature = "firewall-ddos",
        feature = "firewall",
        feature = "oauth2-server"
    )
))]
#[tokio::test]
async fn check_login_hooks_device_anomaly_failure_broadcasts() {
    use crate::listener::GarrisonListenerManager;
    let iface = MockInterface::new();
    let lm = Arc::new(GarrisonListenerManager::new());

    struct DeviceFailHook;
    #[async_trait]
    impl crate::strategy::GarrisonFirewallCheckHook for DeviceFailHook {
        async fn check_login_frequency(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_brute_force(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_geo_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_token_reuse(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_device_anomaly(&self, _ctx: &LoginContext) -> GarrisonResult<()> {
            Err(GarrisonError::Session("device anomaly blocked".to_string()))
        }
    }

    let fw = GarrisonPermissionStrategyDefault::new(Arc::new(iface))
        .with_firewall_hook(Arc::new(DeviceFailHook))
        .with_listener_manager(lm);
    let ctx = LoginContext::new("1001");
    let result = fw.check_login_hooks("1001", &ctx).await;
    assert!(result.is_err(), "device_anomaly 失败应阻断");
}

/// 调用 `get_permission_list_with_type` / `get_role_list_with_type` 默认委托方法,覆盖 async_trait 生成的 wrapper 函数。
#[tokio::test]
async fn mock_interface_default_methods_with_type_coverage() {
    let mut iface = MockInterface::new();
    iface.set_permissions("1001", &["user:read", "user:write"]);
    iface.set_roles("1001", &["admin", "user"]);

    // 默认实现委托 get_permission_list / get_role_list
    let perms = iface
        .get_permission_list_with_type("1001", "user")
        .await
        .unwrap();
    assert_eq!(perms, vec!["user:read", "user:write"]);
    let roles = iface
        .get_role_list_with_type("1001", "admin")
        .await
        .unwrap();
    assert_eq!(roles, vec!["admin", "user"]);
}

/// 调用 FailingDao 的原子方法以覆盖 atomic_test_fallback! 生成的 async wrapper。
#[tokio::test]
async fn failing_dao_atomic_methods_coverage() {
    use crate::dao::GarrisonDao;

    /// 简单 DAO,set 成功,用于原子方法测试。
    struct SimpleDao;
    #[async_trait]
    impl crate::dao::GarrisonDao for SimpleDao {
        async fn get(&self, key: &str) -> crate::error::GarrisonResult<Option<String>> {
            Ok(Some(key.to_string()))
        }
        async fn set(
            &self,
            _key: &str,
            _value: &str,
            _ttl: u64,
        ) -> crate::error::GarrisonResult<()> {
            Ok(())
        }
        async fn update(&self, _key: &str, _value: &str) -> crate::error::GarrisonResult<()> {
            Ok(())
        }
        async fn expire(&self, _key: &str, _seconds: u64) -> crate::error::GarrisonResult<()> {
            Ok(())
        }
        async fn delete(&self, _key: &str) -> crate::error::GarrisonResult<()> {
            Ok(())
        }
        crate::atomic_test_fallback!();
    }

    let dao = SimpleDao;
    let _ = dao.set_if_absent("k1", "v1", 60).await;
    let _ = dao.get_and_delete("k1").await;
    let _ = dao.incr("counter", 60).await;
    let _ = dao.decr("counter").await;
    let _ = dao.rename("old", "new").await;
    let _ = dao.compare_and_swap("k2", Some("old"), "new", 60).await;
}