garrison 0.7.2

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
//! Copyright (c) 2026 Kirky.X. All rights reserved.
//! See LICENSE for full license text.

//! Keycloak OIDC RP 模块。
//!
//! 提供 `KeycloakProvider` 作为 OIDC 依赖方(RP),对接 Keycloak IdP:
//! - `KeycloakConfig`:配置 base_url / client_id / client_secret / redirect_uri / expected_iss
//! - `KeycloakProvider`:discover / verify_id_token / exchange_code
//! - `KeycloakClaims`:Keycloak 特有 claim(realm_access.roles / resource_access / aud / iss)
//!
//! ## 与 `oauth2::oidc` 模块的关系
//!
//! `oauth2::oidc` 提供通用 OIDC handler(HS256 sign/verify id_token + discovery metadata),
//! 本模块针对 Keycloak 特化(JWKS 验签、Keycloak 特有 claim 解析、RP 流程)。
//!
//! ## Keycloak OIDC 端点约定
//!
//! Keycloak realm 的 OIDC 端点均基于 `{base_url}`(即 realm URL,形如
//! `https://kc.example.com:8443/realms/{realm}`),按 Keycloak 官方文档约定:
//!
//! | 端点 | 路径 |
//! |------|------|
//! | Discovery | `{base_url}/.well-known/openid-configuration` |
//! | JWKS | `{base_url}/protocol/openid-connect/certs` |
//! | Authorization | `{base_url}/protocol/openid-connect/auth` |
//! | Token | `{base_url}/protocol/openid-connect/token` |
//! | UserInfo | `{base_url}/protocol/openid-connect/userinfo` |

use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::loc;
use crate::protocol::oauth2::client::{build_safe_http_client, read_limited_bytes};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

/// JWKS 公钥缓存 TTL。
///
/// 10 分钟内复用缓存的 JWKS 公钥,避免每次 `verify_id_token` 都拉取 JWKS endpoint。
const JWKS_CACHE_TTL: Duration = Duration::from_secs(600);

/// Keycloak OIDC RP 配置。
///
/// 持有对接 Keycloak IdP 所需的最小配置:realm base_url、client_id、
/// client_secret(confidential client 必填,public client 可为 None)、redirect_uri、
/// expected_iss(issuer 校验)。
///
/// # 字段
///
/// - `base_url`: Keycloak realm 根 URL,形如 `https://kc.example.com:8443/realms/myrealm`。
///   末尾不应有 `/`(URL 拼接时直接追加路径)。
/// - `client_id`: 在 Keycloak 中注册的 OIDC client ID。
/// - `client_secret`: confidential client 的密钥;public client(如 SPA)为 `None`。
/// - `redirect_uri`: 授权码回调地址,必须与 Keycloak client 配置中登记的 URL 一致。
/// - `expected_iss`: 预期的 issuer,通常等于 `base_url`,
///   用于 [`KeycloakProvider::verify_id_token`] 的 `validate_iss` 校验。
///
/// # 端点推导
///
/// [`KeycloakConfig`] 提供 5 个端点推导方法,按 Keycloak OIDC 约定拼接 URL:
/// [`discovery_url`](Self::discovery_url) / [`jwks_url`](Self::jwks_url) /
/// [`authorize_url`](Self::authorize_url) / [`token_url`](Self::token_url) /
/// [`userinfo_url`](Self::userinfo_url)。
#[derive(Debug, Clone)]
pub struct KeycloakConfig {
    /// Keycloak realm 根 URL(末尾无 `/`)。
    pub base_url: String,
    /// OIDC client ID。
    pub client_id: String,
    /// confidential client 密钥(public client 为 `None`)。
    pub client_secret: Option<String>,
    /// 授权码回调地址。
    pub redirect_uri: String,
    /// 预期的 issuer。
    /// 通常等于 `base_url`,用于 [`KeycloakProvider::verify_id_token`] 的 `validate_iss` 校验。
    pub expected_iss: String,
}

impl KeycloakConfig {
    /// 构造 OIDC Discovery 端点 URL。
    ///
    /// 返回 `{base_url}/.well-known/openid-configuration`,用于 `KeycloakProvider::discover`
    /// 拉取 Keycloak 的 OIDC discovery metadata。
    pub fn discovery_url(&self) -> String {
        format!("{}/.well-known/openid-configuration", self.base_url)
    }

    /// 构造 JWKS 端点 URL。
    ///
    /// 返回 `{base_url}/protocol/openid-connect/certs`,用于 `KeycloakProvider::verify_id_token`
    /// 拉取公钥集合以验签 id_token。
    pub fn jwks_url(&self) -> String {
        format!("{}/protocol/openid-connect/certs", self.base_url)
    }

    /// 构造 Authorization 端点 URL。
    ///
    /// 返回 `{base_url}/protocol/openid-connect/auth`,用于浏览器跳转引导用户完成登录。
    pub fn authorize_url(&self) -> String {
        format!("{}/protocol/openid-connect/auth", self.base_url)
    }

    /// 构造 Token 端点 URL。
    ///
    /// 返回 `{base_url}/protocol/openid-connect/token`,用于 `KeycloakProvider::exchange_code`
    /// 以授权码换取 access_token / refresh_token / id_token。
    pub fn token_url(&self) -> String {
        format!("{}/protocol/openid-connect/token", self.base_url)
    }

    /// 构造 UserInfo 端点 URL。
    ///
    /// 返回 `{base_url}/protocol/openid-connect/userinfo`,用于查询用户信息 claim。
    pub fn userinfo_url(&self) -> String {
        format!("{}/protocol/openid-connect/userinfo", self.base_url)
    }
}

/// OIDC Discovery Metadata。
///
/// 表示从 `/.well-known/openid-configuration` 拉取的 IdP 元数据。
/// 仅声明 Keycloak RP 流程所需的最小子集;其他字段(如 `response_types_supported`)
/// 在反序列化时被忽略。
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct OidcDiscoveryMetadata {
    /// 签发者标识(Keycloak realm URL)。
    pub issuer: String,
    /// 授权端点 URL。
    pub authorization_endpoint: String,
    /// 令牌端点 URL。
    pub token_endpoint: String,
    /// JWKS 公钥集合端点 URL。
    pub jwks_uri: String,
}

/// JWKS 中的单个 RSA 公钥。
///
/// 表示从 `/.well-known/openid-configuration` 的 `jwks_uri` 拉取的公钥集合中的一个条目。
/// 仅声明 RS256 验签所需字段;其他字段(如 `use` / `alg`)在反序列化时被忽略。
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Jwk {
    /// 公钥标识(Key ID),与 JWT header 的 `kid` 匹配以选择验签公钥。
    pub kid: String,
    /// RSA 模数(base64url 编码,无 padding)。
    pub n: String,
    /// RSA 公钥指数(base64url 编码,无 padding)。
    pub e: String,
}

/// JWKS 公钥集合响应。
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JwksResponse {
    /// 公钥列表。
    pub keys: Vec<Jwk>,
}

/// JWKS 缓存 key 前缀(拼入 DAO key:`keycloak:jwks:{expected_iss}`)。
///
/// 通过 [`GarrisonDao`] 抽象层委托 oxcache 管理 JWKS JSON + TTL,
/// 禁止手写内存缓存(用户铁律:所有缓存由 oxcache 接管)。
const JWKS_CACHE_KEY_PREFIX: &str = "keycloak:jwks:";

/// Keycloak realm 访问信息。
///
/// 对应 Keycloak id_token 中 `realm_access` claim,含 realm 级别的角色列表。
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct RealmAccess {
    /// realm 级别角色列表(如 `user` / `admin`)。
    pub roles: Vec<String>,
}

/// Keycloak id_token 的 claims。
///
/// 包含标准 OIDC claims(`sub` / `preferred_username` / `email` / `aud` / `iss`)+
/// Keycloak 特有 claim(`realm_access` / `resource_access`)+ 多租户扩展(`tenant_id`)。
///
/// # 字段
///
/// - `sub`: 主体标识(Keycloak 用户 ID)。
/// - `exp`: 过期时间(Unix 秒,RFC 7519 §4.1.4,用于 `validate_exp` 校验)。
/// - `aud`: Audience(RFC 7519 §4.1.3)。支持单个 String 或 Vec<String>,
///   用 `serde_json::Value` 兼容两种形式,由 `verify_id_token` 的 `validate_aud` 校验。
/// - `iss`: Issuer(RFC 7519 §4.1.1)。由 `verify_id_token` 的
///   `validate_iss` 校验,旧 token 可能无此字段故用 `Option`。
/// - `preferred_username`: 用户名(Keycloak 登录名)。
/// - `email`: 邮箱(可选,需 `email` scope)。
/// - `realm_access`: realm 级别角色([`RealmAccess`])。
/// - `resource_access`: client 级别角色映射(key 为 client_id,value 为 [`RealmAccess`])。
/// - `tenant_id`: Garrison 多租户标识(可选,由 Keycloak mapper 注入)。
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct KeycloakClaims {
    /// 主体标识(Keycloak 用户 ID)。
    pub sub: String,
    /// 过期时间(Unix 秒,RFC 7519 §4.1.4,用于 `validate_exp` 校验)。
    pub exp: i64,
    /// Audience(RFC 7519 §4.1.3)。
    /// 支持单个 String 或 Vec<String>,用 `serde_json::Value` 兼容两种形式。
    #[serde(default)]
    pub aud: serde_json::Value,
    /// Issuer(RFC 7519 §4.1.1)。旧 token 可能无此字段故用 `Option`。
    #[serde(default)]
    pub iss: Option<String>,
    /// 用户名(Keycloak 登录名)。
    pub preferred_username: Option<String>,
    /// 邮箱(可选,需 `email` scope)。
    pub email: Option<String>,
    /// realm 级别角色。
    pub realm_access: RealmAccess,
    /// client 级别角色映射(key 为 client_id)。
    pub resource_access: HashMap<String, RealmAccess>,
    /// 多租户标识(可选,由 Keycloak mapper 注入)。
    #[serde(default)]
    pub tenant_id: Option<i64>,
}

/// Keycloak token endpoint 响应。
///
/// 表示 `exchange_code` 成功后 Keycloak 返回的 token 集合。
/// 仅声明 RP 流程所需的最小字段;其他字段(如 `token_type` / `scope`)在反序列化时被忽略。
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct KeycloakTokenSet {
    /// 访问令牌(用于调用 Keycloak 保护的资源 API)。
    pub access_token: String,
    /// 刷新令牌(用于在 access_token 过期后获取新的 access_token)。
    pub refresh_token: String,
    /// OIDC id_token(JWT 格式,含用户身份 claims,可由 `verify_id_token` 验签解析)。
    pub id_token: String,
    /// access_token 过期时间(秒)。
    pub expires_in: u64,
}

/// Keycloak OIDC 依赖方。
///
/// 持有 `KeycloakConfig` 与可复用的 `reqwest::Client`,提供 OIDC RP 流程:
/// - [`discover`](Self::discover):从 `/.well-known/openid-configuration` 拉取 IdP 元数据
/// - [`verify_id_token`](Self::verify_id_token):JWKS 验签 + Keycloak claim 解析
/// - [`exchange_code`](Self::exchange_code)(T117-T118 实现):授权码换 token set
///
/// # 设计决策
///
/// - `http: reqwest::Client` 复用连接池,`Send + Sync` 可在多线程共享。
/// - JWKS 公钥缓存通过 [`GarrisonDao`](oxcache 抽象层)管理,TTL 由 [`JWKS_CACHE_TTL`]
///   控制,避免每次 `verify_id_token` 都拉取 JWKS endpoint。
///   **禁止手写内存缓存**(用户铁律:所有缓存由 oxcache 接管)。
///   调用方必须通过 [`with_dao`](Self::with_dao) 注入 DAO 实例,
///   否则 `verify_id_token` 返回 [`GarrisonError::Config`] 错误。
pub struct KeycloakProvider {
    /// RP 配置(base_url / client_id / client_secret / redirect_uri / expected_iss)。
    config: KeycloakConfig,
    /// 可复用的 HTTP 客户端。
    http: reqwest::Client,
    /// DAO 抽象(通过 oxcache 管理 JWKS 缓存)。
    ///
    /// `None` 时 `verify_id_token` 返回 [`GarrisonError::Config`] 错误。
    /// 调用方通过 [`with_dao`](Self::with_dao) 注入。
    dao: Option<Arc<dyn GarrisonDao>>,
    /// PKCE code_verifier。
    ///
    /// 由 [`with_pkce`](Self::with_pkce) 设置;`Some` 时 `exchange_code` 改用 PKCE 鉴权
    /// (请求体追加 `code_verifier`,跳过 `client_secret`)。`client_secret=None` 的
    /// public client 必须调用 `with_pkce`,否则 `exchange_code` 返回错误。
    pkce_verifier: Option<String>,
}

impl KeycloakProvider {
    /// 构造 `KeycloakProvider`。
    ///
    /// # 参数
    ///
    /// - `config`: [`KeycloakConfig`] 配置实例。
    ///
    /// # 错误
    ///
    /// - `GarrisonError::Network`: `reqwest::Client` 构建失败。
    pub fn new(config: KeycloakConfig) -> GarrisonResult<Self> {
        let http = build_safe_http_client().map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-http-client-build-failed",
                format!("Failed to build HTTP client: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        Ok(Self {
            config,
            http,
            dao: None,
            pkce_verifier: None,
        })
    }

    /// 注入 [`GarrisonDao`] 实例以接管 JWKS 缓存。
    ///
    /// **必选调用**:`verify_id_token` 依赖 DAO 缓存 JWKS 公钥集合,
    /// 未注入 DAO 时返回 [`GarrisonError::Config`] 错误。
    ///
    /// JWKS 缓存 key 格式:`keycloak:jwks:{expected_iss}`,TTL 由 [`JWKS_CACHE_TTL`] 控制。
    ///
    /// # 参数
    ///
    /// - `dao`: DAO 实例(通常为 `Arc<GarrisonDaoOxcache>` 或测试用 `Arc<MockDao>`)。
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let provider = KeycloakProvider::new(config)?
    ///     .with_dao(Arc::new(GarrisonDaoOxcache::new().await?));
    /// ```
    pub fn with_dao(mut self, dao: Arc<dyn GarrisonDao>) -> Self {
        self.dao = Some(dao);
        self
    }

    /// 设置 PKCE code_verifier。
    ///
    /// 调用后,[`exchange_code`](Self::exchange_code) 改用 PKCE 鉴权:
    /// - 请求体追加 `code_verifier` 字段
    /// - 跳过 `client_secret` 字段(即使已配置,PKCE 优先级更高)
    ///
    /// `client_secret=None` 的 public client 必须调用此方法,否则 `exchange_code`
    /// 返回 [`GarrisonError::Config`] 错误。
    ///
    /// # 参数
    ///
    /// - `verifier`: PKCE code_verifier,RFC 7636 §4.1 要求:
    ///   - 长度 43-128 字符
    ///   - 仅允许 `[A-Z]/[a-z]/[0-9]/-./_/~`
    ///
    /// # 错误
    ///
    /// - [`GarrisonError::InvalidParam`]: verifier 长度或字符集不合法(透传自
    ///   [`OAuth2Client::generate_pkce_challenge`](crate::protocol::oauth2::OAuth2Client::generate_pkce_challenge))。
    pub fn with_pkce(mut self, verifier: &str) -> GarrisonResult<Self> {
        // 复用 OAuth2Client::generate_pkce_challenge 校验 verifier 长度 43-128 + 字符集
        //(RFC 7636 §4.1)。challenge 值本身不使用(授权服务器在 token endpoint 重新计算并比对
        // code_verifier 与授权请求中的 code_challenge)。
        crate::protocol::oauth2::OAuth2Client::generate_pkce_challenge(verifier)?;
        self.pkce_verifier = Some(verifier.to_string());
        Ok(self)
    }

    /// 从 `/.well-known/openid-configuration` 拉取 OIDC discovery metadata
    ///
    /// HTTP GET [`KeycloakConfig::discovery_url`],响应体按 JSON 解析为
    /// [`OidcDiscoveryMetadata`]。
    ///
    /// # 错误
    ///
    /// - `GarrisonError::Network`: HTTP 请求失败或非 2xx 状态码。
    /// - `GarrisonError::Deserialize`: 响应体 JSON 无法解析为 `OidcDiscoveryMetadata`。
    pub async fn discover(&self) -> GarrisonResult<OidcDiscoveryMetadata> {
        let url = self.config.discovery_url();
        let resp = self.http.get(&url).send().await.map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-discovery-request-failed",
                format!("discovery request failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        if !resp.status().is_success() {
            return Err(GarrisonError::Network(loc!(
                "keycloak-discovery-status-not-2xx",
                format!("discovery response status not 2xx: {}", resp.status()),
                ("detail", &resp.status().to_string())
            )));
        }
        // E2:限制响应体大小,防止恶意 IdP 通过超大 discovery JSON 触发 OOM
        let bytes = read_limited_bytes(resp).await.map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-discovery-body-read-failed",
                format!("discovery body read failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        serde_json::from_slice::<OidcDiscoveryMetadata>(&bytes).map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-discovery-response-parse-failed",
                format!("discovery response parse failed: {}", e),
                ("detail", &e.to_string())
            ))
        })
    }

    /// 构造 JWKS 在 DAO 中的缓存 key。
    ///
    /// 格式:`keycloak:jwks:{expected_iss}`,按 issuer 区分不同 Keycloak realm。
    fn jwks_cache_key(&self) -> String {
        format!("{}{}", JWKS_CACHE_KEY_PREFIX, self.config.expected_iss)
    }

    /// 拉取 JWKS 公钥集合并写入 DAO 缓存。
    ///
    /// HTTP GET [`KeycloakConfig::jwks_url`],响应体按 JSON 解析为 [`JwksResponse`],
    /// 序列化为 JSON 字符串后通过 `dao.set(key, json, JWKS_CACHE_TTL.as_secs())` 写入缓存。
    /// TTL 由 oxcache 自动管理(set 时传入 TTL),过期后下次 `verify_id_token` 自动重新拉取。
    ///
    /// # 错误
    ///
    /// - `GarrisonError::Config`: 未调用 [`with_dao`](Self::with_dao) 注入 DAO。
    /// - `GarrisonError::Network`: HTTP 请求失败、非 2xx 状态码或 JSON 解析失败。
    /// - `GarrisonError::Dao`: DAO 写入失败。
    async fn fetch_jwks(&self) -> GarrisonResult<()> {
        let dao = self.dao.as_ref().ok_or_else(|| {
            GarrisonError::Config(loc!(
                "keycloak-dao-not-injected",
                "KeycloakProvider DAO not injected, cannot cache JWKS (call with_dao to inject GarrisonDao)"
                    .to_string()
            ))
        })?;
        let url = self.config.jwks_url();
        let resp = self.http.get(&url).send().await.map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-jwks-request-failed",
                format!("JWKS request failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        if !resp.status().is_success() {
            return Err(GarrisonError::Network(loc!(
                "keycloak-jwks-status-not-2xx",
                format!("JWKS response status not 2xx: {}", resp.status()),
                ("detail", &resp.status().to_string())
            )));
        }
        // E2:限制响应体大小,防止恶意 IdP 通过超大 JWKS JSON 触发 OOM
        let bytes = read_limited_bytes(resp).await.map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-jwks-body-read-failed",
                format!("JWKS body read failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        let jwks: JwksResponse = serde_json::from_slice(&bytes).map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-jwks-response-parse-failed",
                format!("JWKS response parse failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        // 序列化为 JSON 字符串存入 DAO(反序列化时按相同结构解析)
        let json = serde_json::to_string(&jwks).map_err(|e| {
            GarrisonError::Internal(loc!(
                "keycloak-jwks-serialize-failed",
                format!("JWKS serialize failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        let cache_key = self.jwks_cache_key();
        dao.set(&cache_key, &json, JWKS_CACHE_TTL.as_secs()).await?;
        Ok(())
    }

    /// 验证 id_token 签名并解析 Keycloak claims
    ///
    /// # 流程
    ///
    /// 1. 解析 JWT header,提取 `kid`。
    /// 2. 从 DAO 缓存读取 JWKS(key=`keycloak:jwks:{expected_iss}`),
    ///    缓存 miss 或反序列化失败时调用 `fetch_jwks` 重新拉取并写入缓存。
    /// 3. 按 `kid` 匹配 JWKS 公钥,用 `n`/`e` 模数构造 `DecodingKey`。
    /// 4. 用 RS256 算法验签,解析为 [`KeycloakClaims`]。
    /// 5. 校验 `exp`(过期时间)/ `nbf`(生效时间)/ `aud`(受众)/ `iss`(签发者),
    ///    启用 aud/iss/nbf 三重校验,防止 token 被重放给非预期 client/issuer。
    ///
    /// # 错误
    ///
    /// - `GarrisonError::Config`: 未调用 [`with_dao`](Self::with_dao) 注入 DAO。
    /// - `GarrisonError::InvalidToken`: JWT header 解析失败 / kid 缺失 / JWKS 无匹配公钥 /
    ///   签名验证失败 / claims 解析失败 / token 已过期 / aud 不匹配 / iss 不匹配 / nbf 未生效。
    /// - `GarrisonError::Network`: JWKS 拉取失败。
    /// - `GarrisonError::Dao`: DAO 读写失败。
    pub async fn verify_id_token(&self, id_token: &str) -> GarrisonResult<KeycloakClaims> {
        use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};

        let dao = self.dao.as_ref().ok_or_else(|| {
            GarrisonError::Config(loc!(
                "keycloak-dao-not-injected",
                "KeycloakProvider DAO not injected, cannot cache JWKS (call with_dao to inject GarrisonDao)"
                    .to_string()
            ))
        })?;

        // 1. 解析 JWT header,提取 kid
        let header = jsonwebtoken::decode_header(id_token).map_err(|e| {
            GarrisonError::InvalidToken(loc!(
                "keycloak-id-token-header-parse-failed",
                format!("id_token header parse failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        let kid = header.kid.as_deref().ok_or_else(|| {
            GarrisonError::InvalidToken(loc!(
                "keycloak-id-token-header-missing-kid",
                "id_token header missing kid field".to_string()
            ))
        })?;

        // 2. 从 DAO 读取 JWKS 缓存;缓存 miss 或反序列化失败(缓存损坏)时重新拉取
        let cache_key = self.jwks_cache_key();
        let cached = dao.get(&cache_key).await?;
        let jwks: JwksResponse = match cached
            .as_deref()
            .and_then(|json| serde_json::from_str(json).ok())
        {
            Some(jwks) => jwks,
            None => {
                // 缓存 miss / TTL 过期 / 反序列化失败:重新拉取并写入缓存
                self.fetch_jwks().await?;
                let json = dao.get(&cache_key).await?.ok_or_else(|| {
                    GarrisonError::Internal(loc!(
                        "keycloak-jwks-cache-miss-after-fetch",
                        "cache miss after fetch_jwks (DAO write anomaly)".to_string()
                    ))
                })?;
                serde_json::from_str(&json).map_err(|e| {
                    GarrisonError::Internal(loc!(
                        "keycloak-jwks-deserialize-failed",
                        format!("JWKS deserialize failed: {}", e),
                        ("detail", &e.to_string())
                    ))
                })?
            },
        };

        // 3. 按 kid 匹配 JWKS 公钥
        let jwk = jwks.keys.iter().find(|k| k.kid == kid).cloned();
        let jwk = jwk.ok_or_else(|| {
            GarrisonError::InvalidToken(loc!(
                "keycloak-jwks-key-not-found",
                format!("JWKS key not found for kid={}", kid),
                ("kid", kid)
            ))
        })?;

        // 4. 构造 DecodingKey 并验签
        let decoding_key = DecodingKey::from_rsa_components(&jwk.n, &jwk.e).map_err(|e| {
            GarrisonError::InvalidToken(loc!(
                "keycloak-rsa-public-key-build-failed",
                format!("Failed to build RSA public key: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        // 启用 aud/iss/nbf 三重校验
        // - validate_exp: 校验 exp(过期时间),T119-T120 已启用
        // - validate_nbf: 校验 nbf(生效时间),防止 token 在生效前被使用
        // - validate_aud: 校验 aud(受众),期望 aud 包含 client_id,防止 token 被重放给非预期 client
        // - set_audience: 设置期望的 audience = client_id
        // - set_issuer: 设置期望的 issuer = expected_iss,防止 token 被重放给非预期 issuer
        let mut validation = Validation::new(Algorithm::RS256);
        validation.validate_exp = true;
        validation.validate_nbf = true; // 启用 nbf 校验
        validation.validate_aud = true; // 启用 aud 校验
        validation.set_audience(&[&self.config.client_id]); // 期望 aud = client_id
        validation.set_issuer(&[&self.config.expected_iss]); // 期望 iss = expected_iss
        validation.leeway = 0;

        let token_data =
            decode::<KeycloakClaims>(id_token, &decoding_key, &validation).map_err(|e| {
                let msg = e.to_string();
                if msg.contains("ExpiredSignature") {
                    GarrisonError::InvalidToken(loc!(
                        "keycloak-token-expired",
                        "token expired".to_string()
                    ))
                } else if msg.contains("ImmatureSignature") {
                    // nbf 校验失败(token 尚未生效)
                    GarrisonError::InvalidToken(loc!(
                        "keycloak-token-immature",
                        "token not yet valid (nbf)".to_string()
                    ))
                } else if msg.contains("InvalidAudience") {
                    // aud 校验失败(audience 不匹配 client_id)
                    GarrisonError::InvalidToken(loc!(
                        "keycloak-token-invalid-audience",
                        "invalid audience".to_string()
                    ))
                } else if msg.contains("InvalidIssuer") {
                    // iss 校验失败(issuer 不匹配 expected_iss)
                    GarrisonError::InvalidToken(loc!(
                        "keycloak-token-invalid-issuer",
                        "invalid issuer".to_string()
                    ))
                } else {
                    GarrisonError::InvalidToken(loc!(
                        "keycloak-id-token-verify-failed",
                        format!("id_token verify failed: {}", e),
                        ("detail", &e.to_string())
                    ))
                }
            })?;
        Ok(token_data.claims)
    }

    /// 用授权码换取 token set
    ///
    /// # 流程
    ///
    /// POST 请求 [`KeycloakConfig::token_url`],以 `application/x-www-form-urlencoded`
    /// 格式提交:
    /// - `grant_type=authorization_code`
    /// - `code`: 授权码
    /// - `client_id`: [`KeycloakConfig::client_id`]
    /// - `redirect_uri`: [`KeycloakConfig::redirect_uri`]
    /// - 鉴权字段:
    ///   - 调用过 [`with_pkce`](Self::with_pkce):追加 `code_verifier`,跳过 `client_secret`
    ///   - 仅配置 `client_secret`:追加 `client_secret`
    ///   - 两者均无:返回 [`GarrisonError::Config`](public client 必须使用 PKCE)
    ///
    /// # 错误
    ///
    /// - `GarrisonError::Network`: HTTP 请求失败、非 2xx 状态码或 JSON 解析失败。
    /// - `GarrisonError::InvalidParam`: `code` 为空。
    /// - `GarrisonError::Config`: `client_secret=None` 且未调用 [`with_pkce`](Self::with_pkce)
    ///   (public client 必须使用 PKCE 鉴权)。
    pub async fn exchange_code(&self, code: &str) -> GarrisonResult<KeycloakTokenSet> {
        if code.is_empty() {
            return Err(GarrisonError::InvalidParam(loc!(
                "keycloak-code-empty",
                "code cannot be empty".to_string()
            )));
        }

        let mut form: Vec<(&str, &str)> = vec![
            ("grant_type", "authorization_code"),
            ("code", code),
            ("client_id", &self.config.client_id),
            ("redirect_uri", &self.config.redirect_uri),
        ];

        // 鉴权方式选择:
        // - 设置了 PKCE verifier:使用 code_verifier,跳过 client_secret
        // - 仅设置了 client_secret:使用 client_secret
        // - 两者均无:返回错误(public client 必须调用 with_pkce)
        match (&self.pkce_verifier, &self.config.client_secret) {
            (Some(verifier), _) => form.push(("code_verifier", verifier.as_str())),
            (None, Some(secret)) => form.push(("client_secret", secret.as_str())),
            (None, None) => {
                return Err(GarrisonError::Config(loc!(
                    "keycloak-public-client-requires-pkce",
                    "public client (client_secret=None) must call with_pkce to set PKCE verifier"
                        .to_string()
                )));
            },
        }

        let url = self.config.token_url();
        let resp = self.http.post(&url).form(&form).send().await.map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-exchange-code-request-failed",
                format!("exchange_code request failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        if !resp.status().is_success() {
            return Err(GarrisonError::Network(loc!(
                "keycloak-exchange-code-status-not-2xx",
                format!("exchange_code response status not 2xx: {}", resp.status()),
                ("detail", &resp.status().to_string())
            )));
        }
        // E2:限制响应体大小,防止恶意 IdP 通过超大 token JSON 触发 OOM
        let bytes = read_limited_bytes(resp).await.map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-exchange-code-body-read-failed",
                format!("exchange_code body read failed: {}", e),
                ("detail", &e.to_string())
            ))
        })?;
        serde_json::from_slice::<KeycloakTokenSet>(&bytes).map_err(|e| {
            GarrisonError::Network(loc!(
                "keycloak-exchange-code-response-parse-failed",
                format!("exchange_code response parse failed: {}", e),
                ("detail", &e.to_string())
            ))
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dao::MockDao;

    // ========================================================================
    // T111-KeycloakConfig Red-Green
    // ========================================================================

    /// T111 Red: `KeycloakConfig` 构造 + `discovery_url()` 返回正确 URL
    ///
    /// Red 阶段:`KeycloakConfig` 类型不存在 → 编译失败。
    /// Green 阶段(T112):定义 `KeycloakConfig` + `discovery_url()` 后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 构造 `KeycloakConfig { base_url, client_id, client_secret: None, redirect_uri }`
    /// 2. 断言四个字段可读且值正确
    /// 3. 断言 `discovery_url()` 返回 `{base_url}/.well-known/openid-configuration`
    #[test]
    fn keycloak_config_constructs_with_base_url_client_id() {
        let config = KeycloakConfig {
            base_url: "https://kc.example.com:8443/realms/myrealm".into(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: "https://kc.example.com:8443/realms/myrealm".into(),
        };

        assert_eq!(
            config.base_url,
            "https://kc.example.com:8443/realms/myrealm"
        );
        assert_eq!(config.client_id, "garrison-rp");
        assert!(config.client_secret.is_none());
        assert_eq!(config.redirect_uri, "https://app.example.com/cb");

        assert_eq!(
            config.discovery_url(),
            "https://kc.example.com:8443/realms/myrealm/.well-known/openid-configuration"
        );
    }

    // ========================================================================
    // T113-KeycloakProvider::discover Red-Green
    // ========================================================================

    /// T113 Red: `KeycloakProvider::discover` 从 `/.well-known/openid-configuration`
    /// 拉取 OIDC discovery metadata。
    ///
    /// Red 阶段:`KeycloakProvider` / `OidcDiscoveryMetadata` 类型不存在 → 编译失败。
    /// Green 阶段(T114):定义 struct + discover 方法后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 启动 wiremock MockServer,挂载 `GET /.well-known/openid-configuration`
    ///    返回标准 OIDC discovery JSON(含 issuer / authorization_endpoint / token_endpoint / jwks_uri)
    /// 2. 用 mock server URI 作为 base_url 构造 `KeycloakConfig`
    /// 3. 构造 `KeycloakProvider::new(config)`,调用 `discover().await?`
    /// 4. 断言返回 `OidcDiscoveryMetadata` 的四个字段值正确
    #[tokio::test]
    async fn keycloak_provider_discover_fetches_metadata_from_well_known() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;

        let issuer = server.uri();
        let authorization_endpoint = format!("{}/protocol/openid-connect/auth", server.uri());
        let token_endpoint = format!("{}/protocol/openid-connect/token", server.uri());
        let jwks_uri = format!("{}/protocol/openid-connect/certs", server.uri());

        Mock::given(method("GET"))
            .and(path("/.well-known/openid-configuration"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "issuer": issuer,
                "authorization_endpoint": authorization_endpoint,
                "token_endpoint": token_endpoint,
                "jwks_uri": jwks_uri,
                "response_types_supported": ["code"],
                "subject_types_supported": ["public"],
                "id_token_signing_alg_values_supported": ["RS256"],
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let provider = KeycloakProvider::new(config).expect("KeycloakProvider::new 应成功");
        let metadata = provider.discover().await.expect("discover 应返回 Ok");

        assert_eq!(metadata.issuer, issuer);
        assert_eq!(metadata.authorization_endpoint, authorization_endpoint);
        assert_eq!(metadata.token_endpoint, token_endpoint);
        assert_eq!(metadata.jwks_uri, jwks_uri);
    }

    // ========================================================================
    // T115-KeycloakProvider::verify_id_token Red-Green
    // ========================================================================

    /// T115 Red: `KeycloakProvider::verify_id_token` 用 JWKS 公钥验签 id_token
    /// 并解析 Keycloak 特有 claim。
    ///
    /// Red 阶段:`KeycloakClaims` 类型不存在 → 编译失败。
    /// Green 阶段(T116):定义 struct + verify_id_token 方法后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 生成 RSA 2048 测试密钥对
    /// 2. 提取公钥 n/e 模数编码为 base64url(JWKS 格式)
    /// 3. 用私钥签发 JWT(header 含 kid=key1,claims 含 sub/preferred_username/
    ///    realm_access.roles/resource_access.account.roles/aud/iss)
    /// 4. mock JWKS endpoint 返回公钥集合
    /// 5. 调用 `verify_id_token(id_token).await?`
    /// 6. 断言返回 `KeycloakClaims` 的 `sub` 与 `realm_access.roles` 正确
    #[tokio::test]
    async fn keycloak_provider_verify_id_token_validates_signature_and_claims() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine;
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use rand::rngs::OsRng;
        use rsa::pkcs1::EncodeRsaPrivateKey;
        use rsa::traits::PublicKeyParts;
        use rsa::{RsaPrivateKey, RsaPublicKey};
        use serde::Serialize;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        // 1. 生成 RSA 2048 测试密钥对
        let mut rng = OsRng;
        let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("生成 RSA 私钥应成功");
        let public_key = RsaPublicKey::from(&private_key);

        // 2. 提取公钥 n/e 模数编码为 base64url(JWKS 格式)
        let n_bytes = public_key.n().to_bytes_be();
        let e_bytes = public_key.e().to_bytes_be();
        let n_b64 = URL_SAFE_NO_PAD.encode(n_bytes);
        let e_b64 = URL_SAFE_NO_PAD.encode(e_bytes);

        // 3. 用私钥签发 JWT(header 含 kid=key1)
        //    jsonwebtoken 10 的 EncodingKey::from_rsa_der 期望 PKCS#1 DER(非 PKCS#8)
        let der = private_key.to_pkcs1_der().expect("转 PKCS#1 DER 应成功");
        let encoding_key = EncodingKey::from_rsa_der(der.as_bytes());

        // 先启动 mock server,iss claim 需要 server.uri() 作为 issuer
        let server = MockServer::start().await;
        let issuer = server.uri();

        #[derive(Serialize)]
        struct KeycloakTestClaims {
            sub: String,
            exp: i64,
            aud: serde_json::Value, // audience claim
            iss: String,            // issuer claim
            preferred_username: String,
            email: String,
            realm_access: serde_json::Value,
            resource_access: serde_json::Value,
        }

        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("key1".to_string());

        // exp 设为当前时间 + 3600 秒(1 小时后过期,确保 validate_exp 通过)
        let exp = (std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("系统时间应早于 UNIX_EPOCH")
            .as_secs() as i64)
            + 3600;

        let claims = KeycloakTestClaims {
            sub: "user-123".into(),
            exp,
            aud: serde_json::Value::String("garrison-rp".to_string()), // aud = client_id
            iss: issuer.clone(),                                       // iss = expected_iss
            preferred_username: "alice".into(),
            email: "alice@example.com".into(),
            realm_access: serde_json::json!({ "roles": ["user", "admin"] }),
            resource_access: serde_json::json!({
                "account": { "roles": ["manage-account"] }
            }),
        };

        let id_token = encode(&header, &claims, &encoding_key).expect("签发 JWT 应成功");

        // 4. mock JWKS endpoint
        Mock::given(method("GET"))
            .and(path("/protocol/openid-connect/certs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "keys": [{
                    "kty": "RSA",
                    "kid": "key1",
                    "use": "sig",
                    "alg": "RS256",
                    "n": n_b64,
                    "e": e_b64,
                }]
            })))
            .mount(&server)
            .await;

        // 5. 构造 KeycloakProvider 并调用 verify_id_token
        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: issuer,
        };
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_dao(Arc::new(MockDao::new()));
        let keycloak_claims = provider
            .verify_id_token(&id_token)
            .await
            .expect("verify_id_token 应返回 Ok");

        // 6. 断言 KeycloakClaims 字段
        assert_eq!(keycloak_claims.sub, "user-123");
        assert_eq!(keycloak_claims.realm_access.roles, vec!["user", "admin"]);
    }

    // ========================================================================
    // T117-KeycloakProvider::exchange_code Red-Green
    // ========================================================================

    /// T117 Red: `KeycloakProvider::exchange_code` 用授权码换取 token set
    ///
    /// Red 阶段:`KeycloakTokenSet` 类型 / `exchange_code` 方法不存在 → 编译失败。
    /// Green 阶段(T118):定义 struct + exchange_code 方法后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 启动 wiremock MockServer,挂载 `POST /protocol/openid-connect/token`
    ///    返回标准 token 响应 JSON
    /// 2. 构造 `KeycloakProvider`,调用 `exchange_code("code").await?`
    /// 3. 断言返回 `KeycloakTokenSet` 含 access_token / refresh_token / id_token / expires_in
    #[tokio::test]
    async fn keycloak_provider_exchange_code_returns_token_set() {
        use wiremock::matchers::{body_string, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/protocol/openid-connect/token"))
            .and(body_string(
                "grant_type=authorization_code&code=auth_code_123&client_id=garrison-rp&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcb&client_secret=secret123",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "at-456",
                "refresh_token": "rt-789",
                "id_token": "it-012",
                "expires_in": 3600,
                "token_type": "Bearer",
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: Some("secret123".into()),
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let provider = KeycloakProvider::new(config).expect("KeycloakProvider::new 应成功");
        let token_set = provider
            .exchange_code("auth_code_123")
            .await
            .expect("exchange_code 应返回 Ok");

        assert_eq!(token_set.access_token, "at-456");
        assert_eq!(token_set.refresh_token, "rt-789");
        assert_eq!(token_set.id_token, "it-012");
        assert_eq!(token_set.expires_in, 3600);
    }

    // ========================================================================
    // T119-过期 id_token 被拒绝(已实现于 T116,此为回归测试)
    // ========================================================================

    /// T119 回归测试: `verify_id_token` 拒绝已过期的 id_token
    ///
    /// T116 的 `verify_id_token` 实现已含 `validate_exp = true` +
    /// `ExpiredSignature` → `InvalidToken("token expired")` 映射。
    /// 本测试验证该行为,确保过期 token 不会被误判为有效。
    ///
    /// # 测试流程
    ///
    /// 1. 生成 RSA 密钥对,签发一个 `exp` 已过期的 ID Token(aud/iss 正确以隔离 exp 校验)
    /// 2. mock JWKS endpoint 返回公钥
    /// 3. 调用 `verify_id_token`,断言返回 `GarrisonError::InvalidToken("token expired")`
    #[tokio::test]
    async fn keycloak_provider_rejects_expired_id_token() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine;
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use rand::rngs::OsRng;
        use rsa::pkcs1::EncodeRsaPrivateKey;
        use rsa::traits::PublicKeyParts;
        use rsa::{RsaPrivateKey, RsaPublicKey};
        use serde::Serialize;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        // 1. 生成 RSA 密钥对 + 签发过期 JWT
        let mut rng = OsRng;
        let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("生成 RSA 私钥应成功");
        let public_key = RsaPublicKey::from(&private_key);

        let n_b64 = URL_SAFE_NO_PAD.encode(public_key.n().to_bytes_be());
        let e_b64 = URL_SAFE_NO_PAD.encode(public_key.e().to_bytes_be());

        let der = private_key.to_pkcs1_der().expect("转 PKCS#1 DER 应成功");
        let encoding_key = EncodingKey::from_rsa_der(der.as_bytes());

        // 先启动 mock server,iss claim 需要 server.uri() 作为 issuer
        let server = MockServer::start().await;
        let issuer = server.uri();

        #[derive(Serialize)]
        struct ExpiredTestClaims {
            sub: String,
            exp: i64,
            aud: serde_json::Value, // audience claim(正确值以隔离 exp 校验)
            iss: String,            // issuer claim(正确值以隔离 exp 校验)
            realm_access: serde_json::Value,
            resource_access: serde_json::Value,
        }

        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("key1".to_string());

        // exp 设为当前时间 - 3600 秒(1 小时前已过期)
        let exp = (std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("系统时间应早于 UNIX_EPOCH")
            .as_secs() as i64)
            - 3600;

        let claims = ExpiredTestClaims {
            sub: "user-123".into(),
            exp,
            aud: serde_json::Value::String("garrison-rp".to_string()), // aud 正确
            iss: issuer.clone(),                                       // iss 正确
            realm_access: serde_json::json!({ "roles": ["user"] }),
            resource_access: serde_json::json!({
                "account": { "roles": ["manage-account"] }
            }),
        };

        let id_token = encode(&header, &claims, &encoding_key).expect("签发 JWT 应成功");

        // 2. mock JWKS endpoint
        Mock::given(method("GET"))
            .and(path("/protocol/openid-connect/certs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "keys": [{
                    "kty": "RSA",
                    "kid": "key1",
                    "n": n_b64,
                    "e": e_b64,
                }]
            })))
            .mount(&server)
            .await;

        // 3. 调用 verify_id_token,断言返回 InvalidToken(启用 i18n 时消息本地化,
        //    关闭 i18n 时回退到 fallback 字面量,故用 contains 兼容两种构建)
        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: issuer,
        };
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_dao(Arc::new(MockDao::new()));
        let result = provider.verify_id_token(&id_token).await;

        match result {
            Err(crate::error::GarrisonError::InvalidToken(msg)) => {
                assert!(
                    msg.contains("expired") || msg.contains("过期"),
                    "过期 token 应返回过期相关消息,实际: {}",
                    msg
                );
            },
            other => panic!("过期 token 应返回 InvalidToken 过期消息,实际: {:?}", other),
        }
    }

    // ========================================================================
    // aud/iss 校验测试
    // ========================================================================

    /// 测试 1:`verify_id_token` 拒绝 aud 不匹配 client_id 的 id_token
    ///
    /// 启用 `validate_aud = true` + `set_audience(&[client_id])` 后,
    /// aud 不包含 client_id 的 token 应返回 `InvalidToken("invalid audience")`。
    ///
    /// # 测试流程
    ///
    /// 1. 生成 RSA 密钥对,签发 aud="wrong-audience"(不匹配 client_id="garrison-rp")的 JWT
    /// 2. mock JWKS endpoint 返回公钥
    /// 3. 调用 `verify_id_token`,断言返回 `InvalidToken` 且消息含 "audience"
    #[tokio::test]
    async fn keycloak_verify_id_token_rejects_wrong_audience() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine;
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use rand::rngs::OsRng;
        use rsa::pkcs1::EncodeRsaPrivateKey;
        use rsa::traits::PublicKeyParts;
        use rsa::{RsaPrivateKey, RsaPublicKey};
        use serde::Serialize;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mut rng = OsRng;
        let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("生成 RSA 私钥应成功");
        let public_key = RsaPublicKey::from(&private_key);

        let n_b64 = URL_SAFE_NO_PAD.encode(public_key.n().to_bytes_be());
        let e_b64 = URL_SAFE_NO_PAD.encode(public_key.e().to_bytes_be());

        let der = private_key.to_pkcs1_der().expect("转 PKCS#1 DER 应成功");
        let encoding_key = EncodingKey::from_rsa_der(der.as_bytes());

        let server = MockServer::start().await;
        let issuer = server.uri();

        #[derive(Serialize)]
        struct WrongAudTestClaims {
            sub: String,
            exp: i64,
            aud: serde_json::Value,
            iss: String,
            realm_access: serde_json::Value,
            resource_access: serde_json::Value,
        }

        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("key1".to_string());

        let exp = (std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("系统时间应早于 UNIX_EPOCH")
            .as_secs() as i64)
            + 3600;

        let claims = WrongAudTestClaims {
            sub: "user-123".into(),
            exp,
            aud: serde_json::Value::String("wrong-audience".to_string()), // 故意不匹配 client_id
            iss: issuer.clone(),
            realm_access: serde_json::json!({ "roles": ["user"] }),
            resource_access: serde_json::json!({
                "account": { "roles": ["manage-account"] }
            }),
        };

        let id_token = encode(&header, &claims, &encoding_key).expect("签发 JWT 应成功");

        Mock::given(method("GET"))
            .and(path("/protocol/openid-connect/certs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "keys": [{
                    "kty": "RSA",
                    "kid": "key1",
                    "n": n_b64,
                    "e": e_b64,
                }]
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: issuer,
        };
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_dao(Arc::new(MockDao::new()));
        let result = provider.verify_id_token(&id_token).await;

        match result {
            Err(crate::error::GarrisonError::InvalidToken(msg)) => {
                assert!(
                    msg.contains("audience"),
                    "aud 不匹配应返回 audience 相关消息,实际: {}",
                    msg
                );
            },
            other => panic!("aud 不匹配应返回 InvalidToken,实际: {:?}", other),
        }
    }

    /// 测试 2:`verify_id_token` 拒绝 iss 不匹配 expected_iss 的 id_token
    ///
    /// 启用 `set_issuer(&[expected_iss])` 后,
    /// iss 不等于 expected_iss 的 token 应返回 `InvalidToken("invalid issuer")`。
    ///
    /// # 测试流程
    ///
    /// 1. 生成 RSA 密钥对,签发 iss="https://wrong-issuer.example.com"(不匹配 expected_iss)的 JWT
    /// 2. mock JWKS endpoint 返回公钥
    /// 3. 调用 `verify_id_token`,断言返回 `InvalidToken` 且消息含 "issuer"
    #[tokio::test]
    async fn keycloak_verify_id_token_rejects_wrong_issuer() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine;
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use rand::rngs::OsRng;
        use rsa::pkcs1::EncodeRsaPrivateKey;
        use rsa::traits::PublicKeyParts;
        use rsa::{RsaPrivateKey, RsaPublicKey};
        use serde::Serialize;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mut rng = OsRng;
        let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("生成 RSA 私钥应成功");
        let public_key = RsaPublicKey::from(&private_key);

        let n_b64 = URL_SAFE_NO_PAD.encode(public_key.n().to_bytes_be());
        let e_b64 = URL_SAFE_NO_PAD.encode(public_key.e().to_bytes_be());

        let der = private_key.to_pkcs1_der().expect("转 PKCS#1 DER 应成功");
        let encoding_key = EncodingKey::from_rsa_der(der.as_bytes());

        let server = MockServer::start().await;
        let issuer = server.uri();

        #[derive(Serialize)]
        struct WrongIssTestClaims {
            sub: String,
            exp: i64,
            aud: serde_json::Value,
            iss: String,
            realm_access: serde_json::Value,
            resource_access: serde_json::Value,
        }

        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("key1".to_string());

        let exp = (std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("系统时间应早于 UNIX_EPOCH")
            .as_secs() as i64)
            + 3600;

        let claims = WrongIssTestClaims {
            sub: "user-123".into(),
            exp,
            aud: serde_json::Value::String("garrison-rp".to_string()), // aud 正确
            iss: "https://wrong-issuer.example.com".to_string(),       // 故意不匹配 expected_iss
            realm_access: serde_json::json!({ "roles": ["user"] }),
            resource_access: serde_json::json!({
                "account": { "roles": ["manage-account"] }
            }),
        };

        let id_token = encode(&header, &claims, &encoding_key).expect("签发 JWT 应成功");

        Mock::given(method("GET"))
            .and(path("/protocol/openid-connect/certs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "keys": [{
                    "kty": "RSA",
                    "kid": "key1",
                    "n": n_b64,
                    "e": e_b64,
                }]
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: issuer,
        };
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_dao(Arc::new(MockDao::new()));
        let result = provider.verify_id_token(&id_token).await;

        match result {
            Err(crate::error::GarrisonError::InvalidToken(msg)) => {
                assert!(
                    msg.contains("issuer"),
                    "iss 不匹配应返回 issuer 相关消息,实际: {}",
                    msg
                );
            },
            other => panic!("iss 不匹配应返回 InvalidToken,实际: {:?}", other),
        }
    }

    /// 测试 3:`verify_id_token` 接受 aud 为数组形式(包含 client_id)的 id_token
    ///
    /// RFC 7519 §4.1.3 规定 aud 可以是 String 或 Vec<String>。
    /// Keycloak 实际签发的 token 中 aud 常为数组(如 `["garrison-rp", "account"]`)。
    /// 本测试验证 `serde_json::Value` 反序列化 + `validate_aud` 能正确处理数组形式。
    ///
    /// # 测试流程
    ///
    /// 1. 生成 RSA 密钥对,签发 aud=`["garrison-rp", "account"]`(数组含 client_id)的 JWT
    /// 2. mock JWKS endpoint 返回公钥
    /// 3. 调用 `verify_id_token`,断言返回 `Ok` 且 `sub` 正确
    #[tokio::test]
    async fn keycloak_verify_id_token_accepts_aud_array() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine;
        use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
        use rand::rngs::OsRng;
        use rsa::pkcs1::EncodeRsaPrivateKey;
        use rsa::traits::PublicKeyParts;
        use rsa::{RsaPrivateKey, RsaPublicKey};
        use serde::Serialize;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mut rng = OsRng;
        let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("生成 RSA 私钥应成功");
        let public_key = RsaPublicKey::from(&private_key);

        let n_b64 = URL_SAFE_NO_PAD.encode(public_key.n().to_bytes_be());
        let e_b64 = URL_SAFE_NO_PAD.encode(public_key.e().to_bytes_be());

        let der = private_key.to_pkcs1_der().expect("转 PKCS#1 DER 应成功");
        let encoding_key = EncodingKey::from_rsa_der(der.as_bytes());

        let server = MockServer::start().await;
        let issuer = server.uri();

        #[derive(Serialize)]
        struct AudArrayTestClaims {
            sub: String,
            exp: i64,
            aud: serde_json::Value,
            iss: String,
            realm_access: serde_json::Value,
            resource_access: serde_json::Value,
        }

        let mut header = Header::new(Algorithm::RS256);
        header.kid = Some("key1".to_string());

        let exp = (std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("系统时间应早于 UNIX_EPOCH")
            .as_secs() as i64)
            + 3600;

        let claims = AudArrayTestClaims {
            sub: "user-123".into(),
            exp,
            // aud 为数组形式,包含 client_id "garrison-rp" 和 "account"
            aud: serde_json::json!(["garrison-rp", "account"]),
            iss: issuer.clone(),
            realm_access: serde_json::json!({ "roles": ["user", "admin"] }),
            resource_access: serde_json::json!({
                "account": { "roles": ["manage-account"] }
            }),
        };

        let id_token = encode(&header, &claims, &encoding_key).expect("签发 JWT 应成功");

        Mock::given(method("GET"))
            .and(path("/protocol/openid-connect/certs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "keys": [{
                    "kty": "RSA",
                    "kid": "key1",
                    "n": n_b64,
                    "e": e_b64,
                }]
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: issuer,
        };
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_dao(Arc::new(MockDao::new()));
        let keycloak_claims = provider
            .verify_id_token(&id_token)
            .await
            .expect("aud 为数组含 client_id 时应返回 Ok");

        assert_eq!(keycloak_claims.sub, "user-123");
        assert_eq!(keycloak_claims.realm_access.roles, vec!["user", "admin"]);
    }

    // ========================================================================
    // T092-KeycloakProvider PKCE (RFC 7636 / D2) Red-Green
    // ========================================================================

    /// T092 测试 1:`with_pkce` 设置有效 verifier 后,`exchange_code` 请求体包含 `code_verifier`
    ///
    ///
    /// Red 阶段:`with_pkce` 方法体为 `todo!()` → 调用时 panic。
    /// Green 阶段(T093):实现 `with_pkce` 后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 构造 `KeycloakConfig`(`client_secret: None`)
    /// 2. `KeycloakProvider::new(config)?.with_pkce(VALID_VERIFIER)?`
    /// 3. mock token endpoint 返回 200 + 标准 token set
    /// 4. 调用 `exchange_code("code").await?`
    /// 5. 断言返回 `KeycloakTokenSet`
    /// 6. 断言收到的请求体包含 `code_verifier=`,不包含 `client_secret=`
    #[tokio::test]
    async fn keycloak_pkce_flow_succeeds_with_valid_verifier() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/protocol/openid-connect/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "at-pkce",
                "refresh_token": "rt-pkce",
                "id_token": "it-pkce",
                "expires_in": 3600,
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_pkce(verifier)
            .expect("with_pkce 应成功");

        let token_set = provider
            .exchange_code("auth_code_123")
            .await
            .expect("exchange_code 应返回 Ok");
        assert_eq!(token_set.access_token, "at-pkce");
        assert_eq!(token_set.refresh_token, "rt-pkce");
        assert_eq!(token_set.id_token, "it-pkce");
        assert_eq!(token_set.expires_in, 3600);

        // 验证请求体包含 code_verifier,不包含 client_secret
        let received = server.received_requests().await.expect("应收到请求");
        assert_eq!(received.len(), 1, "应只收到 1 个请求");
        let body = std::str::from_utf8(&received[0].body).expect("body 应为 UTF-8");
        assert!(
            body.contains("code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
            "请求体应包含 code_verifier 字段,实际: {}",
            body
        );
        assert!(
            !body.contains("client_secret="),
            "PKCE 流程不应包含 client_secret 字段,实际: {}",
            body
        );
    }

    /// T092 测试 2:`with_pkce` 传入无效 verifier(长度 < 43)返回 `InvalidParam` 错误
    ///
    ///
    /// Red 阶段:`with_pkce` 方法体为 `todo!()` → 调用时 panic(非预期 InvalidParam)。
    /// Green 阶段(T093):实现校验后返回 `InvalidParam` 错误。
    #[test]
    fn keycloak_pkce_flow_fails_on_invalid_verifier() {
        let config = KeycloakConfig {
            base_url: "https://kc.example.com:8443/realms/myrealm".into(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: "https://kc.example.com:8443/realms/myrealm".into(),
        };
        let provider = KeycloakProvider::new(config).expect("KeycloakProvider::new 应成功");

        // verifier 长度 5 < 43(RFC 7636 §4.1 下限)
        let result = provider.with_pkce("short");
        assert!(result.is_err(), "无效 verifier 应返回错误");
        match result.err() {
            Some(crate::error::GarrisonError::InvalidParam(msg)) => {
                assert!(
                    msg.contains("43") || msg.contains("长度"),
                    "错误消息应说明长度约束,实际: {}",
                    msg
                );
            },
            other => panic!("期望 InvalidParam 错误,实际: {:?}", other),
        }
    }

    /// T092 测试 3:`client_secret=None` 且未调用 `with_pkce`,`exchange_code` 返回错误
    ///
    ///
    /// Red 阶段:`exchange_code` 现有实现只检查 `client_secret.is_some()`,
    /// `client_secret=None` 时直接跳过 secret 字段,不返回错误 → 测试失败。
    /// Green 阶段(T093):在 `exchange_code` 中校验鉴权方式后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 构造 `KeycloakConfig`(`client_secret: None`)
    /// 2. 不调用 `with_pkce`
    /// 3. 调用 `exchange_code("code")`,断言返回 `Err(Config)`
    #[tokio::test]
    async fn keycloak_without_client_secret_and_without_pkce_returns_error() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        // 即使挂载了成功的 mock,exchange_code 也应在发送 HTTP 请求前返回错误
        Mock::given(method("POST"))
            .and(path("/protocol/openid-connect/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "should-not-reach",
                "refresh_token": "x",
                "id_token": "x",
                "expires_in": 3600,
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: None,
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let provider = KeycloakProvider::new(config).expect("KeycloakProvider::new 应成功");

        let result = provider.exchange_code("auth_code_123").await;
        assert!(result.is_err(), "无 client_secret 且无 PKCE 应返回错误");
        match result.err() {
            Some(crate::error::GarrisonError::Config(msg)) => {
                assert!(
                    msg.contains("with_pkce") || msg.contains("PKCE"),
                    "错误消息应提示调用 with_pkce,实际: {}",
                    msg
                );
            },
            other => panic!("期望 Config 错误,实际: {:?}", other),
        }

        // 验证未发送 HTTP 请求(鉴权校验应在 HTTP 调用前失败)
        let received = server.received_requests().await.expect("应能获取请求记录");
        assert_eq!(
            received.len(),
            0,
            "无鉴权方式时不应发送 HTTP 请求,实际收到 {} 个请求",
            received.len()
        );
    }

    /// T092 测试 4:同时配置 `client_secret` 和 PKCE 时,`exchange_code` 使用 PKCE 鉴权
    ///
    ///
    /// Red 阶段:`with_pkce` 方法体为 `todo!()` → 调用时 panic。
    /// Green 阶段(T093):实现 PKCE 优先级逻辑后测试通过。
    ///
    /// # 测试流程
    ///
    /// 1. 构造 `KeycloakConfig`(`client_secret: Some("secret123")`)
    /// 2. `with_pkce(VALID_VERIFIER)?`
    /// 3. mock token endpoint 返回 200
    /// 4. 调用 `exchange_code("code").await?`
    /// 5. 断言返回 `KeycloakTokenSet`
    /// 6. 断言请求体包含 `code_verifier=`,不包含 `client_secret=`
    #[tokio::test]
    async fn keycloak_with_pkce_overrides_client_secret_auth() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/protocol/openid-connect/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "at-override",
                "refresh_token": "rt-override",
                "id_token": "it-override",
                "expires_in": 1800,
            })))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: Some("secret123".into()),
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let provider = KeycloakProvider::new(config)
            .expect("KeycloakProvider::new 应成功")
            .with_pkce(verifier)
            .expect("with_pkce 应成功");

        let token_set = provider
            .exchange_code("auth_code_456")
            .await
            .expect("exchange_code 应返回 Ok");
        assert_eq!(token_set.access_token, "at-override");

        // 验证请求体使用 PKCE(code_verifier),不使用 client_secret
        let received = server.received_requests().await.expect("应收到请求");
        assert_eq!(received.len(), 1, "应只收到 1 个请求");
        let body = std::str::from_utf8(&received[0].body).expect("body 应为 UTF-8");
        assert!(
            body.contains("code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
            "PKCE 优先:请求体应包含 code_verifier 字段,实际: {}",
            body
        );
        assert!(
            !body.contains("client_secret="),
            "PKCE 优先:请求体不应包含 client_secret 字段,实际: {}",
            body
        );
    }

    // ========================================================================
    // Keycloak 异常消息 i18n(feature = "i18n")
    //
    // 验证 keycloak 的 loc! 宏在中英文 locale 下返回正确翻译。
    // 直接调用 loc! 宏避免依赖 HTTP mock,聚焦 i18n 翻译正确性。
    // ========================================================================

    /// T021 i18n 测试 6:zh locale 下 keycloak-token-expired 返回中文消息(无参数)。
    #[cfg(feature = "i18n")]
    #[test]
    fn loc_i18n_keycloak_token_expired_zh() {
        use crate::i18n::{set_locale, GarrisonLocale};
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = crate::loc!("keycloak-token-expired", "token expired".to_string());
        assert_eq!(msg, "token 已过期");
    }

    /// T021 i18n 测试 7:en locale 下 keycloak-token-expired 返回英文消息(无参数)。
    #[cfg(feature = "i18n")]
    #[test]
    fn loc_i18n_keycloak_token_expired_en() {
        use crate::i18n::{set_locale, GarrisonLocale};
        let _guard = set_locale(GarrisonLocale::En);
        let msg = crate::loc!("keycloak-token-expired", "token expired".to_string());
        assert_eq!(msg, "Token expired");
    }

    /// T021 i18n 测试 8:zh locale 下 keycloak-jwks-key-not-found 带 kid 参数返回中文。
    #[cfg(feature = "i18n")]
    #[test]
    fn loc_i18n_keycloak_jwks_key_not_found_with_kid_zh() {
        use crate::i18n::{set_locale, GarrisonLocale};
        let _guard = set_locale(GarrisonLocale::Zh);
        let msg = crate::loc!(
            "keycloak-jwks-key-not-found",
            "JWKS key not found for kid=abc123".to_string(),
            ("kid", "abc123")
        );
        assert_eq!(msg, "JWKS 中未找到 kid=abc123 的公钥");
    }

    // ========================================================================
    // E1: reqwest 客户端超时(KeycloakProvider 复用 protocol::oauth2::client)
    // ========================================================================

    /// E1 回归测试:KeycloakProvider::new 使用带超时的 HTTP 客户端。
    ///
    /// 验证 `build_safe_http_client()` 通过 `KeycloakProvider::new` 正常注入。
    /// 不直接断言 timeout 值(reqwest 不暴露运行时内省),由 client.rs 的
    /// `e1_read_timeout_triggers_on_slow_server` 行为测试覆盖。
    #[test]
    fn e1_keycloak_provider_new_uses_safe_http_client() {
        let config = KeycloakConfig {
            base_url: "https://kc.example.com:8443/realms/myrealm".into(),
            client_id: "garrison-rp".into(),
            client_secret: Some("secret".into()),
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: "https://kc.example.com:8443/realms/myrealm".into(),
        };
        let provider = KeycloakProvider::new(config);
        assert!(provider.is_ok(), "KeycloakProvider::new 必须成功");
    }

    // ========================================================================
    // E2: 响应体大小限制(KeycloakProvider discover/fetch_jwks/exchange_code)
    // ========================================================================

    /// E2 集成测试:KeycloakProvider::discover 拒绝超大 discovery JSON。
    ///
    /// wiremock 返回 5 MiB 的 discovery JSON,验证 discover() 返回 Err。
    #[tokio::test]
    async fn e2_keycloak_discover_rejects_oversized_response() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        // 构造 5 MiB 的 discovery JSON(合法结构但超过上限)
        let huge_value = "x".repeat(5 * 1024 * 1024);
        let huge_json = format!(
            r#"{{"issuer":"https://kc.example.com","authorization_endpoint":"{}","token_endpoint":"{}","jwks_uri":"{}","userinfo_endpoint":"{}"}}"#,
            huge_value, huge_value, huge_value, huge_value
        );
        Mock::given(method("GET"))
            .and(path("/.well-known/openid-configuration"))
            .respond_with(ResponseTemplate::new(200).set_body_string(huge_json))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: Some("secret".into()),
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let provider = KeycloakProvider::new(config).expect("provider 构建成功");
        let result = provider.discover().await;
        assert!(result.is_err(), "超大 discovery JSON 必须被拒绝");
    }

    /// E2 集成测试:KeycloakProvider::exchange_code 拒绝超大 token 响应。
    ///
    /// wiremock 返回 5 MiB 的 token JSON,验证 exchange_code() 返回 Err。
    #[tokio::test]
    async fn e2_keycloak_exchange_code_rejects_oversized_response() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let huge_value = "x".repeat(5 * 1024 * 1024);
        let huge_json = format!(r#"{{"access_token":"{}"}}"#, huge_value);
        Mock::given(method("POST"))
            .and(path("/protocol/openid-connect/token"))
            .respond_with(ResponseTemplate::new(200).set_body_string(huge_json))
            .mount(&server)
            .await;

        let config = KeycloakConfig {
            base_url: server.uri(),
            client_id: "garrison-rp".into(),
            client_secret: Some("secret".into()),
            redirect_uri: "https://app.example.com/cb".into(),
            expected_iss: server.uri(),
        };
        let provider = KeycloakProvider::new(config).expect("provider 构建成功");
        let result = provider.exchange_code("code123").await;
        assert!(result.is_err(), "超大 token JSON 必须被拒绝");
    }
}