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

//! /oauth2/token 端点 — RFC 6749 §4 token 签发,支持 4 种 grant type + PKCE 强制:
//! `authorization_code`(授权码交换 access/refresh token,强制 PKCE)、`refresh_token`、
//! `client_credentials`(无 user_id 与 refresh_token)、`password`(需注入 PasswordVerifier)。

use crate::constants::{DaoKeyPrefix, TokenType};
use crate::dao::{GarrisonDao, InMemoryDao};
use crate::error::{GarrisonError, GarrisonResult};
use crate::limiteron::GarrisonDaoDistributedLimiter;
use crate::loc;
use crate::oauth2_server::authorize::AuthorizeHandler;
use crate::oauth2_server::client::{GrantType, OAuth2Client, OAuth2ClientStore};
#[cfg(feature = "db-sqlite")]
use crate::protocol::jwt::refresh::RefreshTokenRotation;
use async_trait::async_trait;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use base64::Engine;
use chrono::{DateTime, Duration, Utc};
use limiteron::limiters::DistributedLimiter;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration as StdDuration;

/// OAuth2 refresh_token 的 DAO fallback key:`oauth2:rtoken:{token}`。
///
/// 未注入 `RefreshTokenRotation`(需 `db-sqlite`)时 refresh token 经 DAO 键值存储签发/消费/吊销
/// (无 reuse detection,见各 handler 文档)。
fn oauth2_refresh_token_key(token: &str) -> String {
    debug_assert!(
        !token.contains(':'),
        "oauth2 refresh_token key: token must not contain ':' (ambiguous key)"
    );
    format!("oauth2:rtoken:{}", token)
}

/// access_token 有效期(1 小时,RFC 6749 建议)。
const ACCESS_TOKEN_TTL_SECONDS: u64 = 3600;
/// refresh_token 有效期(30 天)。
const REFRESH_TOKEN_TTL_SECONDS: u64 = 30 * 24 * 3600;

/// /oauth2/token 请求参数。
#[derive(Debug, Clone, Deserialize)]
pub struct TokenRequest {
    /// grant_type(authorization_code / refresh_token / client_credentials / password)。
    pub grant_type: String,
    /// 客户端 ID。
    ///
    /// RFC 6749 §2.3.1:凭证可经 `Authorization: Basic` 头传递,此时 body 省略本字段(缺省空串);
    /// 认证层(`authenticate_client_with_authorization`)Basic 头优先,头与 body 均无则 `invalid_client`(fail-closed)。
    #[serde(default)]
    pub client_id: String,
    /// 客户端密钥(同 [`TokenRequest::client_id`]:Basic Auth 时 body 可省略)。
    #[serde(default)]
    pub client_secret: String,
    /// 授权码(authorization_code grant type 必填)。
    pub code: Option<String>,
    /// 重定向 URI(authorization_code grant type 必填,需与 authorize 一致)。
    pub redirect_uri: Option<String>,
    /// PKCE code_verifier(authorization_code grant type 必填)。
    pub code_verifier: Option<String>,
    /// 刷新令牌(refresh_token grant type 必填)。
    pub refresh_token: Option<String>,
    /// 请求的 scope(空格分隔,可选)。
    pub scope: Option<String>,
    /// 用户名(password grant type 必填)。
    pub username: Option<String>,
    /// 密码(password grant type 必填)。
    pub password: Option<String>,
}

/// /oauth2/token 响应。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct TokenResponse {
    /// 访问令牌。
    pub access_token: String,
    /// 令牌类型(固定 "Bearer")。
    pub token_type: String,
    /// 过期时间(秒)。
    pub expires_in: u64,
    /// 刷新令牌(client_credentials 不返回)。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<String>,
    /// 实际授予的 scope。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
}

/// token 记录(存储在 DAO 中)。
///
/// `issued_at` / `jti` / `username` 用于 RFC 7662 内省完整字段;所有字段必填,反序列化缺失任一即失败(fail-closed)。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenRecord {
    /// token 字符串。
    pub token: String,
    /// 关联的客户端 ID。
    pub client_id: String,
    /// 关联的用户 ID(client_credentials 为 None)。
    pub user_id: Option<i64>,
    /// 授权的 scope 列表。
    pub scopes: Vec<String>,
    /// token 类型("access" 或 "refresh")。
    pub token_type: String,
    /// 过期时间(UTC)。
    pub expires_at: DateTime<Utc>,
    /// 签发时间(UTC,RFC 7662 §2.3 `iat` 字段)。
    pub issued_at: DateTime<Utc>,
    /// token 唯一标识(RFC 7519 §4.1.7 `jti`,RFC 7662 内省返回)。
    pub jti: Option<String>,
    /// 用户名(password grant type 时有值,RFC 7662 §2.3 `username` 字段)。
    pub username: Option<String>,
}

/// 解析 HTTP Basic Authentication 头(RFC 6749 §2.3.1),期望 `Basic <base64(client_id:client_secret)>`。
///
/// 头非 Basic Auth、base64 / UTF-8 解码失败或不含 `:` 分隔符时返回 `None`。不限制 `client_id` /
/// `client_secret` 中的字符(RFC 6749 §2.3.1 允许 percent-encoded):空 id(`":secret"`)与空密钥
/// (`"cid:"`)均原样返回,由调用方决定是否拒绝。
pub(crate) fn parse_basic_auth(header: &str) -> Option<(String, String)> {
    let encoded = header.strip_prefix("Basic ")?;
    // RFC 7617 要求 STANDARD base64(含 +/= 与 padding);RFC 6749 §2.3.1 规定编码前需
    // percent-encoding,但多数客户端直接 base64,故此处接受 STANDARD 输入
    let decoded = STANDARD.decode(encoded.trim()).ok()?;
    let decoded_str = String::from_utf8(decoded).ok()?;
    let (client_id, client_secret) = decoded_str.split_once(':')?;
    Some((client_id.to_string(), client_secret.to_string()))
}

/// password grant type 验证器 trait:业务方实现后注入 `TokenHandler`;未注入时 password grant
/// 返回 `unauthorized_grant_type` 错误。
#[async_trait]
pub trait PasswordVerifier: Send + Sync {
    /// 验证用户名密码并返回用户 ID:`Ok(None)` 表示用户名或密码错误。
    async fn verify(&self, username: &str, password: &str) -> GarrisonResult<Option<i64>>;
}

/// Password grant 失败计数器 — 防 brute-force。
///
/// per-username 维度(与中间件级 per-IP 的 `RateLimitState` 互补):窗口 `window_seconds` 内失败次数
/// 达 `max_attempts` 即锁定至窗口过期,验证成功后重置。计数经 `GarrisonDaoDistributedLimiter` +
/// `InMemoryDao` 原子实现(TTL 语义自动重置窗口,无需手写时间窗口判断)。
///
/// Key 格式:`rate_limit:pw:{username}`(经 `InMemoryDao::keys("rate_limit:pw:*")` 可扫描全部 entry)。
pub struct PasswordRateLimiter {
    /// 限流器(基于 `GarrisonDaoDistributedLimiter`,内部用 `InMemoryDao` 进程内原子)
    limiter: GarrisonDaoDistributedLimiter,
    /// 保留 `InMemoryDao` 引用以支持 `entry_count()` 测试辅助方法
    dao: Arc<InMemoryDao>,
    /// 窗口内允许的最大失败次数(达此值后锁定至窗口过期)
    max_attempts: u32,
    /// 滑动窗口时长(秒)
    window_seconds: u64,
}

impl PasswordRateLimiter {
    /// 创建失败计数器(内部 `InMemoryDao` + `GarrisonDaoDistributedLimiter`,进程内原子计数);
    /// `max_attempts` 为窗口内允许的最大失败次数,`window_seconds` 为窗口时长(过期后计数自动重置)。
    pub fn new(max_attempts: u32, window_seconds: u64) -> Self {
        let dao = Arc::new(InMemoryDao::new());
        let limiter = GarrisonDaoDistributedLimiter::new(dao.clone());
        Self {
            limiter,
            dao,
            // 至少 1,避免 max_attempts=0 导致所有请求被锁
            max_attempts: max_attempts.max(1),
            window_seconds,
        }
    }

    /// 检查 username 是否允许尝试(未锁定):窗口内失败次数达上限返回 `false`,窗口过期由 TTL 语义自动重置。
    ///
    /// **fail-closed**:`limiteron::get_count` 出错(DAO 通信失败 / 计数损坏)时返回 `false`。本计数器防御
    /// 定向撞库——故障放行会让攻击者制造 DAO 故障使锁定失效、无限撞库;与 `check_client` 的 fail-open
    /// (仅防滥用、可用性优先)刻意不同。
    pub async fn check(&self, username: &str) -> bool {
        let key = format!("rate_limit:pw:{}", username);
        match self.limiter.get_count(&key).await {
            Ok(count) => count < self.max_attempts as u64,
            Err(e) => {
                tracing::warn!(
                    "PasswordRateLimiter::check get_count failed (fail-closed, rejecting): {}",
                    e
                );
                false
            },
        }
    }

    /// 记录一次失败(`incr_with_ttl` 原子递增):首次失败设 count=1 + TTL=`window_seconds`(窗口起点),
    /// 后续仅递增不重置 TTL,窗口过期由 TTL 语义自动重置。
    pub async fn record_failure(&self, username: &str) {
        let key = format!("rate_limit:pw:{}", username);
        let ttl = StdDuration::from_secs(self.window_seconds);
        if let Err(e) = self.limiter.incr_with_ttl(&key, 1, ttl).await {
            tracing::warn!(
                "PasswordRateLimiter::record_failure incr_with_ttl failed: {}",
                e
            );
        }
    }

    /// 验证成功后重置 username 的计数。
    pub async fn reset(&self, username: &str) {
        let key = format!("rate_limit:pw:{}", username);
        if let Err(e) = self.limiter.reset(&key).await {
            tracing::warn!("PasswordRateLimiter::reset failed: {}", e);
        }
    }

    /// 当前未过期 entry 数量(测试/运维用)。
    ///
    /// 通过 `InMemoryDao::keys("rate_limit:pw:*")` 扫描,返回未过期的 entry 数。
    /// 已过期的 key 不会计入(与 `InMemoryDao::keys` 语义一致)。
    pub async fn entry_count(&self) -> usize {
        self.dao
            .keys("rate_limit:pw:*")
            .await
            .map(|v| v.len())
            .unwrap_or(0)
    }

    /// 滑动窗口时长(秒),供限流 429 的 `Retry-After` 保守提示。
    pub fn window_seconds(&self) -> u64 {
        self.window_seconds
    }
}

/// /token 端点速率限制器 — 防暴力枚举 `client_secret` / 密码。
///
/// 两层独立限速(计数经 `GarrisonDaoDistributedLimiter` 原子 check-and-increment):per-client_id 限
/// `/token` 请求速率(默认 10 req/s,防暴力枚举单一 client 的 `client_secret`);per-username 限
/// password grant 的请求速率(默认 5 req/min,与 `PasswordRateLimiter` 失败计数器互补)。
///
/// **Fail 策略**:username 维度(撞库防护)DAO 错误 fail-closed 拒绝;client QPS 维度 fail-open 放行
/// (仅防滥用,可用性优先)。
///
/// Key 格式:`rate_limit:token:client:{client_id}` / `rate_limit:token:user:{username}`。
pub struct TokenRateLimiter {
    /// 限流器(基于 `GarrisonDaoDistributedLimiter`,内部用 `InMemoryDao` 进程内原子)
    limiter: GarrisonDaoDistributedLimiter,
    /// per-client_id 窗口内最大请求数
    client_max: u64,
    /// per-client_id 窗口时长(秒)
    client_window_secs: u64,
    /// per-username 窗口内最大请求数
    username_max: u64,
    /// per-username 窗口时长(秒)
    username_window_secs: u64,
}

impl TokenRateLimiter {
    /// 创建默认配置的速率限制器:10 req/s per-client_id(覆盖正常刷新与短时重试)
    /// + 5 req/min per-username(限制单账户密码暴力尝试)。
    pub fn new() -> Self {
        Self::with_limits(10, 1, 5, 60)
    }

    /// 自定义限速参数(测试 / 运维调优用);所有参数 clamp 到至少 1,避免 `max=0` 拒绝所有请求。
    pub fn with_limits(
        client_max: u64,
        client_window_secs: u64,
        username_max: u64,
        username_window_secs: u64,
    ) -> Self {
        let dao = Arc::new(InMemoryDao::new());
        let limiter = GarrisonDaoDistributedLimiter::new(dao);
        Self {
            limiter,
            // 至少 1,避免 max=0 导致所有请求被拒
            client_max: client_max.max(1),
            client_window_secs: client_window_secs.max(1),
            username_max: username_max.max(1),
            username_window_secs: username_window_secs.max(1),
        }
    }

    /// 检查 client_id 是否允许请求(调用即计数):已达窗口上限返回 `false`。
    ///
    /// **fail-open**:DAO 错误时返回 `true`(放行),本维度仅限请求 QPS(防滥用),失效代价可接受;
    /// 与 `PasswordRateLimiter::check` / [`Self::check_username`] 的 fail-closed 刻意不同(后两者防撞库)。
    pub async fn check_client(&self, client_id: &str) -> bool {
        let key = format!("rate_limit:token:client:{}", client_id);
        let ttl = StdDuration::from_secs(self.client_window_secs);
        match self
            .limiter
            .atomic_check_and_incr(&key, self.client_max, ttl)
            .await
        {
            Ok(allowed) => allowed,
            Err(e) => {
                tracing::warn!("TokenRateLimiter::check_client failed: {}", e);
                true
            },
        }
    }

    /// 检查 username 是否允许请求(调用即计数);仅 password grant type 调用,限制单账户密码尝试 QPS。
    ///
    /// **fail-closed**:DAO 错误时返回 `false`——本维度属撞库防护面,故障放行等于允许无限撞库。
    pub async fn check_username(&self, username: &str) -> bool {
        let key = format!("rate_limit:token:user:{}", username);
        let ttl = StdDuration::from_secs(self.username_window_secs);
        match self
            .limiter
            .atomic_check_and_incr(&key, self.username_max, ttl)
            .await
        {
            Ok(allowed) => allowed,
            Err(e) => {
                tracing::warn!(
                    "TokenRateLimiter::check_username failed (fail-closed, rejecting): {}",
                    e
                );
                false
            },
        }
    }

    /// 双窗口时长的上界(秒):桥接层(`server::oauth2_routes`)无法区分具体触发的窗口与剩余秒数,
    /// 取上界作 429 `Retry-After` 的保守提示,保证客户端不早于任一窗口过期重试。
    pub fn window_upper_bound_secs(&self) -> u64 {
        self.client_window_secs.max(self.username_window_secs)
    }
}

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

/// /oauth2/token handler,处理 4 种 grant type。
///
/// # Refresh Token 统一
///
/// `db-sqlite` 下经 `with_refresh_rotation` 注入 `RefreshTokenRotation` 后走统一轮换路径
/// (`issue_tokens` 委托 `issue`(hash chain + INSERT),`handle_refresh_token` 委托 `rotate`
/// (reuse detection + 链式撤销));未注入时退化为 DAO 键值存储(`oauth2:rtoken:` 前缀),
/// 无 reuse detection(安全风险见各 handler 文档)。
pub struct TokenHandler {
    store: Arc<dyn OAuth2ClientStore>,
    dao: Arc<dyn GarrisonDao>,
    authorize_handler: Arc<AuthorizeHandler>,
    password_verifier: Option<Arc<dyn PasswordVerifier>>,
    /// Password grant 失败计数器(防 brute-force,构造必需参数)。
    password_rate_limiter: Arc<PasswordRateLimiter>,
    /// /token 端点速率限制器(per-client_id + per-username QPS 限制,构造必需参数)。
    token_rate_limiter: Arc<TokenRateLimiter>,
    /// 统一的 refresh token 轮换服务(db-sqlite feature 启用时可用)。
    /// 为 None 时退化为 DAO 键值存储(无 reuse detection)。
    #[cfg(feature = "db-sqlite")]
    refresh_rotation: Option<Arc<RefreshTokenRotation>>,
}

impl TokenHandler {
    /// 创建 handler(两个限流器均为必需注入,不提供"未注入 = 无账户锁定"的构造形态)。
    ///
    /// `token_rate_limiter` 在 client 认证前按 `client_id`、账户锁定检查前按 `username` 限速,防暴力枚举。
    pub fn new(
        store: Arc<dyn OAuth2ClientStore>,
        dao: Arc<dyn GarrisonDao>,
        authorize_handler: Arc<AuthorizeHandler>,
        password_rate_limiter: Arc<PasswordRateLimiter>,
        token_rate_limiter: Arc<TokenRateLimiter>,
    ) -> Self {
        Self {
            store,
            dao,
            authorize_handler,
            password_verifier: None,
            password_rate_limiter,
            token_rate_limiter,
            #[cfg(feature = "db-sqlite")]
            refresh_rotation: None,
        }
    }

    /// 注入 password grant type 验证器。
    pub fn with_password_verifier(mut self, verifier: Arc<dyn PasswordVerifier>) -> Self {
        self.password_verifier = Some(verifier);
        self
    }

    /// 注入 RefreshTokenRotation 启用统一轮换 + reuse detection(仅 `db-sqlite` feature 启用时可用)。
    ///
    /// 注入后 `issue_tokens`(`with_refresh=true` 时)委托 `rotation.issue()`,`handle_refresh_token` 委托 `rotation.rotate()`;未注入时退化为 DAO 路径(无 reuse detection)。
    #[cfg(feature = "db-sqlite")]
    pub fn with_refresh_rotation(mut self, rotation: Arc<RefreshTokenRotation>) -> Self {
        self.refresh_rotation = Some(rotation);
        self
    }

    /// refresh 轮换服务是否已注入(reuse detection 可用性探针)。
    ///
    /// 供 `OAuth2State` 构造完成时的结构性告警与部署自检使用:
    /// `false` 表示 refresh grant 将走 DAO 退化路径(无 reuse detection)。
    #[cfg(feature = "db-sqlite")]
    pub fn has_refresh_rotation(&self) -> bool {
        self.refresh_rotation.is_some()
    }

    /// 限流窗口时长上界(秒):`TokenRateLimiter` 双窗口与 `PasswordRateLimiter`
    /// 锁定窗口的最大值。
    ///
    /// OAuth2 限流错误(`rate_limited` 消息前缀)经 `server::oauth2_routes`
    /// 桥接为 `RateLimited` 时用作 `Retry-After` 保守提示——滑动窗口 TTL 起点
    /// 在首次计数时确立,桥接处拿不到精确剩余秒数,取上界保证客户端不早于
    /// 任一窗口过期重试(宁长勿短)。
    pub fn rate_limit_window_upper_bound_secs(&self) -> u64 {
        self.token_rate_limiter
            .window_upper_bound_secs()
            .max(self.password_rate_limiter.window_seconds())
    }

    /// 处理 token 请求。
    pub async fn handle(&self, req: &TokenRequest) -> GarrisonResult<TokenResponse> {
        self.handle_with_authorization(req, None).await
    }

    /// 处理 token 请求,支持 HTTP Basic Auth 客户端认证(RFC 6749 §2.3.1)。
    ///
    /// `authorization` 为 `Some("Basic ...")` 时优先从头解码 `client_id:client_secret`,否则回退 body 参数。
    pub async fn handle_with_authorization(
        &self,
        req: &TokenRequest,
        authorization: Option<&str>,
    ) -> GarrisonResult<TokenResponse> {
        // per-client_id 速率限制(在 client 认证前):即使凭证错误也计入限速,防御暴力枚举 client_secret
        //(与 PasswordRateLimiter 在密码验证前 check 的设计一致)。
        let client_id = authorization
            .and_then(parse_basic_auth)
            .map(|(id, _)| id)
            .unwrap_or_else(|| req.client_id.clone());
        if !client_id.is_empty() && !self.token_rate_limiter.check_client(&client_id).await {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-rate-limited-client",
                "rate_limited: client requests too frequent, please retry later"
            )));
        }

        let client = self
            .authenticate_client_with_authorization(
                authorization,
                &req.client_id,
                &req.client_secret,
            )
            .await?;

        // 根据 grant_type 分发(GrantType 枚举,避免硬编码字符串)
        let grant_type: GrantType = req.grant_type.parse()?;
        match grant_type {
            GrantType::AuthorizationCode => self.handle_authorization_code(&client, req).await,
            GrantType::RefreshToken => self.handle_refresh_token(&client, req).await,
            GrantType::ClientCredentials => self.handle_client_credentials(&client, req).await,
            GrantType::Password => self.handle_password(&client, req).await,
        }
    }

    /// 验证客户端凭证,支持 HTTP Basic Auth。
    ///
    /// 优先解析 `Authorization: Basic` 头;若未提供或解析失败,回退到 body 参数。
    /// 两种来源均未提供 client_id 时返回 `invalid_client`。
    async fn authenticate_client_with_authorization(
        &self,
        authorization: Option<&str>,
        body_client_id: &str,
        body_client_secret: &str,
    ) -> GarrisonResult<OAuth2Client> {
        // 优先解析 Authorization: Basic 头(RFC 6749 §2.3.1)
        let (client_id, client_secret) = match authorization.and_then(parse_basic_auth) {
            Some((id, secret)) => (id, secret),
            None => (body_client_id.to_string(), body_client_secret.to_string()),
        };

        if client_id.is_empty() {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-client-id-missing",
                "invalid_client: client_id missing (provided neither in Authorization header nor body)"
            )));
        }

        let client = self.store.get(&client_id).await?.ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-client-not-exist",
                format!("invalid_client: client {client_id} does not exist"),
                ("client_id", client_id.as_str())
            ))
        })?;
        if !client.verify_secret(&client_secret)? {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-client-secret-mismatch",
                "invalid_client: client_secret mismatch"
            )));
        }
        Ok(client)
    }

    /// authorization_code grant type:授权码交换 token。
    async fn handle_authorization_code(
        &self,
        client: &OAuth2Client,
        req: &TokenRequest,
    ) -> GarrisonResult<TokenResponse> {
        if !client.allows_grant_type(&GrantType::AuthorizationCode) {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-grant-not-allowed-auth-code",
                "unauthorized_client: authorization_code grant type not allowed for this client"
            )));
        }

        let code = req.code.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-code-param-missing",
                "invalid_request: missing code parameter"
            ))
        })?;
        let code_verifier = req.code_verifier.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-code-verifier-missing",
                "invalid_request: missing code_verifier parameter (PKCE enforced)"
            ))
        })?;
        let redirect_uri = req.redirect_uri.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-redirect-uri-param-missing",
                "invalid_request: missing redirect_uri parameter"
            ))
        })?;

        // 消费授权码(一次性)
        let auth_code = self
            .authorize_handler
            .consume_code(code)
            .await?
            .ok_or_else(|| {
                GarrisonError::OAuth2(loc!(
                    "oauth2-code-invalid-or-expired",
                    "invalid_grant: authorization code invalid or expired"
                ))
            })?;

        if auth_code.client_id != client.client_id {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-code-client-mismatch",
                "invalid_grant: authorization code does not match client_id"
            )));
        }

        if auth_code.redirect_uri != *redirect_uri {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-redirect-uri-mismatch",
                "invalid_grant: redirect_uri differs from the one used at authorization time"
            )));
        }

        if !crate::oauth2_server::authorize::verify_pkce(code_verifier, &auth_code.code_challenge)?
        {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-pkce-verify-failed",
                "invalid_grant: PKCE code_verifier verification failed"
            )));
        }

        let scopes = auth_code.scopes.clone();
        // 校验授权码中的 scope 是否在客户端 allowed_scopes 内(纵深防御)
        client.validate_scopes(&scopes)?;
        let user_id = auth_code.user_id;
        self.issue_tokens(
            &client.client_id,
            Some(user_id),
            &scopes,
            true, // 返回 refresh_token
            None, // authorization_code grant type 不携带 username
        )
        .await
    }

    /// refresh_token grant type:刷新令牌。
    ///
    /// 启用 `db-sqlite` 且注入 `RefreshTokenRotation` 时走统一轮换(`rotation.rotate()`:hash chain + reuse detection + 链式撤销);
    /// 未注入时退化为 DAO 路径:`get_and_delete` 原子消费旧 token 防双花、校验 client_id、签发新 token 对,
    /// 签发失败补偿回写旧 token(剩余 TTL),旧 token 再次使用 → `invalid_grant`(隐式 reuse detection)。
    async fn handle_refresh_token(
        &self,
        client: &OAuth2Client,
        req: &TokenRequest,
    ) -> GarrisonResult<TokenResponse> {
        if !client.allows_grant_type(&GrantType::RefreshToken) {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-grant-not-allowed-refresh-token",
                "unauthorized_client: refresh_token grant type not allowed for this client"
            )));
        }

        let refresh_token = req.refresh_token.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-refresh-token-param-missing",
                "invalid_request: missing refresh_token parameter"
            ))
        })?;

        // 统一路径:RefreshTokenRotation.rotate(reuse detection + hash chain)
        #[cfg(feature = "db-sqlite")]
        {
            if let Some(rotation) = &self.refresh_rotation {
                // rotate 直接处理 reuse detection + 链式撤销:
                // - reuse → TokenRevoked(透传)
                // - not found → InvalidToken(映射为 OAuth2 invalid_grant)
                let (new_access, new_refresh) = match rotation.rotate(refresh_token).await {
                    Ok(t) => t,
                    Err(GarrisonError::InvalidToken(_)) => {
                        return Err(GarrisonError::OAuth2(loc!(
                            "oauth2-refresh-token-invalid-or-expired",
                            "invalid_grant: refresh_token invalid or expired"
                        )));
                    },
                    Err(e) => return Err(e),
                };
                // validate 新 token 获取 scopes + client_id 供响应
                let record = rotation.validate(&new_refresh).await?.ok_or_else(|| {
                    GarrisonError::Internal(loc!(
                        "oauth2-rotated-token-validate-failed",
                        "validation failed for rotated refresh_token"
                    ))
                })?;
                let record_client_id = record.client_id.as_deref().unwrap_or("");
                if record_client_id != client.client_id {
                    return Err(GarrisonError::OAuth2(loc!(
                        "oauth2-refresh-token-client-mismatch",
                        "invalid_grant: refresh_token does not match client_id"
                    )));
                }
                let scopes: Vec<String> = record
                    .scopes
                    .as_ref()
                    .map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
                    .unwrap_or_default();
                let scope_str = if scopes.is_empty() {
                    None
                } else {
                    Some(scopes.join(" "))
                };
                return Ok(TokenResponse {
                    access_token: new_access,
                    token_type: TokenType::Bearer.to_string(),
                    expires_in: ACCESS_TOKEN_TTL_SECONDS,
                    refresh_token: Some(new_refresh),
                    scope: scope_str,
                });
            }
        }

        // DAO fallback 路径显性化(每次降级刷新告警一次):本路径无 reuse detection,盗用 refresh_token 的重放
        // 仅因单次消费失败而拒绝,不会触发链式撤销;启动期已输出结构性 warn,此处为按请求级标记。
        tracing::warn!(
            "{}",
            crate::i18n::translate_detail("logs-oauth2-refresh-rotation-not-configured", &[])
        );
        //
        // 原子消费(get_and_delete):读取 + 删除在 DAO 单次临界区内完成,
        // 并发对同一 refresh_token 的刷新仅有一个调用方拿到记录(防双花),
        // 消除 get→delete 的 TOCTOU 竞态窗口。
        // 旧 token 删除后,再次使用会因 get_and_delete 返回 None 而返回 invalid_grant
        // (隐式 reuse detection:旧 token 无法重用)
        let key = oauth2_refresh_token_key(refresh_token);
        let json = self.dao.get_and_delete(&key).await?.ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-refresh-token-invalid-or-expired",
                "invalid_grant: refresh_token invalid or expired"
            ))
        })?;
        let record: TokenRecord = serde_json::from_str(&json).map_err(|e| {
            GarrisonError::Internal(loc!(
                "oauth2-server-token-deserialize",
                format!("TokenRecord deserialize failed: {e}"),
                ("arg0", &e.to_string())
            ))
        })?;

        if record.client_id != client.client_id {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-refresh-token-client-mismatch",
                "invalid_grant: refresh_token does not match client_id"
            )));
        }

        // 签发新 access_token + 新 refresh_token(with_refresh=true 轮换)
        let user_id = record.user_id;
        let scopes = record.scopes.clone();
        let username = record.username.clone();
        let resp = match self
            .issue_tokens(
                &client.client_id,
                user_id,
                &scopes,
                true, // 轮换 — 签发新 refresh_token
                username.as_deref(),
            )
            .await
        {
            Ok(resp) => resp,
            Err(e) => {
                // 补偿回写:旧 token 已被原子消费,若签发失败且不回写,
                // 用户将同时失去旧 token 与新 token(凭据丢失)。
                // 以原记录剩余寿命为 TTL 回写,签发成功后旧 token 保持已删除。
                let remaining = (record.expires_at - Utc::now()).num_seconds();
                if remaining > 0 {
                    if let Err(set_err) = self.dao.set(&key, &json, remaining as u64).await {
                        tracing::warn!(
                            error = %set_err,
                            "handle_refresh_token: failed to restore refresh token after issue failure"
                        );
                    }
                }
                return Err(e);
            },
        };
        Ok(resp)
    }

    /// client_credentials grant type:服务间认证 token。
    async fn handle_client_credentials(
        &self,
        client: &OAuth2Client,
        req: &TokenRequest,
    ) -> GarrisonResult<TokenResponse> {
        if !client.allows_grant_type(&GrantType::ClientCredentials) {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-grant-not-allowed-client-credentials",
                "unauthorized_client: client_credentials grant type not allowed for this client"
            )));
        }

        let scopes: Vec<String> = req
            .scope
            .as_ref()
            .map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
            .unwrap_or_default();

        client.validate_scopes(&scopes)?;

        // 无 user_id,无 refresh_token
        self.issue_tokens(&client.client_id, None, &scopes, false, None)
            .await
    }

    /// password grant type:用户名密码验证 + token。
    async fn handle_password(
        &self,
        client: &OAuth2Client,
        req: &TokenRequest,
    ) -> GarrisonResult<TokenResponse> {
        if !client.allows_grant_type(&GrantType::Password) {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-grant-not-allowed-password",
                "unauthorized_client: password grant type not allowed for this client"
            )));
        }

        let verifier = self.password_verifier.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-password-verifier-not-configured",
                "unauthorized_grant_type: PasswordVerifier not configured for password grant type"
            ))
        })?;

        let username = req.username.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-username-param-missing",
                "invalid_request: missing username parameter"
            ))
        })?;
        let password = req.password.as_ref().ok_or_else(|| {
            GarrisonError::OAuth2(loc!(
                "oauth2-password-param-missing",
                "invalid_request: missing password parameter"
            ))
        })?;

        // per-username QPS 速率限制(在账户锁定检查前,防暴力撞库)
        //
        // 与 PasswordRateLimiter(失败计数器)互补 —— 后者限制窗口内失败次数,
        // 本结构限制窗口内请求 QPS,两者叠加形成纵深防御。
        if !self.token_rate_limiter.check_username(username).await {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-rate-limited-user",
                "rate_limited: user requests too frequent, please retry later"
            )));
        }

        // 验证密码前检查账户锁定状态(防 brute-force)
        if !self.password_rate_limiter.check(username).await {
            return Err(GarrisonError::OAuth2(loc!(
                "oauth2-account-temp-locked",
                "rate_limited: account temporarily locked, please retry later"
            )));
        }

        let user_id = match verifier.verify(username, password).await? {
            Some(uid) => uid,
            None => {
                self.password_rate_limiter.record_failure(username).await;
                return Err(GarrisonError::OAuth2(loc!(
                    "oauth2-invalid-credentials",
                    "invalid_grant: invalid username or password"
                )));
            },
        };

        self.password_rate_limiter.reset(username).await;

        let scopes: Vec<String> = req
            .scope
            .as_ref()
            .map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
            .unwrap_or_default();

        client.validate_scopes(&scopes)?;

        self.issue_tokens(
            &client.client_id,
            Some(user_id),
            &scopes,
            true,
            Some(username.as_str()),
        )
        .await
    }

    /// 签发 token 并存储。
    ///
    /// `username` 仅 password grant type 有值(RFC 7662 §2.3 内省返回)。
    ///
    /// # Refresh Token 统一
    ///
    /// `with_refresh=true` 时:
    /// - 启用 `db-sqlite` 且注入 `RefreshTokenRotation` → 委托 `rotation.issue()`
    /// - 否则 → DAO 路径(`oauth2:rtoken:` 前缀,无 reuse detection)
    async fn issue_tokens(
        &self,
        client_id: &str,
        user_id: Option<i64>,
        scopes: &[String],
        with_refresh: bool,
        username: Option<&str>,
    ) -> GarrisonResult<TokenResponse> {
        let access_token = generate_token();
        let now = Utc::now();
        let at_expires_at = now + Duration::seconds(ACCESS_TOKEN_TTL_SECONDS as i64);
        // RFC 7519 §4.1.7 jti:保证同一秒内签发的 token 唯一
        let at_jti = uuid::Uuid::new_v4().to_string();

        let at_record = TokenRecord {
            token: access_token.clone(),
            client_id: client_id.to_string(),
            user_id,
            scopes: scopes.to_vec(),
            token_type: TokenType::Access.to_string(),
            expires_at: at_expires_at,
            issued_at: now,
            jti: Some(at_jti),
            username: username.map(|s| s.to_string()),
        };

        let at_key = DaoKeyPrefix::OAuth2AccessToken.build_key(&access_token);
        let at_json = serde_json::to_string(&at_record).map_err(|e| {
            GarrisonError::Internal(loc!(
                "oauth2-server-token-serialize",
                format!("TokenRecord serialize failed: {e}"),
                ("arg0", &e.to_string())
            ))
        })?;
        self.dao
            .set(&at_key, &at_json, ACCESS_TOKEN_TTL_SECONDS)
            .await?;

        let refresh_token = if with_refresh {
            // 统一路径:RefreshTokenRotation.issue(hash chain + INSERT)
            #[cfg(feature = "db-sqlite")]
            {
                if let Some(rotation) = &self.refresh_rotation {
                    let login_id = user_id.unwrap_or(0);
                    let rt = rotation
                        .issue(
                            client_id,
                            user_id,
                            scopes,
                            username,
                            login_id,
                            0, // tenant_id: 默认租户
                            REFRESH_TOKEN_TTL_SECONDS as i64,
                        )
                        .await?;
                    Some(rt)
                } else {
                    // Fallback: DAO 存储(无 reuse detection)
                    self.issue_refresh_via_dao(client_id, user_id, scopes, username, now)
                        .await?
                }
            }
            #[cfg(not(feature = "db-sqlite"))]
            {
                self.issue_refresh_via_dao(client_id, user_id, scopes, username, now)
                    .await?
            }
        } else {
            None
        };

        let scope_str = if scopes.is_empty() {
            None
        } else {
            Some(scopes.join(" "))
        };

        Ok(TokenResponse {
            access_token,
            token_type: TokenType::Bearer.to_string(),
            expires_in: ACCESS_TOKEN_TTL_SECONDS,
            refresh_token,
            scope: scope_str,
        })
    }

    /// DAO fallback 路径签发 refresh_token(无 reuse detection)。
    ///
    /// 当 `RefreshTokenRotation` 未注入或 `db-sqlite` feature 未启用时使用。
    /// refresh_token 存储在 DAO 中(`oauth2:rtoken:` 前缀),
    /// 无 hash chain、无 reuse detection、无链式撤销。
    async fn issue_refresh_via_dao(
        &self,
        client_id: &str,
        user_id: Option<i64>,
        scopes: &[String],
        username: Option<&str>,
        now: DateTime<Utc>,
    ) -> GarrisonResult<Option<String>> {
        let rt = generate_token();
        let rt_expires_at = now + Duration::seconds(REFRESH_TOKEN_TTL_SECONDS as i64);
        let rt_jti = uuid::Uuid::new_v4().to_string();
        let rt_record = TokenRecord {
            token: rt.clone(),
            client_id: client_id.to_string(),
            user_id,
            scopes: scopes.to_vec(),
            token_type: TokenType::Refresh.to_string(),
            expires_at: rt_expires_at,
            issued_at: now,
            jti: Some(rt_jti),
            username: username.map(|s| s.to_string()),
        };
        let rt_key = oauth2_refresh_token_key(&rt);
        let rt_json = serde_json::to_string(&rt_record).map_err(|e| {
            GarrisonError::Internal(loc!(
                "oauth2-server-token-serialize",
                format!("TokenRecord serialize failed: {e}"),
                ("arg0", &e.to_string())
            ))
        })?;
        self.dao
            .set(&rt_key, &rt_json, REFRESH_TOKEN_TTL_SECONDS)
            .await?;
        Ok(Some(rt))
    }

    /// 查找 access_token 记录(供 introspect 端点使用)。
    pub async fn get_access_token_record(
        &self,
        token: &str,
    ) -> GarrisonResult<Option<TokenRecord>> {
        let key = DaoKeyPrefix::OAuth2AccessToken.build_key(token);
        let json = self.dao.get(&key).await?;
        match json {
            Some(json) => {
                let record: TokenRecord = serde_json::from_str(&json).map_err(|e| {
                    GarrisonError::Internal(loc!(
                        "oauth2-server-token-deserialize",
                        format!("TokenRecord deserialize failed: {e}"),
                        ("arg0", &e.to_string())
                    ))
                })?;
                Ok(Some(record))
            },
            None => Ok(None),
        }
    }

    /// 查找 refresh_token 记录(供 introspect / revoke 端点使用)。
    ///
    /// `db-sqlite` + `RefreshTokenRotation` 注入时存 SQLite `refresh_tokens` 表(SHA-256 hash 为键,查 rotation.validate()),
    /// 否则查 DAO `oauth2:rtoken:` 记录。过期过滤不在此处——返回记录含 `expires_at`,由调用方判定 active。
    pub async fn get_refresh_token_record(
        &self,
        token: &str,
    ) -> GarrisonResult<Option<TokenRecord>> {
        #[cfg(feature = "db-sqlite")]
        {
            if let Some(rotation) = &self.refresh_rotation {
                let record = match rotation.validate(token).await? {
                    Some(r) => r,
                    None => return Ok(None),
                };
                let expires_at =
                    DateTime::<Utc>::from_timestamp(record.expires_at, 0).ok_or_else(|| {
                        GarrisonError::Internal("refresh-token-expires-at-invalid".into())
                    })?;
                let issued_at =
                    DateTime::<Utc>::from_timestamp(record.created_at, 0).unwrap_or(expires_at);
                return Ok(Some(TokenRecord {
                    token: token.to_string(),
                    client_id: record.client_id.unwrap_or_default(),
                    // 旧记录可能无独立 user_id,回退到 login_id(签发时取自 user_id)
                    user_id: record.user_id.or(Some(record.login_id)),
                    scopes: record
                        .scopes
                        .as_ref()
                        .map(|s| s.split_whitespace().map(|x| x.to_string()).collect())
                        .unwrap_or_default(),
                    token_type: TokenType::Refresh.to_string(),
                    expires_at,
                    issued_at,
                    jti: Some(record.token_hash),
                    username: record.username,
                }));
            }
        }
        let key = oauth2_refresh_token_key(token);
        let json = self.dao.get(&key).await?;
        match json {
            Some(json) => {
                let record: TokenRecord = serde_json::from_str(&json).map_err(|e| {
                    GarrisonError::Internal(loc!(
                        "oauth2-server-token-deserialize",
                        format!("TokenRecord deserialize failed: {e}"),
                        ("arg0", &e.to_string())
                    ))
                })?;
                Ok(Some(record))
            },
            None => Ok(None),
        }
    }

    /// 撤销 token(供 revoke 端点使用)。
    ///
    /// 同时覆盖两种 refresh token 存储路径:
    /// - DAO fallback:删除 `oauth2:atoken:` / `oauth2:rtoken:` 记录
    /// - `RefreshTokenRotation` 注入(db-sqlite):rotation 签发的 refresh token
    ///   存 SQLite `refresh_tokens` 表,DAO 删除对其无效,需经
    ///   `rotation.revoke_chain` 撤销(fail-safe:连带撤销该链子代)
    pub async fn revoke_token(&self, token: &str) -> GarrisonResult<()> {
        let at_key = DaoKeyPrefix::OAuth2AccessToken.build_key(token);
        self.dao.delete(&at_key).await?;
        // 尝试删除 refresh_token(DAO fallback 路径;同一 token 值不会同时是两种类型)
        let rt_key = oauth2_refresh_token_key(token);
        self.dao.delete(&rt_key).await?;
        // RefreshTokenRotation 注入时,refresh token 存 SQLite(以 SHA-256 hash 为键),
        // 上面两条 DAO 删除对其无效——按 RFC 7009 语义撤销 rotation 记录。
        #[cfg(feature = "db-sqlite")]
        if let Some(rotation) = &self.refresh_rotation {
            use sha2::{Digest, Sha256};
            let mut hasher = Sha256::new();
            hasher.update(token.as_bytes());
            let token_hash: String = hasher
                .finalize()
                .iter()
                .map(|b| format!("{:02x}", b))
                .collect();
            // access token 的 hash 不在 refresh_tokens 表中 → UPDATE 影响 0 行,无副作用
            rotation.revoke_chain(&token_hash).await?;
        }
        Ok(())
    }
}

/// 生成 token(32 字节随机数 → BASE64URL 编码)。
fn generate_token() -> String {
    let mut bytes = [0u8; 32];
    // 直接读 OS CSPRNG(getrandom::fill),与 src/oauth2_server/authorize.rs 授权码路径同一安全立场
    getrandom::fill(&mut bytes).expect("OS CSPRNG 不可用");
    URL_SAFE_NO_PAD.encode(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dao::InMemoryDao;
    use crate::oauth2_server::authorize::AuthorizeHandler;
    use crate::oauth2_server::client::DaoOAuth2ClientStore;

    /// 测试用 PasswordVerifier。
    struct TestPasswordVerifier;
    #[async_trait]
    impl PasswordVerifier for TestPasswordVerifier {
        async fn verify(&self, username: &str, password: &str) -> GarrisonResult<Option<i64>> {
            if username == "alice" && password == "wonderland" {
                Ok(Some(5001))
            } else {
                Ok(None)
            }
        }
    }

    /// 创建测试用 handler(含 password verifier,限速参数放宽以免干扰功能测试)。
    fn make_handler() -> (TokenHandler, Arc<InMemoryDao>) {
        make_handler_with_limiters(
            Arc::new(PasswordRateLimiter::new(1000, 300)),
            Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
        )
    }

    /// 创建指定限速参数的测试用 handler(含 password verifier)。
    fn make_handler_with_limiters(
        password_rate_limiter: Arc<PasswordRateLimiter>,
        token_rate_limiter: Arc<TokenRateLimiter>,
    ) -> (TokenHandler, Arc<InMemoryDao>) {
        let dao = Arc::new(InMemoryDao::new());
        let store = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
        let authorize_handler = Arc::new(AuthorizeHandler::new(
            store.clone(),
            dao.clone(),
            "https://auth.example.com/login".into(),
        ));
        let handler = TokenHandler::new(
            store,
            dao.clone(),
            authorize_handler,
            password_rate_limiter,
            token_rate_limiter,
        )
        .with_password_verifier(Arc::new(TestPasswordVerifier));
        (handler, dao)
    }

    /// 创建测试用客户端(支持所有 grant type)。
    fn make_full_client(id: &str) -> OAuth2Client {
        OAuth2Client::new(
            id,
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![
                GrantType::AuthorizationCode,
                GrantType::RefreshToken,
                GrantType::ClientCredentials,
                GrantType::Password,
            ],
            vec!["read".into(), "write".into()],
        )
        .unwrap()
    }

    /// 通过 authorize 端点获取授权码。
    async fn get_auth_code(handler: &TokenHandler, client_id: &str, verifier: &str) -> String {
        let challenge = crate::oauth2_server::authorize::generate_code_challenge(verifier);
        let req = crate::oauth2_server::authorize::AuthorizeRequest {
            response_type: "code".into(),
            client_id: client_id.into(),
            redirect_uri: "https://app.example.com/cb".into(),
            scope: Some("read".into()),
            state: Some("xyz".into()),
            code_challenge: challenge,
            code_challenge_method: "S256".into(),
            prompt: None,
        };
        let resp = handler
            .authorize_handler
            .authorize(&req, Some(1001))
            .await
            .unwrap();
        match resp {
            crate::oauth2_server::authorize::AuthorizeResponse::Redirect { location } => location
                .split("code=")
                .nth(1)
                .unwrap()
                .split('&')
                .next()
                .unwrap()
                .to_string(),
            _ => panic!("期望 Redirect"),
        }
    }

    // 客户端认证测试

    #[tokio::test]
    async fn handle_invalid_client_id() {
        let (handler, _) = make_handler();
        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "no-such".into(),
            client_secret: "secret".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("invalid_client"));
    }

    #[tokio::test]
    async fn handle_invalid_client_secret() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("c-secret"))
            .await
            .unwrap();
        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "c-secret".into(),
            client_secret: "wrong".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("invalid_client"));
    }

    /// parse_basic_auth 正确解析标准 Basic Auth 头。
    #[test]
    fn parse_basic_auth_decodes_valid_header() {
        // "cid:secret" → base64 → "Y2lkOnNlY3JldA=="
        let header = "Basic Y2lkOnNlY3JldA==";
        let result = parse_basic_auth(header);
        assert_eq!(result, Some(("cid".to_string(), "secret".to_string())));
    }

    /// parse_basic_auth 对非 Basic 头返回 None。
    #[test]
    fn parse_basic_auth_rejects_non_basic() {
        assert!(parse_basic_auth("Bearer token123").is_none());
        assert!(parse_basic_auth("").is_none());
    }

    /// parse_basic_auth 对无效 base64 返回 None。
    #[test]
    fn parse_basic_auth_rejects_invalid_base64() {
        assert!(parse_basic_auth("Basic !!!not-base64!!!").is_none());
    }

    /// parse_basic_auth 对不含 `:` 的解码结果返回 None。
    #[test]
    fn parse_basic_auth_rejects_no_colon() {
        // "noseparator" → base64 → "bm9zZXBhcmF0b3I="
        assert!(parse_basic_auth("Basic bm9zZXBhcmF0b3I=").is_none());
    }

    /// parse_basic_auth 正确处理空 client_id(":secret")。
    #[test]
    fn parse_basic_auth_handles_empty_client_id() {
        // ":secret" → base64 → "OnNlY3JldA=="
        let result = parse_basic_auth("Basic OnNlY3JldA==");
        assert_eq!(result, Some(("".to_string(), "secret".to_string())));
    }

    /// parse_basic_auth 正确处理空 client_secret("cid:")。
    #[test]
    fn parse_basic_auth_handles_empty_client_secret() {
        // "cid:" → base64 → "Y2lkOg=="
        let result = parse_basic_auth("Basic Y2lkOg==");
        assert_eq!(result, Some(("cid".to_string(), "".to_string())));
    }

    /// parse_basic_auth 正确处理 client_secret 中含冒号("cid:sec:ret")。
    #[test]
    fn parse_basic_auth_handles_colon_in_secret() {
        // "cid:sec:ret" → base64 → "Y2lkOnNlYzpyZXQ="
        let result = parse_basic_auth("Basic Y2lkOnNlYzpyZXQ=");
        assert_eq!(result, Some(("cid".to_string(), "sec:ret".to_string())));
    }

    /// parse_basic_auth 正确处理含特殊字符的凭证。
    #[test]
    fn parse_basic_auth_handles_special_chars() {
        // "user@domain:p@ss!word" → base64
        use base64::engine::general_purpose::STANDARD;
        use base64::Engine;
        let encoded = STANDARD.encode("user@domain:p@ss!word");
        let header = format!("Basic {}", encoded);
        let result = parse_basic_auth(&header);
        assert_eq!(
            result,
            Some(("user@domain".to_string(), "p@ss!word".to_string()))
        );
    }

    /// parse_basic_auth 对 "Basic" 后无内容返回 None。
    #[test]
    fn parse_basic_auth_handles_basic_prefix_only() {
        // "Basic " 后无编码内容 → decode 空字符串 → 无冒号 → None
        assert!(parse_basic_auth("Basic ").is_none());
    }

    /// parse_basic_auth 对 "basic" 小写前缀返回 None(区分大小写)。
    #[test]
    fn parse_basic_auth_case_sensitive_prefix() {
        use base64::engine::general_purpose::STANDARD;
        use base64::Engine;
        let encoded = STANDARD.encode("cid:secret");
        assert!(parse_basic_auth(&format!("basic {}", encoded)).is_none());
        assert!(parse_basic_auth(&format!("BASIC {}", encoded)).is_none());
    }

    /// parse_basic_auth 对 "Bearer" 前缀返回 None。
    #[test]
    fn parse_basic_auth_rejects_bearer_prefix() {
        assert!(parse_basic_auth("Bearer Y2lkOnNlY3JldA==").is_none());
    }

    /// handle_with_authorization 使用 Basic Auth 头认证客户端。
    ///
    /// 场景:client_id/client_secret 通过 Authorization 头传递,body 中为空。
    /// 期望:认证成功,token 签发成功。
    #[tokio::test]
    async fn handle_with_authorization_uses_basic_auth() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("basic-auth-cid"))
            .await
            .unwrap();

        // "basic-auth-cid:secret-123" → base64
        let credentials = STANDARD.encode("basic-auth-cid:secret-123");
        let auth_header = format!("Basic {}", credentials);

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "".into(), // body 中为空,依赖 Basic Auth
            client_secret: "".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        let resp = handler
            .handle_with_authorization(&req, Some(&auth_header))
            .await
            .expect("Basic Auth 认证应成功");
        assert_eq!(resp.token_type, "Bearer");
        assert_eq!(resp.expires_in, 3600);
    }

    /// Basic Auth 头优先于 body 参数。
    ///
    /// 场景:Authorization 头含正确凭证,body 中含错误凭证。
    /// 期望:使用 Basic Auth 头的凭证认证成功(RFC 6749 §2.3.1 优先级)。
    #[tokio::test]
    async fn handle_with_authorization_basic_auth_overrides_body() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("override-cid"))
            .await
            .unwrap();

        let credentials = STANDARD.encode("override-cid:secret-123");
        let auth_header = format!("Basic {}", credentials);

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "override-cid".into(),
            client_secret: "WRONG-SECRET".into(), // body 中错误
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        let resp = handler
            .handle_with_authorization(&req, Some(&auth_header))
            .await
            .expect("Basic Auth 应优先,body 错误凭证被忽略");
        assert_eq!(resp.token_type, "Bearer");
    }

    /// 无 Basic Auth 头时使用 body 参数认证(RFC 6749 §2.3.1 允许两种传递方式)。
    #[tokio::test]
    async fn handle_with_authorization_falls_back_to_body() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("fallback-cid"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "fallback-cid".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        let resp = handler
            .handle_with_authorization(&req, None)
            .await
            .expect("body 参数认证应成功");
        assert_eq!(resp.token_type, "Bearer");
    }

    /// Basic Auth 头凭证错误时返回 invalid_client。
    #[tokio::test]
    async fn handle_with_authorization_basic_auth_wrong_secret() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("wrong-secret-cid"))
            .await
            .unwrap();

        let credentials = STANDARD.encode("wrong-secret-cid:WRONG");
        let auth_header = format!("Basic {}", credentials);

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "".into(),
            client_secret: "".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        let err = handler
            .handle_with_authorization(&req, Some(&auth_header))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("invalid_client"));
    }

    /// 既无 Basic Auth 头又无 body client_id 时返回 invalid_client。
    #[tokio::test]
    async fn handle_with_authorization_no_credentials_returns_error() {
        let (handler, _) = make_handler();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "".into(),
            client_secret: "".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        let err = handler
            .handle_with_authorization(&req, None)
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("invalid_client"),
            "无凭证应返回 invalid_client,实际: {}",
            err
        );
    }

    // unsupported_grant_type 测试

    #[tokio::test]
    async fn handle_unsupported_grant_type() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("c-gt"))
            .await
            .unwrap();
        let req = TokenRequest {
            grant_type: "implicit".into(),
            client_id: "c-gt".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("unsupported_grant_type"));
    }

    // authorization_code grant type 测试

    #[tokio::test]
    async fn handle_authorization_code_success() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("ac-001"))
            .await
            .unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "ac-001", verifier).await;

        let req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "ac-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let resp = handler.handle(&req).await.expect("签发 token");
        assert_eq!(resp.token_type, "Bearer");
        assert_eq!(resp.expires_in, 3600);
        assert!(!resp.access_token.is_empty());
        assert!(resp.refresh_token.is_some());
    }

    #[tokio::test]
    async fn handle_authorization_code_pkce_mismatch() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("ac-002"))
            .await
            .unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "ac-002", verifier).await;

        let req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "ac-002".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some("wrong-verifier-wrong-verifier-wrong-verifier-wrong".into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("PKCE"));
    }

    #[tokio::test]
    async fn handle_authorization_code_already_used() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("ac-003"))
            .await
            .unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "ac-003", verifier).await;

        let req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "ac-003".into(),
            client_secret: "secret-123".into(),
            code: Some(code.clone()),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        handler.handle(&req).await.expect("首次签发");
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("invalid_grant"));
    }

    // refresh_token grant type 测试

    #[tokio::test]
    async fn handle_refresh_token_success() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("rt-001"))
            .await
            .unwrap();

        // 先通过 authorization_code 获取 refresh_token
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rt-001", verifier).await;
        let req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rt-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let first_resp = handler.handle(&req).await.unwrap();
        let refresh_token = first_resp.refresh_token.clone().unwrap();

        let refresh_req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rt-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(refresh_token),
            scope: None,
            username: None,
            password: None,
        };
        let resp = handler.handle(&refresh_req).await.expect("刷新 token");
        assert_eq!(resp.token_type, "Bearer");
        assert_eq!(resp.expires_in, 3600);
        // refresh_token 轮换 — 应返回新 refresh_token
        assert!(
            resp.refresh_token.is_some(),
            "VULN-0009: 刷新应轮换返回新 refresh_token"
        );
        assert_ne!(
            resp.refresh_token.as_ref().unwrap(),
            first_resp.refresh_token.as_ref().unwrap(),
            "VULN-0009: 新 refresh_token 应与旧的不同(轮换)"
        );
    }

    #[tokio::test]
    async fn handle_refresh_token_invalid() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("rt-002"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rt-002".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some("invalid-token".into()),
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("invalid_grant"));
    }

    /// refresh_token 轮换后旧 token 被删除,重用返回 invalid_grant(authorization_code 取 old_token → 刷新得 new_token 并删除 old_token → 再用 old_token 刷新返回 invalid_grant)。
    #[tokio::test]
    async fn handle_refresh_token_rotation_deletes_old_token() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("rt-rot-001"))
            .await
            .unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rt-rot-001", verifier).await;
        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rt-rot-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.unwrap();
        let old_token = issue_resp.refresh_token.unwrap();

        let refresh_req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rt-rot-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(old_token.clone()),
            scope: None,
            username: None,
            password: None,
        };
        let refresh_resp = handler
            .handle(&refresh_req)
            .await
            .expect("第一次刷新应成功");
        let new_token = refresh_resp.refresh_token.unwrap();
        assert_ne!(&new_token, &old_token, "新 refresh_token 应与旧的不同");

        let err = handler.handle(&refresh_req).await.unwrap_err();
        assert!(
            err.to_string().contains("invalid_grant"),
            "VULN-0009: 重用已删除的旧 refresh_token 应返回 invalid_grant,实际: {}",
            err
        );
    }

    /// 并发刷新同一 refresh_token:get_and_delete 原子消费保证仅一个请求成功,
    /// 其余返回 invalid_grant(消除 get→校验→delete 的 TOCTOU 双花竞态)。
    #[tokio::test(flavor = "multi_thread")]
    async fn handle_refresh_token_concurrent_only_one_wins() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("rt-conc-001"))
            .await
            .unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rt-conc-001", verifier).await;
        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rt-conc-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.unwrap();
        let old_token = issue_resp.refresh_token.expect("应有 refresh_token");

        // 16 个并发任务用同一旧 refresh_token 刷新
        let handler = Arc::new(handler);
        let mut handles = Vec::new();
        for _ in 0..16 {
            let h = handler.clone();
            let t = old_token.clone();
            handles.push(tokio::spawn(async move {
                let req = TokenRequest {
                    grant_type: "refresh_token".into(),
                    client_id: "rt-conc-001".into(),
                    client_secret: "secret-123".into(),
                    code: None,
                    redirect_uri: None,
                    code_verifier: None,
                    refresh_token: Some(t),
                    scope: None,
                    username: None,
                    password: None,
                };
                h.handle(&req).await
            }));
        }
        let mut wins = 0usize;
        for h in handles {
            if h.await.unwrap().is_ok() {
                wins += 1;
            }
        }
        assert_eq!(
            wins, 1,
            "并发刷新同一 refresh_token 仅一个应成功(防双花),实际 {}",
            wins
        );
    }

    // client_credentials grant type 测试

    #[tokio::test]
    async fn handle_client_credentials_success() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("cc-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "cc-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("read".into()),
            username: None,
            password: None,
        };
        let resp = handler.handle(&req).await.expect("签发 token");
        assert_eq!(resp.token_type, "Bearer");
        assert_eq!(resp.expires_in, 3600);
        assert!(
            resp.refresh_token.is_none(),
            "client_credentials 不应返回 refresh_token"
        );
        assert_eq!(resp.scope.as_deref(), Some("read"));
    }

    #[tokio::test]
    async fn handle_client_credentials_grant_not_allowed() {
        let (handler, _) = make_handler();
        // 创建仅支持 authorization_code 的客户端
        let client = OAuth2Client::new(
            "cc-only-auth",
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![GrantType::AuthorizationCode],
            vec![],
        )
        .unwrap();
        handler.store.create(client).await.unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "cc-only-auth".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("unauthorized_client"));
    }

    // password grant type 测试

    #[tokio::test]
    async fn handle_password_success() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("pw-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("read".into()),
            username: Some("alice".into()),
            password: Some("wonderland".into()),
        };
        let resp = handler.handle(&req).await.expect("签发 token");
        assert_eq!(resp.token_type, "Bearer");
        assert!(resp.refresh_token.is_some());
        assert_eq!(resp.scope.as_deref(), Some("read"));
    }

    #[tokio::test]
    async fn handle_password_wrong_credentials() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("pw-002"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-002".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: Some("alice".into()),
            password: Some("wrong-password".into()),
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains("invalid_grant"));
    }

    /// 连续失败超过阈值后再尝试返回 rate_limited 错误(账户锁定):max_attempts=3 时前 3 次失败返回 invalid_grant,第 4 次尝试返回 rate_limited 且不调用 verifier。
    #[tokio::test]
    async fn handle_password_rate_limited_after_max_attempts() {
        let (handler, _) = make_handler_with_limiters(
            Arc::new(PasswordRateLimiter::new(3, 300)),
            Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
        );
        handler
            .store
            .create(make_full_client("pw-rl-001"))
            .await
            .unwrap();

        let wrong_req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-rl-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: Some("alice".into()),
            password: Some("wrong".into()),
        };

        // 前 3 次失败:返回 invalid_grant(凭据错误,未超阈值 max_attempts=3)
        for i in 0..3 {
            let err = handler.handle(&wrong_req).await.unwrap_err();
            assert!(
                err.to_string().contains("invalid_grant"),
                "第 {} 次失败应为 invalid_grant,实际: {}",
                i + 1,
                err
            );
        }

        // 第 4 次尝试:rate_limited(账户锁定)
        let err = handler.handle(&wrong_req).await.unwrap_err();
        assert!(
            err.to_string().contains("rate_limited"),
            "第 4 次尝试应为 rate_limited,实际: {}",
            err
        );
    }

    /// 成功登录后重置失败计数(max_attempts=3:2 次失败后 1 次成功重置,再 3 次失败未超阈值,第 4 次尝试 rate_limited)。
    #[tokio::test]
    async fn handle_password_rate_limit_resets_on_success() {
        let (handler, _) = make_handler_with_limiters(
            Arc::new(PasswordRateLimiter::new(3, 300)),
            Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
        );
        handler
            .store
            .create(make_full_client("pw-rl-002"))
            .await
            .unwrap();

        let wrong_req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-rl-002".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: Some("alice".into()),
            password: Some("wrong".into()),
        };

        let right_req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-rl-002".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: Some("alice".into()),
            password: Some("wonderland".into()),
        };

        for _ in 0..2 {
            let _ = handler.handle(&wrong_req).await.unwrap_err();
        }

        let resp = handler.handle(&right_req).await.expect("成功登录");
        assert_eq!(resp.token_type, "Bearer");

        for i in 0..3 {
            let err = handler.handle(&wrong_req).await.unwrap_err();
            assert!(
                err.to_string().contains("invalid_grant"),
                "重置后第 {} 次失败应为 invalid_grant,实际: {}",
                i + 1,
                err
            );
        }

        let err = handler.handle(&wrong_req).await.unwrap_err();
        assert!(
            err.to_string().contains("rate_limited"),
            "重置后第 4 次尝试应为 rate_limited,实际: {}",
            err
        );
    }

    /// `record_failure` 经 `limiteron::incr_with_ttl` 原子递增计数器:首次失败 count=1,后续递增不重置 TTL(窗口起点保持)。
    #[tokio::test]
    async fn password_rate_limiter_record_failure_increments_count() {
        let limiter = PasswordRateLimiter::new(5, 300);
        limiter.record_failure("alice").await;
        assert!(
            limiter.check("alice").await,
            "count=1 < max_attempts=5,应允许"
        );
        // 第 2、3 次失败:count 应分别为 2、3
        limiter.record_failure("alice").await;
        limiter.record_failure("alice").await;
        assert!(
            limiter.check("alice").await,
            "count=3 < max_attempts=5,应允许"
        );
        // 验证 entry_count 反映活跃 entry
        assert_eq!(limiter.entry_count().await, 1, "应仅 1 个 entry");
    }

    /// `check` 在失败次数达阈值时返回 `false`(账户锁定)。
    #[tokio::test]
    async fn password_rate_limiter_check_returns_false_at_threshold() {
        let limiter = PasswordRateLimiter::new(3, 300);
        // 3 次失败后,第 4 次 check 应返回 false
        limiter.record_failure("bob").await;
        limiter.record_failure("bob").await;
        limiter.record_failure("bob").await;
        // count=3 = max_attempts=3,应锁定
        assert!(
            !limiter.check("bob").await,
            "count=3 = max_attempts=3,应锁定(check 返回 false)"
        );
    }

    /// `check` 对未失败的 username 返回 `true`(无 entry = 未锁定)。
    #[tokio::test]
    async fn password_rate_limiter_check_passes_for_new_user() {
        let limiter = PasswordRateLimiter::new(3, 300);
        assert!(
            limiter.check("new-user").await,
            "未失败的 username 应允许尝试(check 返回 true)"
        );
        assert_eq!(limiter.entry_count().await, 0, "无失败记录时 entry_count=0");
    }

    /// `reset` 清除指定 username 的计数(验证成功后调用)。
    #[tokio::test]
    async fn password_rate_limiter_reset_clears_counter() {
        let limiter = PasswordRateLimiter::new(3, 300);
        limiter.record_failure("carol").await;
        limiter.record_failure("carol").await;
        assert_eq!(limiter.entry_count().await, 1, "失败 2 次后应有 1 个 entry");
        limiter.reset("carol").await;
        assert_eq!(limiter.entry_count().await, 0, "reset 后应无 entry");
        // reset 后再次失败应从 1 开始(而非继续累加)
        limiter.record_failure("carol").await;
        assert!(
            limiter.check("carol").await,
            "reset 后重新计数,count=1 < max_attempts=3,应允许"
        );
    }

    /// 不同 username 的计数器相互独立(验证 per-username 维度隔离)。
    #[tokio::test]
    async fn password_rate_limiter_users_are_independent() {
        let limiter = PasswordRateLimiter::new(2, 300);
        // alice 失败 2 次(达阈值,锁定)
        limiter.record_failure("alice").await;
        limiter.record_failure("alice").await;
        assert!(!limiter.check("alice").await, "alice 应被锁定");
        // bob 未失败,应允许
        assert!(limiter.check("bob").await, "bob 应允许(独立计数器)");
        assert_eq!(limiter.entry_count().await, 1, "应仅 alice 1 个 entry");
    }

    /// `max_attempts=0` 会被 clamp 到 1(避免所有请求被锁)。
    #[tokio::test]
    async fn password_rate_limiter_max_attempts_zero_clamps_to_one() {
        let limiter = PasswordRateLimiter::new(0, 300);
        // max_attempts 被 clamp 到 1,首次失败后即锁定
        limiter.record_failure("dave").await;
        // count=1 = max_attempts=1(clamped),应锁定
        assert!(
            !limiter.check("dave").await,
            "max_attempts=0 被 clamp 到 1,首次失败后应锁定"
        );
    }

    // OAuth2 scope 校验测试

    /// client_credentials 请求超出 allowed_scopes 的 scope 返回 invalid_scope。
    /// make_full_client 的 allowed_scopes = ["read", "write"],请求 "admin" 应被拒绝。
    #[tokio::test]
    async fn handle_client_credentials_scope_not_allowed() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("cc-scope-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "cc-scope-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("admin".into()),
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(
            err.to_string().contains(&crate::i18n::translate_detail(
                "oauth2-server-client-invalid-scope",
                &[("arg0", "admin")],
            )),
            "期望 invalid-scope 错误,实际: {}",
            err
        );
    }

    /// client_credentials 请求部分 scope 超出 allowed_scopes 也应拒绝。
    /// 请求 "read admin"(read 合法,admin 不合法)应返回 invalid_scope。
    #[tokio::test]
    async fn handle_client_credentials_partial_scope_not_allowed() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("cc-scope-002"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "cc-scope-002".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("read admin".into()),
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(err.to_string().contains(&crate::i18n::translate_detail(
            "oauth2-server-client-invalid-scope",
            &[("arg0", "admin")],
        )));
    }

    /// password grant 请求超出 allowed_scopes 的 scope 返回 invalid_scope。
    #[tokio::test]
    async fn handle_password_scope_not_allowed() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("pw-scope-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-scope-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("admin".into()),
            username: Some("alice".into()),
            password: Some("wonderland".into()),
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(
            err.to_string().contains(&crate::i18n::translate_detail(
                "oauth2-server-client-invalid-scope",
                &[("arg0", "admin")],
            )),
            "期望 invalid-scope 错误,实际: {}",
            err
        );
    }

    /// 空 allowed_scopes 的客户端 fail-closed:任意 scope 请求被拒。
    #[tokio::test]
    async fn handle_client_credentials_empty_allowed_scopes_fail_closed() {
        let (handler, _) = make_handler();
        // 空 allowed_scopes = 不允许任何 scope(fail-closed;需显式配置或用 ["*"])
        let client = OAuth2Client::new(
            "cc-empty-scopes",
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![GrantType::ClientCredentials],
            vec![],
        )
        .unwrap();
        handler.store.create(client).await.unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "cc-empty-scopes".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("any-scope".into()),
            username: None,
            password: None,
        };
        let err = handler.handle(&req).await.unwrap_err();
        assert!(
            err.to_string().contains(&crate::i18n::translate_detail(
                "oauth2-server-client-invalid-scope",
                &[("arg0", "any-scope")],
            )),
            "空 allowed_scopes 应拒绝任意 scope(fail-closed),实际: {}",
            err
        );
    }

    /// allowed_scopes = ["*"] 通配允许任意 scope(替代旧空列表语义)。
    #[tokio::test]
    async fn handle_client_credentials_wildcard_scope_allows_any() {
        let (handler, _) = make_handler();
        let client = OAuth2Client::new(
            "cc-wildcard-scopes",
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![GrantType::ClientCredentials],
            vec!["*".into()],
        )
        .unwrap();
        handler.store.create(client).await.unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "cc-wildcard-scopes".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("any-scope".into()),
            username: None,
            password: None,
        };
        let resp = handler
            .handle(&req)
            .await
            .expect("通配 allowed_scopes 应允许任意 scope");
        assert_eq!(resp.scope.as_deref(), Some("any-scope"));
    }

    // revoke / introspect 辅助方法测试

    #[tokio::test]
    async fn get_access_token_record_after_issue() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("rec-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "rec-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: Some("read write".into()),
            username: None,
            password: None,
        };
        let resp = handler.handle(&req).await.unwrap();

        let record = handler
            .get_access_token_record(&resp.access_token)
            .await
            .unwrap()
            .expect("应存在");
        assert_eq!(record.client_id, "rec-001");
        assert!(record.user_id.is_none(), "client_credentials 无 user_id");
        assert_eq!(record.scopes, vec!["read", "write"]);
        assert_eq!(record.token_type, "access");
    }

    #[tokio::test]
    async fn revoke_token_makes_it_inaccessible() {
        let (handler, _) = make_handler();
        handler
            .store
            .create(make_full_client("rev-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "rev-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let resp = handler.handle(&req).await.unwrap();

        // 撤销前:存在
        assert!(handler
            .get_access_token_record(&resp.access_token)
            .await
            .unwrap()
            .is_some());

        handler.revoke_token(&resp.access_token).await.unwrap();

        // 撤销后:不存在
        assert!(handler
            .get_access_token_record(&resp.access_token)
            .await
            .unwrap()
            .is_none());
    }

    #[test]
    fn generate_token_produces_unique() {
        let t1 = generate_token();
        let t2 = generate_token();
        assert_ne!(t1, t2);
        assert!(t1.len() >= 43);
    }

    /// `TokenRateLimiter::new()` 使用默认配置(10 req/s per-client + 5 req/min per-username)。
    #[test]
    fn token_rate_limiter_new_uses_defaults() {
        let limiter = TokenRateLimiter::new();
        assert_eq!(limiter.client_max, 10);
        assert_eq!(limiter.client_window_secs, 1);
        assert_eq!(limiter.username_max, 5);
        assert_eq!(limiter.username_window_secs, 60);
    }

    /// `Default::default()` 与 `new()` 等价。
    #[test]
    fn token_rate_limiter_default_equals_new() {
        let limiter = TokenRateLimiter::default();
        assert_eq!(limiter.client_max, 10);
        assert_eq!(limiter.username_max, 5);
    }

    /// `with_limits(0, 0, 0, 0)` 被 clamp 到 (1, 1, 1, 1),避免 max=0 导致全部被拒。
    #[test]
    fn token_rate_limiter_with_limits_zero_clamps_to_one() {
        let limiter = TokenRateLimiter::with_limits(0, 0, 0, 0);
        assert_eq!(limiter.client_max, 1);
        assert_eq!(limiter.client_window_secs, 1);
        assert_eq!(limiter.username_max, 1);
        assert_eq!(limiter.username_window_secs, 1);
    }

    /// `PasswordRateLimiter::check` DAO 故障(计数器值损坏)时 fail-closed 拒绝。
    #[tokio::test]
    async fn password_rate_limiter_check_fails_closed_on_dao_error() {
        let dao = Arc::new(InMemoryDao::new());
        // 注入非数字计数器值,模拟 DAO 数据/通信故障
        dao.set("rate_limit:pw:alice", "not-a-number", 60)
            .await
            .unwrap();
        let limiter = PasswordRateLimiter {
            limiter: GarrisonDaoDistributedLimiter::new(dao.clone()),
            dao,
            max_attempts: 5,
            window_seconds: 60,
        };
        assert!(
            !limiter.check("alice").await,
            "DAO 故障时应拒绝本次密码校验(fail-closed,防绕过撞库锁定)"
        );
    }

    /// DAO 故障时 `check_username`(撞库防护)fail-closed、`check_client`(QPS 防滥用)fail-open。
    #[tokio::test]
    async fn token_rate_limiter_dao_error_applies_different_fail_strategies() {
        let dao = Arc::new(InMemoryDao::new());
        dao.set("rate_limit:token:user:bob", "corrupt", 60)
            .await
            .unwrap();
        dao.set("rate_limit:token:client:c1", "corrupt", 60)
            .await
            .unwrap();
        let limiter = TokenRateLimiter {
            limiter: GarrisonDaoDistributedLimiter::new(dao.clone()),
            client_max: 10,
            client_window_secs: 1,
            username_max: 5,
            username_window_secs: 60,
        };
        assert!(
            !limiter.check_username("bob").await,
            "username 维度应 fail-closed(撞库防护不允许故障放行)"
        );
        assert!(
            limiter.check_client("c1").await,
            "client QPS 维度应保持 fail-open(可用性优先)"
        );
    }

    /// per-client_id 限速:前 N 次允许,第 N+1 次拒绝。
    #[tokio::test]
    async fn token_rate_limiter_check_client_allows_within_limit() {
        let limiter = TokenRateLimiter::with_limits(3, 60, 100, 60);
        for i in 0..3 {
            assert!(
                limiter.check_client("client-A").await,
                "第 {} 次应允许",
                i + 1
            );
        }
        assert!(
            !limiter.check_client("client-A").await,
            "第 4 次应拒绝(超 client_max=3)"
        );
    }

    /// per-client_id 隔离:不同 client_id 独立计数。
    #[tokio::test]
    async fn token_rate_limiter_check_client_isolates_clients() {
        let limiter = TokenRateLimiter::with_limits(2, 60, 100, 60);
        assert!(limiter.check_client("client-A").await);
        assert!(limiter.check_client("client-A").await);
        assert!(!limiter.check_client("client-A").await, "client-A 达上限");
        // client-B 独立计数,仍允许
        assert!(
            limiter.check_client("client-B").await,
            "client-B 应允许(独立计数器)"
        );
    }

    /// per-username 限速:前 N 次允许,第 N+1 次拒绝。
    #[tokio::test]
    async fn token_rate_limiter_check_username_allows_within_limit() {
        let limiter = TokenRateLimiter::with_limits(100, 60, 3, 60);
        for i in 0..3 {
            assert!(
                limiter.check_username("alice").await,
                "第 {} 次应允许",
                i + 1
            );
        }
        assert!(
            !limiter.check_username("alice").await,
            "第 4 次应拒绝(超 username_max=3)"
        );
    }

    /// per-username 隔离:不同 username 独立计数。
    #[tokio::test]
    async fn token_rate_limiter_check_username_isolates_users() {
        let limiter = TokenRateLimiter::with_limits(100, 60, 2, 60);
        assert!(limiter.check_username("alice").await);
        assert!(limiter.check_username("alice").await);
        assert!(!limiter.check_username("alice").await, "alice 达上限");
        // bob 独立计数
        assert!(
            limiter.check_username("bob").await,
            "bob 应允许(独立计数器)"
        );
    }

    /// `handle_with_authorization` per-client_id 限速:超阈值后返回 rate_limited。
    ///
    /// client_max=2,前 2 次 client_credentials grant 成功,第 3 次被限速。
    #[tokio::test]
    async fn handle_with_authorization_rate_limited_after_client_threshold() {
        let (handler, _) = make_handler_with_limiters(
            Arc::new(PasswordRateLimiter::new(1000, 300)),
            Arc::new(TokenRateLimiter::with_limits(2, 60, 100, 60)),
        );
        handler
            .store
            .create(make_full_client("rl-cid"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "rl-cid".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        for i in 0..2 {
            let resp = handler.handle(&req).await;
            assert!(resp.is_ok(), "第 {} 次应成功,实际: {:?}", i + 1, resp);
        }

        // 第 3 次被 per-client_id 限速
        let err = handler.handle(&req).await.unwrap_err();
        assert!(
            err.to_string().contains("rate_limited"),
            "第 3 次应被限速,实际: {}",
            err
        );
    }

    /// per-client_id 限速通过 Basic Auth 头提取 client_id(body 中 client_id 为空时)。
    #[tokio::test]
    async fn handle_with_authorization_rate_limits_by_basic_auth_client_id() {
        let (handler, _) = make_handler_with_limiters(
            Arc::new(PasswordRateLimiter::new(1000, 300)),
            Arc::new(TokenRateLimiter::with_limits(1, 60, 100, 60)),
        );
        handler
            .store
            .create(make_full_client("ba-rl"))
            .await
            .unwrap();

        let credentials = STANDARD.encode("ba-rl:secret-123");
        let auth_header = format!("Basic {}", credentials);

        let req = TokenRequest {
            grant_type: "client_credentials".into(),
            client_id: "".into(), // body 中为空,依赖 Basic Auth
            client_secret: "".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };

        let _ = handler
            .handle_with_authorization(&req, Some(&auth_header))
            .await
            .expect("第 1 次应成功");

        // 第 2 次被限速(通过 Basic Auth 提取的 client_id 限速)
        let err = handler
            .handle_with_authorization(&req, Some(&auth_header))
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("rate_limited"),
            "第 2 次应被限速(Basic Auth client_id),实际: {}",
            err
        );
    }

    /// `handle_password` per-username 限速:超阈值后返回 rate_limited。
    ///
    /// username_max=2,前 2 次成功登录,第 3 次被 per-username 限速。
    #[tokio::test]
    async fn handle_password_rate_limited_after_username_threshold() {
        let (handler, _) = make_handler_with_limiters(
            Arc::new(PasswordRateLimiter::new(1000, 300)),
            Arc::new(TokenRateLimiter::with_limits(100, 60, 2, 60)),
        );
        handler
            .store
            .create(make_full_client("pw-url-001"))
            .await
            .unwrap();

        let req = TokenRequest {
            grant_type: "password".into(),
            client_id: "pw-url-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: None,
            scope: None,
            username: Some("alice".into()),
            password: Some("wonderland".into()),
        };

        for i in 0..2 {
            let resp = handler.handle(&req).await;
            assert!(resp.is_ok(), "第 {} 次应成功,实际: {:?}", i + 1, resp);
        }

        // 第 3 次被 per-username 限速
        let err = handler.handle(&req).await.unwrap_err();
        assert!(
            err.to_string().contains("rate_limited"),
            "第 3 次应被 per-username 限速,实际: {}",
            err
        );
    }
}

#[cfg(all(test, feature = "db-sqlite"))]
mod refresh_rotation_tests {
    use super::*;
    use crate::dao::{init_dbnexus, GarrisonMigration};
    use crate::oauth2_server::authorize::AuthorizeHandler;
    use crate::oauth2_server::client::{DaoOAuth2ClientStore, GrantType, OAuth2Client};
    use crate::protocol::jwt::refresh::RefreshTokenRotation;
    use crate::protocol::jwt::JwtHandler;
    use dbnexus::DbPool;
    use std::path::PathBuf;
    use std::sync::{Arc, RwLock};

    /// 定位项目根目录的 migrations/sqlite/ 目录。
    fn project_migrations_dir() -> PathBuf {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        PathBuf::from(manifest_dir)
            .join("migrations")
            .join("sqlite")
    }

    /// 创建并初始化 SQLite in-memory 数据库。
    async fn setup_db() -> DbPool {
        let pool = init_dbnexus("sqlite::memory:")
            .await
            .expect("init_dbnexus 应成功");
        let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
        migration.migrate_core().await.expect("migrate_core 应成功");
        pool
    }

    /// 创建测试用 PasswordVerifier。
    struct TestPasswordVerifier;
    #[async_trait]
    impl PasswordVerifier for TestPasswordVerifier {
        async fn verify(&self, username: &str, password: &str) -> GarrisonResult<Option<i64>> {
            if username == "alice" && password == "wonderland" {
                Ok(Some(5001))
            } else {
                Ok(None)
            }
        }
    }

    /// 创建注入 RefreshTokenRotation 的 TokenHandler。
    async fn make_handler_with_rotation() -> TokenHandler {
        let pool = setup_db().await;
        let dao = Arc::new(crate::dao::InMemoryDao::new());
        let store = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
        let authorize_handler = Arc::new(AuthorizeHandler::new(
            store.clone(),
            dao.clone(),
            "https://auth.example.com/login".into(),
        ));
        let jwt_handler = Arc::new(JwtHandler::new("test_secret_that_is_at_least_32_bytes"));
        let rotation = Arc::new(RefreshTokenRotation::new(
            pool,
            jwt_handler,
            Arc::new(RwLock::new(1)),
        ));
        TokenHandler::new(
            store,
            dao,
            authorize_handler,
            Arc::new(PasswordRateLimiter::new(1000, 300)),
            Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
        )
        .with_password_verifier(Arc::new(TestPasswordVerifier))
        .with_refresh_rotation(rotation)
    }

    /// 创建未注入 RefreshTokenRotation 的 TokenHandler(fallback 路径)。
    fn make_handler_without_rotation() -> TokenHandler {
        let dao = Arc::new(crate::dao::InMemoryDao::new());
        let store = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
        let authorize_handler = Arc::new(AuthorizeHandler::new(
            store.clone(),
            dao.clone(),
            "https://auth.example.com/login".into(),
        ));
        TokenHandler::new(
            store,
            dao,
            authorize_handler,
            Arc::new(PasswordRateLimiter::new(1000, 300)),
            Arc::new(TokenRateLimiter::with_limits(100_000, 60, 100_000, 60)),
        )
        .with_password_verifier(Arc::new(TestPasswordVerifier))
    }

    /// 创建支持所有 grant type 的客户端。
    fn make_full_client(id: &str) -> OAuth2Client {
        OAuth2Client::new(
            id,
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![
                GrantType::AuthorizationCode,
                GrantType::RefreshToken,
                GrantType::ClientCredentials,
                GrantType::Password,
            ],
            vec!["read".into(), "write".into()],
        )
        .unwrap()
    }

    /// 通过 authorize 端点获取授权码。
    async fn get_auth_code(handler: &TokenHandler, client_id: &str, verifier: &str) -> String {
        let challenge = crate::oauth2_server::authorize::generate_code_challenge(verifier);
        let req = crate::oauth2_server::authorize::AuthorizeRequest {
            response_type: "code".into(),
            client_id: client_id.into(),
            redirect_uri: "https://app.example.com/cb".into(),
            scope: Some("read".into()),
            state: Some("xyz".into()),
            code_challenge: challenge,
            code_challenge_method: "S256".into(),
            prompt: None,
        };
        let resp = handler
            .authorize_handler
            .authorize(&req, Some(1001))
            .await
            .unwrap();
        match resp {
            crate::oauth2_server::authorize::AuthorizeResponse::Redirect { location } => location
                .split("code=")
                .nth(1)
                .unwrap()
                .split('&')
                .next()
                .unwrap()
                .to_string(),
            _ => panic!("期望 Redirect"),
        }
    }

    /// `TokenHandler::with_refresh_rotation` 构造成功。
    #[tokio::test(flavor = "multi_thread")]
    async fn token_handler_with_refresh_rotation() {
        let handler = make_handler_with_rotation().await;
        assert!(
            handler.refresh_rotation.is_some(),
            "注入后 refresh_rotation 应为 Some"
        );
    }

    /// 注入 rotation 后,authorization_code grant 签发的 refresh_token 存在于 refresh_tokens 表。
    #[tokio::test(flavor = "multi_thread")]
    async fn issue_tokens_with_rotation_uses_issue_method() {
        let handler = make_handler_with_rotation().await;
        let client = make_full_client("rot-auth-001");
        handler
            .store
            .create(client.clone())
            .await
            .expect("create client 应成功");

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rot-auth-001", verifier).await;

        let req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rot-auth-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let resp = handler.handle(&req).await.expect("token 签发应成功");
        assert!(resp.refresh_token.is_some(), "应返回 refresh_token");

        let rotation = handler.refresh_rotation.as_ref().unwrap();
        let record = rotation
            .validate(resp.refresh_token.as_ref().unwrap())
            .await
            .expect("validate 应成功");
        assert!(record.is_some(), "refresh_token 应在 refresh_tokens 表中");
        let record = record.unwrap();
        assert_eq!(record.client_id, Some("rot-auth-001".to_string()));
    }

    /// 注入 rotation 后,refresh_token grant type 返回新 refresh_token(轮换)。
    #[tokio::test(flavor = "multi_thread")]
    async fn handle_refresh_token_with_rotation_rotates() {
        let handler = make_handler_with_rotation().await;
        let client = make_full_client("rot-refresh-001");
        handler.store.create(client.clone()).await.unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rot-refresh-001", verifier).await;

        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rot-refresh-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.unwrap();
        let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");

        let refresh_req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rot-refresh-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(old_refresh.clone()),
            scope: None,
            username: None,
            password: None,
        };
        let refresh_resp = handler.handle(&refresh_req).await.expect("refresh 应成功");
        assert!(
            refresh_resp.refresh_token.is_some(),
            "轮换后应返回新 refresh_token"
        );
        assert_ne!(
            refresh_resp.refresh_token.as_ref().unwrap(),
            &old_refresh,
            "新 refresh_token 应与旧的不同(轮换)"
        );
    }

    /// reuse detection — 同一 refresh_token 两次使用,第二次返回 TokenRevoked。
    #[tokio::test(flavor = "multi_thread")]
    async fn handle_refresh_token_reuse_detection() {
        let handler = make_handler_with_rotation().await;
        let client = make_full_client("rot-reuse-001");
        handler.store.create(client.clone()).await.unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rot-reuse-001", verifier).await;

        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rot-reuse-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.unwrap();
        let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");

        let refresh_req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rot-reuse-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(old_refresh.clone()),
            scope: None,
            username: None,
            password: None,
        };
        let _first = handler
            .handle(&refresh_req)
            .await
            .expect("第一次 refresh 应成功");

        // 第二次 refresh(重用):应返回 TokenRevoked
        let result = handler.handle(&refresh_req).await;
        assert!(
            matches!(&result, Err(GarrisonError::TokenRevoked(_))),
            "重用已消费的 refresh token 应返回 TokenRevoked,实际: {:?}",
            result
        );
    }

    /// revoke_token 必须能撤销 rotation 路径签发的 refresh token:
    /// 该路径的 refresh token 存 SQLite refresh_tokens 表(DAO 无对应键),
    /// 仅删 DAO 两前缀对其无效。
    #[tokio::test(flavor = "multi_thread")]
    async fn revoke_token_revokes_rotation_refresh_token() {
        let handler = make_handler_with_rotation().await;
        let client = make_full_client("rot-revoke-001");
        handler.store.create(client.clone()).await.unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rot-revoke-001", verifier).await;
        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rot-revoke-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.unwrap();
        let refresh_token = issue_resp.refresh_token.expect("应有 refresh_token");

        let rotation = handler.refresh_rotation.as_ref().unwrap();
        assert!(rotation.validate(&refresh_token).await.unwrap().is_some());

        handler.revoke_token(&refresh_token).await.unwrap();

        assert!(
            rotation.validate(&refresh_token).await.unwrap().is_none(),
            "revoke_token 应撤销 rotation 路径签发的 refresh token"
        );
        let refresh_req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rot-revoke-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(refresh_token),
            scope: None,
            username: None,
            password: None,
        };
        let err = handler.handle(&refresh_req).await.unwrap_err();
        assert!(
            err.to_string().contains("invalid_grant") || err.to_string().contains("revoke"),
            "已撤销的 refresh token 不得再刷新,实际: {}",
            err
        );
    }

    /// fallback: 未注入 rotation 时退化为 DAO 路径(轮换 + 删除旧 token)。
    #[tokio::test(flavor = "multi_thread")]
    async fn handle_refresh_token_without_rotation_fallback() {
        let handler = make_handler_without_rotation();
        let client = make_full_client("rot-fallback-001");
        handler.store.create(client.clone()).await.unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rot-fallback-001", verifier).await;

        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rot-fallback-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.unwrap();
        let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");

        // 使用 refresh_token 刷新(fallback 路径轮换 + 删除旧 token)
        let refresh_req = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rot-fallback-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(old_refresh.clone()),
            scope: None,
            username: None,
            password: None,
        };
        let refresh_resp = handler.handle(&refresh_req).await.expect("refresh 应成功");
        // fallback 路径现在轮换 — 应返回新 refresh_token
        assert!(
            refresh_resp.refresh_token.is_some(),
            "VULN-0009: Fallback 路径应轮换返回新 refresh_token"
        );
        assert_ne!(
            refresh_resp.refresh_token.as_ref().unwrap(),
            &old_refresh,
            "VULN-0009: 新 refresh_token 应与旧的不同"
        );

        // 旧 refresh_token 应已删除,重用返回 invalid_grant
        let reuse_err = handler.handle(&refresh_req).await.unwrap_err();
        assert!(
            reuse_err.to_string().contains("invalid_grant"),
            "VULN-0009: 重用旧 refresh_token 应返回 invalid_grant,实际: {}",
            reuse_err
        );
    }

    /// 端到端集成测试 — authorization_code → refresh → reuse detection → revoke_chain(token1 轮换 token2 再轮换 token3,重用 token1 触发 revoke_chain,token1/token2 revoked=1、token3 仍有效)。
    #[tokio::test(flavor = "multi_thread")]
    async fn oauth2_full_flow_with_refresh_rotation() {
        let handler = make_handler_with_rotation().await;
        let client = make_full_client("rot-e2e-001");
        handler.store.create(client.clone()).await.unwrap();

        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let code = get_auth_code(&handler, "rot-e2e-001", verifier).await;
        let issue_req = TokenRequest {
            grant_type: "authorization_code".into(),
            client_id: "rot-e2e-001".into(),
            client_secret: "secret-123".into(),
            code: Some(code),
            redirect_uri: Some("https://app.example.com/cb".into()),
            code_verifier: Some(verifier.into()),
            refresh_token: None,
            scope: None,
            username: None,
            password: None,
        };
        let issue_resp = handler.handle(&issue_req).await.expect("签发 token");
        let token1 = issue_resp.refresh_token.expect("应有 refresh_token");

        let refresh_req_1 = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rot-e2e-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(token1.clone()),
            scope: None,
            username: None,
            password: None,
        };
        let resp1 = handler
            .handle(&refresh_req_1)
            .await
            .expect("第一次 refresh");
        let token2 = resp1.refresh_token.expect("应返回新 refresh_token");
        assert_ne!(&token2, &token1, "token2 应与 token1 不同");

        let refresh_req_2 = TokenRequest {
            grant_type: "refresh_token".into(),
            client_id: "rot-e2e-001".into(),
            client_secret: "secret-123".into(),
            code: None,
            redirect_uri: None,
            code_verifier: None,
            refresh_token: Some(token2.clone()),
            scope: None,
            username: None,
            password: None,
        };
        let resp2 = handler
            .handle(&refresh_req_2)
            .await
            .expect("第二次 refresh");
        let token3 = resp2.refresh_token.expect("应返回新 refresh_token");
        assert_ne!(&token3, &token2, "token3 应与 token2 不同");

        let reuse_result = handler.handle(&refresh_req_1).await;
        assert!(
            matches!(&reuse_result, Err(GarrisonError::TokenRevoked(_))),
            "重用 token1 应返回 TokenRevoked,实际: {:?}",
            reuse_result
        );

        // 验证整条链 token1 / token2 / token3 均已 revoked:revoke_chain 撤销给定 token 及其所有子代(安全最佳实践:泄露一个即吊销全部)
        let rotation = handler.refresh_rotation.as_ref().unwrap();
        let token1_record = rotation.validate(&token1).await.expect("validate token1");
        assert!(
            token1_record.is_none(),
            "token1 应已 revoked(validate 返回 None)"
        );
        let token2_record = rotation.validate(&token2).await.expect("validate token2");
        assert!(
            token2_record.is_none(),
            "token2 应已 revoked(链式撤销子代,validate 返回 None)"
        );
        let token3_record = rotation.validate(&token3).await.expect("validate token3");
        assert!(
            token3_record.is_none(),
            "token3 应已 revoked(链式撤销孙代,validate 返回 None)"
        );
    }

    /// 进程内日志捕获 writer(fmt Layer 的 MakeWriter,收集格式化行)。
    #[derive(Clone)]
    struct LogCapture(Arc<std::sync::Mutex<Vec<String>>>);

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogCapture {
        type Writer = LogCaptureWriter;
        fn make_writer(&'a self) -> Self::Writer {
            LogCaptureWriter(self.0.clone())
        }
    }

    struct LogCaptureWriter(Arc<std::sync::Mutex<Vec<String>>>);

    impl std::io::Write for LogCaptureWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0
                .lock()
                .expect("日志缓冲锁应可用")
                .push(String::from_utf8_lossy(buf).to_string());
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// 退化 refresh(未注入 rotation)必须输出结构性 warn:含 reuse detection
    /// 不可用后果说明;同时 has_refresh_rotation 探针为 false(对照:注入后为
    /// true 且不告警)。
    #[test]
    fn degraded_refresh_emits_structured_warning() {
        use tracing_subscriber::layer::SubscriberExt;
        use tracing_subscriber::util::SubscriberInitExt;

        let logs = LogCapture(Arc::new(std::sync::Mutex::new(Vec::new())));
        let subscriber = tracing_subscriber::registry().with(
            tracing_subscriber::fmt::layer()
                .with_ansi(false)
                .with_writer(logs.clone()),
        );

        // 单线程 runtime + with_default:保证 warn 事件落在捕获订阅者内
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime 构建应成功");

        let _guard = subscriber.set_default();
        let logs_value = rt.block_on(async {
            let handler = make_handler_without_rotation();
            // 对照探针:未注入 → false
            assert!(
                !handler.has_refresh_rotation(),
                "未注入 rotation 时探针应为 false"
            );

            let handler = handler.with_password_verifier(Arc::new(TestPasswordVerifier));
            let client = make_full_client("rot-degraded-warn-001");
            handler.store.create(client).await.unwrap();

            // password grant 签发(带 refresh_token)
            let issue_req = TokenRequest {
                grant_type: "password".into(),
                client_id: "rot-degraded-warn-001".into(),
                client_secret: "secret-123".into(),
                code: None,
                redirect_uri: None,
                code_verifier: None,
                refresh_token: None,
                scope: None,
                username: Some("alice".into()),
                password: Some("wonderland".into()),
            };
            let issue_resp = handler
                .handle(&issue_req)
                .await
                .expect("password 签发应成功");
            let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");

            // 退化路径 refresh(rotation 未注入 → DAO fallback + warn)
            let refresh_req = TokenRequest {
                grant_type: "refresh_token".into(),
                client_id: "rot-degraded-warn-001".into(),
                client_secret: "secret-123".into(),
                code: None,
                redirect_uri: None,
                code_verifier: None,
                refresh_token: Some(old_refresh),
                scope: None,
                username: None,
                password: None,
            };
            handler
                .handle(&refresh_req)
                .await
                .expect("退化路径 refresh 应成功(行为降级非功能损坏)");

            logs.0.lock().expect("日志缓冲锁应可用").clone()
        });

        // 期望文案按当前 locale 取值(同 backchannel deliver 断言),避免系统语言探测差异
        let degraded_warn =
            crate::i18n::translate_detail("logs-oauth2-refresh-rotation-not-configured", &[]);
        let degraded_warns: Vec<&String> = logs_value
            .iter()
            .filter(|l| l.contains(&degraded_warn))
            .collect();
        assert_eq!(
            degraded_warns.len(),
            1,
            "单次降级刷新应恰好输出一条退化 warn,日志: {:?}",
            logs_value
        );
    }

    /// 注入 rotation 后(对照):同一流程不再输出退化 warn,探针为 true。
    #[test]
    fn rotation_injected_refresh_emits_no_degraded_warning() {
        use tracing_subscriber::layer::SubscriberExt;
        use tracing_subscriber::util::SubscriberInitExt;

        let logs = LogCapture(Arc::new(std::sync::Mutex::new(Vec::new())));
        let subscriber = tracing_subscriber::registry().with(
            tracing_subscriber::fmt::layer()
                .with_ansi(false)
                .with_writer(logs.clone()),
        );

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime 构建应成功");

        let _guard = subscriber.set_default();
        let logs_value = rt.block_on(async {
            let handler = make_handler_with_rotation().await;
            assert!(
                handler.has_refresh_rotation(),
                "注入 rotation 后探针应为 true"
            );
            let handler = handler.with_password_verifier(Arc::new(TestPasswordVerifier));
            let client = make_full_client("rot-warn-clean-001");
            handler.store.create(client).await.unwrap();

            let issue_req = TokenRequest {
                grant_type: "password".into(),
                client_id: "rot-warn-clean-001".into(),
                client_secret: "secret-123".into(),
                code: None,
                redirect_uri: None,
                code_verifier: None,
                refresh_token: None,
                scope: None,
                username: Some("alice".into()),
                password: Some("wonderland".into()),
            };
            let issue_resp = handler
                .handle(&issue_req)
                .await
                .expect("password 签发应成功");
            let old_refresh = issue_resp.refresh_token.expect("应有 refresh_token");

            let refresh_req = TokenRequest {
                grant_type: "refresh_token".into(),
                client_id: "rot-warn-clean-001".into(),
                client_secret: "secret-123".into(),
                code: None,
                redirect_uri: None,
                code_verifier: None,
                refresh_token: Some(old_refresh),
                scope: None,
                username: None,
                password: None,
            };
            handler
                .handle(&refresh_req)
                .await
                .expect("统一路径 refresh 应成功");

            logs.0.lock().expect("日志缓冲锁应可用").clone()
        });

        // 期望文案按当前 locale 取值(同上),避免系统语言探测差异令断言只对英文成立
        let degraded_warn =
            crate::i18n::translate_detail("logs-oauth2-refresh-rotation-not-configured", &[]);
        assert!(
            !logs_value.iter().any(|l| l.contains(&degraded_warn)),
            "注入 rotation 后不得输出退化 warn,日志: {:?}",
            logs_value
        );
    }
}