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

use super::mock::MockDao;
use super::*;
use crate::core::token::UuidTokenStyle;
use crate::dao::GarrisonDao;
use crate::session::token_key;
use async_trait::async_trait;
use std::time::Duration;

/// 辅助函数:创建 AuthLogicDefault 实例(UuidTokenStyle + MockDao,默认 DenyAllSwitchToGuard)。
fn make_auth_logic(timeout: u64, active_timeout: u64) -> AuthLogicDefault {
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let session = Arc::new(GarrisonSession::new(dao, timeout, active_timeout, 0));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    AuthLogicDefault::new(session, token_handler, timeout as i64)
}

/// 测试用 allow-all guard:允许所有 switch_to 切换。
struct TestAllowAllGuard;
#[async_trait::async_trait]
impl SwitchToGuard for TestAllowAllGuard {
    async fn check(&self, _original: &str, _target: &str) -> GarrisonResult<()> {
        Ok(())
    }
}

/// 辅助函数:创建 AuthLogicDefault 实例,注入 TestAllowAllGuard。
fn make_auth_logic_allow_switch(timeout: u64, active_timeout: u64) -> AuthLogicDefault {
    make_auth_logic(timeout, active_timeout).with_switch_to_guard(Arc::new(TestAllowAllGuard))
}

// login 测试

/// login 生成非空 token 并建立会话。
#[tokio::test]
async fn login_generates_token_and_session() {
    let auth = make_auth_logic(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    assert!(!token.is_empty());
    assert!(auth.is_login(&token).await.unwrap());
}

/// login 后 get_login_id 返回关联 ID。
#[tokio::test]
async fn login_associates_login_id() {
    let auth = make_auth_logic(3600, 86400);
    let token = auth.login("2002", None).await.unwrap();
    let login_id = auth.get_login_id(&token).await.unwrap();
    assert_eq!(login_id, Some("2002".to_string()));
}

/// login 多次生成不同 token。
#[tokio::test]
async fn login_generates_unique_tokens() {
    let auth = make_auth_logic(3600, 86400);
    let t1 = auth.login("1001", None).await.unwrap();
    let t2 = auth.login("1001", None).await.unwrap();
    assert_ne!(t1, t2);
}

// logout 测试

/// logout 销毁指定 token 会话。
#[tokio::test]
async fn logout_destroys_session() {
    let auth = make_auth_logic(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    assert!(auth.is_login(&token).await.unwrap());
    auth.logout(&token).await.unwrap();
    assert!(!auth.is_login(&token).await.unwrap());
}

/// logout 幂等处理无效 token。
#[tokio::test]
async fn logout_idempotent_for_invalid_token() {
    let auth = make_auth_logic(3600, 86400);
    let result = auth.logout("non-existent-token").await;
    assert_eq!(
        result.unwrap(),
        (),
        "不存在的 token logout 应返回 Ok(())(幂等)"
    );
}

/// logout 不影响同账号的其他 token。
#[tokio::test]
async fn logout_preserves_other_tokens() {
    let auth = make_auth_logic(3600, 86400);
    let t1 = auth.login("1001", None).await.unwrap();
    let t2 = auth.login("1001", None).await.unwrap();
    auth.logout(&t1).await.unwrap();
    assert!(auth.is_login(&t2).await.unwrap());
    assert!(!auth.is_login(&t1).await.unwrap());
}

// is_login 测试

/// is_login 有效 token 返回 true。
#[tokio::test]
async fn is_login_valid_token_returns_true() {
    let auth = make_auth_logic(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    assert!(auth.is_login(&token).await.unwrap());
}

/// is_login 无效 token 返回 false。
#[tokio::test]
async fn is_login_invalid_token_returns_false() {
    let auth = make_auth_logic(3600, 86400);
    assert!(!auth.is_login("invalid-token").await.unwrap());
}

// get_login_id 测试

/// get_login_id 有效 token 返回 Some(id)。
#[tokio::test]
async fn get_login_id_valid_token_returns_some() {
    let auth = make_auth_logic(3600, 86400);
    let token = auth.login("3003", None).await.unwrap();
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("3003".to_string())
    );
}

/// get_login_id 无效 token 返回 None。
#[tokio::test]
async fn get_login_id_invalid_token_returns_none() {
    let auth = make_auth_logic(3600, 86400);
    assert_eq!(auth.get_login_id("invalid").await.unwrap(), None);
}

// verify_token 测试

/// verify_token 有效 token 返回 login_id。
#[tokio::test]
async fn verify_token_valid_returns_login_id() {
    let auth = make_auth_logic(3600, 86400);
    let token = auth.login("4004", None).await.unwrap();
    assert_eq!(auth.verify_token(&token).await.unwrap(), "4004".to_string());
}

/// verify_token 无效 token 返回 InvalidToken 错误。
#[tokio::test]
async fn verify_token_invalid_returns_error() {
    let auth = make_auth_logic(3600, 86400);
    let result = auth.verify_token("invalid-token").await;
    assert!(result.is_err());
    match result.err() {
        Some(GarrisonError::InvalidToken(_)) => {},
        other => panic!("期望 InvalidToken,实际: {:?}", other),
    }
}

/// verify_token 已过期 token 返回错误。
#[tokio::test]
async fn verify_token_expired_returns_error() {
    let auth = make_auth_logic(1, 1);
    let token = auth.login("5005", None).await.unwrap();
    // 等待 token 过期(timeout=1s + active_timeout=1s)
    tokio::time::sleep(Duration::from_secs(2)).await;
    let result = auth.verify_token(&token).await;
    assert!(result.is_err());
}

// switch_to 测试

/// switch_to 更新 login_id 并存储 switched_from(使用 AllowAll guard)。
#[tokio::test]
async fn switch_to_updates_login_id_and_stores_switched_from() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // ensure_token_in_account_session 拒绝创建新 Account-Session,
    // 需预先 login target 以确保其 Account-Session 存在。
    let _ = auth.login("2002", None).await.unwrap();
    auth.switch_to(&token, "2002").await.unwrap();
    // get_login_id 应返回新的 login_id
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("2002".to_string())
    );
    let switched_from = auth.session.get(&token, "switched_from").await.unwrap();
    assert_eq!(switched_from, Some("1001".to_string()));
}

/// switch_to 清空因子账本与 auth_time(fail-closed:原主体 step-up 成果不得让目标身份免认证)。
#[tokio::test]
async fn switch_to_resets_amr_ledger_and_auth_time() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    let _ = auth.login("2002", None).await.unwrap();

    // 原主体完成一次 otp step-up(账本升级到 aal 2)
    auth.session
        .append_amr_entry(&token, "otp", 2, chrono::Utc::now().timestamp())
        .await
        .unwrap();
    let before = auth
        .session
        .get_token_session(&token)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(before.amr_ledger.len(), 2, "前置:账本应含 pwd + otp");
    assert!(before.auth_time.is_some(), "前置:auth_time 应已播种");

    auth.switch_to(&token, "2002").await.unwrap();

    let after = auth
        .session
        .get_token_session(&token)
        .await
        .unwrap()
        .unwrap();
    assert!(
        after.amr_ledger.is_empty(),
        "身份切换后因子账本应清空(原主体 step-up 不得继承),实际: {:?}",
        after.amr_ledger
    );
    assert_eq!(
        after.auth_time, None,
        "身份切换后 auth_time 应置 None(freshness 判 Stale 强制重新 step-up)"
    );
}

/// switch_to 后 token 仍然有效(is_login 返回 true)。
#[tokio::test]
async fn switch_to_preserves_token_validity() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // 需预先创建 target Account-Session。
    let _ = auth.login("2002", None).await.unwrap();
    auth.switch_to(&token, "2002").await.unwrap();
    assert!(auth.is_login(&token).await.unwrap());
}

/// switch_to 无效 token 返回 NotLogin 错误。
#[tokio::test]
async fn switch_to_invalid_token_returns_not_login() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let result = auth.switch_to("invalid-token", "2002").await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "无效 token 应返回 NotLogin,实际: {:?}",
        result
    );
}

/// switch_to 空 target_login_id 返回 InvalidParam 错误。
#[tokio::test]
async fn switch_to_empty_target_returns_invalid_param() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    let result = auth.switch_to(&token, "").await;
    assert!(
        matches!(result, Err(GarrisonError::InvalidParam(_))),
        "空 target_login_id 应返回 InvalidParam,实际: {:?}",
        result
    );
}

/// switch_to 后 verify_token 返回新的 login_id。
#[tokio::test]
async fn switch_to_verify_token_returns_new_login_id() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // 需预先创建 target Account-Session。
    let _ = auth.login("9999", None).await.unwrap();
    auth.switch_to(&token, "9999").await.unwrap();
    assert_eq!(auth.verify_token(&token).await.unwrap(), "9999");
}

/// switch_to 多次切换,switched_from 记录最近一次的原始 login_id。
#[tokio::test]
async fn switch_to_multiple_times_updates_switched_from() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // 需预先创建 target Account-Session(2002 + 3003)。
    let _ = auth.login("2002", None).await.unwrap();
    let _ = auth.login("3003", None).await.unwrap();
    auth.switch_to(&token, "2002").await.unwrap();
    assert_eq!(
        auth.session.get(&token, "switched_from").await.unwrap(),
        Some("1001".to_string())
    );
    auth.switch_to(&token, "3003").await.unwrap();
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("3003".to_string())
    );
    // switched_from 应记录最近一次切换前的 login_id(2002)
    assert_eq!(
        auth.session.get(&token, "switched_from").await.unwrap(),
        Some("2002".to_string())
    );
}

/// switch_to 保留 TokenSession 的其他 attrs(不丢失已有属性)。
#[tokio::test]
async fn switch_to_preserves_existing_attrs() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // 需预先创建 target Account-Session。
    let _ = auth.login("2002", None).await.unwrap();
    auth.session.set(&token, "device", "web").await.unwrap();
    auth.switch_to(&token, "2002").await.unwrap();
    let device = auth.session.get(&token, "device").await.unwrap();
    assert_eq!(device, Some("web".to_string()));
    let switched_from = auth.session.get(&token, "switched_from").await.unwrap();
    assert_eq!(switched_from, Some("1001".to_string()));
}

// switch_to 必须从 original Account-Session 移除 token(避免 list_devices 误返回已切换
// token、logout_by_login_id 越权踢出、enforce_max_login_count 误算)。

/// switch_to 后,original login_id 的 AccountSession.tokens 不应再包含该 token。
///
/// 复现:login("1001") 创建 token;login("2002") 预创建 target Account-Session;
/// switch_to(token, "2002") 后,原 1001 的 AccountSession.tokens 应不再含 token。
#[tokio::test]
async fn switch_to_removes_token_from_original_account_session() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    let _ = auth.login("2002", None).await.unwrap();

    // 切换前:original AccountSession 应包含 token
    let original_before = auth
        .session
        .get_account_session("1001")
        .await
        .unwrap()
        .expect("切换前 original AccountSession 应存在");
    assert!(
        original_before.tokens.iter().any(|ti| ti.token == token),
        "切换前 original AccountSession 应包含该 token"
    );

    auth.switch_to(&token, "2002").await.unwrap();

    // 切换后:original AccountSession 不应再包含 token
    let original_after = auth
        .session
        .get_account_session("1001")
        .await
        .unwrap()
        .expect("切换后 original AccountSession 应仍存在");
    assert!(
        !original_after.tokens.iter().any(|ti| ti.token == token),
        "切换后 original AccountSession 不应再包含该 token(H1 数据一致性),实际 tokens: {:?}",
        original_after.tokens
    );

    // 同时:target AccountSession 应包含 token
    let target_after = auth
        .session
        .get_account_session("2002")
        .await
        .unwrap()
        .expect("切换后 target AccountSession 应存在");
    assert!(
        target_after.tokens.iter().any(|ti| ti.token == token),
        "切换后 target AccountSession 应包含该 token,实际 tokens: {:?}",
        target_after.tokens
    );
}

/// switch_to 后内存 login_token_map 也应从 original 移除:`list_devices(original)` 经
/// `get_tokens_by_login_id` 读内存索引,不同步会导致误返回已切换的 token。
#[tokio::test]
async fn switch_to_removes_token_from_original_login_token_map() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    let _ = auth.login("2002", None).await.unwrap();

    // 切换前:original 内存索引应包含 token
    let tokens_before: Vec<String> = auth.session.get_tokens_by_login_id("1001");
    assert!(
        tokens_before.iter().any(|t| t == &token),
        "切换前 original 内存索引应包含该 token"
    );

    auth.switch_to(&token, "2002").await.unwrap();

    // 切换后:original 内存索引不应再包含 token
    let tokens_after: Vec<String> = auth.session.get_tokens_by_login_id("1001");
    assert!(
        !tokens_after.iter().any(|t| t == &token),
        "切换后 original 内存索引不应再包含该 token(H1 内存索引一致性),实际: {:?}",
        tokens_after
    );

    // target 内存索引应包含 token
    let target_tokens: Vec<String> = auth.session.get_tokens_by_login_id("2002");
    assert!(
        target_tokens.iter().any(|t| t == &token),
        "切换后 target 内存索引应包含该 token,实际: {:?}",
        target_tokens
    );
}

/// switch_to 默认实现返回 NotImplemented。
#[tokio::test]
async fn switch_to_default_impl_returns_not_implemented() {
    struct NoSwitchAuth;
    #[async_trait]
    impl AuthLogic for NoSwitchAuth {
        async fn login(&self, _id: &str, _params: Option<&str>) -> GarrisonResult<String> {
            Ok("token".to_string())
        }
        async fn logout(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn is_login(&self, _token: &str) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn get_login_id(&self, _token: &str) -> GarrisonResult<Option<String>> {
            Ok(Some("id".to_string()))
        }
        async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
            Ok("id".to_string())
        }
    }
    let auth = NoSwitchAuth;
    let result = auth.switch_to("token", "target").await;
    assert!(
        matches!(result, Err(GarrisonError::NotImplemented(_))),
        "默认实现应返回 NotImplemented,实际: {:?}",
        result
    );
    // 覆盖率补充:调用所有 trait 方法以覆盖 async_trait 生成代码
    let _ = auth.login("u1", None).await.unwrap();
    auth.logout("t").await.unwrap();
    let _ = auth.is_login("t").await.unwrap();
    let _ = auth.get_login_id("t").await.unwrap();
    let _ = auth.verify_token("t").await.unwrap();
}

// switch_to 权限校验测试

/// 默认 DenyAllSwitchToGuard 应拒绝所有 switch_to 调用(fail-closed)。
#[tokio::test]
async fn switch_to_default_guard_denies_all_switches() {
    let auth = make_auth_logic(3600, 86400); // 默认 DenyAllSwitchToGuard
    let token = auth.login("1001", None).await.unwrap();
    // 需预先创建 target Account-Session,否则 target_account_exists 校验先返回 InvalidParam
    let _ = auth.login("2002", None).await.unwrap();
    let result = auth.switch_to(&token, "2002").await;
    assert!(
        matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("core-switch-to-denied")),
        "默认 guard 应拒绝切换并返回 NotPermission,实际: {:?}",
        result
    );
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("1001".to_string())
    );
}

/// 自定义 guard 拒绝时返回 NotPermission 且不修改 session。
#[tokio::test]
async fn switch_to_custom_guard_denies_preserves_session() {
    struct DenyTargetGuard;
    #[async_trait]
    impl SwitchToGuard for DenyTargetGuard {
        async fn check(&self, _original: &str, target: &str) -> GarrisonResult<()> {
            if target == "admin" {
                return Err(GarrisonError::NotPermission(format!(
                    "禁止切换到管理员身份: {}",
                    target
                )));
            }
            Ok(())
        }
    }
    let auth = make_auth_logic(3600, 86400).with_switch_to_guard(Arc::new(DenyTargetGuard));
    let token = auth.login("1001", None).await.unwrap();
    // 需预先创建 target Account-Session(user-2002 + admin)。
    let _ = auth.login("user-2002", None).await.unwrap();
    // admin 也需预先创建 Account-Session,否则 target_account_exists 校验先返回 InvalidParam
    let _ = auth.login("admin", None).await.unwrap();

    let result = auth.switch_to(&token, "admin").await;
    assert!(
        matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("禁止切换")),
        "切换到 admin 应被拒绝,实际: {:?}",
        result
    );
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("1001".to_string())
    );

    auth.switch_to(&token, "user-2002").await.unwrap();
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("user-2002".to_string())
    );
}

// target_account_exists 校验测试

/// switch_to 切换到不存在的 target 返回统一的模糊 NotPermission(`core-auth-switch-to-denied`),
/// 与「无权切换」外部不可区分,防 login_id 枚举。
#[tokio::test]
async fn switch_to_nonexistent_target_returns_invalid_param() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // 不创建 "ghost-user" 的 Account-Session
    let result = auth.switch_to(&token, "ghost-user").await;
    assert!(
        matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("core-auth-switch-to-denied")),
        "切换到不存在的 target 应返回统一的模糊 NotPermission(issue 2663 反枚举),实际: {:?}",
        result
    );
    assert_eq!(
        auth.get_login_id(&token).await.unwrap(),
        Some("1001".to_string())
    );
}

/// target_account_exists 校验先于 guard 执行:即使 guard 是 allow-all,target 不存在仍被
/// 拒绝,且错误与 guard 拒绝同为模糊 NotPermission(不可区分)。
#[tokio::test]
async fn switch_to_target_check_precedes_guard() {
    let auth = make_auth_logic_allow_switch(3600, 86400);
    let token = auth.login("1001", None).await.unwrap();
    // 不创建 "ghost" 的 Account-Session
    let result = auth.switch_to(&token, "ghost").await;
    assert!(
        matches!(result, Err(GarrisonError::NotPermission(ref msg)) if msg.contains("core-auth-switch-to-denied")),
        "target 不存在时应优先返回统一的模糊 NotPermission,实际: {:?}",
        result
    );
}

// renew_to_equivalent 测试

/// renew_to_equivalent 返回新 token,新 token 有效且 login_id 相同。
#[tokio::test]
async fn renew_to_equivalent_returns_new_valid_token_with_same_login_id() {
    let auth = make_auth_logic(3600, 86400);
    let old_token = auth.login("1001", None).await.unwrap();
    let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
    assert!(!new_token.is_empty());
    assert!(auth.is_login(&new_token).await.unwrap());
    assert_eq!(
        auth.get_login_id(&new_token).await.unwrap(),
        Some("1001".to_string())
    );
}

/// renew_to_equivalent 生成与旧 token 不同的字符串。
#[tokio::test]
async fn renew_to_equivalent_generates_different_token_string() {
    let auth = make_auth_logic(3600, 86400);
    let old_token = auth.login("1001", None).await.unwrap();
    let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
    assert_ne!(old_token, new_token);
}

/// renew_to_equivalent 后旧 token 失效(session 已删除)。
#[tokio::test]
async fn renew_to_equivalent_invalidates_old_token() {
    let auth = make_auth_logic(3600, 86400);
    let old_token = auth.login("1001", None).await.unwrap();
    assert!(auth.is_login(&old_token).await.unwrap());
    let _new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
    assert!(!auth.is_login(&old_token).await.unwrap());
}

/// renew_to_equivalent 保留旧 session 的 attrs。
#[tokio::test]
async fn renew_to_equivalent_preserves_attrs() {
    let auth = make_auth_logic(3600, 86400);
    let old_token = auth.login("1001", None).await.unwrap();
    auth.session
        .set(&old_token, "device", "web-chrome")
        .await
        .unwrap();
    auth.session.set(&old_token, "role", "admin").await.unwrap();
    let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
    let device = auth.session.get(&new_token, "device").await.unwrap();
    assert_eq!(device, Some("web-chrome".to_string()));
    let role = auth.session.get(&new_token, "role").await.unwrap();
    assert_eq!(role, Some("admin".to_string()));
}

/// renew_to_equivalent 保留旧 session 的 device 字段。
#[tokio::test]
async fn renew_to_equivalent_preserves_device() {
    let auth = make_auth_logic(3600, 86400);
    let old_token = auth.login("1001", None).await.unwrap();
    auth.session
        .set_device(&old_token, "mobile-ios")
        .await
        .unwrap();
    let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
    let ts = auth.session.get_token_session(&new_token).await.unwrap();
    assert!(ts.is_some(), "新 token session 应存在");
    assert_eq!(ts.unwrap().device, Some("mobile-ios".to_string()));
}

/// renew_to_equivalent 无效 token 返回 NotLogin 错误。
#[tokio::test]
async fn renew_to_equivalent_invalid_token_returns_not_login() {
    let auth = make_auth_logic(3600, 86400);
    let result = auth.renew_to_equivalent("invalid-token").await;
    assert!(
        matches!(result, Err(GarrisonError::NotLogin(_))),
        "无效 token 应返回 NotLogin,实际: {:?}",
        result
    );
}

/// renew_to_equivalent 继承剩余 TTL(不重置为原始 timeout)。
#[tokio::test]
async fn renew_to_equivalent_preserves_remaining_ttl() {
    // 手动构建 auth + dao,以便直接操作 DAO 的 TTL
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let session = Arc::new(GarrisonSession::new(dao.clone(), 3600, 86400, 0));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    let auth = AuthLogicDefault::new(session, token_handler, 3600);

    let old_token = auth.login("1001", None).await.unwrap();

    // 手动缩短旧 token 的 TTL 到 100s(模拟部分过期)
    let token_session_key = token_key(&old_token);
    dao.expire(&token_session_key, 100).await.unwrap();

    let old_ttl = auth.session.get_token_timeout(&old_token).await.unwrap();
    assert!(old_ttl.is_some(), "旧 token 应有 TTL");
    let old_secs = old_ttl.unwrap().as_secs();
    assert!(old_secs <= 100, "旧 TTL 应 ≤ 100s,实际: {}", old_secs);

    let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();

    // 新 token 的 TTL 应继承剩余 TTL(≈100s),而非重置为 3600s
    let new_ttl = auth.session.get_token_timeout(&new_token).await.unwrap();
    assert!(new_ttl.is_some(), "新 token 应有 TTL");
    let new_secs = new_ttl.unwrap().as_secs();
    assert!(
        new_secs <= 100,
        "新 TTL 应继承剩余 TTL (≤100s),实际: {}(可能被重置为 3600s)",
        new_secs
    );
}

/// renew_to_equivalent 默认实现返回 NotImplemented。
#[tokio::test]
async fn renew_to_equivalent_default_impl_returns_not_implemented() {
    struct NoRenewAuth;
    #[async_trait]
    impl AuthLogic for NoRenewAuth {
        async fn login(&self, _id: &str, _params: Option<&str>) -> GarrisonResult<String> {
            Ok("token".to_string())
        }
        async fn logout(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn is_login(&self, _token: &str) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn get_login_id(&self, _token: &str) -> GarrisonResult<Option<String>> {
            Ok(Some("id".to_string()))
        }
        async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
            Ok("id".to_string())
        }
    }
    let auth = NoRenewAuth;
    let result = auth.renew_to_equivalent("token").await;
    assert!(
        matches!(result, Err(GarrisonError::NotImplemented(_))),
        "默认实现应返回 NotImplemented,实际: {:?}",
        result
    );
    // 覆盖率补充:调用所有 trait 方法以覆盖 async_trait 生成代码
    let _ = auth.login("u1", None).await.unwrap();
    auth.logout("t").await.unwrap();
    let _ = auth.is_login("t").await.unwrap();
    let _ = auth.get_login_id("t").await.unwrap();
    let _ = auth.verify_token("t").await.unwrap();
}

// renew_to_equivalent 顺序测试(先创建新 token,再失效旧 token)
//
// 顺序必须为"先 create 后 delete"以消除 DoS gap(CWE-362 / CVSS 7.5):delete-first 在
// delete 与 create 之间存在用户无任何有效 token 的窗口。

/// 追踪 DAO 操作顺序的 wrapper(包装 `MockDao`):验证不变量——新 token 必须在旧 token
/// 删除之前创建。
struct OrderTrackingDao {
    inner: MockDao,
    tracking_state: std::sync::Mutex<OrderTrackingState>,
}

struct OrderTrackingState {
    /// 是否开始追踪(仅在 renew_to_equivalent 期间启用)。
    enabled: bool,
    /// 旧 token(用于检测 delete("token:session:{old_token}") 是否已调用)。
    old_token: String,
    /// 新 token session 是否已创建;追踪期间 new_token 未知,set 任意 token:session:*
    /// 且 key != old_token 即视为已创建。
    new_token_created: bool,
    /// 旧 token 的 session key 是否已被 delete。
    old_token_deleted: bool,
    /// 是否检测到 DoS gap 违规(delete(old) 早于 set(new));不变量应为 false。
    dos_gap_violation: bool,
}

impl OrderTrackingDao {
    fn new() -> Self {
        Self {
            inner: MockDao::new(),
            tracking_state: std::sync::Mutex::new(OrderTrackingState {
                enabled: false,
                old_token: String::new(),
                new_token_created: false,
                old_token_deleted: false,
                dos_gap_violation: false,
            }),
        }
    }

    /// 开始追踪 renew 操作顺序(login 完成后调用)。
    fn start_tracking(&self, old_token: String) {
        let mut state = self.tracking_state.lock().unwrap();
        state.enabled = true;
        state.old_token = old_token;
        state.new_token_created = false;
        state.old_token_deleted = false;
        state.dos_gap_violation = false;
    }

    /// 是否检测到 DoS gap 违规;不变量应为 false。
    fn was_dos_gap_violation(&self) -> bool {
        self.tracking_state.lock().unwrap().dos_gap_violation
    }

    /// 旧 token 是否最终被删除(清理完成)。
    fn was_old_token_deleted(&self) -> bool {
        self.tracking_state.lock().unwrap().old_token_deleted
    }
}

#[async_trait]
impl GarrisonDao for OrderTrackingDao {
    async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
        self.inner.get(key).await
    }

    async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
        // 追踪窗口内 set token:session:*(非 old_token)即标记新 token 已创建。
        {
            let mut state = self.tracking_state.lock().unwrap();
            if state.enabled
                && key.starts_with("token:session:")
                && key != token_key(&state.old_token)
            {
                state.new_token_created = true;
            }
        }
        self.inner.set(key, value, ttl_seconds).await
    }

    async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
        self.inner.update(key, value).await
    }

    async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
        self.inner.expire(key, seconds).await
    }

    async fn delete(&self, key: &str) -> GarrisonResult<()> {
        // 标记旧 token 已 delete;delete(old) 早于 set(new) 即 DoS gap 违规。
        {
            let mut state = self.tracking_state.lock().unwrap();
            if state.enabled && key == token_key(&state.old_token) {
                if !state.new_token_created {
                    // 旧 token 被删除时,新 token 尚未创建 → DoS gap 违规
                    state.dos_gap_violation = true;
                }
                state.old_token_deleted = true;
            }
        }
        self.inner.delete(key).await
    }

    async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
        self.inner.get_timeout(key).await
    }
    crate::atomic_test_fallback!();
}

/// renew 必须先创建新 token session 再失效旧 token(先 create 后 delete),消除 DoS gap
///(CWE-362 / CVSS 7.5)。
#[tokio::test]
async fn a9_renew_to_equivalent_creates_new_before_deleting_old() {
    // atomic + 默认 trait 方法覆盖
    {
        let d = OrderTrackingDao::new();
        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 tracking_dao = Arc::new(OrderTrackingDao::new());
    let session = Arc::new(GarrisonSession::new(
        tracking_dao.clone() as Arc<dyn GarrisonDao>,
        3600,
        86400,
        0,
    ));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    let auth = AuthLogicDefault::new(session, token_handler, 3600);

    let old_token = auth.login("1001", None).await.unwrap();

    // 开始追踪 renew 操作的顺序
    tracking_dao.start_tracking(old_token.clone());

    let new_token = auth.renew_to_equivalent(&old_token).await;
    assert!(
        new_token.is_ok(),
        "renew 应成功,实际: {:?}",
        new_token.err()
    );

    // 不变量 1:不允许 DoS gap(delete(old) 在 set(new) 之前)
    assert!(
        !tracking_dao.was_dos_gap_violation(),
        "A9 违规:旧 token 在新 token 创建前被删除(DoS gap window),\
         应先创建新 token 再删除旧 token"
    );

    // 不变量 2:旧 token 最终应被删除(清理完成,避免旧 token 永久残留)
    assert!(
        tracking_dao.was_old_token_deleted(),
        "A9 清理校验:旧 token session 应在 renew 完成后被删除"
    );
}

/// renew 期间旧 token 在新 token 创建前仍有效(无 DoS gap):set(new) 发生时
/// delete(old) 尚未执行。
#[tokio::test]
async fn a9_renew_to_equivalent_old_token_valid_until_new_created() {
    let tracking_dao = Arc::new(OrderTrackingDao::new());
    let session = Arc::new(GarrisonSession::new(
        tracking_dao.clone() as Arc<dyn GarrisonDao>,
        3600,
        86400,
        0,
    ));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    let auth = AuthLogicDefault::new(session, token_handler, 3600);

    let old_token = auth.login("1002", None).await.unwrap();
    tracking_dao.start_tracking(old_token.clone());

    let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();

    assert!(
        !auth.is_login(&old_token).await.unwrap(),
        "renew 后旧 token 应失效"
    );
    assert!(
        auth.is_login(&new_token).await.unwrap(),
        "renew 后新 token 应有效"
    );
    assert_eq!(
        auth.get_login_id(&new_token).await.unwrap(),
        Some("1002".to_string()),
        "新 token 的 login_id 应与旧 token 相同"
    );

    // 核心校验:整个 renew 过程中无 DoS gap
    assert!(
        !tracking_dao.was_dos_gap_violation(),
        "A9 违规:renew 过程中存在 DoS gap(旧 token 先于新 token 创建被删除)"
    );
}

// remember_me 测试

/// 辅助函数:创建带 remember_me 配置的 AuthLogicDefault 实例。
fn make_auth_logic_with_remember_me(
    timeout: u64,
    active_timeout: u64,
    rm_enabled: bool,
    rm_timeout: i64,
) -> AuthLogicDefault {
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let session = Arc::new(GarrisonSession::new(dao, timeout, active_timeout, 0));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    AuthLogicDefault::new(session, token_handler, timeout as i64)
        .with_remember_me(rm_enabled, rm_timeout)
}

/// login with remember_me=true 且 enabled 时使用扩展超时。
#[tokio::test]
async fn login_with_remember_me_true_uses_extended_timeout() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
    let token = auth.login("1001", Some("remember_me=true")).await.unwrap();
    assert!(auth.is_login(&token).await.unwrap());
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some(), "Token-Session 应有 TTL");
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs > 3_600 && secs <= 7_776_000,
        "remember_me TTL 应接近 7776000s,实际: {}s",
        secs
    );
}

/// login with remember_me=true 但 disabled 时使用默认超时。
#[tokio::test]
async fn login_with_remember_me_true_but_disabled_uses_default_timeout() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, false, 7_776_000);
    let token = auth.login("1001", Some("remember_me=true")).await.unwrap();
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some());
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs <= 3600,
        "disabled 时 TTL 应为默认 3600s,实际: {}s",
        secs
    );
}

/// login with remember_me=false 使用默认超时。
#[tokio::test]
async fn login_with_remember_me_false_uses_default_timeout() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
    let token = auth.login("1001", Some("remember_me=false")).await.unwrap();
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some());
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs <= 3600,
        "remember_me=false 时 TTL 应为默认 3600s,实际: {}s",
        secs
    );
}

/// login with None params 使用默认超时。
#[tokio::test]
async fn login_with_none_params_uses_default_timeout() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
    let token = auth.login("1001", None).await.unwrap();
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some());
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs <= 3600,
        "None params 时 TTL 应为默认 3600s,实际: {}s",
        secs
    );
}

/// login with empty params 使用默认超时。
#[tokio::test]
async fn login_with_empty_params_uses_default_timeout() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
    let token = auth.login("1001", Some("")).await.unwrap();
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some());
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs <= 3600,
        "empty params 时 TTL 应为默认 3600s,实际: {}s",
        secs
    );
}

/// login with remember_me=true 与其他参数组合仍检测到 remember_me。
#[tokio::test]
async fn login_with_remember_me_and_other_params() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
    let token = auth
        .login("1001", Some("remember_me=true&device=web"))
        .await
        .unwrap();
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some());
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs > 3_600 && secs <= 7_776_000,
        "组合参数中 remember_me=true 应使用扩展 TTL,实际: {}s",
        secs
    );
}

/// login with malformed params 使用默认超时(容错)。
#[tokio::test]
async fn login_with_malformed_params_uses_default_timeout() {
    let auth = make_auth_logic_with_remember_me(3600, 86400, true, 7_776_000);
    let token = auth.login("1001", Some("malformed")).await.unwrap();
    let ttl = auth.session.get_token_timeout(&token).await.unwrap();
    assert!(ttl.is_some());
    let secs = ttl.unwrap().as_secs();
    assert!(
        secs <= 3600,
        "malformed params 时 TTL 应为默认 3600s,实际: {}s",
        secs
    );
}

/// parse_remember_me_param 各种输入解析正确。
#[test]
fn parse_remember_me_param_various_inputs() {
    assert!(parse_remember_me_param(Some("remember_me=true")));
    assert!(!parse_remember_me_param(Some("remember_me=false")));
    assert!(parse_remember_me_param(Some("remember_me=true&device=web")));
    assert!(parse_remember_me_param(Some("device=web&remember_me=true")));
    assert!(!parse_remember_me_param(Some("")));
    assert!(!parse_remember_me_param(None));
    assert!(!parse_remember_me_param(Some("remember_me=1")));
    assert!(!parse_remember_me_param(Some("malformed")));
}

// renew_to_equivalent 并发串行化测试

/// 并发 renew 同一 token 必须串行化(修复 CWE-362 TOCTOU):3 个并发 renew 恰好 1 个 Ok +
/// 2 个 Err。用 `tokio::spawn` 真并行(`join!` 在当前 task 顺序 poll 无法触发竞态),
/// `Arc<AuthLogicDefault>` 跨 task 共享。
#[tokio::test(flavor = "multi_thread")]
async fn renew_to_equivalent_concurrent_serialization() {
    let auth = Arc::new(make_auth_logic(3600, 86400));
    let old_token = auth.login("race-user", None).await.unwrap();

    let auth1 = auth.clone();
    let auth2 = auth.clone();
    let auth3 = auth.clone();
    let old1 = old_token.clone();
    let old2 = old_token.clone();
    let old3 = old_token.clone();
    let h1 = tokio::spawn(async move { auth1.renew_to_equivalent(&old1).await });
    let h2 = tokio::spawn(async move { auth2.renew_to_equivalent(&old2).await });
    let h3 = tokio::spawn(async move { auth3.renew_to_equivalent(&old3).await });

    let res1 = h1.await.expect("h1 join failed");
    let res2 = h2.await.expect("h2 join failed");
    let res3 = h3.await.expect("h3 join failed");

    let results = [res1, res2, res3];
    let success_count = results.iter().filter(|r| r.is_ok()).count();
    let err_count = results.iter().filter(|r| r.is_err()).count();

    assert_eq!(
        success_count, 1,
        "并发 renew 应恰好 1 个成功,实际 {} 个成功 — 揭示 CWE-362 TOCTOU 竞态未修复",
        success_count
    );
    assert_eq!(
        err_count, 2,
        "并发 renew 应 2 个失败,实际 {} 个失败",
        err_count
    );
}

/// renew 完成后 renew_locks 不残留无引用 entry:先 drop guard 与 Arc,再
/// `remove_if` 检查 `Arc::strong_count == 1`。无清理时攻击者可用大量随机 token 灌满
/// DashMap 导致 OOM(CWE-770)。
#[tokio::test]
async fn renew_locks_entry_cleaned_after_successful_renew() {
    let auth = Arc::new(make_auth_logic(3600, 86400));
    let old_token = auth.login("cleanup-user", None).await.unwrap();

    // renew 前 renew_locks 应为空(无并发 renew 进行中)
    assert!(
        auth.renew_locks.is_empty(),
        "renew 前 renew_locks 应为空,实际有 {} 个 entry",
        auth.renew_locks.len()
    );

    let new_token = auth
        .renew_to_equivalent(&old_token)
        .await
        .expect("renew 应成功");

    // renew 后 renew_locks 应再次为空(entry 已被清理)
    assert!(
        auth.renew_locks.is_empty(),
        "renew 后 renew_locks 应被清理为空,实际残留 {} 个 entry",
        auth.renew_locks.len()
    );

    assert!(
        !auth.is_login(&old_token).await.unwrap(),
        "旧 token 应已失效"
    );
    assert!(auth.is_login(&new_token).await.unwrap(), "新 token 应有效");
}

/// renew 失败(NotLogin)后 entry 也应被清理,避免失败 renew 累积导致 OOM;
/// 对同一无效 token 多次 renew,每次失败后 renew_locks 应为空。
#[tokio::test]
async fn renew_locks_entry_cleaned_after_failed_renew() {
    let auth = Arc::new(make_auth_logic(3600, 86400));

    // 对不存在的 token 调用 renew(应返回 NotLogin)
    for i in 0..5 {
        let fake_token = format!("fake-token-{}", i);
        let result = auth.renew_to_equivalent(&fake_token).await;
        assert!(result.is_err(), "fake token renew 应失败(迭代 {})", i);
        // 每次失败后 renew_locks 应为空(entry 已清理)
        assert!(
            auth.renew_locks.is_empty(),
            "失败 renew 后 renew_locks 应清理为空(迭代 {}),实际残留 {} 个 entry",
            i,
            auth.renew_locks.len()
        );
    }
}

/// 并发 renew 完成后 renew_locks 不残留 entry:与 `renew_to_equivalent_concurrent_serialization`
/// 互补(后者验证串行化语义,本测试验证并发完成后的内存清理)。
#[tokio::test(flavor = "multi_thread")]
async fn renew_locks_entry_cleaned_after_concurrent_renew() {
    let auth = Arc::new(make_auth_logic(3600, 86400));
    let old_token = auth.login("concurrent-cleanup-user", None).await.unwrap();

    // 并发 3 个 renew 同一 token
    let auth1 = auth.clone();
    let auth2 = auth.clone();
    let auth3 = auth.clone();
    let old1 = old_token.clone();
    let old2 = old_token.clone();
    let old3 = old_token.clone();
    let h1 = tokio::spawn(async move { auth1.renew_to_equivalent(&old1).await });
    let h2 = tokio::spawn(async move { auth2.renew_to_equivalent(&old2).await });
    let h3 = tokio::spawn(async move { auth3.renew_to_equivalent(&old3).await });

    let _ = h1.await.expect("h1 join failed");
    let _ = h2.await.expect("h2 join failed");
    let _ = h3.await.expect("h3 join failed");

    // 所有 task 完成后 renew_locks 应为空(所有 entry 已清理)
    assert!(
        auth.renew_locks.is_empty(),
        "并发 renew 全部完成后 renew_locks 应清理为空,实际残留 {} 个 entry",
        auth.renew_locks.len()
    );
}

// 覆盖率补测:renew_to_equivalent 错误路径(三步失败分支 + 回滚)
//
// `default.rs` renew 流程的步骤 3(创建新 session)/ 5(挂 Account-Session)/ 6(失效旧 token)
// 失败分支:FailingDao 按 key 前缀选择性注入 DAO 故障,验证无 DoS / 可回滚契约。

use std::sync::atomic::{AtomicBool, Ordering};

/// 按故障开关选择性失败的 DAO 包装(包装 `super::mock::MockDao`),三个开关分别命中
/// renew 的失败步骤:`fail_token_session_set` → 步骤 3、`fail_account_session_set` → 步骤 5、
/// `fail_token_session_delete` → 步骤 6。
struct FailingDao {
    inner: MockDao,
    fail_token_session_set: AtomicBool,
    fail_account_session_set: AtomicBool,
    fail_token_session_delete: AtomicBool,
}

impl FailingDao {
    fn new() -> Self {
        Self {
            inner: MockDao::new(),
            fail_token_session_set: AtomicBool::new(false),
            fail_account_session_set: AtomicBool::new(false),
            fail_token_session_delete: AtomicBool::new(false),
        }
    }
}

#[async_trait]
impl GarrisonDao for FailingDao {
    async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
        self.inner.get(key).await
    }

    async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
        if key.starts_with("token:session:") && self.fail_token_session_set.load(Ordering::SeqCst) {
            return Err(GarrisonError::Dao(format!("failing-dao-set::{}", key)));
        }
        if key.starts_with("account:session:")
            && self.fail_account_session_set.load(Ordering::SeqCst)
        {
            return Err(GarrisonError::Dao(format!("failing-dao-set::{}", key)));
        }
        self.inner.set(key, value, ttl_seconds).await
    }

    async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
        self.inner.update(key, value).await
    }

    async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
        self.inner.expire(key, seconds).await
    }

    async fn delete(&self, key: &str) -> GarrisonResult<()> {
        if key.starts_with("token:session:")
            && self.fail_token_session_delete.load(Ordering::SeqCst)
        {
            return Err(GarrisonError::Dao(format!("failing-dao-delete::{}", key)));
        }
        self.inner.delete(key).await
    }

    async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
        self.inner.get_timeout(key).await
    }

    async fn get_with_ttl(&self, key: &str) -> GarrisonResult<Option<(String, Option<Duration>)>> {
        self.inner.get_with_ttl(key).await
    }
    crate::atomic_test_fallback!();
}

/// 辅助:基于 FailingDao 构建 AuthLogicDefault。
fn make_auth_logic_with_failing_dao(dao: Arc<FailingDao>) -> AuthLogicDefault {
    let session = Arc::new(GarrisonSession::new(
        dao as Arc<dyn GarrisonDao>,
        3600,
        86400,
        0,
    ));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    AuthLogicDefault::new(session, token_handler, 3600)
}

/// renew 步骤 3 失败:创建新 Token-Session 的 DAO set 失败时返回 Internal,
/// 旧 token 仍有效(契约:无 DoS,旧 token 未被触碰)。
#[tokio::test]
async fn renew_create_new_token_session_fails_old_token_untouched() {
    // atomic + 默认 trait 方法覆盖
    {
        let d = FailingDao::new();
        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 failing = Arc::new(FailingDao::new());
    let auth = make_auth_logic_with_failing_dao(failing.clone());
    let old_token = auth.login("1001", None).await.unwrap();

    // login 完成后启用故障:set("token:session:*") 一律失败
    failing.fail_token_session_set.store(true, Ordering::SeqCst);

    let result = auth.renew_to_equivalent(&old_token).await;
    assert!(
        matches!(result, Err(GarrisonError::Internal(ref msg))
            if msg.contains("core-auth-token-renew-create-failed")),
        "创建新 Token-Session 失败应返回 Internal,实际: {:?}",
        result
    );
    // 旧 token 仍有效(步骤 3 失败时旧 token 未被触碰,无 DoS)
    assert!(
        auth.is_login(&old_token).await.unwrap(),
        "步骤 3 失败后旧 token 必须仍有效(A9 无 DoS 契约)"
    );
}

/// renew 步骤 5 失败:新 token 加入 Account-Session 失败时返回 Internal,
/// 并回滚删除新 token(旧 token 仍有效,新 token 不残留)。
#[tokio::test]
async fn renew_add_to_account_session_fails_rolls_back_new_token() {
    let failing = Arc::new(FailingDao::new());
    let auth = make_auth_logic_with_failing_dao(failing.clone());
    let old_token = auth.login("1001", None).await.unwrap();

    // login 完成后启用故障:set("account:session:*") 一律失败
    failing
        .fail_account_session_set
        .store(true, Ordering::SeqCst);

    let result = auth.renew_to_equivalent(&old_token).await;
    assert!(
        matches!(result, Err(GarrisonError::Internal(ref msg))
            if msg.contains("core-auth-token-renew-add-to-account-failed")),
        "加入 Account-Session 失败应返回 Internal,实际: {:?}",
        result
    );
    assert!(
        auth.is_login(&old_token).await.unwrap(),
        "步骤 5 失败回滚后旧 token 必须仍有效"
    );
    // 回滚(best-effort logout new_token)生效:Account-Session 仅剩旧 token,无残留。
    let account = auth
        .session
        .get_account_session("1001")
        .await
        .unwrap()
        .expect("Account-Session 应存在");
    assert_eq!(
        account.tokens.len(),
        1,
        "回滚后 Account-Session 应仅剩旧 token(无残留),实际: {:?}",
        account.tokens
    );
    assert_eq!(account.tokens[0].token, old_token);
}

/// renew 步骤 6 失败:失效旧 token 的 DAO delete 失败时**仍返回 Ok(new_token)**
///(用户已持有新 token,返回 Err 反而制造新 DoS;旧 token 残留交由运维)。
#[tokio::test]
async fn renew_old_token_cleanup_failure_still_returns_new_token() {
    let failing = Arc::new(FailingDao::new());
    let auth = make_auth_logic_with_failing_dao(failing.clone());
    let old_token = auth.login("1001", None).await.unwrap();

    // login 完成后启用故障:delete("token:session:*") 一律失败
    failing
        .fail_token_session_delete
        .store(true, Ordering::SeqCst);

    let result = auth.renew_to_equivalent(&old_token).await;
    let new_token = result.expect("步骤 6 失败不应改变 renew 的 Ok 契约(告警而非失败)");
    assert_ne!(old_token, new_token);
    assert!(
        auth.is_login(&new_token).await.unwrap(),
        "新 token 必须有效(A9:新 token 已完全建立后才失效旧 token)"
    );
}

// amr / auth_time claim 签发收口(jwt 风格)

#[cfg(feature = "protocol-jwt")]
mod amr_claim_issuance {
    use super::mock::MockDao;
    use super::*;
    use crate::core::token::JwtTokenStyle;

    /// 构造 jwt 风格 AuthLogicDefault(共享 make 逻辑,密钥固定),返回 (auth, session)
    /// 供测试直接操作会话账本。
    fn make_jwt_auth_logic() -> (AuthLogicDefault, Arc<GarrisonSession>) {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let session = Arc::new(GarrisonSession::new(dao, 3600, 86400, 0));
        let token_handler: Arc<dyn Token> =
            Arc::new(JwtTokenStyle::new("0123456789abcdef0123456789abcdef"));
        (
            AuthLogicDefault::new(Arc::clone(&session), token_handler, 3600),
            session,
        )
    }

    fn verify_claims(token: &str) -> crate::protocol::jwt::GarrisonJwtClaims {
        crate::protocol::jwt::JwtHandler::new("0123456789abcdef0123456789abcdef")
            .verify(token)
            .unwrap()
    }

    /// AuthLogic login(jwt 风格)签发携带主因子 amr=["pwd"] 与 auth_time。
    #[tokio::test]
    async fn jwt_login_carries_primary_amr_and_auth_time() {
        let (auth, _session) = make_jwt_auth_logic();
        let token = auth.login("1001", None).await.unwrap();
        let claims = verify_claims(&token);
        assert_eq!(
            claims.amr,
            Some(vec![crate::stp::mfa::PRIMARY_FACTOR_AMR.to_string()]),
            "主登录签发应带主因子 amr"
        );
        assert!(claims.auth_time.is_some(), "主登录签发应带 auth_time");
    }

    /// renew 后新 token 的 amr/auth_time 与会话账本一致:step-up 追加 otp 后 renew,claim
    /// 应映射 ["pwd","otp"],auth_time 延续旧会话(凭空消失即本回归锚点)。
    #[tokio::test]
    async fn renew_to_equivalent_preserves_ledger_claims() {
        let (auth, session) = make_jwt_auth_logic();
        let old_token = auth.login("1001", None).await.unwrap();

        // 会话内 step-up:追加 otp(经公共账本 API,与 renew 读同一份账本)
        let ts_auth_time = {
            let ts = session
                .get_token_session(&old_token)
                .await
                .unwrap()
                .unwrap();
            ts.auth_time.unwrap()
        };
        session
            .append_amr_entry(&old_token, "otp", 2, ts_auth_time + 30)
            .await
            .unwrap();

        let new_token = auth.renew_to_equivalent(&old_token).await.unwrap();
        let claims = verify_claims(&new_token);
        assert_eq!(
            claims.amr,
            Some(vec!["pwd".to_string(), "otp".to_string()]),
            "renew 后 amr 应从账本映射(含 step-up 因子)"
        );
        assert_eq!(
            claims.auth_time,
            Some(ts_auth_time),
            "renew 后 auth_time 应延续会话 auth_time"
        );
    }
}

// seed_primary_amr 播种开关测试

/// 辅助函数:创建带 seed_primary_amr 配置的 AuthLogicDefault 实例。
fn make_auth_logic_with_seed(seed_enabled: bool) -> AuthLogicDefault {
    let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
    let session = Arc::new(GarrisonSession::new(dao, 3600, 86400, 0));
    let token_handler: Arc<dyn Token> = Arc::new(UuidTokenStyle);
    AuthLogicDefault::new(session, token_handler, 3600).with_seed_primary_amr(seed_enabled)
}

/// 默认 seed_primary_amr=true:login 播种 pwd/aal:1 账本与 auth_time(行为不变对照)。
#[tokio::test]
async fn core_login_seeds_primary_amr_by_default() {
    let auth = make_auth_logic_with_seed(true);
    let token = auth.login("seed-user-1", None).await.unwrap();
    let ts = auth
        .session
        .get_token_session(&token)
        .await
        .unwrap()
        .expect("会话应存在");
    assert_eq!(ts.amr_ledger.len(), 1, "默认应播种主因子");
    assert_eq!(ts.amr_ledger[0].method, "pwd");
    assert_eq!(ts.amr_ledger[0].aal, 1);
    assert!(ts.auth_time.is_some(), "默认应写 auth_time");
}

/// seed_primary_amr=false:login 不播种账本、auth_time 为 None。
#[tokio::test]
async fn core_login_skips_amr_seeding_when_disabled() {
    let auth = make_auth_logic_with_seed(false);
    let token = auth.login("seed-user-2", None).await.unwrap();
    let ts = auth
        .session
        .get_token_session(&token)
        .await
        .unwrap()
        .expect("会话应存在");
    assert!(
        ts.amr_ledger.is_empty(),
        "开关关闭时不得播种 pwd 账本,实际: {:?}",
        ts.amr_ledger
    );
    assert!(ts.auth_time.is_none(), "开关关闭时 auth_time 应为 None");
}