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

use super::*;
use crate::backend::types::LoginParams;
use crate::error::GarrisonError;
#[cfg(feature = "oauth2-server")]
use crate::GarrisonDao;
use crate::GarrisonResult;
use async_trait::async_trait;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;

/// 测试用 Mock AuthBackend。
struct MockAuthBackend;

#[async_trait]
impl AuthBackend for MockAuthBackend {
    async fn login(&self, login_id: &str, _params: &LoginParams) -> GarrisonResult<String> {
        Ok(format!("token-{}", login_id))
    }
    async fn logout(&self, _token: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn check_login(&self, token: &str) -> GarrisonResult<bool> {
        Ok(token.starts_with("token-"))
    }
    async fn check_permission(&self, _token: &str, _permission: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn check_role(&self, _token: &str, _role: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn check_safe(&self, _token: &str) -> GarrisonResult<bool> {
        Ok(false)
    }
    async fn check_disable(&self, _token: &str) -> GarrisonResult<bool> {
        Ok(false)
    }
    async fn check_api_key(&self, _api_key: &str, _namespace: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn get_token_info(
        &self,
        token: &str,
    ) -> GarrisonResult<crate::backend::types::TokenInfo> {
        Ok(crate::backend::types::TokenInfo {
            token: token.to_string(),
            created_at: 1000,
            last_active_at: 2000,
        })
    }
    async fn get_session(&self, token: &str) -> GarrisonResult<crate::backend::types::SessionData> {
        Ok(crate::backend::types::SessionData {
            token: token.to_string(),
            login_id: "mock-user".to_string(),
            created_at: 1000,
            last_active_at: 2000,
            attrs: std::collections::HashMap::new(),
            device: None,
            ip: None,
            user_agent: None,
            safe_services: std::collections::HashMap::new(),
            #[cfg(feature = "session-extra")]
            dynamic_active_timeout: None,
            #[cfg(feature = "session-extra")]
            is_anon: false,
            effective_timeout: None,
            amr_ledger: Vec::new(),
            auth_time: None,
        })
    }
    async fn kickout(&self, _login_id: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn switch_to(&self, _token: &str, _target_login_id: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn renew_to_equivalent(&self, token: &str) -> GarrisonResult<String> {
        Ok(format!("renewed-{}", token))
    }
}

fn make_server() -> GarrisonAuthServer {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100)
        // 框架默认拒绝外网 login(secure-by-default);此处显式开启供既有链路测试,专用回归见下方
        .with_external_login_enabled(true)
}

/// 默认配置下外网 login 返回 404(secure-by-default 回归钉)。
#[tokio::test]
async fn test_external_router_login_disabled_by_default() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100);
    assert!(
        !server.config.external_login_enabled,
        "AuthServerConfig 默认应关闭外网 login"
    );
    let app = server.external_router();
    let body = serde_json::json!({
        "login_id": "user1",
        "params": LoginParams::default()
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "默认配置下外网 login 应返回 404(凭证校验由业务方注入后显式开启)"
    );
}

/// 默认拒绝仅作用于 login;logout/refresh(凭证持有语义)不受影响。
#[tokio::test]
async fn test_external_router_logout_not_gated_by_login_flag() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100);
    let app = server.external_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/logout")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"token":"token-user1"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::OK,
        "logout 属凭证持有语义,不应被 login gate 拦截"
    );
}

/// with_external_login_enabled 显式开启后 login 恢复可达。
#[tokio::test]
async fn test_external_router_login_reachable_when_enabled() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100)
        .with_external_login_enabled(true);
    assert!(server.config.external_login_enabled);
    let app = server.external_router();
    let body = serde_json::json!({
        "login_id": "user1",
        "params": LoginParams::default()
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_external_router_handles_login() {
    let server = make_server();
    let app = server.external_router();
    let body = serde_json::json!({
        "login_id": "user1",
        "params": LoginParams::default()
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let resp_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(resp_json["data"], "token-user1");
}

#[tokio::test]
async fn test_internal_router_handles_health() {
    let server = make_server();
    let app = server.internal_router();
    // health 端点需要 API Key
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/api/v1/auth/health")
                .header("x-api-key", "test-api-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let resp_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(resp_json["data"], "ok");
}

#[tokio::test]
async fn test_internal_router_rejects_missing_api_key() {
    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/api/v1/auth/health")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn test_external_router_rate_limit() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(2)
        // 限流断言以 login 为探测端点,需显式开启(框架默认 404,见上方默认拒绝回归测试)
        .with_external_login_enabled(true);
    let app = server.external_router();
    let body = serde_json::json!({
        "login_id": "user1",
        "params": LoginParams::default()
    });

    for _ in 0..2 {
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/v1/auth/login")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
}

#[tokio::test]
async fn test_builder_methods() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(9000)
        .with_internal_port(9001)
        .with_rate_limit(50)
        .with_internal_api_key("my-key");

    assert_eq!(server.config.external_port, 9000);
    assert_eq!(server.config.internal_port, 9001);
    assert_eq!(server.config.external_rate_limit_per_ip, 50);
    assert_eq!(server.config.internal_api_key, "my-key");
}

#[tokio::test]
async fn test_default_config() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend);
    assert_eq!(server.config.external_port, 8080);
    assert_eq!(server.config.internal_port, 8081);
    assert_eq!(server.config.external_rate_limit_per_ip, 100);
    assert!(
        server.config.internal_api_key.is_empty(),
        "Default internal_api_key 必须为空(fail-closed,M-SAST-1/M-5)"
    );
}

/// 测试 new_with_kit 通过 AsyncKit 构建后端并创建 server。
#[cfg(feature = "backend-kit")]
#[tokio::test]
async fn test_new_with_kit_builds_server() {
    use crate::backend::BackendModule;
    use trait_kit::kit::AsyncKit;

    let mut kit = AsyncKit::new();
    kit.register::<BackendModule>()
        .expect("register BackendModule failed");
    let kit = kit.build().await.expect("kit build failed");
    let server = GarrisonAuthServer::new_with_kit(kit)
        .await
        .expect("new_with_kit failed");
    assert_eq!(server.config.external_port, 8080);
    assert_eq!(server.config.internal_port, 8081);
}

/// 测试 new_with_kit 在 kit 未注册 BackendModule 时返回错误。
#[cfg(feature = "backend-kit")]
#[tokio::test]
async fn test_new_with_kit_missing_module_fails() {
    use trait_kit::kit::AsyncKit;

    let kit = AsyncKit::new();
    let kit = kit.build().await.expect("empty build should succeed");
    let result = GarrisonAuthServer::new_with_kit(kit).await;
    assert!(
        result.is_err(),
        "new_with_kit 应在 kit 未注册 BackendModule 时返回错误"
    );
}

/// with_tls(cert_path, key_path) 后 server.tls_config 含正确证书/密钥路径(feature = "tls")。
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_with_tls_sets_config() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend).with_tls("/path/to/cert.pem", "/path/to/key.pem");

    let tls_config = server
        .tls_config
        .as_ref()
        .expect("with_tls 后 tls_config 必须为 Some");
    assert_eq!(
        tls_config.cert_path,
        std::path::PathBuf::from("/path/to/cert.pem")
    );
    assert_eq!(
        tls_config.key_path,
        std::path::PathBuf::from("/path/to/key.pem")
    );
}

/// 测试未调用 with_tls 时 tls_config 为 None(feature = "tls")。
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_without_tls_config_is_none() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend);
    assert!(
        server.tls_config.is_none(),
        "未调用 with_tls 时 tls_config 必须为 None"
    );
}

/// 测试 with_tls 链式调用不破坏其他 builder 设置(feature = "tls")。
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_with_tls_chainable() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(9000)
        .with_internal_port(9001)
        .with_rate_limit(50)
        .with_internal_api_key("my-key")
        .with_tls("/cert.pem", "/key.pem");

    assert_eq!(server.config.external_port, 9000);
    assert_eq!(server.config.internal_port, 9001);
    assert_eq!(server.config.external_rate_limit_per_ip, 50);
    assert_eq!(server.config.internal_api_key, "my-key");
    assert!(server.tls_config.is_some());
}

// to_api_response 测试

/// 测试 to_api_response 在 Ok 时返回包含数据的成功响应。
#[test]
fn test_to_api_response_ok() {
    let result: Result<i32, GarrisonError> = Ok(42);
    let resp = to_api_response(result);
    assert_eq!(resp.data, Some(42));
    assert!(resp.error_code.is_none());
    assert!(resp.message.is_none());
}

/// 测试 to_api_response 在 Err 时返回包含错误码和消息的失败响应。
#[test]
fn test_to_api_response_err() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::Internal("test error".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("INTERNAL_ERROR"));
    assert_eq!(resp.message.as_deref(), Some("Internal error"));
}

// 路由 path-filter 测试

/// external_path_filter 仅放行 login/logout/refresh,内网端点(如 check/login)返回 404。
#[tokio::test]
async fn test_external_router_rejects_internal_path() {
    let server = make_server();
    let app = server.external_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/api/v1/auth/check/login")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

/// internal_path_filter 拒绝 login/logout/refresh,即使携带有效 API Key 也返回 404。
#[tokio::test]
async fn test_internal_router_rejects_external_path() {
    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("x-api-key", "test-api-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

/// 测试内网路由在 API Key 错误时返回 401。
#[tokio::test]
async fn test_internal_router_rejects_wrong_api_key() {
    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/api/v1/auth/health")
                .header("x-api-key", "wrong-api-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

// AuthServerConfig 测试

/// 测试 AuthServerConfig::default() 返回正确的默认值。
#[test]
fn test_auth_server_config_default() {
    let config = AuthServerConfig::default();
    assert_eq!(config.external_port, 8080);
    assert_eq!(config.internal_port, 8081);
    assert_eq!(config.external_rate_limit_per_ip, 100);
    assert!(
        config.internal_api_key.is_empty(),
        "Default internal_api_key 必须为空(fail-closed)"
    );
    // 绑定地址默认 0.0.0.0(向后兼容既有下游 listen 行为);安全收口由调用方 with_external_bind/with_internal_bind
    // 注入(部署 bin 缺省 127.0.0.1)
    assert_eq!(
        config.external_bind,
        std::net::IpAddr::from([0, 0, 0, 0]),
        "默认外网绑定必须保持 0.0.0.0(向后兼容)"
    );
    assert_eq!(
        config.internal_bind,
        std::net::IpAddr::from([0, 0, 0, 0]),
        "默认内网绑定必须保持 0.0.0.0(向后兼容)"
    );
}

/// Debug 输出必须脱敏 `internal_api_key`(CWE-532:防日志/错误报告泄露内网 API Key)。
#[test]
fn test_auth_server_config_debug_redacts_internal_api_key() {
    let secret = "0123456789abcdef0123456789abcdef";
    let config = AuthServerConfig {
        internal_api_key: secret.to_string(),
        external_login_ack: Some(EXTERNAL_LOGIN_ACK.to_string()),
        ..AuthServerConfig::default()
    };

    let debug = format!("{:?}", config);
    assert!(
        debug.contains("[REDACTED]"),
        "Debug 必须输出 [REDACTED] 占位,实际: {debug}"
    );
    assert!(
        !debug.contains(secret),
        "Debug 不得包含 internal_api_key 明文,实际: {debug}"
    );
    assert!(
        debug.contains("AuthServerConfig") && debug.contains("external_port"),
        "Debug 应保留非敏感字段,实际: {debug}"
    );
}

/// 严格档两条拒绝 + 通配绑定不误伤 + 非严格档只告警不拒绝(TDD 红测试)。
#[test]
fn test_strict_security_tiers() {
    let wildcard = std::net::IpAddr::from([0, 0, 0, 0]);
    let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
    // 严格档:12 字节短密钥拒绝。
    let strict_short = AuthServerConfig {
        internal_api_key: "short-key-12".to_string(),
        strict_security: true,
        ..AuthServerConfig::default()
    };
    assert!(
        matches!(strict_short.validate(), Err(m) if m.contains("server-internal-api-key-too-short")),
        "严格档短密钥应拒绝,实际: {:?}",
        strict_short.validate()
    );
    // 严格档:外网登录暴露未确认拒绝。
    let strict_unacked = AuthServerConfig {
        internal_api_key: "0123456789abcdef0123456789abcdef".to_string(),
        strict_security: true,
        external_login_enabled: true,
        external_bind: wildcard,
        ..AuthServerConfig::default()
    };
    assert!(
        matches!(strict_unacked.validate(), Err(m) if m.contains("server-external-login-unacknowledged")),
        "严格档未确认的外网登录暴露应拒绝,实际: {:?}",
        strict_unacked.validate()
    );
    // 严格档:精确确认串放行。
    let strict_acked = AuthServerConfig {
        external_login_ack: Some(EXTERNAL_LOGIN_ACK.to_string()),
        ..strict_unacked.clone()
    };
    assert!(
        strict_acked.validate().is_ok(),
        "严格档精确确认串应放行,实际: {:?}",
        strict_acked.validate()
    );
    // 严格档:通配绑定不误伤(容器场景)。
    let strict_wildcard = AuthServerConfig {
        internal_api_key: "0123456789abcdef0123456789abcdef".to_string(),
        strict_security: true,
        external_bind: wildcard,
        internal_bind: wildcard,
        ..AuthServerConfig::default()
    };
    assert!(
        strict_wildcard.validate().is_ok(),
        "严格档通配绑定不应误伤,实际: {:?}",
        strict_wildcard.validate()
    );
    // 非严格档(默认):上述四组全部 Ok(只告警不拒绝)。
    for cfg in [
        AuthServerConfig {
            strict_security: false,
            ..strict_short.clone()
        },
        AuthServerConfig {
            strict_security: false,
            ..strict_unacked.clone()
        },
        AuthServerConfig {
            strict_security: false,
            ..strict_acked.clone()
        },
        AuthServerConfig {
            strict_security: false,
            ..strict_wildcard.clone()
        },
    ] {
        assert!(
            cfg.validate().is_ok(),
            "非严格档应只告警不拒绝,实际: {:?}",
            cfg.validate()
        );
    }
    let _ = loopback;
}

// 非严格档告警锁定:只告警不拒绝且逐条可观测(LogCapture 范式沿用 `src/oauth2_server/token.rs`,set_default 线程局部不互干)。

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

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

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

impl std::io::Write for ServerLogCaptureWriter {
    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(())
    }
}

/// 统计含指定子串的 warn 行数。
fn count_warn(lines: &[String], needle: &str) -> usize {
    lines
        .iter()
        .filter(|l| l.contains("WARN") && l.contains(needle))
        .count()
}

/// 三条非严格档告警各恰好输出一次且文案含错误码与 1.0 迁移指引;严格档同输入直接拒绝、不产生告警。
#[test]
fn non_strict_tier_emits_each_warning_exactly_once() {
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::util::SubscriberInitExt;

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

    // 一次 validate() 同时命中三个条件:短密钥 + 外网登录未 ACK + 双端通配绑定
    let relaxed = AuthServerConfig {
        internal_api_key: "short-key-12".to_string(),
        strict_security: false,
        external_login_enabled: true,
        external_bind: std::net::IpAddr::from([0, 0, 0, 0]),
        internal_bind: std::net::IpAddr::from([0, 0, 0, 0]),
        external_login_ack: None,
        ..AuthServerConfig::default()
    };
    assert!(relaxed.validate().is_ok(), "非严格档应放行");

    let lines = capture.0.lock().expect("日志缓冲锁应可用").clone();
    // 短密钥:含错误码 + 下限 + 1.0 转为拒绝的迁移动作
    assert_eq!(
        count_warn(&lines, "server-internal-api-key-too-short"),
        1,
        "短密钥告警应恰好一次,实际捕获: {:?}",
        lines
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("server-internal-api-key-too-short")
                && l.contains("1.0")
                && l.contains("min=32")),
        "短密钥告警应含 1.0 迁移说明与下限,实际: {:?}",
        lines
    );
    // 外网登录未 ACK:含错误码 + 绑定地址 + 确认串字段名
    assert_eq!(
        count_warn(&lines, "server-external-login-unacknowledged"),
        1,
        "外网登录未 ACK 告警应恰好一次,实际捕获: {:?}",
        lines
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("server-external-login-unacknowledged")
                && l.contains("external_login_ack")
                && l.contains("1.0")),
        "未 ACK 告警应含 external_login_ack 与 1.0 迁移说明,实际: {:?}",
        lines
    );
    // 通配绑定:含两个 builder 修复动作
    assert_eq!(
        count_warn(&lines, "server-wildcard-bind-default"),
        1,
        "通配绑定告警应恰好一次(双端均通配也只一行),实际捕获: {:?}",
        lines
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("server-wildcard-bind-default")
                && l.contains("with_external_bind")
                && l.contains("with_internal_bind")
                && l.contains("1.0")),
        "通配绑定告警应同时给出 with_external_bind / with_internal_bind 与 1.0 迁移,实际: {:?}",
        lines
    );

    // 严格档:同输入直接拒绝,不输出上述任何一条告警
    let strict_lines_base = capture.0.lock().expect("日志缓冲锁应可用").len();
    let strict = AuthServerConfig {
        strict_security: true,
        ..relaxed.clone()
    };
    assert!(strict.validate().is_err(), "严格档应拒绝");
    let lines_after = capture.0.lock().expect("日志缓冲锁应可用").clone();
    assert_eq!(
        lines_after.len(),
        strict_lines_base,
        "严格档不得追加告警(它走拒绝分支),新增: {:?}",
        &lines_after[strict_lines_base..]
    );
}

/// 测试 with_external_bind / with_internal_bind builder 注入绑定地址并保持链式语义。
#[test]
fn test_with_bind_builders() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
    let v6_loopback = std::net::IpAddr::from([0, 0, 0, 0, 0, 0, 0, 1]);
    let server = GarrisonAuthServer::new(backend)
        .with_external_bind(loopback)
        .with_internal_bind(v6_loopback);

    assert_eq!(server.config.external_bind, loopback);
    assert_eq!(server.config.internal_bind, v6_loopback);
}

// listen() 测试

/// listen 未配置 `internal_api_key` 时被 `validate()` 短路(fail-closed):首行校验失败即返回 Config 错误,
/// 不触达端口绑定路径;覆盖 bind 失败路径的测试见 `test_listen_bind_failure_external_port_with_valid_config`。
#[tokio::test]
async fn test_listen_validates_config_first_external() {
    // 占用外网端口(但 validate 短路,此占用无实际影响)
    let external_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
        .await
        .expect("绑定测试端口应成功");
    let external_port = external_listener
        .local_addr()
        .expect("获取端口应成功")
        .port();

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    // 未调用 with_internal_api_key → validate 失败,listen 在 bind 前短路
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(external_port)
        .with_internal_port(0); // 内网用随机端口

    let result = server.listen().await;
    assert!(
        matches!(&result, Err(GarrisonError::Config(msg)) if msg.contains("server-internal-api-key-missing")),
        "未配置 internal_api_key 时 listen 应返回 Config 错误(validate 短路),实际: {:?}",
        result
    );
    // external_listener 在函数结束时 drop
}

/// 与 `test_listen_validates_config_first_external` 对称(内网端口场景),错误来源是 validate 而非 bind。
#[tokio::test]
async fn test_listen_validates_config_first_internal() {
    let internal_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
        .await
        .expect("绑定测试端口应成功");
    let internal_port = internal_listener
        .local_addr()
        .expect("获取端口应成功")
        .port();

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    // 未调用 with_internal_api_key → validate 失败,listen 在 bind 前短路
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(0) // 外网用随机端口
        .with_internal_port(internal_port);

    let result = server.listen().await;
    assert!(
        matches!(&result, Err(GarrisonError::Config(msg)) if msg.contains("server-internal-api-key-missing")),
        "未配置 internal_api_key 时 listen 应返回 Config 错误(validate 短路),实际: {:?}",
        result
    );
}

/// listen 成功启动后持续运行(不立即返回):tokio::select! 竞速,300ms 内未返回即说明已启动。
#[tokio::test]
async fn test_listen_starts_and_runs() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(0)
        .with_internal_port(0)
        .with_internal_api_key("test-api-key");

    tokio::select! {
           result = server.listen() => {
               panic!("listen 不应在 300ms 内返回: {:?}", result);
           },
           _ = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
    // listen 在正常运行中,测试通过
           },
       }
}

/// listen 按配置的绑定地址绑定外网端口(而非硬编码 0.0.0.0):占住 `127.0.0.1:P` 后以 `with_external_bind(127.0.0.2)`
/// + 同端口应能绑定成功——若仍通配绑定会 EADDRINUSE 与既有 specific-address 冲突并立即返回错误。
#[cfg_attr(
    target_os = "macos",
    ignore = "macOS lo0 默认仅含 127.0.0.1,无法绑定 127.0.0.2(平台能力差异,非缺陷)"
)]
#[tokio::test]
async fn test_listen_uses_configured_external_bind() {
    // 占住 127.0.0.1 上的端口(specific-address 绑定,与通配绑定互斥)
    let occupier = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("绑定 127.0.0.1 应成功");
    let port = occupier.local_addr().expect("读取端口应成功").port();

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(port)
        .with_external_bind(std::net::IpAddr::from([127, 0, 0, 2]))
        .with_internal_port(0)
        .with_internal_api_key("test-api-key");

    tokio::select! {
        result = server.listen() => {
            panic!("配置 127.0.0.2 绑定应成功启动(不受 127.0.0.1 占用影响): {:?}", result);
        },
        _ = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
            // listen 按配置地址绑定成功并正常运行
        },
    }
}

/// bind 冲突发生在配置的绑定地址上时错误显性化:占住 `127.0.0.1:P` 后同址启动 → EADDRINUSE,
/// listen 返回 `server-external-bind` 错误。
#[tokio::test]
async fn test_listen_bind_failure_on_configured_external_bind() {
    let occupier = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("绑定 127.0.0.1 应成功");
    let port = occupier.local_addr().expect("读取端口应成功").port();

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(port)
        .with_external_bind(std::net::IpAddr::from([127, 0, 0, 1]))
        .with_internal_port(0)
        .with_internal_api_key("test-api-key");

    let result = server.listen().await;
    assert!(
        matches!(&result, Err(GarrisonError::Internal(msg)) if msg.contains("server-external-bind")),
        "同地址端口冲突应返回 server-external-bind 错误,实际: {:?}",
        result
    );
}

/// TLS 证书文件不存在时 listen 返回错误(feature = "tls")。
#[cfg(feature = "tls")]
#[tokio::test]
async fn test_listen_tls_returns_error_when_cert_not_found() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(0)
        .with_internal_port(0)
        .with_tls("/nonexistent/cert.pem", "/nonexistent/key.pem");

    let result = server.listen().await;
    assert!(result.is_err(), "TLS 证书不存在时 listen 应返回错误");
}

// to_api_response 补充测试(更多 GarrisonError 变体)

/// 测试 to_api_response 处理 NotLogin 错误(401 + NOT_LOGIN)。
#[test]
fn test_to_api_response_with_not_login_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::NotLogin("not logged in".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_LOGIN"));
    assert_eq!(resp.message.as_deref(), Some("Not logged in"));
}

/// 测试 to_api_response 处理 Dao 错误(500 + DAO_ERROR)。
#[test]
fn test_to_api_response_with_dao_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::Dao("db connection failed".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("DAO_ERROR"));
    assert_eq!(resp.message.as_deref(), Some("Data access error"));
}

/// 测试 to_api_response 处理 InvalidParam 错误(400 + INVALID_PARAM)。
#[test]
fn test_to_api_response_with_invalid_param_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::InvalidParam("missing field".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("INVALID_PARAM"));
    assert_eq!(resp.message.as_deref(), Some("Invalid parameter"));
}

/// 测试 to_api_response 处理 NotPermission 错误(403 + NOT_PERMISSION)。
#[test]
fn test_to_api_response_with_not_permission_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::NotPermission("admin:read".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_PERMISSION"));
    assert_eq!(resp.message.as_deref(), Some("Permission denied"));
}

/// 测试 to_api_response 处理 ExpiredToken 错误(401 + EXPIRED_TOKEN)。
#[test]
fn test_to_api_response_with_expired_token_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::ExpiredToken("token-abc".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("EXPIRED_TOKEN"));
    assert_eq!(resp.message.as_deref(), Some("Token expired"));
}

// to_api_response 补充测试(剩余 GarrisonError 变体)

/// 测试 to_api_response 处理 NotRole 错误(403 + NOT_ROLE)。
#[test]
fn test_to_api_response_with_not_role_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::NotRole("admin".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_ROLE"));
    assert_eq!(resp.message.as_deref(), Some("Role required"));
}

/// 测试 to_api_response 处理 InvalidToken 错误(401 + INVALID_TOKEN)。
#[test]
fn test_to_api_response_with_invalid_token_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::InvalidToken("bad-format".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("INVALID_TOKEN"));
    assert_eq!(resp.message.as_deref(), Some("Invalid token"));
}

/// 测试 to_api_response 处理 TokenRevoked 错误(401 + TOKEN_REVOKED)。
#[test]
fn test_to_api_response_with_token_revoked_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::TokenRevoked("revoked-token".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("TOKEN_REVOKED"));
    assert_eq!(resp.message.as_deref(), Some("Token revoked"));
}

/// 测试 to_api_response 处理 Config 错误(500 + CONFIG_ERROR)。
#[test]
fn test_to_api_response_with_config_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::Config("invalid config".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("CONFIG_ERROR"));
    assert_eq!(resp.message.as_deref(), Some("Configuration error"));
}

/// 测试 to_api_response 处理 Session 错误(500 + SESSION_ERROR)。
#[test]
fn test_to_api_response_with_session_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::Session("session expired".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("SESSION_ERROR"));
    assert_eq!(resp.message.as_deref(), Some("Session error"));
}

/// 测试 to_api_response 处理 Network 错误(502 + NETWORK_ERROR)。
#[test]
fn test_to_api_response_with_network_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::Network("timeout".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NETWORK_ERROR"));
    assert_eq!(resp.message.as_deref(), Some("Network error"));
}

/// 测试 to_api_response 处理 NotImplemented 错误(501 + NOT_IMPLEMENTED)。
#[test]
fn test_to_api_response_with_not_implemented_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::NotImplemented("not yet".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_IMPLEMENTED"));
    assert_eq!(resp.message.as_deref(), Some("Not implemented"));
}

/// 测试 to_api_response 处理 FirewallBlocked 错误(403 + FIREWALL_BLOCKED)。
#[test]
fn test_to_api_response_with_firewall_blocked_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> =
        Err(GarrisonError::FirewallBlocked("bruteforce".to_string()));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("FIREWALL_BLOCKED"));
    assert_eq!(resp.message.as_deref(), Some("Firewall blocked"));
}

/// 测试 to_api_response 处理 DisableService 错误(403 + DISABLE_SERVICE)。
#[test]
fn test_to_api_response_with_disable_service_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::DisableService {
        service: "default".to_string(),
        until: None,
    });
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("DISABLE_SERVICE"));
    assert_eq!(resp.message.as_deref(), Some("Account disabled"));
}

/// 测试 to_api_response 处理 NotSafe 错误(400 + NOT_SAFE)。
#[test]
fn test_to_api_response_with_not_safe_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::NotSafe {
        reason: "MFA_REQUIRED".to_string(),
    });
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_SAFE"));
    assert_eq!(
        resp.message.as_deref(),
        Some("Two-factor authentication required")
    );
}

/// 测试 to_api_response 处理 SmsRateLimitExceeded 错误(429 + SMS_RATE_LIMIT_EXCEEDED)。
#[test]
fn test_to_api_response_with_sms_rate_limit_exceeded_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsRateLimitExceeded {
        window: "hourly".to_string(),
    });
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("SMS_RATE_LIMIT_EXCEEDED"));
    assert_eq!(resp.message.as_deref(), Some("SMS rate limit exceeded"));
}

/// 测试 to_api_response 处理 SmsVerifyMaxAttempts 错误(400 + SMS_VERIFY_MAX_ATTEMPTS)。
#[test]
fn test_to_api_response_with_sms_verify_max_attempts_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsVerifyMaxAttempts);
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("SMS_VERIFY_MAX_ATTEMPTS"));
    assert_eq!(
        resp.message.as_deref(),
        Some("Verification code attempts exceeded")
    );
}

/// 测试 to_api_response 处理 SmsCodeNotFound 错误(400 + SMS_CODE_NOT_FOUND)。
#[test]
fn test_to_api_response_with_sms_code_not_found_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsCodeNotFound);
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("SMS_CODE_NOT_FOUND"));
    assert_eq!(
        resp.message.as_deref(),
        Some("Verification code not found or expired")
    );
}

/// 测试 to_api_response 处理 SmsChannelRecycled 错误(403 + SMS_CHANNEL_RECYCLED)。
#[test]
fn test_to_api_response_with_sms_channel_recycled_error() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    let result: Result<i32, GarrisonError> = Err(GarrisonError::SmsChannelRecycled);
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("SMS_CHANNEL_RECYCLED"));
    assert_eq!(resp.message.as_deref(), Some("SMS channel recycled"));
}

/// 测试 to_api_response 处理 Exception(code=-1) 错误(401 + NOT_LOGIN + exception_code)。
#[test]
fn test_to_api_response_with_exception_not_login() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    use crate::exception::GarrisonException;
    let result: Result<i32, GarrisonError> = Err(GarrisonError::Exception(Box::new(
        GarrisonException::new(-1, "请先登录"),
    )));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_LOGIN"));
    assert_eq!(resp.message.as_deref(), Some("Not logged in"));
}

/// 测试 to_api_response 处理 Exception(code=-2) 错误(403 + NOT_PERMISSION + exception_code)。
#[test]
fn test_to_api_response_with_exception_not_permission() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    use crate::exception::GarrisonException;
    let result: Result<i32, GarrisonError> = Err(GarrisonError::Exception(Box::new(
        GarrisonException::new(-2, "无权限"),
    )));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("NOT_PERMISSION"));
    assert_eq!(resp.message.as_deref(), Some("Permission denied"));
}

/// 测试 to_api_response 处理 Exception(其他 code) 错误(500 + EXCEPTION + exception_code)。
#[test]
fn test_to_api_response_with_exception_other_code() {
    let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
    use crate::exception::GarrisonException;
    let result: Result<i32, GarrisonError> = Err(GarrisonError::Exception(Box::new(
        GarrisonException::new(1001, "业务异常"),
    )));
    let resp = to_api_response(result);
    assert!(resp.data.is_none());
    assert_eq!(resp.error_code.as_deref(), Some("EXCEPTION"));
    assert_eq!(resp.message.as_deref(), Some("Business exception"));
}

// 限速边缘条件测试

/// rate_limit(0):token bucket 初始为空、无令牌可消耗,所有外网请求 429。
#[tokio::test]
async fn test_rate_limit_zero_rejects_all_requests() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(0);
    let app = server.external_router();
    let body = serde_json::json!({
        "login_id": "user1",
        "params": LoginParams::default()
    });

    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::TOO_MANY_REQUESTS,
        "rate_limit=0 时所有请求应被限速"
    );
}

/// 空 API Key(`with_internal_api_key("")`)时 api_key_auth_middleware 拒绝所有内网请求(401)。
#[tokio::test]
async fn test_empty_internal_api_key_rejects_all() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("")
        .with_rate_limit(100);
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/api/v1/auth/health")
                .header("x-api-key", "")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::UNAUTHORIZED,
        "空 API Key 应拒绝所有内网请求"
    );
}

// OAuth2 路由集成测试(feature = "oauth2-server")

/// 简化 Mock DAO,仅实现 GarrisonDao 的 5 个必需方法。
#[cfg(feature = "oauth2-server")]
struct SimpleMockDao;

#[cfg(feature = "oauth2-server")]
#[async_trait]
impl GarrisonDao for SimpleMockDao {
    async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
        Ok(None)
    }
    async fn set(&self, _key: &str, _value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
        Ok(())
    }
    async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
        Ok(())
    }
    async fn delete(&self, _key: &str) -> GarrisonResult<()> {
        Ok(())
    }
    crate::atomic_test_fallback!();
}

/// 调用 SimpleMockDao 的 atomic + 默认 trait 方法以覆盖 async_trait wrapper。
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn simple_mock_dao_atomic_and_default_methods_coverage() {
    let dao = SimpleMockDao;
    let _ = dao.set_if_absent("a", "v", 60).await;
    let _ = dao.get_and_delete("a").await;
    let _ = dao.incr("c", 60).await;
    let _ = dao.decr("c").await;
    let _ = dao.rename("a", "b").await;
    let _ = dao.compare_and_swap("b", Some("v"), "v2", 60).await;
    let _ = dao.set_permanent("p", "v").await;
    let _ = dao.get_timeout("k").await;
    let _ = dao.get_with_ttl("k").await;
    let _ = dao.keys("*").await;
    let _ = dao.find_social_binding(0, "w", "o").await;
    let _ = dao.insert_social_binding(0, "u", "w", "o", None, 0).await;
    let _ = dao.compare_and_update_if_greater("k", 1, 60).await;
    let _ = dao.eval_lua("r", vec![], vec![]).await;
    #[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
    {
        let _ = dao.insert_credit_consumption(0, "r", 1, 1, 1, 0).await;
        let _ = dao.query_credit_consumption(0, 0, 0).await;
        let _ = dao.query_role_hierarchy_edges(0).await;
        let _ = dao.insert_role_hierarchy_edge(0, "c", "p").await;
        let _ = dao.delete_role_hierarchy_edge(0, "c", "p").await;
    }
}

/// 简化 Mock OAuth2ClientStore,仅实现 trait 的 5 个方法。
#[cfg(feature = "oauth2-server")]
struct SimpleMockClientStore;

#[cfg(feature = "oauth2-server")]
#[async_trait]
impl crate::oauth2_server::client::OAuth2ClientStore for SimpleMockClientStore {
    async fn create(
        &self,
        _client: crate::oauth2_server::client::OAuth2Client,
    ) -> GarrisonResult<()> {
        Ok(())
    }
    async fn get(
        &self,
        _client_id: &str,
    ) -> GarrisonResult<Option<crate::oauth2_server::client::OAuth2Client>> {
        Ok(None)
    }
    async fn update(
        &self,
        _client: crate::oauth2_server::client::OAuth2Client,
    ) -> GarrisonResult<()> {
        Ok(())
    }
    async fn delete(&self, _client_id: &str) -> GarrisonResult<()> {
        Ok(())
    }
    async fn list(&self) -> GarrisonResult<Vec<crate::oauth2_server::client::OAuth2Client>> {
        Ok(Vec::new())
    }
}

/// with_oauth2 后 external_router 含 OAuth2 端点:/oauth2/token 不再 404(返回 handler 响应)。
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_external_router_includes_oauth2_routes_when_set() {
    let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
    let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
        Arc::new(SimpleMockClientStore);
    let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
        store,
        dao,
        "http://localhost/login".to_string(),
    ));

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100)
        .with_oauth2(oauth2_state);

    let app = server.external_router();

    // /oauth2/authorize 端点应存在(不再 404,而是返回 OAuth2 handler 响应)
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/oauth2/authorize?response_type=code&client_id=test&redirect_uri=http://localhost/cb&code_challenge=test&code_challenge_method=S256&state=xyz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // 不应返回 404(路由存在),具体状态码由 OAuth2 handler 决定
    assert_ne!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "with_oauth2 设置后 /oauth2/authorize 端点应存在"
    );
}

/// 测试 with_oauth2 设置 oauth2_state 后 internal_router 包含 OAuth2 introspect 端点。
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_internal_router_includes_oauth2_routes_when_set() {
    let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
    let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
        Arc::new(SimpleMockClientStore);
    let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
        store,
        dao,
        "http://localhost/login".to_string(),
    ));

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100)
        .with_oauth2(oauth2_state);

    let app = server.internal_router();

    // /oauth2/introspect 端点应存在(不再 404)
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/oauth2/introspect")
                .header("x-api-key", "test-api-key")
                .header("content-type", "application/x-www-form-urlencoded")
                .body(Body::from("token=test"))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "with_oauth2 设置后 /oauth2/introspect 端点应存在"
    );
}

/// 测试未设置 oauth2_state 时 external_router 不包含 OAuth2 端点(404)。
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_external_router_excludes_oauth2_routes_when_not_set() {
    let server = make_server();
    let app = server.external_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/oauth2/authorize")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "未设置 oauth2_state 时 /oauth2/authorize 应返回 404"
    );
}

/// 测试未设置 oauth2_state 时 internal_router 不包含 OAuth2 端点(404)。
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_internal_router_excludes_oauth2_routes_when_not_set() {
    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/oauth2/introspect")
                .header("x-api-key", "test-api-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "未设置 oauth2_state 时 /oauth2/introspect 应返回 404"
    );
}

/// 测试 with_oauth2 链式调用不破坏其他 builder 设置。
#[cfg(feature = "oauth2-server")]
#[tokio::test]
async fn test_with_oauth2_chainable() {
    let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
    let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
        Arc::new(SimpleMockClientStore);
    let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
        store,
        dao,
        "http://localhost/login".to_string(),
    ));

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(9000)
        .with_internal_port(9001)
        .with_rate_limit(50)
        .with_internal_api_key("my-key")
        .with_oauth2(oauth2_state);

    assert_eq!(server.config.external_port, 9000);
    assert_eq!(server.config.internal_port, 9001);
    assert_eq!(server.config.external_rate_limit_per_ip, 50);
    assert_eq!(server.config.internal_api_key, "my-key");
    assert!(
        server.oauth2_state.is_some(),
        "with_oauth2 后 oauth2_state 必须为 Some"
    );
}

// builder 边缘条件测试

/// 测试 with_rate_limit 设置极大值时正常工作。
#[tokio::test]
async fn test_with_rate_limit_large_value() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(u32::MAX);
    assert_eq!(server.config.external_rate_limit_per_ip, u32::MAX);
}

/// 测试 with_internal_api_key 接受 &str 和 String。
#[tokio::test]
async fn test_with_internal_api_key_accepts_str_and_string() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);

    let server1 = GarrisonAuthServer::new(backend.clone()).with_internal_api_key("str-key");
    assert_eq!(server1.config.internal_api_key, "str-key");

    let server2 = GarrisonAuthServer::new(backend).with_internal_api_key("string-key".to_string());
    assert_eq!(server2.config.internal_api_key, "string-key");
}

// body limit 配置测试

/// AuthServerConfig 默认 body limit 值正确(外网 256KB、内网 1MB)。
#[tokio::test]
async fn test_default_body_limits() {
    let config = AuthServerConfig::default();
    assert_eq!(config.external_body_limit, 256 * 1024, "外网默认应为 256KB");
    assert_eq!(config.internal_body_limit, 1024 * 1024, "内网默认应为 1MB");
}

/// builder 方法可覆盖默认 body limit 值。
#[tokio::test]
async fn test_with_body_limits() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_body_limit(512 * 1024)
        .with_internal_body_limits(2 * 1024 * 1024);
    assert_eq!(server.config.external_body_limit, 512 * 1024);
    assert_eq!(server.config.internal_body_limit, 2 * 1024 * 1024);
}

// 覆盖率补测:listen 校验失败 / 真实 bind 失败分支 / builder 补充 / 租户解析器两态

/// listen 在 `internal_api_key` 未配置时被 config validate 短路(fail-closed):校验失败不进入端口绑定,直接返回 Config 错误。
#[tokio::test]
async fn test_listen_validate_fails_when_internal_api_key_empty() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    // 不调用 with_internal_api_key → 默认空串 → validate 失败
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(0)
        .with_internal_port(0);

    let result = server.listen().await;
    assert!(
        matches!(result, Err(GarrisonError::Config(ref msg)) if msg.contains("server-internal-api-key-missing")),
        "空 internal_api_key 时 listen 应返回 Config 错误,实际: {:?}",
        result
    );
}

/// listen 配置合法且外网端口被占用时返回 bind 错误:与 `test_listen_validates_config_first_external` 不同,
/// 本测试设置合法 api_key、真正进入 tokio::spawn 的 bind 路径,覆盖外网 bind 失败分支与 select 的 external 错误臂。
#[tokio::test]
async fn test_listen_bind_failure_external_port_with_valid_config() {
    let external_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
        .await
        .expect("占用测试端口应成功");
    let external_port = external_listener.local_addr().unwrap().port();

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(external_port)
        .with_internal_port(0)
        .with_internal_api_key("test-api-key");

    let result = server.listen().await;
    assert!(
        matches!(result, Err(GarrisonError::Internal(ref msg)) if msg.contains("server-external-bind")),
        "外网端口被占用应返回 server-external-bind 错误,实际: {:?}",
        result
    );
}

/// listen 配置合法且内网端口被占用时返回 bind 错误(覆盖内网 bind 失败分支与 select 的 internal 错误臂;
/// internal 失败时显式 abort external task)。
#[tokio::test]
async fn test_listen_bind_failure_internal_port_with_valid_config() {
    let internal_listener = tokio::net::TcpListener::bind("0.0.0.0:0")
        .await
        .expect("占用测试端口应成功");
    let internal_port = internal_listener.local_addr().unwrap().port();

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_external_port(0)
        .with_internal_port(internal_port)
        .with_internal_api_key("test-api-key");

    let result = server.listen().await;
    assert!(
        matches!(result, Err(GarrisonError::Internal(ref msg)) if msg.contains("server-internal-bind")),
        "内网端口被占用应返回 server-internal-bind 错误,实际: {:?}",
        result
    );
}

/// 测试 with_trusted_proxies / with_rate_limit_max_entries builder 存储配置。
#[tokio::test]
async fn test_with_trusted_proxies_and_rate_limit_max_entries() {
    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let proxies = ["127.0.0.1".parse::<std::net::IpAddr>().unwrap()].to_vec();
    let server = GarrisonAuthServer::new(backend)
        .with_trusted_proxies(proxies.clone())
        .with_rate_limit_max_entries(1234);

    assert_eq!(server.config.rate_limit_trusted_proxies, proxies);
    assert_eq!(server.config.rate_limit_max_entries, 1234);
}

/// with_tenant_resolver 两态(feature = "tenant-isolation"):默认 `None` 不挂载租户中间件,
/// `Some(..)` 时 external / internal 路由均挂载(路由可正常构建)。
#[cfg(feature = "tenant-isolation")]
#[tokio::test]
async fn test_with_tenant_resolver_states_none_and_some() {
    use crate::context::tenant::HeaderTenantResolver;

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);

    // None 态(默认)
    let server_none = GarrisonAuthServer::new(backend.clone())
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100);
    assert!(
        server_none.tenant_resolver.is_none(),
        "默认不应注入租户解析器"
    );
    // None 态路由构建不受影响
    let _ = server_none.external_router();
    let _ = server_none.internal_router();

    // Some 态
    let server_some = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100)
        .with_tenant_resolver(Some(Arc::new(HeaderTenantResolver)));
    assert!(
        server_some.tenant_resolver.is_some(),
        "with_tenant_resolver(Some(..)) 后应持有解析器"
    );
    // Some 态下 external / internal 路由挂载租户中间件后仍可构建
    let _ = server_some.external_router();
    let _ = server_some.internal_router();
}

/// with_oauth2 + with_tenant_resolver 组合:OAuth2 router merge 前单独注入租户中间件(axum merge 不合并 layer),
/// external / internal 端点均可达。
#[cfg(all(feature = "tenant-isolation", feature = "oauth2-server"))]
#[tokio::test]
async fn test_oauth2_with_tenant_resolver_routes_reachable() {
    use crate::context::tenant::HeaderTenantResolver;

    let dao: Arc<dyn GarrisonDao> = Arc::new(SimpleMockDao);
    let store: Arc<dyn crate::oauth2_server::client::OAuth2ClientStore> =
        Arc::new(SimpleMockClientStore);
    let oauth2_state = Arc::new(oauth2_routes::OAuth2State::new(
        store,
        dao,
        "http://localhost/login".to_string(),
    ));

    let backend: Arc<dyn AuthBackend> = Arc::new(MockAuthBackend);
    let server = GarrisonAuthServer::new(backend)
        .with_internal_api_key("test-api-key")
        .with_rate_limit(100)
        .with_tenant_resolver(Some(Arc::new(HeaderTenantResolver)))
        .with_oauth2(oauth2_state);

    let external_app = server.external_router();
    let internal_app = server.internal_router();

    // external:带合法租户头的 authorize 不被租户中间件阻断(SimpleMockClientStore 无注册客户端 → 业务错误 400;
    // 租户中间件缺失/解析失败会表现为 404/500,视为路由装配失败)
    let resp = external_app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/oauth2/authorize?response_type=code&client_id=test")
                .header("x-tenant-id", "1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let status = resp.status();
    assert_ne!(
        status,
        StatusCode::NOT_FOUND,
        "oauth2 + 租户中间件组合下 /oauth2/authorize 应存在"
    );
    assert_ne!(
        status,
        StatusCode::INTERNAL_SERVER_ERROR,
        "合法租户头不应被租户中间件拒绝(500),实际: {status}"
    );
    assert_ne!(
        status,
        StatusCode::UNAUTHORIZED,
        "合法租户头不应触发 401,实际: {status}"
    );

    // internal:introspect 在租户中间件 + merge 后仍存在(不 404 即证明路由装配未被破坏)
    let resp = internal_app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/oauth2/introspect")
                .header("x-tenant-id", "1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "oauth2 + 租户中间件组合下 /oauth2/introspect 应存在"
    );
}

/// 探针在两端口均绕过全部中间件:外网仅 `/healthz`(最小语义无版本号,`/readyz` 404),
/// 内网 `/healthz`/`/readyz` 均不要求 API Key(K8s 探针不持有 api_key_auth 凭证);
/// sdforge readiness 注册表是进程级全局态,与其他注册检查测试串行执行。
#[cfg(feature = "server-health-check")]
#[serial_test::serial]
#[tokio::test]
async fn test_health_probes_bypass_middleware() {
    sdforge::health::clear_readiness_checks();
    let server = make_server();

    // 外网端口:仅 liveness,readiness 不暴露
    let app = server.external_router();
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK, "/healthz 外网端口应返回 200");
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(
        json,
        serde_json::json!({"status": "healthy"}),
        "GAR-14: 外网 healthz 仅含 status,不回显版本号"
    );

    let app = server.external_router();
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/readyz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "GAR-14: 外网端口不应暴露 /readyz"
    );

    // 内网端口:无 X-API-Key 仍应 200(绕过 api_key_auth)
    let app = server.internal_router();
    for uri in ["/healthz", "/readyz"] {
        let resp = app
            .clone()
            .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "{uri} 内网端口应绕过 api_key_auth 返回 200"
        );
    }
}

/// 内网 /readyz 默认剥离 checks[].details(可能含内部依赖拓扑),显式 with_health_details(true) 后透传。
#[cfg(feature = "server-health-check")]
#[serial_test::serial]
#[tokio::test]
async fn test_internal_readyz_details_gated_by_config() {
    sdforge::health::register_readiness_check_fn("primary-db", || sdforge::health::CheckOutcome {
        name: "primary-db".to_string(),
        healthy: true,
        details: Some(serde_json::json!({"host": "db.internal:5432", "latency_ms": 3})),
    });

    // 默认(details 关闭):details 字段被剥离
    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/readyz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    let check = &json["checks"][0];
    assert_eq!(check["name"], "primary-db");
    assert!(
        check.get("details").is_none(),
        "默认应剥离 details,实际: {check}"
    );

    // 显式开启:details 原样透传
    let server = make_server().with_health_details(true);
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/readyz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(
        json["checks"][0]["details"]["host"], "db.internal:5432",
        "开启后 details 应透传"
    );

    sdforge::health::clear_readiness_checks();
}

/// readiness 判定语义保持:任一注册检查失败 → 503(details 仍剥离)。
#[cfg(feature = "server-health-check")]
#[serial_test::serial]
#[tokio::test]
async fn test_internal_readyz_failure_returns_503() {
    sdforge::health::register_readiness_check_fn("downstream", || {
        sdforge::health::CheckOutcome::unhealthy("downstream", "connection refused")
    });

    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/readyz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(json["status"], "unavailable");
    assert!(
        json["checks"][0].get("details").is_none(),
        "默认剥离 details(失败原因同样不外泄)"
    );

    sdforge::health::clear_readiness_checks();
}

/// 端到端:外网 login 畸形类型 body 返回统一 JSON 错误体,不含内部类型名/字段名/字节偏移。
#[tokio::test]
async fn test_external_router_sanitizes_422_type_leak() {
    let server = make_server();
    let app = server.external_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from("[1,2,3]".to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::UNPROCESSABLE_ENTITY,
        "状态码保持 4xx"
    );
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/json"
    );
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let text = std::str::from_utf8(&bytes).unwrap();
    for leaked in [
        "LoginRequest",
        "LoginParams",
        "struct",
        "expected",
        "line",
        "column",
        "login_id",
    ] {
        assert!(
            !text.contains(leaked),
            "响应不得泄露 {leaked},实际: {text}"
        );
    }
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(json["error"], "bad_request");
}

/// 端到端:外网 login 读体超限(>256KB)返回 413 统一 JSON 错误体。
#[tokio::test]
async fn test_external_router_oversize_body_returns_413() {
    let server = make_server();
    let app = server.external_router();
    let oversize = vec![b'x'; 256 * 1024 + 1];
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                // 注入 ConnectInfo 使 ClientIp 非 "unknown"(真实外网端口必有连接地址)
                .extension(axum::extract::ConnectInfo(std::net::SocketAddr::new(
                    std::net::IpAddr::V4(std::net::Ipv4Addr::new(203, 0, 113, 1)),
                    40000,
                )))
                .body(Body::from(oversize))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::PAYLOAD_TOO_LARGE,
        "超限 body 应返回 413 而非误导性 400/断连"
    );
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(json["error"], "payload_too_large");
}

/// 端到端:重复 X-API-Key 头经内网路由 fail-closed 401(首值合法亦拒绝,消除与「取末值」网关的判定分裂)。
#[tokio::test]
async fn test_internal_router_rejects_duplicate_api_key_header() {
    let server = make_server().with_api_key_lockout(0, 300);
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/api/v1/auth/health")
                .header("x-api-key", "test-api-key")
                .header("x-api-key", "wrong-key")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::UNAUTHORIZED,
        "重复 X-API-Key 头应 fail-closed 拒绝"
    );
}

/// 端到端:内网 get-session 缺失 caller_login_id 返回 400(fail-closed)。
#[tokio::test]
async fn test_internal_router_get_session_without_caller_rejected() {
    let server = make_server();
    let app = server.internal_router();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/get-session")
                .header("content-type", "application/json")
                .header("x-api-key", "test-api-key")
                .body(Body::from(r#"{"token":"token-user1"}"#.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::BAD_REQUEST,
        "caller_login_id 缺失应 4xx fail-closed"
    );
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert!(json.get("data").is_none(), "拒绝响应不得携带会话数据");
}

/// 端到端:auth-server 聚合含 web-security-headers 后,认证端点响应携带
/// Cache-Control: no-store / X-Content-Type-Options / X-Frame-Options。
#[cfg(feature = "web-security-headers")]
#[tokio::test]
async fn test_external_router_response_has_security_headers() {
    let server = make_server();
    let app = server.external_router();
    let body = serde_json::json!({
        "login_id": "user1",
        "params": LoginParams::default()
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/auth/login")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(
        resp.headers()
            .get("cache-control")
            .map(|v| v.to_str().unwrap()),
        Some("no-store"),
        "GAR-13: token 承载端点应带 Cache-Control: no-store(CWE-525)"
    );
    assert_eq!(
        resp.headers()
            .get("x-content-type-options")
            .map(|v| v.to_str().unwrap()),
        Some("nosniff")
    );
    assert_eq!(
        resp.headers()
            .get("x-frame-options")
            .map(|v| v.to_str().unwrap()),
        Some("DENY")
    );
}