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
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! MFA/step-up 编排基座。
//! 核心组件:`MfaLogic` trait、会话因子账本(`AmrEntry` → RFC 8176 amr / auth_time)、per-client MFA chain 三态、新鲜度断言、`RequiredActionProvider` 三段式(TOTP / WebAuthn)、恢复码管理器与 MFA remember cookie。

use super::current_token;
use super::GarrisonLogicDefault;
#[cfg(feature = "protocol-jwt")]
use crate::config::GarrisonConfig;
// 仅 mfa-recovery 的 key 构造(code_key/misuse_key)使用,门控避免关闭该 feature 时 unused_imports 告警
#[cfg(feature = "mfa-recovery")]
use crate::constants::DaoKeyPrefix;
#[cfg(feature = "protocol-jwt")]
use crate::context::{build_set_cookie_value, CookieType};
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::stp::session::SessionLogic;
use async_trait::async_trait;
// 仅 mfa-recovery(RecoveryCodeManager)在非测试代码使用;webauthn 全流程测试在函数内局部导入(门控 all(test, db-sqlite),与非测试面不同)。
#[cfg(feature = "mfa-recovery")]
use std::sync::Arc;

/// MFA 逻辑 trait,定义二级认证与账号禁用校验契约。
/// 默认实现:`check_safe` 先过会话前置校验再查 `is_safe("default")`,未通过返回 `NotSafe("SAFE_EXPIRED")`;`check_disable` 过前置校验后返回 `Ok(())`,由覆写方查询禁用列表。
#[async_trait]
pub trait MfaLogic: SessionLogic {
    /// 二级认证族检查(`check_safe` / `check_disable`)共用的会话前置校验(先验会话后判 safe/disable,fail-closed)。
    /// 上下文带 token 时须通过与 `check_login` 同等校验,无效/已撤销 token 返回 `Session`(不并入宽松结果);无 token 的非 HTTP 上下文跳过(`Ok(())`)。
    async fn check_session_precondition(&self) -> GarrisonResult<()> {
        if current_token().is_ok() && !self.check_login().await? {
            return Err(GarrisonError::Session(
                "stp-secondary-check-not-login::".to_string(),
            ));
        }
        Ok(())
    }

    /// 检查二级认证(MFA)状态:先过会话前置与 `check_mfa_chain`,再查 `is_safe("default")`——false 返回 `NotSafe("SAFE_EXPIRED")`。
    /// 未覆写 `is_safe` 时默认 `Ok(true)`(有效会话视为已通过,即未启用 MFA 不拦截);会话无效返回 `Session`。
    async fn check_safe(&self) -> GarrisonResult<()> {
        self.check_session_precondition().await?;
        self.check_mfa_chain(None).await?;
        if !self.is_safe("default").await? {
            return Err(Self::not_safe("SAFE_EXPIRED"));
        }
        Ok(())
    }

    /// 校验 per-client MFA 强制链覆盖(gate 入口):因子账本未覆盖全部强制 factor(otp/webauthn → 同名 amr)时返回 `NotSafe { reason: "MFA_CHAIN_INCOMPLETE::<factor>" }`。
    /// `check_safe` 默认先执行本检查;`client_id` 为 `None` 按全局默认链判定,未覆写默认为 `Ok(())`。
    async fn check_mfa_chain(&self, _client_id: Option<&str>) -> GarrisonResult<()> {
        Ok(())
    }

    /// 检查账号是否被禁用:先过会话前置校验,默认返回 `Ok(())`(未实现禁用库);业务方覆写查询当前 login_id,封禁时用 `DisableService`。
    async fn check_disable(&self) -> GarrisonResult<()> {
        self.check_session_precondition().await?;
        Ok(())
    }

    /// 开启指定 service 的二级认证瞬态标记(默认 no-op `Ok(())`);`safe-auth` 启用时由 `GarrisonLogicDefault` 覆写为真实实现。
    async fn open_safe(&self, _service: &str, _duration_secs: u64) -> GarrisonResult<()> {
        Ok(())
    }

    /// 检查指定 service 是否处于二级认证有效期内:默认返回 `Ok(true)`(视为已通过);`safe-auth` 启用时由 `GarrisonLogicDefault` 覆写为真实实现。
    async fn is_safe(&self, _service: &str) -> GarrisonResult<bool> {
        Ok(true)
    }

    /// 关闭指定 service 的二级认证瞬态标记(默认 no-op,幂等);`safe-auth` 启用时由 `GarrisonLogicDefault` 覆写为真实实现。
    async fn close_safe(&self, _service: &str) -> GarrisonResult<()> {
        Ok(())
    }

    /// 构造账号封禁异常(`service` 封禁服务名,`until` 定时解封时间、None 永久),供业务方在自定义 `check_disable` 中抛出:
    ///
    /// ```ignore
    /// async fn check_disable(&self) -> GarrisonResult<()> {
    /// if account_is_banned().await {
    /// return Err(Self::disable_service("default", None));
    /// }
    /// Ok(())
    /// }
    /// ```
    fn disable_service(
        service: &str,
        until: Option<chrono::DateTime<chrono::Utc>>,
    ) -> GarrisonError {
        GarrisonError::DisableService {
            service: service.to_string(),
            until,
        }
    }

    /// 构造未完成二次认证异常(`reason` 为原因标识,如 "MFA_TOTP_REQUIRED"),供业务方在自定义 `check_safe` 中抛出:
    ///
    /// ```ignore
    /// async fn check_safe(&self) -> GarrisonResult<()> {
    /// if !mfa_completed().await {
    /// return Err(Self::not_safe("MFA_TOTP_REQUIRED"));
    /// }
    /// Ok(())
    /// }
    /// ```
    fn not_safe(reason: &str) -> GarrisonError {
        GarrisonError::NotSafe {
            reason: reason.to_string(),
        }
    }
}

// MFA 编排基座:因子账本

/// chain 可引用的 factor 词汇表(强制集合语义;pwd 是主因子不参与 chain)。
pub const KNOWN_CHAIN_FACTORS: &[&str] = &["otp", "webauthn"];

/// 校验 MFA chain 配置:引用 [`KNOWN_CHAIN_FACTORS`] 之外的 factor 时 fail-closed 返回 `Config("config-mfa-chain-factor-unknown::{factor}")`(启动期拒绝,不降级放行);per_client_chains 空集覆盖 = 显式禁用,合法。
pub fn validate_mfa_chains(
    global_chain: &[String],
    per_client_chains: &std::collections::HashMap<String, Vec<String>>,
) -> GarrisonResult<()> {
    for factor in global_chain {
        if !KNOWN_CHAIN_FACTORS.contains(&factor.as_str()) {
            return Err(GarrisonError::Config(format!(
                "config-mfa-chain-factor-unknown::{factor}"
            )));
        }
    }
    for chains in per_client_chains.values() {
        for factor in chains {
            if !KNOWN_CHAIN_FACTORS.contains(&factor.as_str()) {
                return Err(GarrisonError::Config(format!(
                    "config-mfa-chain-factor-unknown::{factor}"
                )));
            }
        }
    }
    Ok(())
}

/// chain factor → amr method 映射(gate 校验用);词汇表外返回 `None`,兜底按未满足处理(fail-closed,启动校验 `validate_mfa_chains` 会先拒绝其入配置)。
pub fn chain_factor_amr(factor: &str) -> Option<&'static str> {
    match factor {
        "otp" => Some("otp"),
        "webauthn" => Some("webauthn"),
        _ => None,
    }
}

/// 强制链覆盖判定:`Require` 时返回账本未满足的首个 factor(词汇表外恒视为未满足),`None` 决策返回 `None`。
pub fn first_unmet_chain_factor(
    decision: &MfaChainDecision,
    ledger: &[AmrEntry],
) -> Option<String> {
    let MfaChainDecision::Require(factors) = decision else {
        return None;
    };
    factors
        .iter()
        .find(|f| match chain_factor_amr(f) {
            Some(amr) => !ledger.iter().any(|e| e.method == amr),
            None => true,
        })
        .cloned()
}

/// per-client MFA chain 的生效决策(三态语义的解析结果)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MfaChainDecision {
    /// 该 client 无 MFA 强制要求(继承全局后为空,或被空集显式禁用)。
    None,
    /// 该 client 必须完成集合内的 factor(任意顺序,全部完成或按 provider 语义)。
    Require(Vec<String>),
}

/// 解析 per-client MFA chain 三态:覆盖表无该 client → 回退全局默认链(空则 `None`);`Some(空集)` → 显式禁用(即使全局有链也不强制);`Some(非空)` → `Require`。
pub fn resolve_mfa_chain(
    per_client: Option<&Vec<String>>,
    global_chain: &[String],
) -> MfaChainDecision {
    match per_client {
        None => {
            if global_chain.is_empty() {
                MfaChainDecision::None
            } else {
                MfaChainDecision::Require(global_chain.to_vec())
            }
        },
        Some(chain) if chain.is_empty() => MfaChainDecision::None,
        Some(chain) => MfaChainDecision::Require(chain.clone()),
    }
}

// 新鲜度断言与 Required Action 三段式(evaluate → challenge → process)

/// step-up 新鲜度门槛:auth_time 窗口与最低 AAL 要求。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MfaFreshness {
    /// `auth_time` 允许的最大年龄(秒);超过即视为过期会话。
    pub max_age_secs: i64,
    /// 账本最高 AAL 必须达到的等级。
    pub min_aal: u8,
}

/// 新鲜度断言的输入快照。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FreshnessInput {
    /// 会话 `auth_time`(主认证时刻;`None` = 历史会话,fail-closed 视为过期)。
    pub auth_time: Option<i64>,
    /// 因子账本最高 AAL。
    pub ledger_max_aal: u8,
    /// 当前时刻(Unix 秒)。
    pub now: i64,
}

/// 新鲜度断言结论。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FreshnessVerdict {
    /// 会话新鲜:免二次 challenge。
    Fresh,
    /// 会话过期或 AAL 不足:触发 Required Action。
    Stale,
}

/// 新鲜度断言(step-up 判定核心):`auth_time` 存在且 `now - auth_time <= max_age_secs` 且账本最高 AAL ≥ `min_aal` 才新鲜,任一不满足返回 [`FreshnessVerdict::Stale`]。
pub fn assert_freshness(input: &FreshnessInput, threshold: &MfaFreshness) -> FreshnessVerdict {
    let Some(auth_time) = input.auth_time else {
        return FreshnessVerdict::Stale;
    };
    if input.now - auth_time > threshold.max_age_secs {
        return FreshnessVerdict::Stale;
    }
    if input.ledger_max_aal < threshold.min_aal {
        return FreshnessVerdict::Stale;
    }
    FreshnessVerdict::Fresh
}

/// step-up 总判定:有效 remember cookie(HMAC/JWT 绑定 stage + credential_id + exp)视为本设备近期已完成该 stage,豁免重复 challenge;否则按新鲜度断言。
pub fn stepup_required(
    input: &FreshnessInput,
    threshold: &MfaFreshness,
    remember_cookie_valid: bool,
) -> bool {
    !remember_cookie_valid && assert_freshness(input, threshold) == FreshnessVerdict::Stale
}

/// Required Action 上下文(provider 三段式的共享输入快照)。
#[derive(Debug, Clone)]
pub struct RequiredActionContext {
    /// 登录主体标识。
    pub login_id: String,
    /// 会话 `auth_time`(Unix 秒;`None` = 历史会话)。
    pub auth_time: Option<i64>,
    /// 因子账本最高 AAL。
    pub ledger_max_aal: u8,
    /// 当前时刻(Unix 秒)。
    pub now: i64,
}

impl RequiredActionContext {
    /// 构造新鲜度断言输入。
    pub fn freshness_input(&self) -> FreshnessInput {
        FreshnessInput {
            auth_time: self.auth_time,
            ledger_max_aal: self.ledger_max_aal,
            now: self.now,
        }
    }
}

/// Required Action 挑战载荷(challenge 段的产出)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequiredActionChallenge {
    /// 动作标识(如 `"otp"`),客户端据此渲染对应 UI。
    pub action: String,
    /// 挑战载荷(TOTP 为静态提示;WebAuthn 为服务器 challenge)。
    pub payload: String,
}

/// process 段的验证结果。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProcessOutcome {
    /// 验证成功:账本按 (method, aal) 升级。
    Verified {
        /// 升级账本使用的 amr method。
        method: &'static str,
        /// 升级到的 AAL。
        aal: u8,
    },
    /// 验证失败:账本不变。
    Rejected,
}

/// Required Action provider 三段式契约(evaluate 判定 → challenge 出挑战 → process 验响应),对齐 authentik `AuthenticatorValidateStageView` 编排;成功后由调用方经 [`complete_required_action`] 升级账本(provider 不直接持有会话)。
#[async_trait]
pub trait RequiredActionProvider: Send + Sync {
    /// 动作唯一标识(如 `"otp"` / `"webauthn"`)。
    fn action_id(&self) -> &'static str;

    /// 判定该动作对当前会话是否必需(新鲜度 / AAL 门槛)。
    async fn evaluate(
        &self,
        ctx: &RequiredActionContext,
        threshold: &MfaFreshness,
    ) -> GarrisonResult<bool>;

    /// 产出挑战载荷。
    async fn challenge(
        &self,
        ctx: &RequiredActionContext,
    ) -> GarrisonResult<RequiredActionChallenge>;

    /// 校验客户端响应(验证码 / authenticator 断言)。
    async fn process(
        &self,
        ctx: &RequiredActionContext,
        response: &str,
        dao: &dyn GarrisonDao,
    ) -> GarrisonResult<ProcessOutcome>;
}

/// process 成功后的账本升级(编排收口:provider 只判结果,会话写入在此):`Verified` 追加 `AmrEntry{method, aal, completed_at}`,`Rejected` no-op。
pub async fn complete_required_action(
    session: &crate::session::GarrisonSession,
    token: &str,
    outcome: &ProcessOutcome,
    completed_at: i64,
) -> GarrisonResult<()> {
    let ProcessOutcome::Verified { method, aal } = outcome else {
        return Ok(());
    };
    session
        .append_amr_entry(token, method, *aal, completed_at)
        .await
}

/// 签发路径允许写入账本的 amr method 词汇表(RFC 8176 已登记值):账本是 amr claim 权威来源,词汇表外的值入账会让签发载荷携带未登记的认证方法引用。
pub const AMR_METHODS: &[&str] = &["pwd", "otp", "webauthn"];

/// 主登录因子对应的 amr method(本框架 `login` 即主认证,约定为密码认证)。
pub const PRIMARY_FACTOR_AMR: &str = "pwd";

/// 主登录因子授予的认证保证等级(密码单因子 = AAL 1)。
pub const PRIMARY_FACTOR_AAL: u8 = 1;

/// 因子账本条目:`method` 为 RFC 8176 amr 值([`AMR_METHODS`] 内)、`aal` 为认证保证等级(1..=3)、`completed_at` 完成时刻(Unix 秒)。
/// 随 [`crate::session::TokenSession`] 持久化,签发 token 时映射为 RFC 8176 `amr` claim(完成顺序去重)与 OIDC `auth_time` claim。
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AmrEntry {
    /// 认证方法(RFC 8176 amr 值)。
    pub method: String,
    /// 该步骤授予的认证保证等级(1..=3)。
    pub aal: u8,
    /// 完成时刻(Unix 秒)。
    pub completed_at: i64,
}

impl AmrEntry {
    /// 构造账本条目并校验词汇表 / AAL 边界;`method` 不在 [`AMR_METHODS`] 或 `aal` 不在 1..=3 返回 `InvalidParam`。
    pub fn new(method: impl Into<String>, aal: u8, completed_at: i64) -> GarrisonResult<Self> {
        let method = method.into();
        if !AMR_METHODS.contains(&method.as_str()) {
            return Err(GarrisonError::InvalidParam(format!(
                "mfa-amr-method-unknown::{method}::allowed={:?}",
                AMR_METHODS
            )));
        }
        if !(1..=3).contains(&aal) {
            return Err(GarrisonError::InvalidParam(format!(
                "mfa-aal-out-of-range::{aal}::allowed=1..=3"
            )));
        }
        Ok(Self {
            method,
            aal,
            completed_at,
        })
    }
}

/// 主登录签发的 claim 映射输入(主因子 amr + 认证时刻单一口径):stp `generate_token` 与 `AuthLogic::login` 共用,签发载荷携 `amr=["pwd"]` 与 `auth_time=签发时刻`(与会话账本播种同源)。
/// 续签/换签路径不得使用本函数——应从会话账本映射([`amr_claim`] + `TokenSession.auth_time`),保证 token claim 与账本一致不凭空消失。
pub fn primary_issuance_claims(now: i64) -> (Vec<String>, Option<i64>) {
    (vec![PRIMARY_FACTOR_AMR.to_string()], Some(now))
}

/// 因子账本 → RFC 8176 `amr` claim:按完成顺序输出、method 去重保序。
///
/// RFC 8176 的 amr 为字符串数组;同一方法多次完成(如多次 step-up)
/// 对 rp 而言只表达一种方法引用,去重保序保证 claim 确定性。
pub fn amr_claim(entries: &[AmrEntry]) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    entries
        .iter()
        .filter(|e| seen.insert(e.method.as_str()))
        .map(|e| e.method.clone())
        .collect()
}

/// 因子账本的最高认证保证等级;空账本为 0(未完成任何认证步骤)。
pub fn ledger_max_aal(entries: &[AmrEntry]) -> u8 {
    entries.iter().map(|e| e.aal).max().unwrap_or(0)
}

// TOTP Required Action provider(复用既有 TOTP 设施)

/// TOTP Required Action provider:evaluate 按新鲜度门槛判定、challenge 产出静态提示、process 委托 [`TotpHandler::validate_and_consume`](crate::secure::totp::TotpHandler::validate_and_consume)(DAO 原子防重放)。
/// secret 由集成方按 login_id 查凭证库后构造 provider;本基座只承载编排,不做凭证存储。
#[cfg(feature = "secure-totp")]
pub struct TotpRequiredActionProvider {
    /// Base32 编码的 TOTP 密钥。
    secret_base32: String,
}

#[cfg(feature = "secure-totp")]
impl TotpRequiredActionProvider {
    /// 构造 provider(`secret_base32` 与凭证库 `secret_data` 同口径)。
    pub fn new(secret_base32: impl Into<String>) -> Self {
        Self {
            secret_base32: secret_base32.into(),
        }
    }

    /// 生成当前时刻的验证码(测试/便捷用途)。
    pub fn generate_current_code(&self, now: i64) -> GarrisonResult<String> {
        self.handler()?.generate(now)
    }

    /// 从 Base32 密钥构造 [`TotpHandler`](step=30 / digits=6,与 [`crate::account::credential::totp::TotpCredential`] 默认口径一致)。
    fn handler(&self) -> GarrisonResult<crate::secure::totp::TotpHandler> {
        let secret = crate::secure::totp::TotpHandler::secret_from_base32(&self.secret_base32)?;
        crate::secure::totp::TotpHandler::new(secret, 30, 6)
    }
}

#[cfg(feature = "secure-totp")]
#[async_trait]
impl RequiredActionProvider for TotpRequiredActionProvider {
    fn action_id(&self) -> &'static str {
        "otp"
    }

    async fn evaluate(
        &self,
        ctx: &RequiredActionContext,
        threshold: &MfaFreshness,
    ) -> GarrisonResult<bool> {
        Ok(assert_freshness(&ctx.freshness_input(), threshold) == FreshnessVerdict::Stale)
    }

    async fn challenge(
        &self,
        _ctx: &RequiredActionContext,
    ) -> GarrisonResult<RequiredActionChallenge> {
        Ok(RequiredActionChallenge {
            action: self.action_id().to_string(),
            payload: "totp:enter-code".to_string(),
        })
    }

    async fn process(
        &self,
        ctx: &RequiredActionContext,
        response: &str,
        dao: &dyn GarrisonDao,
    ) -> GarrisonResult<ProcessOutcome> {
        let handler = self.handler()?;
        let ok = handler
            .validate_and_consume(&ctx.login_id, response, ctx.now, dao)
            .await?;
        if ok {
            Ok(ProcessOutcome::Verified {
                method: "otp",
                aal: 2,
            })
        } else {
            Ok(ProcessOutcome::Rejected)
        }
    }
}

// WebAuthn Required Action provider(protocol-webauthn feature)

/// WebAuthn 二次认证 Required Action provider:`process` 经 [`webauthn_factor`] 进程级注册表取校验函数执行认证仪式(用户绑定写入 challenge payload,不信任请求重传);未注册校验函数时显性报错(装配方漏接线不静默降级为通过)。
#[cfg(feature = "protocol-webauthn")]
pub struct WebauthnRequiredActionProvider;

#[cfg(feature = "protocol-webauthn")]
#[async_trait]
impl RequiredActionProvider for WebauthnRequiredActionProvider {
    fn action_id(&self) -> &'static str {
        "webauthn"
    }

    async fn evaluate(
        &self,
        ctx: &RequiredActionContext,
        threshold: &MfaFreshness,
    ) -> GarrisonResult<bool> {
        Ok(assert_freshness(&ctx.freshness_input(), threshold) == FreshnessVerdict::Stale)
    }

    /// WebAuthn 真实协议挑战(server challenge → authenticator assertion)不在此产出——本 trait 的 `challenge` 仅为客户端 UI 提示;真实挑战由编排方经 `webauthn_factor().service().start_authentication` 获取(用户绑定写于 challenge payload),`process` 消费 assertion JSON。有状态挑战 provider(邮件 OTP 等)应扩展 trait,不复用本形态。
    async fn challenge(
        &self,
        _ctx: &RequiredActionContext,
    ) -> GarrisonResult<RequiredActionChallenge> {
        Ok(RequiredActionChallenge {
            action: self.action_id().to_string(),
            payload: "webauthn:use-passkey".to_string(),
        })
    }

    async fn process(
        &self,
        ctx: &RequiredActionContext,
        response: &str,
        _dao: &dyn GarrisonDao,
    ) -> GarrisonResult<ProcessOutcome> {
        let verifier = webauthn_factor::webauthn_factor().ok_or_else(|| {
            GarrisonError::Config("mfa-webauthn-factor-not-registered::".to_string())
        })?;
        // response 为浏览器 WebAuthn API 产出的 PublicKeyCredential JSON
        let assertion: webauthn_rs::prelude::PublicKeyCredential = serde_json::from_str(response)
            .map_err(|e| {
            GarrisonError::InvalidParam(format!("mfa-webauthn-assertion-parse::{e}"))
        })?;
        let auth = verifier.verify_second_factor(&assertion).await?;
        // 仪式锁定的用户绑定必须与当前会话主体一致,跨用户 assertion(他人 passkey 完成他人 step-up)在此显性拒绝
        if auth.user_id != ctx.login_id {
            return Err(GarrisonError::InvalidParam(format!(
                "mfa-webauthn-subject-mismatch::{}::{}",
                auth.user_id, ctx.login_id
            )));
        }
        Ok(ProcessOutcome::Verified {
            method: "webauthn",
            aal: 2,
        })
    }
}

#[cfg(feature = "protocol-webauthn")]
#[cfg(test)]
mod webauthn_provider_tests {
    use super::*;

    /// 未注册校验函数时 process fail-closed(不静默降级为通过);注册表为进程级共享状态,serial 串行化且先重置保证前置条件自管。
    #[tokio::test(flavor = "multi_thread")]
    #[serial_test::serial]
    async fn process_without_registered_verifier_fails_closed() {
        webauthn_factor::reset_webauthn_factor_for_tests();
        let provider = WebauthnRequiredActionProvider;
        let ctx = RequiredActionContext {
            login_id: "user-wn-provider".to_string(),
            auth_time: None,
            ledger_max_aal: 1,
            now: 1_700_000_000,
        };
        let result = provider
            .process(&ctx, "{}", &crate::dao::InMemoryDao::new())
            .await;
        assert!(
            matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("not-registered")),
            "未注册校验函数应 fail-closed,实际: {result:?}"
        );
    }

    /// 全流程穿透:注册 factor(真实 service + 注册向量绑定凭据)→ provider.process 提交真实认证向量 assertion → `Verified{webauthn, aal:2}`。
    /// 仪式分支语义(重放/克隆/counter/backup flags)见 protocol::webauthn::tests;本用例补齐「装配注册 → 真实 assertion 穿透 process」闭环。
    #[cfg(all(test, feature = "db-sqlite"))]
    #[tokio::test(flavor = "multi_thread")]
    #[serial_test::serial]
    async fn process_with_real_assertion_completes_full_flow() {
        use crate::dao::repository::WebauthnCredentialRepository;
        use crate::protocol::webauthn::tests::{
            domain_to_credential, seed_authentication, service_with_bound_vector_credential,
            test_config, AUTH_VECTOR_JSON,
        };
        use std::sync::Arc;

        // 注册表为进程级共享状态:先重置保证前置条件自管(serial 串行化)
        webauthn_factor::reset_webauthn_factor_for_tests();

        let (service, repo, store, bound) =
            service_with_bound_vector_credential(test_config()).await;
        webauthn_factor::register_webauthn_factor(Arc::new(
            webauthn_factor::WebauthnFactorVerifier::new(Arc::new(service)),
        ))
        .expect("首次注册 factor 应成功");

        // 认证仪式态:植入与认证向量 challenge 一致的 PasskeyAuthentication
        let stored_cred = repo
            .find_by_credential_id(0, &bound.credential_id)
            .await
            .expect("查询应成功")
            .expect("凭据应存在");
        let domain =
            crate::protocol::webauthn::credential::WebauthnCredential::from_row(stored_cred)
                .expect("行重建应成功");
        seed_authentication(&store, 0, "user-1", domain_to_credential(&domain)).await;

        // 仪式锁定的用户绑定 = "user-1",与会话主体一致(跨主体拒绝分支
        // 由 subject-mismatch 单测覆盖,此处走放行路径)
        let provider = WebauthnRequiredActionProvider;
        let ctx = RequiredActionContext {
            login_id: "user-1".to_string(),
            auth_time: None,
            ledger_max_aal: 1,
            now: 1_700_000_000,
        };
        let outcome = provider
            .process(&ctx, AUTH_VECTOR_JSON, &crate::dao::InMemoryDao::new())
            .await
            .expect("真实 assertion 应穿透 process 全流程");
        assert_eq!(
            outcome,
            ProcessOutcome::Verified {
                method: "webauthn",
                aal: 2
            },
            "真实 assertion 应产出 Verified{{webauthn, aal:2}},实际: {outcome:?}"
        );
    }
}

// 恢复码:批量一次性生成 / verify-consume 分离 / CAS 原子消费 / 误用容忍
#[cfg(feature = "mfa-recovery")]
/// 恢复码 verify 结论。
#[cfg(feature = "mfa-recovery")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryVerify {
    /// 码存在且未使用。
    Valid,
    /// 码不存在或已使用(计一次误用)。
    Invalid,
    /// 误用次数超过豁免额度,已锁定(fail-closed,正确码也拒绝)。
    Locked,
}

/// 恢复码管理器:verify(校验)与 consume(置已用)分离。
/// 存储:`mfa:recovery:{len}:{login_id}:{sha256(code)}` → "unused"/"used",`mfa:recovery:misuse:{login_id}` 误用计数(原子 incr)。
/// 并发双花由 [`GarrisonDao::compare_and_swap`] CAS 消除:置已用只在当前值为 "unused" 时成功。
// 与 impl 块同门控:struct 独立于 feature 存在时字段无读取点,关闭 mfa-recovery 会产生 dead_code 告警(-D warnings 下为 error)。
#[cfg(feature = "mfa-recovery")]
pub struct RecoveryCodeManager {
    dao: Arc<dyn GarrisonDao>,
    /// 误用豁免额度(默认 0):连续无效 verify 超过该次数即锁定。
    misuse_tolerance: u32,
}

#[cfg(feature = "mfa-recovery")]
impl RecoveryCodeManager {
    /// 恢复码存储 key 前缀。
    const KEY_PREFIX: &'static str = "recovery:";
    /// 误用计数 key 后缀。
    const MISUSE_SUFFIX: &'static str = "misuse:";

    /// 构造管理器(`misuse_tolerance` 误用豁免额度,0 = 首次误用即锁定)。
    pub fn new(dao: Arc<dyn GarrisonDao>, misuse_tolerance: u32) -> Self {
        Self {
            dao,
            misuse_tolerance,
        }
    }

    /// 恢复码存储 key:`mfa:recovery:{len}:{login_id}:{sha256(code)}`。
    /// 安全约束:只存哈希不存明文(恢复码可直接兑换登录,DAO key 泄露不得等于凭证泄露);长度前缀隔离 login_id 键空间(防 `user1` 与 `user1x` 裸拼接的前缀歧义)。
    fn code_key(&self, login_id: &str, code: &str) -> String {
        let code_hash = Self::code_hash(code);
        format!(
            "{}{}{}:{}:{}",
            DaoKeyPrefix::Mfa.as_str(),
            Self::KEY_PREFIX,
            login_id.len(),
            login_id,
            code_hash
        )
    }

    /// 恢复码哈希(SHA-256 hex;key 侧只落哈希,明文不出现在存储面)。
    fn code_hash(code: &str) -> String {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(code.as_bytes());
        let result = hasher.finalize();
        use std::fmt::Write as _;
        let mut hex = String::with_capacity(result.len() * 2);
        for b in result {
            let _ = write!(hex, "{b:02x}");
        }
        hex
    }

    fn misuse_key(&self, login_id: &str) -> String {
        format!(
            "{}{}{}{}",
            DaoKeyPrefix::Mfa.as_str(),
            Self::KEY_PREFIX,
            Self::MISUSE_SUFFIX,
            login_id
        )
    }

    /// 批量一次性生成恢复码(每码独立存储为未用状态):10 个 hex 字符(5-5 分组),随机源为 OS CSPRNG;`count == 0` 或超过单批上限 64 返回 `InvalidParam`,DAO 写入失败透传。
    pub async fn generate(&self, login_id: &str, count: usize) -> GarrisonResult<Vec<String>> {
        const MAX_BATCH: usize = 64;
        if count == 0 || count > MAX_BATCH {
            return Err(GarrisonError::InvalidParam(format!(
                "mfa-recovery-batch-size-invalid::{count}::allowed=1..={MAX_BATCH}"
            )));
        }
        let mut codes = Vec::with_capacity(count);
        for _ in 0..count {
            let hex = uuid::Uuid::new_v4().simple().to_string();
            let code = format!("{}-{}", &hex[..5], &hex[5..10]);
            self.dao
                .set(&self.code_key(login_id, &code), "unused", 0)
                .await?;
            codes.push(code);
        }
        Ok(codes)
    }

    /// 误用计数当前值。
    async fn misuse_count(&self, login_id: &str) -> GarrisonResult<u64> {
        match self.dao.get(&self.misuse_key(login_id)).await? {
            Some(v) => v
                .parse::<u64>()
                .map_err(|e| GarrisonError::Internal(format!("mfa-recovery-misuse-parse::{}", e))),
            None => Ok(0),
        }
    }

    /// 校验恢复码(不改状态):无效码计一次误用,超豁免即锁定;锁定后连 Valid 码也返回 `Locked`(fail-closed)。
    pub async fn verify(&self, login_id: &str, code: &str) -> GarrisonResult<RecoveryVerify> {
        if self.misuse_count(login_id).await? > self.misuse_tolerance as u64 {
            return Ok(RecoveryVerify::Locked);
        }
        match self.dao.get(&self.code_key(login_id, code)).await? {
            Some(state) if state == "unused" => Ok(RecoveryVerify::Valid),
            // 已用码 = 已识别重放:拒绝但不计误用(合法持有者可能重复提交;消费由 CAS 保护,重放无收益)
            Some(_) => Ok(RecoveryVerify::Invalid),
            // 不存在的码 = 猜测攻击:计一次误用,超豁免即锁定
            None => {
                // 误用计数带 24h TTL:定向 DoS(烧毁恢复码通道)与合法用户手误代价有界,超时自动解冻(运维可删 `mfa:recovery:misuse:{login_id}` 立即解冻)
                const MISUSE_LOCK_TTL_SECS: u64 = 24 * 60 * 60;
                let count = self
                    .dao
                    .incr(&self.misuse_key(login_id), MISUSE_LOCK_TTL_SECS)
                    .await?;
                if count > self.misuse_tolerance as u64 {
                    Ok(RecoveryVerify::Locked)
                } else {
                    Ok(RecoveryVerify::Invalid)
                }
            },
        }
    }

    /// 原子消费恢复码(CAS `unused` → `used`):并发消费同一码仅一个成功,锁定状态直接拒绝。
    /// `Ok(false)` 为码不存在或已被使用(不计误用——并发落败方持有的是有效码);`Err` 为锁定(fail-closed)或 DAO 失败。
    pub async fn consume(&self, login_id: &str, code: &str) -> GarrisonResult<bool> {
        if self.misuse_count(login_id).await? > self.misuse_tolerance as u64 {
            return Err(GarrisonError::NotSafe {
                reason: "MFA_RECOVERY_LOCKED".to_string(),
            });
        }
        self.dao
            .compare_and_swap(&self.code_key(login_id, code), Some("unused"), "used", 0)
            .await
    }

    /// 统计 login_id 名下未消费恢复码数量(管理用途);存储只落 `sha256(code)`,只能计数、不能反解码值,明文码仅在 [`generate`](Self::generate) 返回时出现一次。
    pub async fn unconsumed_count(&self, login_id: &str) -> GarrisonResult<usize> {
        let pattern = format!(
            "{}{}{}:{}:*",
            DaoKeyPrefix::Mfa.as_str(),
            Self::KEY_PREFIX,
            login_id.len(),
            login_id
        );
        let misuse_prefix = self.misuse_key(login_id);
        let mut count = 0;
        for key in self.dao.keys(&pattern).await? {
            if key.starts_with(&misuse_prefix) {
                continue;
            }
            count += 1;
        }
        Ok(count)
    }
}

// MFA remember cookie:JWT(HS256) 绑 stage + login_id + credential_id + exp,
// Set-Cookie 经单一构建点产出

/// MFA remember cookie 载荷(吸收 authentik MFA cookie 的三绑定语义):`stage`(其他 stage 不可复用)+ `login_id`(跨主体不可复用,防持有式豁免退化)+ `credential_id`(跨凭证不可复用)+ `exp`(Unix 秒)。
/// 签名密钥为部署级 secret,客户端无法伪造或跨 stage / credential 重放。
#[cfg(feature = "protocol-jwt")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MfaRememberClaims {
    /// 编排阶段标识(绑定:其他 stage 不可复用)。
    pub stage: String,
    /// 完成认证的主体(绑定:跨主体不通用——防持有式豁免退化为「同 credential 的任意主体可复用」)。
    pub login_id: String,
    /// 完成认证的因子凭证 ID(绑定:跨 credential 不通用)。
    pub credential_id: String,
    /// 过期时刻(Unix 秒)。
    pub exp: i64,
}

/// MFA remember cookie 名(经 [`CookieType::session`] 构建点产出属性)。
#[cfg(feature = "protocol-jwt")]
pub const MFA_REMEMBER_COOKIE_NAME: &str = "mfa_remember";

/// 从部署级 secret 派生 remember cookie 独立签名子钥(HKDF RFC 5869 域分隔;与 protocol-sign / protocol-httpdigest 惯例同习语,零新增依赖)。
#[cfg(feature = "protocol-jwt")]
fn mfa_remember_subkey(secret: &str) -> Vec<u8> {
    use hkdf::Hkdf;
    let hk = Hkdf::<sha2::Sha256>::new(None, secret.as_bytes());
    let mut okm = [0u8; 32];
    hk.expand(b"garrison:mfa-remember-cookie:v1" as &[u8], &mut okm)
        .unwrap_or_else(|e| {
            panic!(
                "{}: {e}",
                crate::i18n::translate_detail("mfa-hkdf-okm-len-static", &[],)
            )
        });
    okm.to_vec()
}

/// 签发 MFA remember cookie 的 Set-Cookie 值:载荷 JWT(HS256,`exp = now + ttl_secs`)作为 cookie 值,属性(HttpOnly 恒定、SameSite 白名单与 None→Lax 降级、production `__Host-`/`__Secure-` 前缀、`Max-Age`)全部由单一构建点 [`build_set_cookie_value`] 产出,本函数不自行拼接属性串。
/// 签名密钥为部署级 secret 经 HKDF 派生的独立子钥(RFC 8725 密钥分离:与主 token 同源不同钥);密钥 < 32 字节或 ttl 负值/溢出报错,cookie 属性非法透传构建点错误。
#[cfg(feature = "protocol-jwt")]
pub fn issue_mfa_remember_cookie(
    secret: &str,
    config: &GarrisonConfig,
    stage: &str,
    login_id: &str,
    credential_id: &str,
    ttl_secs: i64,
) -> GarrisonResult<String> {
    if secret.len() < 32 {
        return Err(GarrisonError::Config(format!(
            "mfa-remember-secret-too-short::{}::min=32",
            secret.len()
        )));
    }
    let signing_key = mfa_remember_subkey(secret);
    let now = chrono::Utc::now().timestamp();
    let claims = MfaRememberClaims {
        stage: stage.to_string(),
        login_id: login_id.to_string(),
        credential_id: credential_id.to_string(),
        exp: now.checked_add(ttl_secs).ok_or_else(|| {
            GarrisonError::InvalidParam(format!("mfa-remember-ttl-overflow::{ttl_secs}"))
        })?,
    };
    let jwt = jsonwebtoken::encode(
        &jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
        &claims,
        &jsonwebtoken::EncodingKey::from_secret(&signing_key),
    )
    .map_err(|e| GarrisonError::Internal(format!("mfa-remember-sign::{}", e)))?;

    let cookie = CookieType {
        max_age: Some(ttl_secs),
        ..CookieType::session(MFA_REMEMBER_COOKIE_NAME, config)?
    };
    build_set_cookie_value(&cookie, &jwt, config.cookie_secure)
}

/// 校验 MFA remember cookie 的 JWT 载荷(三元绑定 + exp,leeway=0):签名有效且 stage / login_id / credential_id 匹配且未过期才 true,否则 false(含 exp 缺失)。
#[cfg(feature = "protocol-jwt")]
pub fn verify_mfa_remember_cookie(
    secret: &str,
    jwt: &str,
    stage: &str,
    login_id: &str,
    credential_id: &str,
    now: i64,
) -> bool {
    if secret.is_empty() {
        return false;
    }
    let signing_key = mfa_remember_subkey(secret);
    let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
    validation.leeway = 0;
    let Ok(data) = jsonwebtoken::decode::<MfaRememberClaims>(
        jwt,
        &jsonwebtoken::DecodingKey::from_secret(&signing_key),
        &validation,
    ) else {
        return false;
    };
    data.claims.stage == stage
        && data.claims.login_id == login_id
        && data.claims.credential_id == credential_id
        && data.claims.exp > now
}
// GarrisonLogicDefault impl

#[async_trait]
impl MfaLogic for GarrisonLogicDefault {
    /// `GarrisonLogicDefault` 覆写:先过会话前置与链检查,再查 `is_safe("default")`(false → `NotSafe("SAFE_EXPIRED")`)。
    /// 必须覆写的原因(编译期契约):async_trait 的 trait default 在泛型上下文 `&Self` 无法解析 inherent `is_safe`(只会走 trait default `Ok(true)`);impl 块中 `self` 是具体类型,`safe-auth` 启用时才能解析到 safe.rs 的 inherent 实现。
    async fn check_safe(&self) -> GarrisonResult<()> {
        self.check_session_precondition().await?;
        self.check_mfa_chain(None).await?;
        if !self.is_safe("default").await? {
            return Err(Self::not_safe("SAFE_EXPIRED"));
        }
        Ok(())
    }

    /// MFA 强制链 gate(fail-closed):决策 `None`(禁用/继承为空)→ `Ok(())`;`Require` 时须已登录(无 token / 无会话视为未满足),账本缺任一 factor → `NotSafe { MFA_CHAIN_INCOMPLETE::<factor> }`。
    async fn check_mfa_chain(&self, client_id: Option<&str>) -> GarrisonResult<()> {
        let decision = crate::stp::mfa::resolve_mfa_chain(
            client_id.and_then(|id| self.config.mfa.per_client_chains.get(id)),
            &self.config.mfa.global_chain,
        );
        if matches!(decision, crate::stp::mfa::MfaChainDecision::None) {
            return Ok(());
        }
        let not_enrolled = || GarrisonError::NotSafe {
            reason: "MFA_CHAIN_INCOMPLETE::no-active-session".to_string(),
        };
        let token = current_token().map_err(|_| not_enrolled())?;
        let ts = self
            .session
            .get_token_session(&token)
            .await?
            .ok_or_else(not_enrolled)?;
        match crate::stp::mfa::first_unmet_chain_factor(&decision, &ts.amr_ledger) {
            None => Ok(()),
            Some(factor) => Err(GarrisonError::NotSafe {
                reason: format!("MFA_CHAIN_INCOMPLETE::{factor}"),
            }),
        }
    }

    /// 检查当前账号是否被封禁(先验会话后判封禁,fail-closed):无效 token → `Session`(不再与「未封禁」合并为 `Ok(())`);无 token 的非 HTTP 上下文 → `Ok(())`;与前置校验竞态时 session 缺失 → `Session`;`DisableRepository::is_disable` 命中 → `DisableService`(`until` 来自 `get_disable_time`,None 永久,Some 定时解封)。
    async fn check_disable(&self) -> GarrisonResult<()> {
        // 先验会话:无效 token 显性拒绝,不进入封禁判定
        self.check_session_precondition().await?;
        // 无 token 上下文时无主体可判禁用,维持既有 Ok 语义
        let token = match current_token() {
            Ok(t) => t,
            Err(_) => {
                tracing::warn!(
                    reason = "no_current_token",
                    "check_disable skipped: no current token (not logged in)"
                );
                return Ok(());
            },
        };
        // 防御分支:前置校验通过后 session 被并发删除(登出/踢出竞态)→ fail-closed
        let ts = match self.session.get_token_session(&token).await? {
            Some(ts) => ts,
            None => {
                return Err(GarrisonError::Session(
                    "stp-check-disable-token-session-not-found::".to_string(),
                ));
            },
        };
        if self
            .disable_repository
            .is_disable(&ts.login_id, "default")
            .await?
        {
            let until = self
                .disable_repository
                .get_disable_time(&ts.login_id, "default")
                .await?;
            return Err(Self::disable_service("default", until));
        }
        Ok(())
    }
}

// WebAuthn factor 接线点(protocol-webauthn feature)

/// WebAuthn 二次认证因子的凭据校验接线点:本接线点只暴露「给 MFA 层一个可调用的 assertion 校验函数」的最小缝,完整 MFA 编排(因子账本 / Required Action / 新鲜度断言)归 stp/mfa 编排基座。
/// [`WebauthnFactorVerifier`](crate::stp::mfa::webauthn_factor::WebauthnFactorVerifier) 包装 [`WebauthnService`](crate::protocol::webauthn::service::WebauthnService) 校验入口,把模块错误词汇映射为 [`GarrisonError`](`InvalidParam` 携显性 detail,不静默吞错)。
/// [`register_webauthn_factor`](crate::stp::mfa::webauthn_factor::register_webauthn_factor) / [`webauthn_factor`] 为进程级注册表,装配方注入一次,编排层按 `webauthn` 方法名取用(未注册返回 `None`,走「因子未配置」分支而非错误)。
#[cfg(feature = "protocol-webauthn")]
pub mod webauthn_factor {
    use super::*;
    use crate::protocol::webauthn::service::WebauthnService;

    use std::sync::{Arc, RwLock};

    static WEBAUTHN_FACTOR: RwLock<Option<Arc<WebauthnFactorVerifier>>> = RwLock::new(None);

    /// WebAuthn 二次认证校验函数(包装 [`WebauthnService`] 认证仪式)。
    pub struct WebauthnFactorVerifier {
        service: Arc<WebauthnService>,
    }

    impl WebauthnFactorVerifier {
        /// 包装既有 service(仪式/challenge/凭据存取均由 service 承载)。
        pub fn new(service: Arc<WebauthnService>) -> Self {
            Self { service }
        }

        /// 校验二次认证 assertion:走认证仪式全流程(challenge 一次性消费、sign_count 单调性克隆检测、backup flags 更新落库)。
        /// 返回仪式锁定的用户绑定(`WebauthnAuthentication`,tenant/user 取自 challenge 暂存),调用方必须与当前会话主体比对,防「自己的 passkey 完成他人 step-up」的跨用户断言。
        pub async fn verify_second_factor(
            &self,
            assertion: &webauthn_rs::prelude::PublicKeyCredential,
        ) -> GarrisonResult<crate::protocol::webauthn::service::WebauthnAuthentication> {
            self.service
                .finish_authentication(assertion)
                .await
                .map_err(GarrisonError::from)
        }

        /// 底层 service(MFA 编排层需要发起 challenge 时使用)。
        pub fn service(&self) -> &Arc<WebauthnService> {
            &self.service
        }
    }

    /// 注册 WebAuthn factor 校验函数(进程级,重复注册显性拒绝——
    /// 静默覆盖会让「后注册者改变全库校验行为」变得不可见)。
    pub fn register_webauthn_factor(verifier: Arc<WebauthnFactorVerifier>) -> GarrisonResult<()> {
        let mut guard = WEBAUTHN_FACTOR.write().unwrap_or_else(|e| {
            panic!(
                "{}: {e}",
                crate::i18n::translate_detail("mfa-webauthn-factor-registry-lock-poisoned", &[],)
            )
        });
        if guard.is_some() {
            return Err(GarrisonError::Config(
                "mfa-webauthn-factor-already-registered::".to_string(),
            ));
        }
        *guard = Some(verifier);
        Ok(())
    }

    /// 取已注册的 WebAuthn factor 校验函数;未注册返回 `None`(编排层
    /// 据此判定「因子未配置」,不视为错误)。
    pub fn webauthn_factor() -> Option<Arc<WebauthnFactorVerifier>> {
        WEBAUTHN_FACTOR
            .read()
            .unwrap_or_else(|e| {
                panic!(
                    "{}: {e}",
                    crate::i18n::translate_detail(
                        "mfa-webauthn-factor-registry-lock-poisoned",
                        &[],
                    )
                )
            })
            .clone()
    }

    /// 重置注册表(仅供测试用,业务代码不应调用)。
    #[cfg(test)]
    pub fn reset_webauthn_factor_for_tests() {
        *WEBAUTHN_FACTOR
            .write()
            .expect("mfa webauthn factor 注册表锁不应中毒") = None;
    }

    // 测试经 sqlite 内存库构造 service 依赖(repository 需 DbPool),
    // 无 db-sqlite 的组合(如 production 门禁)不编译
    #[cfg(all(test, feature = "db-sqlite"))]
    mod tests {
        use super::*;
        use crate::dao::InMemoryDao;
        use crate::protocol::webauthn::WebauthnConfig;

        #[tokio::test(flavor = "multi_thread")]
        #[serial_test::serial]
        async fn register_then_get_and_duplicate_rejected() {
            let pool = crate::dao::init_dbnexus("sqlite::memory:")
                .await
                .expect("init_dbnexus 应成功");
            // 本测试只验证注册表语义(register/get/重复注册拒绝),不触达
            // 凭据存取——repository 仅在构造时被 service 持有
            let service = Arc::new(WebauthnService::new(
                Arc::new(InMemoryDao::new()),
                Arc::new(
                    crate::dao::repository::sqlite::DbnexusWebauthnCredentialRepository::new(pool),
                ),
                WebauthnConfig {
                    issuer: "https://auth.example.com".to_string(),
                    challenge_ttl_secs: 120,
                    passwordless: crate::protocol::webauthn::FactorPolicy { enabled: false },
                    second_factor: crate::protocol::webauthn::FactorPolicy { enabled: true },
                },
            ));
            let verifier = Arc::new(WebauthnFactorVerifier::new(service));
            // 注册表为进程级:先重置保证本测试自管前置条件(顺序无关)
            reset_webauthn_factor_for_tests();
            register_webauthn_factor(verifier.clone()).expect("首次注册应成功");
            let got = webauthn_factor();
            assert!(got.is_some(), "注册后应可取回 factor");
            let dup = register_webauthn_factor(verifier);
            assert!(
                matches!(dup, Err(GarrisonError::Config(_))),
                "重复注册应显性拒绝,实际: {dup:?}"
            );
            if let Err(GarrisonError::Config(m)) = &dup {
                assert!(
                    m.contains("already-registered"),
                    "重复注册错误应含 already-registered 指引,实际: {m}"
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::GarrisonConfig;
    use crate::error::GarrisonResult;
    use crate::stp::core::GarrisonCore;
    use crate::stp::session::SessionLogic;
    use crate::stp::LoginParams;
    use std::sync::Arc;

    /// 最小 mock:实现 `GarrisonCore` + `SessionLogic`(9 必需方法)。
    /// `MfaLogic` 2 个方法均有默认实现,空 impl 即可获得全部默认行为。
    struct MockMfa {
        config: Arc<GarrisonConfig>,
    }

    impl GarrisonCore for MockMfa {
        fn config(&self) -> Arc<GarrisonConfig> {
            Arc::clone(&self.config)
        }
    }

    #[async_trait]
    impl SessionLogic for MockMfa {
        async fn login(
            &self,
            _login_id: &str,
            _params: &crate::stp::LoginParams,
        ) -> GarrisonResult<String> {
            Ok("mock-token".to_string())
        }
        async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout(&self) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_login(&self) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
            Ok(Some("42".to_string()))
        }
    }

    #[async_trait]
    impl MfaLogic for MockMfa {}

    #[tokio::test]
    async fn check_safe_default_ok() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        mock.check_safe().await.unwrap();
    }

    #[tokio::test]
    async fn check_disable_default_ok() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        mock.check_disable().await.unwrap();
    }

    // disable_service / not_safe 构造方法测试

    /// 验证 `disable_service` 构造正确的 `GarrisonError::DisableService` 变体。
    ///
    /// service 字段正确传递,until=None 表示永久封禁。
    #[test]
    fn disable_service_constructs_correct_error() {
        let err = MockMfa::disable_service("default", None);
        match err {
            GarrisonError::DisableService { service, until } => {
                assert_eq!(service, "default");
                assert!(until.is_none(), "until=None 表示永久封禁");
            },
            other => panic!("期望 DisableService 变体,实际: {:?}", other),
        }
    }

    /// 验证 `disable_service` 带 until 时间戳时正确传递。
    #[test]
    fn disable_service_with_until_timestamp() {
        let until = chrono::DateTime::parse_from_rfc3339("2026-12-31T23:59:59Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let err = MockMfa::disable_service("oidc", Some(until));
        match err {
            GarrisonError::DisableService { service, until: u } => {
                assert_eq!(service, "oidc");
                assert!(u.is_some(), "until 应为 Some");
                assert_eq!(u.unwrap().to_rfc3339(), "2026-12-31T23:59:59+00:00");
            },
            other => panic!("期望 DisableService 变体,实际: {:?}", other),
        }
    }

    /// 验证 `not_safe` 构造正确的 `GarrisonError::NotSafe` 变体。
    ///
    /// reason 字段正确传递。
    #[test]
    fn not_safe_constructs_correct_error() {
        let err = MockMfa::not_safe("MFA_TOTP_REQUIRED");
        match err {
            GarrisonError::NotSafe { reason } => {
                assert_eq!(reason, "MFA_TOTP_REQUIRED");
            },
            other => panic!("期望 NotSafe 变体,实际: {:?}", other),
        }
    }

    /// 验证 `not_safe` 可构造 Display 输出包含 reason。
    #[test]
    fn not_safe_display_includes_reason() {
        let err = MockMfa::not_safe("WEBAUTHN_REQUIRED");
        let display = err.to_string();
        assert!(
            display.contains("WEBAUTHN_REQUIRED"),
            "Display 应包含 reason,实际: {}",
            display
        );
        assert!(
            display.contains("authentication required") || display.contains("二次认证"),
            "Display 应包含认证描述,实际: {}",
            display
        );
    }

    /// 验证 `open_safe` trait 默认实现返回 Ok(())(no-op)。
    ///
    /// 覆盖 trait default 路径:未覆写的实现者调用 open_safe 应直接返回 Ok。
    #[tokio::test]
    async fn open_safe_default_returns_ok() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        mock.open_safe("default", 3600).await.unwrap();
    }

    /// 验证 `close_safe` trait 默认实现返回 Ok(())(no-op)。
    ///
    /// 覆盖 trait default 路径:未覆写的实现者调用 close_safe 应直接返回 Ok。
    #[tokio::test]
    async fn close_safe_default_returns_ok() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        mock.close_safe("default").await.unwrap();
    }

    // check_safe 默认实现测试

    /// 不启用 safe-auth 时,MockMfa(只实现 trait defaults)的 check_safe 返回 Ok。
    ///
    /// is_safe 默认返回 Ok(true) → check_safe 返回 Ok(())。
    #[tokio::test]
    async fn t025_check_safe_default_without_safe_auth() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        mock.check_safe().await.unwrap();
    }

    /// MockMfa 不覆写 is_safe,使用 trait default Ok(true)。
    ///
    /// 验证 check_safe 默认调用 is_safe("default"),因 is_safe=true,返回 Ok(())。
    #[tokio::test]
    async fn t025_check_safe_default_uses_is_safe_default() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        // is_safe 默认返回 Ok(true)
        assert!(
            mock.is_safe("default").await.unwrap(),
            "is_safe 默认应返回 Ok(true)"
        );
        assert!(mock.check_safe().await.is_ok(), "check_safe 应返回 Ok(())");
    }

    // check_safe 默认实现:is_safe 覆写场景测试
    // 覆盖 trait default check_safe(lines 42-47)的 false / Err 分支

    /// 可配置 is_safe 返回值的 mock,用于测试 check_safe trait default 的各分支。
    ///
    /// `safe_result` 为 is_safe 预设返回值,覆盖 Ok(true)/Ok(false)/Err 三类分支。
    struct MockMfaSafe {
        config: Arc<GarrisonConfig>,
        safe_result: GarrisonResult<bool>,
    }

    impl GarrisonCore for MockMfaSafe {
        fn config(&self) -> Arc<GarrisonConfig> {
            Arc::clone(&self.config)
        }
    }

    #[async_trait]
    impl SessionLogic for MockMfaSafe {
        async fn login(
            &self,
            _login_id: &str,
            _params: &crate::stp::LoginParams,
        ) -> GarrisonResult<String> {
            Ok("mock-token".to_string())
        }
        async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout(&self) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_login(&self) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
            Ok(Some("42".to_string()))
        }
    }

    #[async_trait]
    impl MfaLogic for MockMfaSafe {
        // 覆写 is_safe 返回预设值,测试 check_safe trait default 各分支
        async fn is_safe(&self, _service: &str) -> GarrisonResult<bool> {
            match &self.safe_result {
                Ok(b) => Ok(*b),
                Err(GarrisonError::Dao(s)) => Err(GarrisonError::Dao(s.clone())),
                Err(GarrisonError::Internal(s)) => Err(GarrisonError::Internal(s.clone())),
                Err(e) => panic!("MockMfaSafe 不支持此错误变体: {:?}", e),
            }
        }
    }

    /// check_safe + is_safe 返回 Ok(false) → 返回 Err(NotSafe("SAFE_EXPIRED"))。
    ///
    /// 覆盖 mfa.rs 第 43-45 行 `!is_safe → Err(Self::not_safe("SAFE_EXPIRED"))` 分支。
    #[tokio::test]
    async fn check_safe_is_safe_false_returns_not_safe() {
        let mock = MockMfaSafe {
            config: Arc::new(GarrisonConfig::default()),
            safe_result: Ok(false),
        };
        let result = mock.check_safe().await;
        match result {
            Err(GarrisonError::NotSafe { reason }) => {
                assert_eq!(
                    reason, "SAFE_EXPIRED",
                    "is_safe=false 时 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
                );
            },
            other => panic!(
                "is_safe=false 时 check_safe 应返回 Err(NotSafe),实际: {:?}",
                other
            ),
        }
    }

    /// check_safe + is_safe 返回 Ok(true) → 返回 Ok(())。
    ///
    /// 覆盖 mfa.rs 第 46 行 `Ok(())` 分支(通过覆写 is_safe 而非 trait default)。
    #[tokio::test]
    async fn check_safe_is_safe_true_returns_ok() {
        let mock = MockMfaSafe {
            config: Arc::new(GarrisonConfig::default()),
            safe_result: Ok(true),
        };
        mock.check_safe().await.unwrap();
    }

    /// check_safe + is_safe 返回 Err(Dao) → 透传错误。
    ///
    /// 覆盖 mfa.rs 第 43 行 `is_safe(...).await?` 错误传播路径。
    #[tokio::test]
    async fn check_safe_is_safe_error_propagates() {
        let mock = MockMfaSafe {
            config: Arc::new(GarrisonConfig::default()),
            safe_result: Err(GarrisonError::Dao("数据源连接失败".to_string())),
        };
        let result = mock.check_safe().await;
        assert!(
            matches!(result, Err(GarrisonError::Dao(ref s)) if s.contains("数据源连接失败")),
            "is_safe 返回 Dao 错误时应透传,实际: {:?}",
            result
        );
    }

    /// check_safe + is_safe 返回 Err(Internal) → 透传错误。
    ///
    /// 覆盖 mfa.rs 第 43 行 `is_safe(...).await?` 错误传播路径(Internal 变体)。
    #[tokio::test]
    async fn check_safe_is_safe_internal_error_propagates() {
        let mock = MockMfaSafe {
            config: Arc::new(GarrisonConfig::default()),
            safe_result: Err(GarrisonError::Internal("内部错误".to_string())),
        };
        let result = mock.check_safe().await;
        assert!(
            matches!(result, Err(GarrisonError::Internal(ref s)) if s.contains("内部错误")),
            "is_safe 返回 Internal 错误时应透传,实际: {:?}",
            result
        );
    }

    // 会话前置校验测试(trait default 路径,GAR-02 / R2-1 回归)

    /// check_login 结果可配置的 mock:仅依赖 trait defaults,验证 check_safe /
    /// check_disable 在进入 safe/disable 判定前的会话前置校验行为。
    struct MockMfaSession {
        config: Arc<GarrisonConfig>,
        logged_in: bool,
    }

    impl GarrisonCore for MockMfaSession {
        fn config(&self) -> Arc<GarrisonConfig> {
            Arc::clone(&self.config)
        }
    }

    #[async_trait]
    impl SessionLogic for MockMfaSession {
        async fn login(
            &self,
            _login_id: &str,
            _params: &crate::stp::LoginParams,
        ) -> GarrisonResult<String> {
            Ok("mock-token".to_string())
        }
        async fn login_with_token(&self, _login_id: &str, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout(&self) -> GarrisonResult<()> {
            Ok(())
        }
        async fn logout_by_login_id(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn kickout_by_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn revoke_token(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn check_login(&self) -> GarrisonResult<bool> {
            Ok(self.logged_in)
        }
        async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
            Ok(Some("42".to_string()))
        }
    }

    #[async_trait]
    impl MfaLogic for MockMfaSession {}

    /// trait default check_safe:上下文携带 token 但会话无效(check_login=false)
    /// → 显性 `Err(Session)`,不再并入「未启用 MFA」的宽松放行(GAR-02)。
    #[tokio::test]
    async fn t_sec_check_safe_trait_default_rejects_invalid_session() {
        let mock = MockMfaSession {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: false,
        };
        let result = crate::stp::with_current_token("forged-token".to_string(), async {
            mock.check_safe().await
        })
        .await;
        assert!(
            matches!(result, Err(GarrisonError::Session(_))),
            "无效会话的 check_safe 应返回 Err(Session),实际: {:?}",
            result
        );
    }

    /// trait default check_disable:上下文携带 token 但会话无效(check_login=false)
    /// → 显性 `Err(Session)`,不再与「未封禁」合并(R2-1)。
    #[tokio::test]
    async fn t_sec_check_disable_trait_default_rejects_invalid_session() {
        let mock = MockMfaSession {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: false,
        };
        let result = crate::stp::with_current_token("forged-token".to_string(), async {
            mock.check_disable().await
        })
        .await;
        assert!(
            matches!(result, Err(GarrisonError::Session(_))),
            "无效会话的 check_disable 应返回 Err(Session),实际: {:?}",
            result
        );
    }

    /// trait default check_safe:有效会话 + token 上下文 → `Ok(())`(行为保持对照:
    /// 未配置 MFA 的有效会话视为已通过二级认证)。
    #[tokio::test]
    async fn t_sec_check_safe_trait_default_valid_session_passes() {
        let mock = MockMfaSession {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: true,
        };
        let result = crate::stp::with_current_token("valid-token".to_string(), async {
            mock.check_safe().await
        })
        .await;
        assert!(
            result.is_ok(),
            "有效会话的 check_safe 应保持 Ok(()),实际: {:?}",
            result
        );
    }

    /// trait default check_safe:无 token 上下文(如 authflow 编排)不触发前置校验,
    /// 维持既有放行语义(is_safe 默认 true → Ok(()))——Mfa(None) 编排兼容性锚定。
    #[tokio::test]
    async fn t_sec_check_safe_trait_default_without_token_context_keeps_pass() {
        let mock = MockMfaSession {
            config: Arc::new(GarrisonConfig::default()),
            logged_in: false,
        };
        // 不设置 current_token:前置校验按存在性守卫跳过
        mock.check_safe().await.unwrap();
    }

    /// 验证 `disable_service` Display 输出包含 service 名称。
    ///
    /// 覆盖 mfa.rs disable_service 关联函数 + Display 实现。
    #[test]
    fn disable_service_display_includes_service() {
        let err = MockMfa::disable_service("payment", None);
        let display = err.to_string();
        assert!(
            display.contains("payment"),
            "Display 应包含 service 名称,实际: {}",
            display
        );
    }

    /// 调用 MockMfa 的所有 SessionLogic + GarrisonCore 方法以确保覆盖。
    #[tokio::test]
    async fn mock_mfa_session_logic_all_methods() {
        let mock = MockMfa {
            config: Arc::new(GarrisonConfig::default()),
        };
        let _ = mock.config();
        let params = LoginParams::default();
        let _ = mock.login("u1", &params).await.unwrap();
        let _ = mock.login_with_token("u1", "tok").await;
        let _ = mock.logout().await;
        let _ = mock.logout_by_login_id("u1").await;
        let _ = mock.kickout("u1").await;
        let _ = mock.kickout_by_token("tok").await;
        let _ = mock.revoke_token("tok").await;
        let _ = mock.check_login().await.unwrap();
        let _ = mock.get_login_id().await.unwrap();
    }

    // per-client MFA chain 三态

    /// per-client 缺失(None)回退全局默认链。
    #[test]
    fn resolve_mfa_chain_none_inherits_global() {
        let global = vec!["otp".to_string()];
        assert_eq!(
            resolve_mfa_chain(None, &global),
            MfaChainDecision::Require(vec!["otp".to_string()])
        );
    }

    /// per-client 缺失且全局链为空 → 不强制。
    #[test]
    fn resolve_mfa_chain_none_empty_global_is_none() {
        assert_eq!(resolve_mfa_chain(None, &[]), MfaChainDecision::None);
    }

    /// per-client 空集显式禁用:全局有默认链也不强制。
    #[test]
    fn resolve_mfa_chain_empty_set_disables() {
        let global = vec!["otp".to_string()];
        let empty = Vec::new();
        assert_eq!(
            resolve_mfa_chain(Some(&empty), &global),
            MfaChainDecision::None,
            "Some(空集) 应显式禁用(压过全局默认)"
        );
    }

    /// per-client 非空集强制该集合(不合并全局)。
    #[test]
    fn resolve_mfa_chain_non_empty_overrides_global() {
        let global = vec!["otp".to_string()];
        let own = vec!["webauthn".to_string()];
        assert_eq!(
            resolve_mfa_chain(Some(&own), &global),
            MfaChainDecision::Require(vec!["webauthn".to_string()])
        );
    }

    /// validate_mfa_chains 拒绝未知 factor(全局与 per-client 两条路径)。
    #[test]
    fn validate_mfa_chains_rejects_unknown_factor() {
        let mut per_client = std::collections::HashMap::new();
        per_client.insert("c1".to_string(), vec!["otp".to_string()]);
        assert!(validate_mfa_chains(&["webauthn".to_string()], &per_client).is_ok());

        assert!(validate_mfa_chains(&["sms".to_string()], &per_client).is_err());
        per_client.insert("c2".to_string(), vec!["pwd".to_string()]);
        let result = validate_mfa_chains(&[], &per_client);
        assert!(
            matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("pwd")),
            "pwd 不入 chain 词汇表(主因子),实际: {:?}",
            result
        );
    }

    // MFA 编排基座:因子账本(AmrEntry / amr claim 映射)

    /// AmrEntry::new 接受词汇表内的 method 与 1..=3 的 aal。
    #[test]
    fn amr_entry_new_accepts_known_method_and_valid_aal() {
        for method in AMR_METHODS {
            let entry = AmrEntry::new(*method, 2, 1_700_000_000).unwrap();
            assert_eq!(entry.method, *method);
            assert_eq!(entry.aal, 2);
            assert_eq!(entry.completed_at, 1_700_000_000);
        }
    }

    /// AmrEntry::new 拒绝词汇表之外的 method(显性化,不入账)。
    #[test]
    fn amr_entry_new_rejects_unknown_method() {
        for method in ["sms", "", "PWD", "push"] {
            let result = AmrEntry::new(method, 2, 0);
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("amr-method")),
                "method={:?} 应被拒绝,实际: {:?}",
                method,
                result.map(|_| ())
            );
        }
    }

    /// AmrEntry::new 拒绝越界 aal(0 与 4)。
    #[test]
    fn amr_entry_new_rejects_out_of_range_aal() {
        for aal in [0u8, 4] {
            let result = AmrEntry::new("otp", aal, 0);
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(ref m)) if m.contains("aal")),
                "aal={} 应被拒绝,实际: {:?}",
                aal,
                result.map(|_| ())
            );
        }
    }

    /// amr_claim 按完成顺序输出并对 method 去重保序(RFC 8176 数组语义)。
    #[test]
    fn amr_claim_preserves_order_and_dedups() {
        let entries = vec![
            AmrEntry::new("pwd", 1, 1).unwrap(),
            AmrEntry::new("otp", 2, 2).unwrap(),
            AmrEntry::new("webauthn", 2, 3).unwrap(),
            AmrEntry::new("otp", 2, 4).unwrap(),
        ];
        assert_eq!(
            amr_claim(&entries),
            vec!["pwd".to_string(), "otp".to_string(), "webauthn".to_string()]
        );
    }

    /// 空账本映射为空 amr 数组。
    #[test]
    fn amr_claim_empty_ledger_maps_to_empty_array() {
        assert!(amr_claim(&[]).is_empty());
    }

    /// ledger_max_aal 取最高等级;空账本为 0。
    #[test]
    fn ledger_max_aal_takes_maximum() {
        assert_eq!(ledger_max_aal(&[]), 0);
        let entries = vec![
            AmrEntry::new("pwd", 1, 1).unwrap(),
            AmrEntry::new("otp", 2, 2).unwrap(),
        ];
        assert_eq!(ledger_max_aal(&entries), 2);
    }

    /// token_style=jwt 的主登录签发:amr=["pwd"] + auth_time=签发时刻。
    #[cfg(feature = "protocol-jwt")]
    #[tokio::test]
    async fn login_jwt_token_carries_primary_amr_and_auth_time() {
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::session::GarrisonSession;
        use crate::strategy::GarrisonPermissionStrategy;

        struct NoopFirewall;

        #[async_trait::async_trait]
        impl GarrisonPermissionStrategy for NoopFirewall {
            async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn check_permission(
                &self,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_any(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_all(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_permission_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _role: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            #[cfg(any(
                feature = "sms-rate-limit",
                feature = "firewall-ratelimit",
                feature = "firewall-bruteforce",
                feature = "firewall-ddos",
                feature = "firewall",
                feature = "oauth2-server"
            ))]
            async fn check_login_hooks(
                &self,
                _login_id: &str,
                _ctx: &crate::strategy::hooks::LoginContext,
            ) -> GarrisonResult<()> {
                Ok(())
            }
        }

        let dao = Arc::new(MockDao::new());
        let session = Arc::new(GarrisonSession::new(
            dao.clone() as Arc<dyn GarrisonDao>,
            3600,
            86400,
            0,
        ));
        let mut config = GarrisonConfig::default_config();
        config.throw_on_not_login = false;
        config.token_style = "jwt".to_string();
        config.jwt_secret = "0123456789abcdef0123456789abcdef".to_string().into();
        let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(NoopFirewall);
        let logic = GarrisonLogicDefault::new(
            session,
            Arc::new(config),
            firewall,
            Arc::new(crate::account::disable::DefaultDisableRepository::new(
                dao.clone() as Arc<dyn GarrisonDao>,
            )),
        );
        let token = logic
            .login("user-mfa-1", &LoginParams::default())
            .await
            .unwrap();
        let handler = crate::protocol::jwt::JwtHandler::new("0123456789abcdef0123456789abcdef");
        // login 的 JWT token 盖戳 nbf=now,宿主墙钟 NTP 回跳会使紧随的 verify
        // 误报 jwt-not-yet-valid,经 tests::verify_ok 容错(说明见该函数)。
        let claims = crate::protocol::jwt::tests::verify_ok(&handler, &token);
        assert_eq!(
            claims.amr,
            Some(vec![PRIMARY_FACTOR_AMR.to_string()]),
            "主登录签发的 amr 应为 [\"pwd\"]"
        );
        let now = chrono::Utc::now().timestamp();
        assert!(
            claims.auth_time.is_some_and(|t| (now - t).abs() <= 5),
            "auth_time 应等于签发时刻(±5s),实际: {:?}",
            claims.auth_time
        );
    }

    /// 调用 MockMfaSafe 的所有 SessionLogic + GarrisonCore 方法以确保覆盖。
    #[tokio::test]
    async fn mock_mfa_safe_session_logic_all_methods() {
        let mock = MockMfaSafe {
            config: Arc::new(GarrisonConfig::default()),
            safe_result: Ok(true),
        };
        let _ = mock.config();
        let params = LoginParams::default();
        let _ = mock.login("u1", &params).await.unwrap();
        let _ = mock.login_with_token("u1", "tok").await;
        let _ = mock.logout().await;
        let _ = mock.logout_by_login_id("u1").await;
        let _ = mock.kickout("u1").await;
        let _ = mock.kickout_by_token("tok").await;
        let _ = mock.revoke_token("tok").await;
        let _ = mock.check_login().await.unwrap();
        let _ = mock.get_login_id().await.unwrap();
    }

    // DisableRepository 集成测试(GarrisonLogicDefault.check_disable)

    mod t019_disable_integration {
        use super::*;
        use crate::account::disable::{DefaultDisableRepository, DisableRepository};
        use crate::config::GarrisonConfig;
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::session::GarrisonSession;
        use crate::stp::with_current_token;
        use crate::stp::LoginParams;
        use crate::strategy::GarrisonPermissionStrategy;
        use async_trait::async_trait;
        use chrono::Utc;
        use std::sync::Arc;

        // MockFirewall:no-op 权限策略,允许所有登录

        struct MockFirewall;

        #[async_trait]
        impl GarrisonPermissionStrategy for MockFirewall {
            async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn check_permission(
                &self,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_any(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_all(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_permission_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                // 测试桩与租户无关:任意租户返回相同结果
                Ok(true)
            }
            async fn check_role_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _role: &str,
            ) -> GarrisonResult<bool> {
                // 测试桩与租户无关:任意租户返回相同结果
                Ok(true)
            }
            #[cfg(any(
                feature = "sms-rate-limit",
                feature = "firewall-ratelimit",
                feature = "firewall-bruteforce",
                feature = "firewall-ddos",
                feature = "firewall",
                feature = "oauth2-server"
            ))]
            async fn check_login_hooks(
                &self,
                _login_id: &str,
                _ctx: &crate::strategy::hooks::LoginContext,
            ) -> GarrisonResult<()> {
                // 测试桩不注入防火墙 hook,显式 no-op
                Ok(())
            }
        }

        // 辅助函数

        /// 创建 GarrisonLogicDefault,返回 (logic, repo, dao) 便于测试。
        fn make_logic_with_repo() -> (
            GarrisonLogicDefault,
            Arc<DefaultDisableRepository>,
            Arc<MockDao>,
        ) {
            let dao = Arc::new(MockDao::new());
            let session = Arc::new(GarrisonSession::new(
                dao.clone() as Arc<dyn GarrisonDao>,
                3600,
                86400,
                0,
            ));
            let mut config = GarrisonConfig::default_config();
            config.throw_on_not_login = false;
            config.token_style = "uuid".to_string();
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
            let repo = Arc::new(DefaultDisableRepository::new(
                dao.clone() as Arc<dyn GarrisonDao>
            ));
            let logic = GarrisonLogicDefault::new(
                session,
                Arc::new(config),
                firewall,
                repo.clone() as Arc<dyn DisableRepository>,
            );
            (logic, repo, dao)
        }

        // 集成测试

        /// 注入 repository 但未封禁,check_disable 返回 Ok。
        #[tokio::test]
        async fn test_check_disable_not_disabled_returns_ok() {
            let (logic, _repo, _dao) = make_logic_with_repo();
            let token = logic.login("1001", &LoginParams::default()).await.unwrap();

            let result = with_current_token(token, async { logic.check_disable().await }).await;

            assert!(
                result.is_ok(),
                "未封禁时 check_disable 应返回 Ok,实际: {:?}",
                result
            );
        }

        /// 注入 repository 且已封禁,check_disable 返回 DisableService 错误。
        #[tokio::test]
        async fn test_check_disable_disabled_returns_error() {
            let (logic, repo, _dao) = make_logic_with_repo();
            let token = logic.login("1001", &LoginParams::default()).await.unwrap();

            let until = Utc::now() + chrono::Duration::seconds(3600);
            repo.disable("1001", "default", Some(until), 0, 3600)
                .await
                .unwrap();

            let result = with_current_token(token, async { logic.check_disable().await }).await;

            match result {
                Err(GarrisonError::DisableService { service, .. }) => {
                    assert_eq!(
                        service, "default",
                        "DisableService 错误的 service 字段应为 'default'"
                    );
                },
                other => panic!(
                    "已封禁时 check_disable 应返回 Err(DisableService),实际: {:?}",
                    other
                ),
            }
        }

        /// 永久封禁(until=None),错误中 until 字段为 None。
        #[tokio::test]
        async fn test_check_disable_permanent_ban_until_none() {
            let (logic, repo, _dao) = make_logic_with_repo();
            let token = logic.login("1002", &LoginParams::default()).await.unwrap();

            // 永久封禁(until=None, duration_secs=0)
            repo.disable("1002", "default", None, 0, 0).await.unwrap();

            let result = with_current_token(token, async { logic.check_disable().await }).await;

            match result {
                Err(GarrisonError::DisableService { service, until }) => {
                    assert_eq!(service, "default");
                    assert!(
                        until.is_none(),
                        "永久封禁 until 应为 None,实际: {:?}",
                        until
                    );
                },
                other => panic!(
                    "永久封禁应返回 Err(DisableService {{ until: None }}),实际: {:?}",
                    other
                ),
            }
        }

        /// 定时封禁(until=Some),错误中 until 字段为 Some 且精确匹配。
        #[tokio::test]
        async fn test_check_disable_timed_ban_until_some() {
            let (logic, repo, _dao) = make_logic_with_repo();
            let token = logic.login("1003", &LoginParams::default()).await.unwrap();

            let until = Utc::now() + chrono::Duration::seconds(7200);
            repo.disable("1003", "default", Some(until), 0, 7200)
                .await
                .unwrap();

            let result = with_current_token(token, async { logic.check_disable().await }).await;

            match result {
                Err(GarrisonError::DisableService { service, until: u }) => {
                    assert_eq!(service, "default");
                    assert!(u.is_some(), "定时封禁 until 应为 Some");
                    assert_eq!(
                        u.unwrap(),
                        until,
                        "定时封禁 until 应精确匹配 disable 时设置的值"
                    );
                },
                other => panic!(
                    "定时封禁应返回 Err(DisableService {{ until: Some(_) }}),实际: {:?}",
                    other
                ),
            }
        }

        /// 未设置 current_token(未登录),check_disable 返回 Ok(不抛错)。
        #[tokio::test]
        async fn test_check_disable_no_token_returns_ok() {
            let (logic, _repo, _dao) = make_logic_with_repo();
            // 不调用 login,也不设置 task_local current_token

            // 直接调用 check_disable(无 task_local 上下文)
            let result = logic.check_disable().await;

            assert!(
                result.is_ok(),
                "未登录(无 current_token)时 check_disable 应返回 Ok,实际: {:?}",
                result
            );
        }

        /// 设置 current_token 但对应 TokenSession 不存在 → 显性 Err(Session)(fail-closed)。
        ///
        /// 覆盖 R2-1 修复:无效 token 不再与「未封禁」合并为 `Ok(())`(原 fail-open
        /// 分支),而是显性拒绝,使消费方可区分「token 无效」与「账号未封禁」。
        #[tokio::test]
        async fn test_check_disable_token_session_not_found_fails_closed() {
            let (logic, _repo, _dao) = make_logic_with_repo();
            // 不调用 login,直接设置一个不存在的 token
            let result = with_current_token("nonexistent-token-xyz".to_string(), async {
                logic.check_disable().await
            })
            .await;

            assert!(
                matches!(result, Err(GarrisonError::Session(_))),
                "token 对应的 TokenSession 不存在时 check_disable 应返回 Err(Session),实际: {:?}",
                result
            );
        }

        /// 直接调用 MockFirewall 的所有方法以确保覆盖。
        #[tokio::test]
        async fn mock_firewall_all_methods() {
            let fw = MockFirewall;
            let _ = fw.get_permission_list("u1").await.unwrap();
            let _ = fw.get_role_list("u1").await.unwrap();
            let _ = fw.check_permission("u1", "user:read").await.unwrap();
            let _ = fw.check_role("u1", "admin").await.unwrap();
            let _ = fw.check_role_any("u1", &["admin", "user"]).await.unwrap();
            let _ = fw.check_role_all("u1", &["admin", "user"]).await.unwrap();
        }
    }

    // 二级认证族会话前置校验(GarrisonLogicDefault 路径,GAR-02 / R2-1 回归)

    /// check_safe / check_disable 的会话前置校验回归(GAR-02 / R2-1):未配置 MFA 的有效会话视为已通过(行为不变),伪造/已撤销 token 显性 `Err(Session)`(与 check-login 语义对齐,不再宽松)。
    /// 直接构造 `GarrisonLogicDefault`(不依赖全局 manager),安全前置校验先于 safe/disable 判定执行,security-extra 启用与否断言一致。
    mod t_sec_session_precondition {
        use super::*;
        use crate::account::disable::DefaultDisableRepository;
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::session::GarrisonSession;
        use crate::stp::with_current_token;
        use crate::stp::LoginParams;
        use crate::strategy::GarrisonPermissionStrategy;
        use async_trait::async_trait;
        use std::sync::Arc;

        struct MockFirewall;

        #[async_trait]
        impl GarrisonPermissionStrategy for MockFirewall {
            async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn check_permission(
                &self,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_any(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_all(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_permission_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _role: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            #[cfg(any(
                feature = "sms-rate-limit",
                feature = "firewall-ratelimit",
                feature = "firewall-bruteforce",
                feature = "firewall-ddos",
                feature = "firewall",
                feature = "oauth2-server"
            ))]
            async fn check_login_hooks(
                &self,
                _login_id: &str,
                _ctx: &crate::strategy::hooks::LoginContext,
            ) -> GarrisonResult<()> {
                Ok(())
            }
        }

        fn make_logic() -> GarrisonLogicDefault {
            let dao = Arc::new(MockDao::new());
            let session = Arc::new(GarrisonSession::new(
                dao.clone() as Arc<dyn GarrisonDao>,
                3600,
                86400,
                0,
            ));
            let mut config = GarrisonConfig::default_config();
            config.throw_on_not_login = false;
            config.token_style = "uuid".to_string();
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
            GarrisonLogicDefault::new(
                session,
                Arc::new(config),
                firewall,
                Arc::new(DefaultDisableRepository::new(dao)),
            )
        }

        /// 伪造 token(任意 UUID)→ check_safe 显性 `Err(Session)`(GAR-02:
        /// 原行为恒返回宽松 true)。
        #[tokio::test]
        async fn check_safe_rejects_forged_token() {
            let logic = make_logic();
            let result =
                with_current_token("00000000-0000-0000-0000-000000000000".to_string(), async {
                    logic.check_safe().await
                })
                .await;
            assert!(
                matches!(result, Err(GarrisonError::Session(_))),
                "伪造 token 的 check_safe 应返回 Err(Session),实际: {:?}",
                result
            );
        }

        /// kickout 后旧 token → check_safe 显性 `Err(Session)`(GAR-02:已撤销
        /// 会话不再被放行)。
        #[tokio::test]
        async fn check_safe_rejects_kicked_out_token() {
            let logic = make_logic();
            let token = logic
                .login("sec-safe-kick", &LoginParams::default())
                .await
                .unwrap();
            logic.kickout("sec-safe-kick").await.unwrap();

            let result = with_current_token(token, async { logic.check_safe().await }).await;
            assert!(
                matches!(result, Err(GarrisonError::Session(_))),
                "kickout 后旧 token 的 check_safe 应返回 Err(Session),实际: {:?}",
                result
            );
        }

        /// 有效 token 行为保持对照:无 security-extra → `Ok(())`(未配置 MFA 视为
        /// 已通过二级认证);有 security-extra → `Err(NotSafe)`(safe_services 为空,
        /// 既有语义不变)。
        #[tokio::test]
        async fn check_safe_valid_token_behavior_preserved() {
            let logic = make_logic();
            let token = logic
                .login("sec-safe-valid", &LoginParams::default())
                .await
                .unwrap();

            let result = with_current_token(token, async { logic.check_safe().await }).await;

            #[cfg(feature = "security-extra")]
            assert!(
                matches!(result, Err(GarrisonError::NotSafe { .. })),
                "security-extra 下有效 token 未 open_safe 应为 NotSafe,实际: {:?}",
                result
            );
            #[cfg(not(feature = "security-extra"))]
            assert!(
                result.is_ok(),
                "无 security-extra 时有效 token 的 check_safe 应保持 Ok,实际: {:?}",
                result
            );
        }

        /// 伪造 token → check_disable 显性 `Err(Session)` 而非 `Ok(())`(R2-1:
        /// 「token 无效」不再与「未封禁」合并为同一 bool)。
        #[tokio::test]
        async fn check_disable_rejects_forged_token() {
            let logic = make_logic();
            let result =
                with_current_token("00000000-0000-0000-0000-000000000000".to_string(), async {
                    logic.check_disable().await
                })
                .await;
            assert!(
                matches!(result, Err(GarrisonError::Session(_))),
                "伪造 token 的 check_disable 应返回 Err(Session),实际: {:?}",
                result
            );
        }

        /// kickout 后旧 token → check_disable 显性 `Err(Session)` 而非 `Ok(())`(R2-1)。
        #[tokio::test]
        async fn check_disable_rejects_kicked_out_token() {
            let logic = make_logic();
            let token = logic
                .login("sec-disable-kick", &LoginParams::default())
                .await
                .unwrap();
            logic.kickout("sec-disable-kick").await.unwrap();

            let result = with_current_token(token, async { logic.check_disable().await }).await;
            assert!(
                matches!(result, Err(GarrisonError::Session(_))),
                "kickout 后旧 token 的 check_disable 应返回 Err(Session),实际: {:?}",
                result
            );
        }

        /// 有效 token 未封禁 → `Ok(())`(行为保持对照)。
        #[tokio::test]
        async fn check_disable_valid_token_unbanned_still_ok() {
            let logic = make_logic();
            let token = logic
                .login("sec-disable-valid", &LoginParams::default())
                .await
                .unwrap();

            let result = with_current_token(token, async { logic.check_disable().await }).await;
            assert!(
                result.is_ok(),
                "有效 token 未封禁时 check_disable 应保持 Ok,实际: {:?}",
                result
            );
        }
    }

    // check_safe 默认实现集成测试(需要 safe-auth feature)

    /// 集成测试:验证 check_safe 默认实现与 GarrisonLogicDefault inherent method
    /// (open_safe / is_safe / close_safe)的交互。
    ///
    /// 仅在 `safe-auth` feature 启用时编译,因为测试需要 inherent method 支持。
    #[cfg(feature = "security-extra")]
    mod t025_check_safe_integration {
        use super::*;
        use crate::config::GarrisonConfig;
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::error::GarrisonError;
        use crate::session::GarrisonSession;
        use crate::stp::session::SessionLogic;
        use crate::stp::with_current_token;
        use crate::stp::LoginParams;
        use crate::strategy::GarrisonPermissionStrategy;
        use async_trait::async_trait;
        use std::sync::Arc;

        // MockFirewall:no-op 权限策略,允许所有登录

        struct MockFirewall;

        #[async_trait]
        impl GarrisonPermissionStrategy for MockFirewall {
            async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn check_permission(
                &self,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_any(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_all(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_permission_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                // 测试桩与租户无关:任意租户返回相同结果
                Ok(true)
            }
            async fn check_role_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _role: &str,
            ) -> GarrisonResult<bool> {
                // 测试桩与租户无关:任意租户返回相同结果
                Ok(true)
            }
            #[cfg(any(
                feature = "sms-rate-limit",
                feature = "firewall-ratelimit",
                feature = "firewall-bruteforce",
                feature = "firewall-ddos",
                feature = "firewall",
                feature = "oauth2-server"
            ))]
            async fn check_login_hooks(
                &self,
                _login_id: &str,
                _ctx: &crate::strategy::hooks::LoginContext,
            ) -> GarrisonResult<()> {
                // 测试桩不注入防火墙 hook,显式 no-op
                Ok(())
            }
        }

        // 辅助函数

        /// 创建 GarrisonLogicDefault 并返回 (logic, dao) 便于测试。
        fn make_logic() -> (GarrisonLogicDefault, Arc<MockDao>) {
            let dao = Arc::new(MockDao::new());
            let session = Arc::new(GarrisonSession::new(
                dao.clone() as Arc<dyn GarrisonDao>,
                3600,
                86400,
                0,
            ));
            let mut config = GarrisonConfig::default_config();
            config.throw_on_not_login = false;
            config.token_style = "uuid".to_string();
            let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(MockFirewall);
            let logic = GarrisonLogicDefault::new(
                session,
                Arc::new(config),
                firewall,
                Arc::new(crate::account::disable::DefaultDisableRepository::new(
                    dao.clone(),
                )),
            );
            (logic, dao)
        }

        // 4 个集成测试

        /// login → open_safe("default", 3600) → check_safe 返回 Ok(())。
        ///
        /// 验证 open_safe 开启二级认证后,check_safe 默认实现(调用 is_safe)
        /// 能正确识别已认证状态并返回 Ok。
        #[tokio::test]
        async fn t025_check_safe_passes_after_open_safe() {
            let (logic, _dao) = make_logic();
            let token = logic
                .login("user-4001", &LoginParams::default())
                .await
                .unwrap();

            let result = with_current_token(token.clone(), async {
                logic.open_safe("default", 3600).await.unwrap();
                logic.check_safe().await
            })
            .await;

            assert!(
                result.is_ok(),
                "open_safe 后 check_safe 应返回 Ok(()),实际: {:?}",
                result
            );
        }

        /// login → check_safe(未 open_safe)→ 返回 Err(NotSafe { reason: "SAFE_EXPIRED" })。
        ///
        /// 验证未开启二级认证时,check_safe 默认实现(调用 is_safe)能正确识别
        /// 未认证状态并返回 NotSafe 错误。
        #[tokio::test]
        async fn t025_check_safe_fails_without_open_safe() {
            let (logic, _dao) = make_logic();
            let token = logic
                .login("user-4002", &LoginParams::default())
                .await
                .unwrap();

            let result =
                with_current_token(token.clone(), async { logic.check_safe().await }).await;

            match result {
                Err(GarrisonError::NotSafe { reason }) => {
                    assert_eq!(
                        reason, "SAFE_EXPIRED",
                        "未 open_safe 时 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
                    );
                },
                other => panic!(
                    "未 open_safe 时 check_safe 应返回 Err(NotSafe {{ reason: \"SAFE_EXPIRED\" }}),实际: {:?}",
                    other
                ),
            }
        }

        /// login → open_safe("default", 0)(立即过期)→ check_safe → 返回 Err(NotSafe)。
        ///
        /// 验证 duration_secs=0 导致立即过期后,check_safe 能正确识别过期状态。
        #[tokio::test]
        async fn t025_check_safe_fails_after_expiry() {
            let (logic, _dao) = make_logic();
            let token = logic
                .login("user-4003", &LoginParams::default())
                .await
                .unwrap();

            let result = with_current_token(token.clone(), async {
                logic.open_safe("default", 0).await.unwrap();
                logic.check_safe().await
            })
            .await;

            match result {
                Err(GarrisonError::NotSafe { reason }) => {
                    assert_eq!(
                        reason, "SAFE_EXPIRED",
                        "过期后 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
                    );
                },
                other => panic!(
                    "过期后 check_safe 应返回 Err(NotSafe {{ reason: \"SAFE_EXPIRED\" }}),实际: {:?}",
                    other
                ),
            }
        }

        /// login → open_safe("default") → close_safe("default") → check_safe → 返回 Err(NotSafe)。
        ///
        /// 验证 close_safe 关闭二级认证后,check_safe 能正确识别未认证状态。
        #[tokio::test]
        async fn t025_check_safe_fails_after_close_safe() {
            let (logic, _dao) = make_logic();
            let token = logic
                .login("user-4004", &LoginParams::default())
                .await
                .unwrap();

            let result = with_current_token(token.clone(), async {
                logic.open_safe("default", 3600).await.unwrap();
                logic.close_safe("default").await.unwrap();
                logic.check_safe().await
            })
            .await;

            match result {
                Err(GarrisonError::NotSafe { reason }) => {
                    assert_eq!(
                        reason, "SAFE_EXPIRED",
                        "close_safe 后 check_safe 应返回 NotSafe(reason=\"SAFE_EXPIRED\")"
                    );
                },
                other => panic!(
                    "close_safe 后 check_safe 应返回 Err(NotSafe {{ reason: \"SAFE_EXPIRED\" }}),实际: {:?}",
                    other
                ),
            }
        }
    }
    // 新鲜度断言(auth_time / aal 门槛)与 Required Action 三段式

    use crate::stp::mfa::{
        assert_freshness, stepup_required, FreshnessInput, FreshnessVerdict, MfaFreshness,
    };
    #[cfg(feature = "secure-totp")]
    use crate::stp::mfa::{ProcessOutcome, RequiredActionContext};

    /// 新鲜度:auth_time 在窗口内且账本最高 AAL 达标 → Fresh(免二次 challenge)。
    #[test]
    fn freshness_fresh_within_window_and_aal() {
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 1,
        };
        let input = FreshnessInput {
            auth_time: Some(1_000),
            ledger_max_aal: 1,
            now: 1_000 + 299,
        };
        assert_eq!(
            assert_freshness(&input, &threshold),
            FreshnessVerdict::Fresh
        );
        assert!(
            !stepup_required(&input, &threshold, false),
            "新鲜会话不应触发 step-up"
        );
    }

    /// 新鲜度:auth_time 超窗 → Stale(触发 Required Action)。
    #[test]
    fn freshness_stale_after_window() {
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 1,
        };
        let input = FreshnessInput {
            auth_time: Some(1_000),
            ledger_max_aal: 2,
            now: 1_000 + 301,
        };
        assert_eq!(
            assert_freshness(&input, &threshold),
            FreshnessVerdict::Stale
        );
        assert!(stepup_required(&input, &threshold, false));
    }

    /// 新鲜度:账本最高 AAL 低于门槛 → Stale(即使时间未超窗)。
    #[test]
    fn freshness_stale_when_aal_below_threshold() {
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 2,
        };
        let input = FreshnessInput {
            auth_time: Some(1_000),
            ledger_max_aal: 1,
            now: 1_005,
        };
        assert_eq!(
            assert_freshness(&input, &threshold),
            FreshnessVerdict::Stale
        );
    }

    /// 新鲜度:无 auth_time(历史会话)→ Stale(fail-closed)。
    #[test]
    fn freshness_stale_without_auth_time() {
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 1,
        };
        let input = FreshnessInput {
            auth_time: None,
            ledger_max_aal: 2,
            now: 1_000,
        };
        assert_eq!(
            assert_freshness(&input, &threshold),
            FreshnessVerdict::Stale
        );
    }

    /// 有效的 MFA remember cookie 跳过二次 challenge(压过过期会话)。
    #[test]
    fn valid_remember_cookie_skips_challenge() {
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 1,
        };
        let stale = FreshnessInput {
            auth_time: Some(1_000),
            ledger_max_aal: 2,
            now: 1_000 + 301,
        };
        assert!(stepup_required(&stale, &threshold, false));
        assert!(
            !stepup_required(&stale, &threshold, true),
            "有效 remember cookie 应跳过重复 challenge"
        );
    }

    /// process 验证成功后经 complete_required_action 升级账本(otp / AAL 2)。
    #[cfg(feature = "secure-totp")]
    #[tokio::test]
    async fn totp_provider_process_upgrades_ledger() {
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::session::token_key;
        use crate::session::GarrisonSession;
        use crate::session::TokenSession;
        use crate::stp::mfa::{complete_required_action, TotpRequiredActionProvider};
        use std::sync::Arc;

        let dao = Arc::new(MockDao::new());
        let session = GarrisonSession::new(dao.clone() as Arc<dyn GarrisonDao>, 3600, 86400, 0);
        session.create("user-ta", "TOK").await.unwrap();
        // 人为老化 auth_time 使会话过期(走 DAO 直写,模拟时间流逝)
        let key = token_key("TOK");
        let raw = dao.get(&key).await.unwrap().unwrap();
        let mut ts: TokenSession = serde_json::from_str(&raw).unwrap();
        ts.auth_time = Some(chrono::Utc::now().timestamp() - 3600);
        dao.set(&key, &serde_json::to_string(&ts).unwrap(), 3600)
            .await
            .unwrap();

        let now = chrono::Utc::now().timestamp();
        let ctx = RequiredActionContext {
            login_id: "user-ta".to_string(),
            auth_time: ts.auth_time,
            ledger_max_aal: 1,
            now,
        };
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 2,
        };
        let provider = TotpRequiredActionProvider::new("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
        // evaluate:过期会话触发 Required Action
        assert!(
            provider.evaluate(&ctx, &threshold).await.unwrap(),
            "过期会话应触发 Required Action"
        );
        let challenge = provider.challenge(&ctx).await.unwrap();
        assert_eq!(challenge.action, "otp");
        assert!(!challenge.payload.is_empty());
        // process:正确验证码 → Verified
        let code = provider.generate_current_code(now).unwrap();
        let outcome = provider.process(&ctx, &code, dao.as_ref()).await.unwrap();
        match outcome {
            ProcessOutcome::Verified { method, aal } => {
                assert_eq!(method, "otp");
                assert_eq!(aal, 2);
            },
            other => panic!("正确验证码应 Verified,实际: {:?}", other),
        }
        // 账本升级
        complete_required_action(&session, "TOK", &outcome, now)
            .await
            .unwrap();
        let upgraded = session.get_token_session("TOK").await.unwrap().unwrap();
        assert_eq!(upgraded.amr_ledger.len(), 2);
        assert_eq!(upgraded.amr_ledger[1].method, "otp");
        assert_eq!(upgraded.amr_ledger[1].aal, 2);
        assert_eq!(
            crate::stp::mfa::ledger_max_aal(&upgraded.amr_ledger),
            2,
            "process 验证成功后账本最高 AAL 应升级"
        );
    }

    /// process 错误验证码 → Rejected 且账本不变。
    #[cfg(feature = "secure-totp")]
    #[tokio::test]
    async fn totp_provider_process_wrong_code_rejected() {
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::session::GarrisonSession;
        use crate::stp::mfa::TotpRequiredActionProvider;
        use std::sync::Arc;

        let dao = Arc::new(MockDao::new());
        let session = GarrisonSession::new(dao.clone() as Arc<dyn GarrisonDao>, 3600, 86400, 0);
        session.create("user-tb", "TOK2").await.unwrap();

        let provider = TotpRequiredActionProvider::new("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
        let ctx = RequiredActionContext {
            login_id: "user-tb".to_string(),
            auth_time: Some(chrono::Utc::now().timestamp() - 3600),
            ledger_max_aal: 1,
            now: chrono::Utc::now().timestamp(),
        };
        let outcome = provider
            .process(&ctx, "000000", dao.as_ref())
            .await
            .unwrap();
        assert!(
            matches!(outcome, ProcessOutcome::Rejected),
            "错误验证码应 Rejected,实际: {:?}",
            outcome
        );
        let ts = session.get_token_session("TOK2").await.unwrap().unwrap();
        assert_eq!(ts.amr_ledger.len(), 1, "Rejected 不得升级账本");
    }

    /// evaluate 对新鲜会话不触发 Required Action。
    #[cfg(feature = "secure-totp")]
    #[tokio::test]
    async fn totp_provider_evaluate_fresh_session_skips() {
        use crate::stp::mfa::TotpRequiredActionProvider;

        let now = chrono::Utc::now().timestamp();
        let ctx = RequiredActionContext {
            login_id: "user-tc".to_string(),
            auth_time: Some(now),
            ledger_max_aal: 2,
            now,
        };
        let threshold = MfaFreshness {
            max_age_secs: 300,
            min_aal: 1,
        };
        let provider = TotpRequiredActionProvider::new("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ");
        assert!(
            !provider.evaluate(&ctx, &threshold).await.unwrap(),
            "新鲜会话不应触发 Required Action"
        );
    }

    // 恢复码:批量一次性生成 / verify-consume 分离 / CAS 原子消费 / 误用容忍

    // 仅恢复码测试(cfg(mfa-recovery))使用;不门控会在关闭该 feature 的
    // 单测编译下产生 unused_imports 告警。
    #[cfg(feature = "mfa-recovery")]
    use crate::dao::tests::MockDao;
    #[cfg(feature = "mfa-recovery")]
    use crate::stp::mfa::{RecoveryCodeManager, RecoveryVerify};

    /// 批量生成:数量正确、码非空且互不相同(一次性批次)。
    #[cfg(feature = "mfa-recovery")]
    #[tokio::test]
    async fn recovery_generate_batch_unique_codes() {
        let dao = Arc::new(MockDao::new());
        let mgr = RecoveryCodeManager::new(dao, 0);
        let codes = mgr.generate("user-rc", 10).await.unwrap();
        assert_eq!(codes.len(), 10);
        assert!(codes.iter().all(|c| !c.is_empty()));
        let unique: std::collections::HashSet<&String> = codes.iter().collect();
        assert_eq!(unique.len(), 10, "同批次码不得重复");
    }

    /// verify 对未用码返回 Valid;consume 后 verify 变 Invalid(已用码拒绝)。
    #[cfg(feature = "mfa-recovery")]
    #[tokio::test]
    async fn recovery_used_code_rejected() {
        let dao = Arc::new(MockDao::new());
        let mgr = RecoveryCodeManager::new(dao, 0);
        let codes = mgr.generate("user-rc2", 1).await.unwrap();
        let code = codes[0].clone();

        assert_eq!(
            mgr.verify("user-rc2", &code).await.unwrap(),
            RecoveryVerify::Valid
        );
        assert!(
            mgr.consume("user-rc2", &code).await.unwrap(),
            "首次 consume 应成功"
        );
        assert_eq!(
            mgr.verify("user-rc2", &code).await.unwrap(),
            RecoveryVerify::Invalid,
            "已用码 verify 应拒绝"
        );
        assert!(
            !mgr.consume("user-rc2", &code).await.unwrap(),
            "已用码二次消费应失败"
        );
    }

    /// 并发消费同一码:CAS 原子性保证仅一个成功。
    #[cfg(feature = "mfa-recovery")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn recovery_concurrent_consume_only_one_succeeds() {
        let dao = Arc::new(MockDao::new());
        let mgr = Arc::new(RecoveryCodeManager::new(dao, 0));
        let codes = mgr.generate("user-rc3", 1).await.unwrap();
        let code = codes[0].clone();

        let m1 = Arc::clone(&mgr);
        let m2 = Arc::clone(&mgr);
        let c1 = code.clone();
        let c2 = code.clone();
        let (r1, r2) = tokio::join!(
            async move { m1.consume("user-rc3", &c1).await },
            async move { m2.consume("user-rc3", &c2).await },
        );
        let successes = [r1.unwrap(), r2.unwrap()]
            .into_iter()
            .filter(|ok| *ok)
            .count();
        assert_eq!(successes, 1, "并发消费同一恢复码应恰好一个成功");
    }

    /// 误用超限锁定:tolerance=0 时一次无效 verify 即锁定(默认 0 豁免)。
    #[cfg(feature = "mfa-recovery")]
    #[tokio::test]
    async fn recovery_misuse_over_tolerance_locks() {
        let dao = Arc::new(MockDao::new());
        let mgr = RecoveryCodeManager::new(dao, 0);
        let codes = mgr.generate("user-rc4", 1).await.unwrap();

        assert_eq!(
            mgr.verify("user-rc4", "wrong-code").await.unwrap(),
            RecoveryVerify::Locked,
            "tolerance=0 时首次误用即锁定"
        );
        // 锁定后连正确码也拒绝消费(fail-closed)
        assert!(
            mgr.consume("user-rc4", &codes[0]).await.is_err(),
            "锁定状态下 consume 应返回错误"
        );
    }

    /// 误用豁免:tolerance=2 时前两次误用仅 Invalid,第三次锁定。
    #[cfg(feature = "mfa-recovery")]
    #[tokio::test]
    async fn recovery_misuse_within_tolerance_excused() {
        let dao = Arc::new(MockDao::new());
        let mgr = RecoveryCodeManager::new(dao, 2);
        let codes = mgr.generate("user-rc5", 1).await.unwrap();

        assert_eq!(
            mgr.verify("user-rc5", "bad-1").await.unwrap(),
            RecoveryVerify::Invalid
        );
        assert_eq!(
            mgr.verify("user-rc5", "bad-2").await.unwrap(),
            RecoveryVerify::Invalid
        );
        assert_eq!(
            mgr.verify("user-rc5", "bad-3").await.unwrap(),
            RecoveryVerify::Locked,
            "第三次误用(超过 tolerance=2)应锁定"
        );
        assert!(
            mgr.consume("user-rc5", &codes[0]).await.is_err(),
            "锁定后正确码也不得消费"
        );
    }

    // MFA remember cookie:签发/校验(经单一构建点)

    /// 有效 cookie:签发 → 校验通过(可跳过重复 challenge),Set-Cookie 属性
    /// 全部来自 Set-Cookie 单一构建点(HttpOnly / SameSite / Path / Max-Age)。
    #[cfg(feature = "protocol-jwt")]
    #[test]
    fn mfa_remember_cookie_roundtrip_and_buildpoint_attributes() {
        let config = GarrisonConfig::default_config();
        let secret = "0123456789abcdef0123456789abcdef";
        let set_cookie =
            issue_mfa_remember_cookie(secret, &config, "login", "user-rc", "cred-1", 3600).unwrap();
        // 写读一致:读侧用构建点的 resolved_name 解析同名(production 前缀自动生效)
        let expected_name = CookieType::session(MFA_REMEMBER_COOKIE_NAME, &config)
            .unwrap()
            .resolved_name(config.cookie_secure);
        assert!(
            set_cookie.starts_with(&format!("{expected_name}=")),
            "cookie 名应与构建点 resolved_name 一致,实际: {}",
            set_cookie
        );
        assert!(
            set_cookie.contains("HttpOnly"),
            "HttpOnly 恒定,实际: {}",
            set_cookie
        );
        assert!(set_cookie.contains("SameSite="), "实际: {}", set_cookie);
        assert!(set_cookie.contains("Path=/"), "实际: {}", set_cookie);
        assert!(set_cookie.contains("Max-Age=3600"), "实际: {}", set_cookie);

        let jwt = set_cookie
            .split(';')
            .next()
            .unwrap()
            .split_once('=')
            .unwrap()
            .1;
        let now = chrono::Utc::now().timestamp();
        assert!(
            verify_mfa_remember_cookie(secret, jwt, "login", "user-rc", "cred-1", now),
            "有效 cookie 应通过校验(跳过重复 challenge)"
        );
    }

    /// 跨 credential 不通用:credential_id 不符 → false。
    #[cfg(feature = "protocol-jwt")]
    #[test]
    fn mfa_remember_cookie_not_portable_across_credentials() {
        let config = GarrisonConfig::default_config();
        let secret = "0123456789abcdef0123456789abcdef";
        let set_cookie =
            issue_mfa_remember_cookie(secret, &config, "login", "user-rc", "cred-1", 3600).unwrap();
        let jwt = set_cookie
            .split(';')
            .next()
            .unwrap()
            .split_once('=')
            .unwrap()
            .1;
        let now = chrono::Utc::now().timestamp();
        assert!(
            !verify_mfa_remember_cookie(secret, jwt, "login", "user-rc", "cred-2", now),
            "跨 credential 的 cookie 不得通用"
        );
        assert!(
            !verify_mfa_remember_cookie(secret, jwt, "other-stage", "user-rc", "cred-1", now),
            "跨 stage 的 cookie 不得通用"
        );
    }

    /// 跨主体不通用:login_id 不符 → false(防持有式豁免跨主体复用)。
    #[cfg(feature = "protocol-jwt")]
    #[test]
    fn mfa_remember_cookie_not_portable_across_subjects() {
        let config = GarrisonConfig::default_config();
        let secret = "0123456789abcdef0123456789abcdef";
        let set_cookie =
            issue_mfa_remember_cookie(secret, &config, "login", "user-a", "cred-1", 3600).unwrap();
        let jwt = set_cookie
            .split(';')
            .next()
            .unwrap()
            .split_once('=')
            .unwrap()
            .1;
        let now = chrono::Utc::now().timestamp();
        assert!(
            !verify_mfa_remember_cookie(secret, jwt, "login", "user-b", "cred-1", now),
            "跨主体的 cookie 不得通用"
        );
    }

    /// 过期失效:exp 已过(leeway=0)→ false。
    #[cfg(feature = "protocol-jwt")]
    #[test]
    fn mfa_remember_cookie_expired_is_invalid() {
        let secret = "0123456789abcdef0123456789abcdef";
        let claims = MfaRememberClaims {
            stage: "login".to_string(),
            login_id: "user-rc".to_string(),
            credential_id: "cred-1".to_string(),
            exp: chrono::Utc::now().timestamp() - 10,
        };
        let jwt = jsonwebtoken::encode(
            &jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
            &claims,
            &jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
        )
        .unwrap();
        assert!(
            !verify_mfa_remember_cookie(
                secret,
                &jwt,
                "login",
                "user-rc",
                "cred-1",
                chrono::Utc::now().timestamp()
            ),
            "过期 cookie 应失效"
        );
    }

    /// 篡改载荷(密钥不符)→ false;短密钥签发 fail-fast。
    #[cfg(feature = "protocol-jwt")]
    #[test]
    fn mfa_remember_cookie_rejects_tamper_and_short_secret() {
        let config = GarrisonConfig::default_config();
        let secret = "0123456789abcdef0123456789abcdef";
        let set_cookie =
            issue_mfa_remember_cookie(secret, &config, "login", "user-rc", "cred-1", 3600).unwrap();
        let jwt = set_cookie
            .split(';')
            .next()
            .unwrap()
            .split_once('=')
            .unwrap()
            .1;
        let now = chrono::Utc::now().timestamp();
        assert!(!verify_mfa_remember_cookie(
            "ffffffffffffffffffffffffffffffff",
            jwt,
            "login",
            "user-rc",
            "cred-1",
            now
        ));

        let result =
            issue_mfa_remember_cookie("short", &config, "login", "user-rc", "cred-1", 3600);
        assert!(
            matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("mfa-remember-secret-too-short")),
            "短密钥应 fail-fast,实际: {:?}",
            result.map(|_| ())
        );
    }

    /// SameSite=None + 非 Secure 上下文:构建点自动降级为 Lax(构建点不变式)。
    #[cfg(feature = "protocol-jwt")]
    #[test]
    fn mfa_remember_cookie_none_downgrades_via_buildpoint() {
        let mut config = GarrisonConfig::default_config();
        config.cookie_same_site = "None".to_string();
        config.cookie_secure = false;
        let set_cookie = issue_mfa_remember_cookie(
            "0123456789abcdef0123456789abcdef",
            &config,
            "login",
            "user-rc",
            "c",
            60,
        )
        .unwrap();
        assert!(
            set_cookie.contains("SameSite=Lax"),
            "非 Secure 上下文应降级 Lax,实际: {}",
            set_cookie
        );
        assert!(!set_cookie.contains("SameSite=None"));
    }
    // MFA 强制链 gate 接线:check_mfa_chain + check_safe 前置链校验

    use crate::stp::mfa::{chain_factor_amr, first_unmet_chain_factor};

    /// chain factor → amr 映射:词汇表内一一对应,词汇表外 None(兜底拒绝)。
    #[test]
    fn chain_factor_amr_maps_vocabulary() {
        assert_eq!(chain_factor_amr("otp"), Some("otp"));
        assert_eq!(chain_factor_amr("webauthn"), Some("webauthn"));
        assert_eq!(chain_factor_amr("sms"), None);
    }

    /// 链覆盖判定:账本覆盖全部强制 factor → None;缺失 → 返回首个未满足 factor。
    #[test]
    fn first_unmet_chain_factor_finds_gap() {
        use crate::stp::mfa::MfaChainDecision;
        let ledger = vec![AmrEntry::new("pwd", 1, 1).unwrap()];
        let decision = MfaChainDecision::Require(vec!["otp".to_string()]);
        assert_eq!(
            first_unmet_chain_factor(&decision, &ledger),
            Some("otp".to_string())
        );
        let full = vec![
            AmrEntry::new("pwd", 1, 1).unwrap(),
            AmrEntry::new("otp", 2, 2).unwrap(),
        ];
        assert_eq!(first_unmet_chain_factor(&decision, &full), None);
        // Disabled 一律满足
        assert_eq!(
            first_unmet_chain_factor(&MfaChainDecision::None, &ledger),
            None
        );
    }

    /// 构造已登录的 GarrisonLogicDefault(返回 logic 与 token)。
    async fn logged_in_logic(config: GarrisonConfig) -> (GarrisonLogicDefault, String) {
        use crate::account::disable::DefaultDisableRepository;
        use crate::dao::tests::MockDao;
        use crate::dao::GarrisonDao;
        use crate::session::GarrisonSession;
        use crate::strategy::GarrisonPermissionStrategy;

        struct NoopFirewall;

        #[async_trait::async_trait]
        impl GarrisonPermissionStrategy for NoopFirewall {
            async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
                Ok(vec![])
            }
            async fn check_permission(
                &self,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_any(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_all(
                &self,
                _login_id: &str,
                _roles: &[&str],
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_permission_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _permission: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            async fn check_role_in_tenant(
                &self,
                _tenant_id: i64,
                _login_id: &str,
                _role: &str,
            ) -> GarrisonResult<bool> {
                Ok(true)
            }
            #[cfg(any(
                feature = "sms-rate-limit",
                feature = "firewall-ratelimit",
                feature = "firewall-bruteforce",
                feature = "firewall-ddos",
                feature = "firewall",
                feature = "oauth2-server"
            ))]
            async fn check_login_hooks(
                &self,
                _login_id: &str,
                _ctx: &crate::strategy::hooks::LoginContext,
            ) -> GarrisonResult<()> {
                Ok(())
            }
        }

        let dao = Arc::new(MockDao::new());
        let session = Arc::new(GarrisonSession::new(
            dao.clone() as Arc<dyn GarrisonDao>,
            3600,
            86400,
            0,
        ));
        let mut config = config;
        config.throw_on_not_login = false;
        let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(NoopFirewall);
        let logic = GarrisonLogicDefault::new(
            session,
            Arc::new(config),
            firewall,
            Arc::new(DefaultDisableRepository::new(dao as Arc<dyn GarrisonDao>)),
        );
        let token = logic
            .login("chain-user", &LoginParams::default())
            .await
            .unwrap();
        (logic, token)
    }

    /// 全局强制链:账本缺 otp 时 check_mfa_chain 拒绝(NotSafe + 具体 factor),
    /// step-up 补齐后通过——gate 面真实强制,不是休眠配置。
    #[tokio::test]
    async fn check_mfa_chain_enforces_global_chain() {
        let mut config = GarrisonConfig::default_config();
        config.mfa.global_chain = vec!["otp".to_string()];
        let (logic, token) = logged_in_logic(config).await;

        use crate::stp::with_current_token;
        let result =
            with_current_token(token.clone(), async { logic.check_mfa_chain(None).await }).await;
        match &result {
            Err(GarrisonError::NotSafe { reason }) => assert_eq!(
                reason, "MFA_CHAIN_INCOMPLETE::otp",
                "缺 otp 时应报告具体缺失因子"
            ),
            other => panic!("账本未覆盖强制链应 Err,实际 ok={:?}", other.is_ok()),
        }

        // step-up 补齐 otp → gate 通过
        logic
            .session
            .append_amr_entry(&token, "otp", 2, chrono::Utc::now().timestamp())
            .await
            .unwrap();
        let result = with_current_token(token, async { logic.check_mfa_chain(None).await }).await;
        assert!(
            result.is_ok(),
            "补齐后链校验应通过,实际: {:?}",
            result.err()
        );
    }

    /// per-client 显式禁用(空集)压过全局强制链;非空集覆盖全局。
    #[tokio::test]
    async fn check_mfa_chain_per_client_tri_state() {
        use crate::stp::with_current_token;

        // 全局 ["otp"],client-acme 显式禁用
        let mut config = GarrisonConfig::default_config();
        config.mfa.global_chain = vec!["otp".to_string()];
        config
            .mfa
            .per_client_chains
            .insert("acme".to_string(), vec![]);
        let (logic, token) = logged_in_logic(config).await;
        let ok =
            with_current_token(token, async { logic.check_mfa_chain(Some("acme")).await }).await;
        assert!(
            ok.is_ok(),
            "显式禁用的 client 不应强制,实际: {:?}",
            ok.err()
        );

        // client-web 非空集 ["otp"] 覆盖全局(同为 otp 但路径不同),未 step-up → 拒绝
        let mut config = GarrisonConfig::default_config();
        config.mfa.global_chain = vec![];
        config
            .mfa
            .per_client_chains
            .insert("web".to_string(), vec!["otp".to_string()]);
        let (logic, token) = logged_in_logic(config).await;
        let result =
            with_current_token(token, async { logic.check_mfa_chain(Some("web")).await }).await;
        assert!(
            matches!(&result, Err(GarrisonError::NotSafe { reason }) if reason == "MFA_CHAIN_INCOMPLETE::otp"),
            "per-client 强制集应生效,实际: {:?}",
            result.map(|_| ())
        );
    }

    /// check_safe 前置链校验:链未满足时在 safe-service 检查之前即拒绝
    /// (authflow Mfa 步骤与 /auth/check-safe 端点经此路径获得链强制)。
    #[cfg(feature = "security-extra")]
    #[tokio::test]
    async fn check_safe_enforces_chain_before_safe_service() {
        use crate::stp::with_current_token;

        let mut config = GarrisonConfig::default_config();
        config.mfa.global_chain = vec!["otp".to_string()];
        let (logic, token) = logged_in_logic(config).await;
        let result = with_current_token(token, async { logic.check_safe().await }).await;
        match &result {
            Err(GarrisonError::NotSafe { reason }) => assert!(
                reason.starts_with("MFA_CHAIN_INCOMPLETE"),
                "链校验应先于 safe-service 检查,实际: {}",
                reason
            ),
            other => panic!("链未满足时 check_safe 应 Err,实际 ok={:?}", other.is_ok()),
        }
    }
}