hypershunt 1.0.0

HTTP server and reverse proxy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
pub mod routes;

mod jws;
use jws::{
    extract_groups_claim, extract_groups_claim_from_json,
    extract_optional_string_claim, extract_string_claim,
    jwks_signature_verifies, parse_compact_jws,
};

mod backchannel;
mod bearer;

// OIDC single sign-on back-end.
//
// On startup `OidcProvider::discover` runs OIDC discovery against the
// configured issuer and caches the resulting `OidcClient`.  Two hooks
// drive the login flow:
//
//   * `begin_login(return_to)` -- builds the authorisation URL,
//     stashes a PKCE verifier + nonce + return_to under the random
//     CSRF state, and returns both the URL and the state id.  Called
//     by the `<login_path>` endpoint dispatched in `listener.rs`.
//
//   * `complete_login(code, state)` -- consumes the stashed state,
//     exchanges the code with the IdP, validates the ID token, and
//     returns an `auth::Identity` plus the original return_to.
//     Called by the `<callback_path>` endpoint.
//
// The post-login identity is then persisted as a JWT session cookie
// via `JwtManager::make_set_cookie`, so subsequent requests carry
// authentication via the normal cookie path.

use crate::auth::Identity;
use crate::config::OidcConfig;
use crate::metrics::Metrics;
use anyhow::{Context, Result, anyhow, bail};
use arc_swap::ArcSwap;
use openidconnect::core::{
    CoreAuthDisplay, CoreAuthPrompt, CoreAuthenticationFlow,
    CoreClaimName, CoreClaimType, CoreClientAuthMethod,
    CoreErrorResponseType, CoreGenderClaim, CoreGrantType,
    CoreJsonWebKey, CoreJweContentEncryptionAlgorithm,
    CoreJweKeyManagementAlgorithm, CoreResponseMode, CoreResponseType,
    CoreRevocableToken, CoreRevocationErrorResponse,
    CoreSubjectIdentifierType, CoreTokenIntrospectionResponse,
    CoreTokenType,
};
use openidconnect::{
    AccessToken, AdditionalProviderMetadata, AsyncHttpClient,
    AuthorizationCode, ClientId,
    ClientSecret, CsrfToken, EmptyExtraTokenFields, EndpointMaybeSet,
    EndpointNotSet, EndpointSet, IdTokenFields, IssuerUrl, Nonce,
    OAuth2TokenResponse, PkceCodeChallenge, PkceCodeVerifier,
    ProviderMetadata, RedirectUrl, RefreshToken, Scope,
    StandardErrorResponse, StandardTokenResponse, TokenResponse,
    UserInfoClaims,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Provider-metadata extension carrying URLs that aren't on the
/// OIDC Core ProviderMetadata struct: RP-Initiated Logout 1.0's
/// `end_session_endpoint` and OAuth 2.0 Token Revocation (RFC 7009)
/// `revocation_endpoint`.  `openidconnect` exposes the
/// `AdditionalProviderMetadata` trait specifically for fields like
/// these.
#[derive(Clone, Debug, Deserialize, Serialize)]
struct LogoutMetadata {
    #[serde(default)]
    end_session_endpoint: Option<url::Url>,
    #[serde(default)]
    revocation_endpoint: Option<url::Url>,
}
impl AdditionalProviderMetadata for LogoutMetadata {}

// Mirror `CoreProviderMetadata` exactly, swapping the additional-
// metadata slot.  This lets discovery deserialise our extra field
// while preserving every other Core type, so the rest of the OIDC
// pipeline keeps working unchanged.
// v4 consolidated the three JWK-related generics (key type, key use,
// signing alg) into a single `JsonWebKey` slot, dropping the arity from
// 15 to 12.  Order: <Additional, AuthDisplay, ClientAuthMethod,
// ClaimName, ClaimType, GrantType, JweContentEnc, JweKeyMgmt,
// JsonWebKey, ResponseMode, ResponseType, SubjectIdentifierType>.
type HypershuntProviderMetadata = ProviderMetadata<
    LogoutMetadata,
    CoreAuthDisplay,
    CoreClientAuthMethod,
    CoreClaimName,
    CoreClaimType,
    CoreGrantType,
    CoreJweContentEncryptionAlgorithm,
    CoreJweKeyManagementAlgorithm,
    CoreJsonWebKey,
    CoreResponseMode,
    CoreResponseType,
    CoreSubjectIdentifierType,
>;

/// Catch-all additional-claims type for ID tokens.  Captures every
/// non-standard claim as raw JSON so operator-configured
/// `username-claim` / `groups-claim` lookups can read them straight
/// off the ID token.  (openidconnect's default,
/// `EmptyAdditionalClaims`, silently discards extra claims at
/// deserialisation — which made those lookups dead code on the
/// ID-token path; only the UserInfo merge ever saw the values.)
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct ExtraClaims(
    pub(crate) serde_json::Map<String, serde_json::Value>,
);
impl openidconnect::AdditionalClaims for ExtraClaims {}

// Mirror `CoreClient` / `CoreTokenResponse` exactly, swapping the
// additional-claims slot for `ExtraClaims` — same pattern as
// `HypershuntProviderMetadata` above.
// v4: IdTokenFields lost its trailing key-type generic (now 5 params):
// <AdditionalClaims, ExtraTokenFields, GenderClaim, JweContentEnc,
// JwsSigningAlgorithm>.
type HsIdTokenFields = IdTokenFields<
    ExtraClaims,
    EmptyExtraTokenFields,
    CoreGenderClaim,
    CoreJweContentEncryptionAlgorithm,
    openidconnect::core::CoreJwsSigningAlgorithm,
>;
type HsTokenResponse =
    StandardTokenResponse<HsIdTokenFields, CoreTokenType>;

// v4: `Client` now carries 11 content generics plus 6 typestate
// markers tracking which endpoints have been configured.  Mirrors
// `CoreClient` but substitutes our `ExtraClaims` and `HsTokenResponse`.
//
// Endpoint markers reflect how `run_discovery` builds the client:
//   * auth URL    -> EndpointSet      (always present after discovery)
//   * token URL   -> EndpointMaybeSet (from_provider_metadata sets this)
//   * userinfo    -> EndpointMaybeSet (optional in discovery)
//   * revocation  -> EndpointSet      (we ALWAYS call set_revocation_url
//                                      so revoke_token type-checks; the
//                                      actual call is guarded on whether
//                                      discovery surfaced a real endpoint)
//   * introspection / device -> EndpointNotSet (unused)
pub(crate) type OidcClient = openidconnect::Client<
    ExtraClaims,
    CoreAuthDisplay,
    CoreGenderClaim,
    CoreJweContentEncryptionAlgorithm,
    CoreJsonWebKey,
    CoreAuthPrompt,
    StandardErrorResponse<CoreErrorResponseType>,
    HsTokenResponse,
    CoreTokenIntrospectionResponse,
    CoreRevocableToken,
    CoreRevocationErrorResponse,
    EndpointSet,    // HasAuthUrl
    EndpointNotSet, // HasDeviceAuthUrl
    EndpointNotSet, // HasIntrospectionUrl
    EndpointSet,    // HasRevocationUrl
    EndpointMaybeSet, // HasTokenUrl
    EndpointMaybeSet, // HasUserInfoUrl
>;

// Typestate produced directly by `from_provider_metadata` (before we
// flip the revocation marker via `set_revocation_url`).  Only used as
// the receiver type for the constructor call; the builder chain then
// yields `OidcClient`.
type OidcClientFromMetadata = openidconnect::Client<
    ExtraClaims,
    CoreAuthDisplay,
    CoreGenderClaim,
    CoreJweContentEncryptionAlgorithm,
    CoreJsonWebKey,
    CoreAuthPrompt,
    StandardErrorResponse<CoreErrorResponseType>,
    HsTokenResponse,
    CoreTokenIntrospectionResponse,
    CoreRevocableToken,
    CoreRevocationErrorResponse,
    EndpointSet,      // HasAuthUrl
    EndpointNotSet,   // HasDeviceAuthUrl
    EndpointNotSet,   // HasIntrospectionUrl
    EndpointNotSet,   // HasRevocationUrl (flipped by set_revocation_url)
    EndpointMaybeSet, // HasTokenUrl
    EndpointMaybeSet, // HasUserInfoUrl
>;

/// Standard OIDC login-flow hints the relying party may forward to
/// the IdP's authorisation endpoint.  All five are optional and
/// pass-through; hypershunt enforces only basic length/charset hygiene
/// at the listener edge.  Definitions: OIDC Core 1.0 §3.1.2.1.
#[derive(Default, Debug, Clone)]
pub struct IdpHints {
    /// Hint to the IdP about the user being authenticated, typically
    /// an email address or login name.  Forwarded as `login_hint`.
    pub login_hint: Option<String>,
    /// Controls re-authentication / consent behaviour.  Allowed
    /// values per spec: `none`, `login`, `consent`, `select_account`.
    /// Forwarded as `prompt`.
    pub prompt: Option<String>,
    /// Maximum allowable authentication age, in seconds, before the
    /// IdP MUST actively re-authenticate.  Forwarded as `max_age`.
    pub max_age: Option<String>,
    /// Space-separated list of authentication context-class refs.
    /// Used to request specific MFA / assurance levels.  Forwarded
    /// as `acr_values`.
    pub acr_values: Option<String>,
    /// Space-separated list of BCP-47 locale tags ordered by
    /// preference.  Forwarded as `ui_locales`.
    pub ui_locales: Option<String>,
}

impl IdpHints {
    /// Iterate the configured (name, value) pairs in the order they
    /// appear on the struct.  Skips `None` fields.
    fn pairs(&self) -> impl Iterator<Item = (&'static str, &str)> {
        [
            ("login_hint", self.login_hint.as_deref()),
            ("prompt", self.prompt.as_deref()),
            ("max_age", self.max_age.as_deref()),
            ("acr_values", self.acr_values.as_deref()),
            ("ui_locales", self.ui_locales.as_deref()),
        ]
        .into_iter()
        .filter_map(|(k, v)| v.map(|val| (k, val)))
    }
}

/// A pending login waiting for the IdP to redirect back to the
/// callback endpoint.
struct StateEntry {
    pkce_verifier: PkceCodeVerifier,
    nonce: Nonce,
    return_to: String,
    created: Instant,
}

/// A live refresh session backed by an IdP refresh token.  Looked up
/// by the opaque sid carried in the `__hypershunt_oidc_refresh` cookie.
struct RefreshEntry {
    refresh_token: RefreshToken,
    // Refresh-token validation does not require the original nonce
    // (it's only meaningful on the initial authorisation code flow).
    // We keep it here only for completeness; current code passes None
    // to the ID-token verifier on refresh.
    expires_at: Instant,
    // Raw ID-token JWT, used as `id_token_hint` when the logout
    // endpoint redirects to the IdP's `end_session_endpoint`.  Some
    // IdPs require this to identify the session being terminated.
    id_token: String,
    // IdP's `sub` claim from the ID token: the stable user
    // identifier at this issuer.  Used by back-channel logout to
    // find every session belonging to a single user when the
    // logout_token carries only `sub` (no `sid`).
    subject: String,
    // IdP's `sid` claim from the ID token, when present.  Used by
    // back-channel logout to target a single session.
    idp_sid: Option<String>,
}

/// Runtime handle for the configured OIDC IdP.  Constructed once at
/// startup; cloned via `Arc` into `AppState`.
///
/// `client` and `end_session_url` are wrapped in `ArcSwap` so they
/// can be hot-swapped by the background refresh task without
/// requiring callers to hold a lock.  When discovery has not yet
/// completed (or has not yet succeeded), `client` is `None` and the
/// hot-path methods return a "not ready" error.
pub struct OidcProvider {
    client: ArcSwap<Option<Arc<OidcClient>>>,
    cfg: OidcConfig,
    metrics: Arc<Metrics>,
    states: Mutex<HashMap<String, StateEntry>>,
    state_ttl: Duration,
    // Refresh sessions; only populated when `cfg.refresh` is true.
    refreshes: Mutex<HashMap<String, RefreshEntry>>,
    refresh_ttl: Duration,
    // IdP's `end_session_endpoint` if exposed during discovery.
    // Without this, RP-initiated logout falls back to a local-only
    // cookie clear and a redirect to `post_logout_uri`.
    end_session_url: ArcSwap<Option<url::Url>>,
    // IdP's `revocation_endpoint` (RFC 7009) if exposed during
    // discovery.  Used by `revoke_refresh_token` to invalidate
    // tokens server-side at logout.  When absent, revocation calls
    // become no-ops.
    revocation_url: ArcSwap<Option<url::Url>>,
    // Cached JWKS from the most recent successful discovery.  Used
    // by the back-channel logout endpoint to verify IdP-signed
    // logout_tokens directly, without re-fetching keys per request.
    jwks: ArcSwap<Option<Arc<openidconnect::core::CoreJsonWebKeySet>>>,
    // Recently-seen `jti` values from back-channel-logout tokens,
    // mapped to their expiry time.  Prevents replay of an already-
    // processed logout_token within the JTI-TTL window.
    seen_jtis: Mutex<HashMap<String, Instant>>,
    // LRU cache of validated bearer tokens, keyed by SHA-256(token).
    // Each entry holds the resolved Identity and the token's `exp`
    // claim so a cache hit can skip the (RSA-heavy) signature
    // verification.  Empty when bearer mode is disabled.
    bearer_cache: Mutex<lru::LruCache<[u8; 32], BearerCacheEntry>>,
    // Shared reqwest client for every OIDC network call.  v4 no longer
    // ships a built-in `async_http_client`; the relying party owns the
    // client and passes it by reference.  Redirects are disabled on it
    // as an SSRF guard (see `build_http_client`).  Cheap to clone and
    // reuse, so we build it once and hold it for the provider's life.
    http_client: openidconnect::reqwest::Client,
}

#[derive(Clone)]
struct BearerCacheEntry {
    identity: Identity,
    expires_at: u64,
}

/// Single discovery attempt: build a fresh `OidcClient`, the
/// optional `end_session_endpoint`, and a copy of the JWKS.
/// Factored out so the bootstrap path and the periodic-refresh path
/// share exactly the same construction logic.  The JWKS is returned
/// separately so the back-channel logout endpoint can verify
/// signatures without going through the (more constrained) ID-token
/// verifier path.
/// Build the shared reqwest client used for every OIDC network call.
/// Redirects are disabled as an SSRF guard (see `run_discovery`).
fn build_http_client() -> Result<openidconnect::reqwest::Client> {
    openidconnect::reqwest::ClientBuilder::new()
        .redirect(openidconnect::reqwest::redirect::Policy::none())
        .build()
        .context("building OIDC HTTP client")
}

// Generic over the HTTP client so the production caller can pass the
// concrete `reqwest::Client` while tests substitute an in-memory async
// closure (openidconnect 4.0 provides a blanket `AsyncHttpClient` impl
// for any `Fn(HttpRequest) -> Future<Result<HttpResponse, E>>`).  The
// `'c` lifetime and the `C: AsyncHttpClient<'c>` bound mirror
// `discover_async`'s own signature: the metadata future borrows the
// client for `'c`, and the client must be borrowable for that span.
async fn run_discovery<'c, C>(
    cfg: &'c OidcConfig,
    http_client: &'c C,
) -> Result<(
    OidcClient,
    Option<url::Url>,
    Option<url::Url>,
    openidconnect::core::CoreJsonWebKeySet,
)>
where
    C: AsyncHttpClient<'c>,
    // `anyhow::Context::with_context` requires the source error to be
    // `Send + Sync + 'static`.  `AsyncHttpClient::Error` is only bounded
    // `Error + 'static`, so we restate the stronger bound here; the
    // concrete production client (`reqwest::Client`) satisfies it.
    <C as AsyncHttpClient<'c>>::Error: Send + Sync,
{
    let issuer_url = IssuerUrl::new(cfg.issuer.clone())
        .with_context(|| format!("invalid OIDC issuer URL: {}", cfg.issuer))?;

    let metadata = HypershuntProviderMetadata::discover_async(
        issuer_url,
        http_client,
    )
    .await
    .with_context(|| format!("OIDC discovery failed for {}", cfg.issuer))?;

    let end_session_url =
        metadata.additional_metadata().end_session_endpoint.clone();
    let revocation_url =
        metadata.additional_metadata().revocation_endpoint.clone();
    let jwks = metadata.jwks().clone();

    let redirect = RedirectUrl::new(cfg.redirect_uri.clone())
        .with_context(|| {
            format!("invalid redirect-uri: {}", cfg.redirect_uri)
        })?;

    // v4 client construction is a typestate builder.
    // `from_provider_metadata` flips HasAuthUrl=Set, HasTokenUrl and
    // HasUserInfoUrl=MaybeSet.  We must then call `set_revocation_url`
    // unconditionally so the `revoke_token` method exists at compile
    // time (it requires HasRevocationUrl=Set).  When discovery did NOT
    // surface a revocation endpoint we set a harmless placeholder (the
    // issuer URL); the runtime revocation path in `revoke_refresh_token`
    // is guarded on `self.revocation_url()` being `Some`, so the
    // placeholder is never actually contacted.
    let revocation_for_client = revocation_url
        .clone()
        .unwrap_or_else(|| metadata.issuer().url().clone());
    let client = OidcClientFromMetadata::from_provider_metadata(
        metadata,
        ClientId::new(cfg.client_id.clone()),
        cfg.client_secret.clone().map(ClientSecret::new),
    )
    .set_redirect_uri(redirect)
    .set_revocation_url(openidconnect::RevocationUrl::from_url(
        revocation_for_client,
    ));

    Ok((client, end_session_url, revocation_url, jwks))
}

impl OidcProvider {
    /// Construct an OIDC provider in a not-ready state and spawn
    /// background tasks for (1) initial discovery with retry and
    /// (2) periodic re-discovery for JWKS hot-swap.  Returns
    /// immediately; the provider becomes ready once the bootstrap
    /// task completes its first successful discovery.
    ///
    /// When `discovery-retry` is `#false` and the bootstrap call
    /// fails, the provider stays in the not-ready state and all
    /// endpoints serve 503.  This matches the user's explicit
    /// fail-fast request without crashing hypershunt; restart picks up
    /// the new IdP state.
    pub fn new(cfg: OidcConfig, metrics: Arc<Metrics>) -> Arc<Self> {
        // Build the SSRF-guarded HTTP client up front.  Constructing a
        // reqwest client with the default TLS backend is effectively
        // infallible; if it ever does fail we must NOT silently fall
        // back to a redirect-following default (that would reopen the
        // SSRF hole).  Instead degrade to a client that still has
        // redirects disabled (only losing connection pooling), and if
        // even that cannot be built, leave `http_client` as a
        // never-ready stub — discovery then fails loudly on first use.
        let http_client = build_http_client().unwrap_or_else(|e| {
            tracing::error!(
                error = %format!("{e:#}"),
                "OIDC HTTP client build failed; using minimal \
                 redirect-disabled client"
            );
            openidconnect::reqwest::Client::builder()
                .redirect(openidconnect::reqwest::redirect::Policy::none())
                .pool_max_idle_per_host(0)
                .build()
                // The redirect policy is identical to the primary
                // builder, so this second attempt cannot regress the
                // SSRF guard; `expect` here only fires if reqwest
                // itself is fundamentally broken at runtime, which is
                // not a recoverable production state.
                .expect("redirect-disabled reqwest client must build")
        });
        let provider = Arc::new(Self {
            http_client,
            client: ArcSwap::new(Arc::new(None)),
            state_ttl: Duration::from_secs(cfg.state_ttl_secs),
            refresh_ttl: Duration::from_secs(cfg.refresh_ttl_secs),
            metrics,
            end_session_url: ArcSwap::new(Arc::new(None)),
            revocation_url: ArcSwap::new(Arc::new(None)),
            jwks: ArcSwap::new(Arc::new(None)),
            seen_jtis: Mutex::new(HashMap::new()),
            bearer_cache: Mutex::new(lru::LruCache::new(
                NonZeroUsize::new(cfg.bearer_cache_size.max(1))
                    .expect("bearer_cache_size >= 1"),
            )),
            states: Mutex::new(HashMap::new()),
            refreshes: Mutex::new(HashMap::new()),
            cfg,
        });

        // Background discovery: exponential-backoff bootstrap, then
        // periodic refresh to pick up JWKS rotation at the IdP.
        let weak = Arc::downgrade(&provider);
        crate::task::spawn_supervised("oidc.discovery", async move {
            let mut attempt: u32 = 0;
            // Bootstrap loop.
            loop {
                let Some(p) = weak.upgrade() else { return };
                match run_discovery(&p.cfg, &p.http_client).await {
                    Ok((client, end_session, revocation, jwks)) => {
                        p.client.store(Arc::new(Some(Arc::new(client))));
                        p.end_session_url.store(Arc::new(end_session));
                        p.revocation_url.store(Arc::new(revocation));
                        p.jwks.store(Arc::new(Some(Arc::new(jwks))));
                        p.metrics.oidc_discoveries.fetch_add(
                            1,
                            std::sync::atomic::Ordering::Relaxed,
                        );
                        tracing::info!(
                            issuer = %p.cfg.issuer,
                            "discovery succeeded"
                        );
                        break;
                    }
                    Err(e) => {
                        p.metrics.oidc_discovery_failures.fetch_add(
                            1,
                            std::sync::atomic::Ordering::Relaxed,
                        );
                        if !p.cfg.discovery_retry {
                            tracing::error!(
                                issuer = %p.cfg.issuer,
                                error = %format!("{e:#}"),
                                "discovery failed (retry disabled); \
                                 provider will remain unavailable"
                            );
                            return;
                        }
                        // Cap backoff at 5 minutes.
                        let secs = std::cmp::min(1u64 << attempt.min(8), 300);
                        tracing::warn!(
                            issuer = %p.cfg.issuer,
                            retry_in = secs,
                            error = %format!("{e:#}"),
                            "discovery failed; retrying"
                        );
                        drop(p);
                        tokio::time::sleep(Duration::from_secs(secs)).await;
                        attempt = attempt.saturating_add(1);
                    }
                }
            }

            // Periodic refresh loop -- only runs after a successful
            // bootstrap, so failures here are silent and leave the
            // last-known-good client in place.  refresh=0 disables
            // the periodic path entirely.
            let Some(p) = weak.upgrade() else { return };
            let interval_secs = p.cfg.discovery_refresh_secs;
            drop(p);
            if interval_secs == 0 {
                return;
            }
            let mut ticker = tokio::time::interval(
                Duration::from_secs(interval_secs),
            );
            // Skip the immediate tick: we just completed discovery.
            ticker.tick().await;
            loop {
                ticker.tick().await;
                let Some(p) = weak.upgrade() else { return };
                match run_discovery(&p.cfg, &p.http_client).await {
                    Ok((client, end_session, revocation, jwks)) => {
                        p.client.store(Arc::new(Some(Arc::new(client))));
                        p.end_session_url.store(Arc::new(end_session));
                        p.revocation_url.store(Arc::new(revocation));
                        p.jwks.store(Arc::new(Some(Arc::new(jwks))));
                        p.metrics.oidc_discoveries.fetch_add(
                            1,
                            std::sync::atomic::Ordering::Relaxed,
                        );
                        tracing::debug!(
                            issuer = %p.cfg.issuer,
                            "discovery refreshed"
                        );
                    }
                    Err(e) => {
                        p.metrics.oidc_discovery_failures.fetch_add(
                            1,
                            std::sync::atomic::Ordering::Relaxed,
                        );
                        tracing::warn!(
                            issuer = %p.cfg.issuer,
                            error = %format!("{e:#}"),
                            "periodic discovery failed; \
                             keeping previous client"
                        );
                    }
                }
            }
        });

        // Periodic eviction of unfinished logins and expired refresh
        // entries.  Spawned separately from the discovery task so
        // their cadences are independent (eviction needs to run on
        // the order of state-ttl, discovery on the order of an hour).
        let weak = Arc::downgrade(&provider);
        let ttl = provider.state_ttl;
        crate::task::spawn_supervised("oidc.eviction", async move {
            // Sweep at one-tenth of the TTL with a sensible floor so
            // entries are evicted promptly without busy-looping for
            // small TTLs.
            let interval = std::cmp::max(ttl / 10, Duration::from_secs(30));
            let mut ticker = tokio::time::interval(interval);
            loop {
                ticker.tick().await;
                let Some(p) = weak.upgrade() else { break };
                p.evict_expired();
            }
        });

        provider
    }

    /// Current OIDC client, if discovery has completed.  Hot-path
    /// methods bail with a "not ready" error when this returns
    /// `None`; the listener turns that into a 503 + `Retry-After`.
    pub fn client(&self) -> Option<Arc<OidcClient>> {
        self.client.load().as_ref().clone()
    }

    /// True when the OIDC provider has completed at least one
    /// successful discovery and is ready to handle login flows.
    pub fn is_ready(&self) -> bool {
        self.client.load().is_some()
    }

    /// Optionally fetch the IdP's `/userinfo` endpoint and merge its
    /// claims with the ones we already extracted from the ID token.
    /// UserInfo wins on non-empty values: the OIDC spec calls it the
    /// canonical source for non-essential claims.  A failed UserInfo
    /// request degrades to the ID-token values and logs a warning so
    /// login still succeeds.
    async fn merge_userinfo(
        &self,
        client: &OidcClient,
        access_token: &AccessToken,
        id_token_username: &str,
        id_token_groups: Vec<String>,
    ) -> (String, Vec<String>) {
        if !self.cfg.userinfo {
            return (id_token_username.to_owned(), id_token_groups);
        }
        let request = match client
            .user_info(access_token.clone(), None)
        {
            Ok(r) => r,
            Err(e) => {
                // Configuration-level error (no userinfo endpoint in
                // discovery, etc.).  Distinct from a network/HTTP
                // failure below; log once but don't keep retrying.
                tracing::warn!(
                    error = %format!("{e:#}"),
                    "userinfo not configurable for this IdP"
                );
                return (id_token_username.to_owned(), id_token_groups);
            }
        };
        // ExtraClaims (not EmptyAdditionalClaims) so non-standard
        // claims like `groups` survive deserialisation and are
        // visible to the JSON round-trip below.
        let info: UserInfoClaims<
            ExtraClaims,
            openidconnect::core::CoreGenderClaim,
        > = match request.request_async(&self.http_client).await {
            Ok(c) => c,
            Err(e) => {
                self.metrics.oidc_userinfo_failures.fetch_add(
                    1,
                    std::sync::atomic::Ordering::Relaxed,
                );
                tracing::warn!(
                    error = %format!("{e:#}"),
                    "userinfo request failed; falling back \
                     to ID-token claims"
                );
                return (id_token_username.to_owned(), id_token_groups);
            }
        };

        // UserInfoClaims doesn't expose its extra fields directly;
        // round-trip through JSON, which is cheap and gives us the
        // same dynamic-claim access we already use on the ID token.
        let json = match serde_json::to_value(&info) {
            Ok(v) => v,
            Err(_) => return (id_token_username.to_owned(), id_token_groups),
        };
        // Reuse the same claim-extraction logic so configured
        // username-claim / groups-claim names work identically on
        // both surfaces.
        let username = match json
            .get(&self.cfg.username_claim)
            .and_then(|v| v.as_str())
        {
            Some(s) if !s.is_empty() => s.to_owned(),
            _ => id_token_username.to_owned(),
        };
        let groups = extract_groups_claim_from_json(
            &self.cfg.groups_claim,
            &json,
        );
        let groups = if groups.is_empty() {
            id_token_groups
        } else {
            groups
        };
        (username, groups)
    }

    /// Build the authorisation URL the browser should be
    /// redirected to.  Returns `None` when discovery has not yet
    /// completed; otherwise the URL plus the CSRF state id (mirrored
    /// back in the callback's query string).  `hints` carries the
    /// optional standard login parameters (`login_hint`, `prompt`,
    /// etc.) that the caller has validated and wishes to forward to
    /// the IdP.
    pub fn begin_login(
        &self,
        return_to: String,
        hints: IdpHints,
    ) -> Option<(url::Url, String)> {
        let client = self.client()?;
        let (pkce_challenge, pkce_verifier) =
            PkceCodeChallenge::new_random_sha256();

        let mut req = client.authorize_url(
            CoreAuthenticationFlow::AuthorizationCode,
            CsrfToken::new_random,
            Nonce::new_random,
        );
        for scope in &self.cfg.scopes {
            req = req.add_scope(Scope::new(scope.clone()));
        }
        // RFC 8707 resource indicators -- include `resource=<uri>`
        // for each configured target so the IdP narrows the access
        // token's `aud` accordingly.  Must also appear on the token
        // exchange in `complete_login`.
        for r in &self.cfg.resources {
            req = req.add_extra_param("resource", r.clone());
        }
        // Pass-through OIDC login hints.  `add_extra_param` URL-
        // encodes the value, so no further escaping is needed here.
        for (name, value) in hints.pairs() {
            req = req.add_extra_param(name, value);
        }
        let (auth_url, csrf, nonce) =
            req.set_pkce_challenge(pkce_challenge).url();

        let state_id = csrf.secret().clone();
        let entry = StateEntry {
            pkce_verifier,
            nonce,
            return_to,
            created: Instant::now(),
        };
        self.states.lock().expect("oidc state mutex").insert(state_id.clone(), entry);

        Some((auth_url, state_id))
    }

    /// True when refresh-token support is enabled for this provider.
    pub fn refresh_enabled(&self) -> bool {
        self.cfg.refresh
    }

    /// Cookie name used to carry the opaque refresh-session id.
    pub fn refresh_cookie_name(&self) -> &str {
        &self.cfg.refresh_cookie_name
    }

    /// Sliding TTL applied to each refresh session, in seconds.
    pub fn refresh_ttl_secs(&self) -> u64 {
        self.cfg.refresh_ttl_secs
    }

    /// Path served as the in-browser logout endpoint.
    pub fn logout_path(&self) -> &str {
        &self.cfg.logout_path
    }

    /// Target the browser is redirected to after logout completes
    /// (whether the IdP-initiated branch ran or not).
    pub fn post_logout_uri(&self) -> &str {
        &self.cfg.post_logout_uri
    }

    /// When true, the logout endpoint bounces the browser through
    /// the IdP's `end_session_endpoint` if discovery exposed one.
    pub fn idp_logout_enabled(&self) -> bool {
        self.cfg.idp_logout
    }

    /// IdP's RP-initiated logout endpoint, if discovery surfaced it.
    /// Returned by value because the ArcSwap-backed storage rules out
    /// borrowing a stable reference; cloning a small `url::Url` is
    /// cheap and the call site happens once per logout request.
    pub fn end_session_url(&self) -> Option<url::Url> {
        (*self.end_session_url.load_full()).clone()
    }

    /// OAuth client id; passed as `client_id` query param on the
    /// end_session redirect for IdPs that accept it without an
    /// `id_token_hint`.
    pub fn client_id(&self) -> &str {
        &self.cfg.client_id
    }

    /// Drop the refresh entry matching `sid` and return its stored
    /// `id_token` and `refresh_token`.  The id_token is sent back
    /// to the IdP as `id_token_hint` on the end-session redirect;
    /// the refresh token is handed to `revoke_refresh_token` so
    /// the IdP can invalidate it immediately (RFC 7009).  Returns
    /// `None` when no entry is present (e.g. the user opens the
    /// logout URL twice).
    pub fn take_logout_session(
        &self,
        sid: &str,
    ) -> Option<(String, RefreshToken)> {
        self.refreshes
            .lock()
            .unwrap()
            .remove(sid)
            .map(|e| (e.id_token, e.refresh_token))
    }

    /// Configured issuer, normalised by stripping any trailing
    /// slash so callers can compare with `iss` claim values
    /// uniformly.  Used by both back-channel logout and the
    /// callback's RFC 9207 iss-parameter check.
    pub fn issuer(&self) -> &str {
        self.cfg.issuer.trim_end_matches('/')
    }

    /// True when the callback endpoint must reject authorization
    /// responses that lack an `iss` parameter (RFC 9207).
    pub fn require_iss(&self) -> bool {
        self.cfg.require_iss
    }

    /// Best-effort RFC 7009 token revocation.  Returns immediately;
    /// the actual IdP call runs in a spawned task so the user-
    /// facing logout response is not blocked on the IdP's
    /// revocation endpoint.  Calls are no-ops when revocation is
    /// disabled in config, when the IdP doesn't advertise a
    /// revocation endpoint, or when the provider hasn't completed
    /// discovery yet -- revocation is defense-in-depth, not a
    /// correctness requirement.
    pub fn revoke_refresh_token(
        self: &Arc<Self>,
        refresh_token: RefreshToken,
    ) {
        if !self.cfg.revoke_on_logout {
            return;
        }
        // v4 typestate forces a revocation URL to always be set on the
        // client (so `revoke_token` compiles); when discovery did not
        // surface a real endpoint we set a never-used placeholder.
        // Guard here so we never POST a revocation to that placeholder:
        // skip entirely unless discovery gave us a genuine endpoint.
        if self.revocation_url.load().is_none() {
            return;
        }
        let Some(client) = self.client() else { return };
        // Move the client Arc, http client, and refresh token into the
        // task so the RevocationRequest borrow is local to the spawned
        // future.
        let metrics = self.metrics.clone();
        let http_client = self.http_client.clone();
        crate::task::spawn_supervised("oidc.revocation", async move {
            // `revoke_token` returns Err for a non-https endpoint
            // (RFC 7009 requires HTTPS); on loopback/plain-http IdPs
            // this is the documented graceful-skip path.
            let request = match client.revoke_token(refresh_token.into()) {
                Ok(r) => r,
                Err(e) => {
                    tracing::debug!(
                        error = %format!("{e:#}"),
                        "revocation not configurable on this \
                         IdP; skipping"
                    );
                    return;
                }
            };
            match request.request_async(&http_client).await {
                Ok(()) => {
                    metrics.oidc_revocations.fetch_add(
                        1,
                        std::sync::atomic::Ordering::Relaxed,
                    );
                    tracing::debug!("refresh token revoked");
                }
                Err(e) => {
                    metrics.oidc_revocation_failures.fetch_add(
                        1,
                        std::sync::atomic::Ordering::Relaxed,
                    );
                    tracing::warn!(
                        error = %format!("{e:#}"),
                        "refresh token revocation failed"
                    );
                }
            }
        });
    }

    /// Exchange the authorisation code returned by the IdP for an ID
    /// token and verify it.  Returns the authenticated identity, the
    /// saved `return_to` URL, and (when refresh support is enabled
    /// and the IdP returned a refresh token) an opaque sid the caller
    /// should set in the refresh cookie.
    pub async fn complete_login(
        &self,
        code: String,
        state_id: &str,
    ) -> Result<(Identity, String, Option<String>)> {
        let client = self
            .client()
            .ok_or_else(|| anyhow!("OIDC provider not ready"))?;

        // Remove the entry first so a replayed callback can't reuse
        // the same PKCE verifier even if validation later fails.
        let entry = self
            .states
            .lock()
            .unwrap()
            .remove(state_id)
            .ok_or_else(|| anyhow!("unknown or expired OIDC state"))?;

        if entry.created.elapsed() > self.state_ttl {
            bail!("OIDC state expired before callback");
        }

        // RFC 8707: forward the same `resource` indicators on the
        // token exchange so the IdP's access-token `aud` narrowing
        // applies here too (the spec requires the parameter on
        // both legs of the flow).
        // v4: `exchange_code` now returns a Result (it validates the
        // client has a token endpoint configured before building the
        // request).
        let mut exchange = client
            .exchange_code(AuthorizationCode::new(code))
            .context("OIDC token endpoint not configured")?
            .set_pkce_verifier(entry.pkce_verifier);
        for r in &self.cfg.resources {
            exchange = exchange.add_extra_param("resource", r.clone());
        }
        let token_response = exchange
            .request_async(&self.http_client)
            .await
            .context("OIDC token exchange failed")?;

        let id_token = token_response
            .id_token()
            .ok_or_else(|| anyhow!("IdP response did not include an id_token"))?;
        let id_token_str = id_token.to_string();
        let claims = id_token
            .claims(&client.id_token_verifier(), &entry.nonce)
            .context("ID token validation failed")?;

        // The OIDC `sub` claim is always present and uniquely
        // identifies the user at this issuer.  When the operator
        // configures a different username claim (e.g.
        // `preferred_username`), we look it up in the serialised
        // claims document — standard and custom claims alike —
        // falling back to `sub` if absent.
        let claims_json = serde_json::to_value(claims)
            .context("serialising ID token claims")?;
        let id_username = extract_string_claim(
            &self.cfg.username_claim,
            &claims_json,
            claims.subject().as_str(),
        );
        let id_groups =
            extract_groups_claim(&self.cfg.groups_claim, &claims_json);
        // Capture the OIDC subject and session id (if any) for use by
        // the back-channel logout endpoint, which keys session lookups
        // on these.  `sub` is always present; `sid` is sent by IdPs
        // that support back-channel logout but is otherwise optional.
        let subject = claims.subject().as_str().to_owned();
        let idp_sid = extract_optional_string_claim("sid", &claims_json);

        // UserInfo merge -- noop when the feature is off.  When on,
        // /userinfo claims take precedence on non-empty values.
        let (username, groups) = self
            .merge_userinfo(
                &client,
                token_response.access_token(),
                &id_username,
                id_groups,
            )
            .await;

        // Stash the refresh token (if any) under a fresh random sid.
        // The caller turns the sid into a long-lived HttpOnly cookie;
        // the refresh token itself never leaves the server.  The raw
        // ID token is stashed alongside it so the logout endpoint can
        // present it to the IdP as `id_token_hint`.
        let sid = if self.cfg.refresh {
            token_response.refresh_token().map(|rt| {
                let id = CsrfToken::new_random().secret().clone();
                self.refreshes.lock().expect("oidc refresh mutex").insert(
                    id.clone(),
                    RefreshEntry {
                        refresh_token: rt.clone(),
                        expires_at: Instant::now() + self.refresh_ttl,
                        id_token: id_token_str.clone(),
                        subject: subject.clone(),
                        idp_sid: idp_sid.clone(),
                    },
                );
                id
            })
        } else {
            None
        };

        Ok((Identity { username, groups }, entry.return_to, sid))
    }

    /// Use a stored refresh token to obtain a fresh ID token, re-
    /// derive the user's identity, and reset the sliding TTL.  When
    /// the IdP rotates the refresh token, the entry is re-keyed under
    /// a new sid; callers detect rotation by comparing the returned
    /// sid against the input.  Returns an error (and drops the entry)
    /// when the IdP rejects the refresh, e.g. because the underlying
    /// session has been revoked.
    pub async fn refresh(
        &self,
        sid: &str,
    ) -> Result<(Identity, String)> {
        let client = self
            .client()
            .ok_or_else(|| anyhow!("OIDC provider not ready"))?;
        let rt = {
            let map = self.refreshes.lock().expect("oidc refresh mutex");
            let entry = map.get(sid).ok_or_else(|| {
                anyhow!("unknown OIDC refresh session")
            })?;
            if Instant::now() > entry.expires_at {
                drop(map);
                self.refreshes.lock().expect("oidc refresh mutex").remove(sid);
                bail!("refresh session expired");
            }
            entry.refresh_token.clone()
        };

        // RFC 8707: forward resources on refresh as well so the
        // re-issued access token carries the same `aud` narrowing.
        // v4: `exchange_refresh_token` returns a Result.
        let mut exchange = client
            .exchange_refresh_token(&rt)
            .context("OIDC token endpoint not configured")?;
        for r in &self.cfg.resources {
            exchange = exchange.add_extra_param("resource", r.clone());
        }
        let token_response = exchange
            .request_async(&self.http_client)
            .await
            .inspect_err(|_| {
                // The IdP's "no" is permanent for this token --
                // a revoked refresh token never becomes valid again.
                self.refreshes.lock().expect("oidc refresh mutex").remove(sid);
            })
            .context("OIDC refresh exchange failed")?;

        let id_token = token_response
            .id_token()
            .ok_or_else(|| anyhow!("refresh response had no id_token"))?;
        // OIDC Core §12.2 says the new id_token is OPTIONAL on
        // refresh -- but every IdP we care about returns one, and
        // without it we can't re-derive the user's identity, so
        // treat its absence as an error.  When it IS present we also
        // stash it for use as `id_token_hint` on logout.
        let new_id_token_str = id_token.to_string();
        // Per OIDC Core 1.0 §12.2 the nonce check is only required on
        // the initial authentication response; refresh responses are
        // bound to the prior session via the refresh token itself.
        let claims = id_token
            .claims(&client.id_token_verifier(), |_: Option<&Nonce>| Ok(()))
            .context("refreshed ID token validation failed")?;

        let claims_json = serde_json::to_value(claims)
            .context("serialising refreshed ID token claims")?;
        let id_username = extract_string_claim(
            &self.cfg.username_claim,
            &claims_json,
            claims.subject().as_str(),
        );
        let id_groups =
            extract_groups_claim(&self.cfg.groups_claim, &claims_json);
        let new_subject = claims.subject().as_str().to_owned();
        let new_idp_sid =
            extract_optional_string_claim("sid", &claims_json);

        // UserInfo merge against the freshly-issued access token.
        let (username, groups) = self
            .merge_userinfo(
                &client,
                token_response.access_token(),
                &id_username,
                id_groups,
            )
            .await;

        // Token rotation: when the IdP returns a new refresh token,
        // re-key the entry under a fresh sid.  The old sid stays
        // valid only long enough for this request's response to
        // arrive at the browser carrying the new cookie value.  The
        // id_token is always updated (some IdPs include a fresh one
        // even when keeping the refresh token, which is what we want
        // to send on logout).
        let new_sid = match token_response.refresh_token() {
            Some(new_rt) => {
                let id = CsrfToken::new_random().secret().clone();
                let mut map = self.refreshes.lock().expect("oidc refresh mutex");
                map.remove(sid);
                map.insert(
                    id.clone(),
                    RefreshEntry {
                        refresh_token: new_rt.clone(),
                        expires_at: Instant::now() + self.refresh_ttl,
                        id_token: new_id_token_str,
                        subject: new_subject,
                        idp_sid: new_idp_sid,
                    },
                );
                id
            }
            None => {
                // Same token still valid: just slide the TTL forward
                // and refresh the stored id_token alongside it.  Also
                // freshen the subject/sid since the IdP may have
                // rotated session identifiers without rotating the
                // refresh token.
                let mut map = self.refreshes.lock().expect("oidc refresh mutex");
                if let Some(e) = map.get_mut(sid) {
                    e.expires_at = Instant::now() + self.refresh_ttl;
                    e.id_token = new_id_token_str;
                    e.subject = new_subject;
                    e.idp_sid = new_idp_sid;
                }
                sid.to_owned()
            }
        };

        Ok((Identity { username, groups }, new_sid))
    }

    /// Path served as the in-browser login endpoint.
    pub fn login_path(&self) -> &str {
        &self.cfg.login_path
    }

    /// Path the IdP redirects to with the authorisation code.
    pub fn callback_path(&self) -> &str {
        &self.cfg.callback_path
    }

    fn evict_expired(&self) {
        let now = Instant::now();
        let ttl = self.state_ttl;
        self.states
            .lock()
            .unwrap()
            .retain(|_, e| now.duration_since(e.created) <= ttl);
        // Refresh sessions use absolute `expires_at` because the TTL
        // slides per refresh; states use a fixed-from-creation
        // window.  Both are bounded by config-level TTLs.
        self.refreshes
            .lock()
            .unwrap()
            .retain(|_, e| now <= e.expires_at);
        // Seen jtis carry absolute expiry too.
        self.seen_jtis
            .lock()
            .unwrap()
            .retain(|_, expires_at| now <= *expires_at);
    }

    #[cfg(test)]
    fn refresh_count(&self) -> usize {
        self.refreshes.lock().expect("oidc refresh mutex").len()
    }
}
#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    // `Digest` brings the `Sha256::digest` associated fn into scope
    // for the bearer-token cache-key tests; `Sha256` itself is
    // referenced fully-qualified there.
    use sha2::Digest;
    use std::time::SystemTime;

    // ---- Server-less discovery tests ----------------------------------
    //
    // openidconnect 4.0 ships a blanket `AsyncHttpClient` impl for any
    // async closure `Fn(HttpRequest) -> Future<Result<HttpResponse, E>>`
    // (`E: Error + 'static`).  These tests exercise the generic
    // `run_discovery` seam with an in-memory closure keyed on request
    // path, so no TCP socket is bound and the tests stay deterministic.

    /// Minimal error type for the fake HTTP client.  `AsyncHttpClient`
    /// requires `Error: std::error::Error + 'static`; we additionally
    /// derive `Send + Sync` so it satisfies `run_discovery`'s restated
    /// bound (anyhow's `with_context` needs `Send + Sync`).
    #[derive(Debug)]
    struct FakeHttpError(String);

    impl std::fmt::Display for FakeHttpError {
        fn fmt(
            &self,
            f: &mut std::fmt::Formatter<'_>,
        ) -> std::fmt::Result {
            write!(f, "fake http error: {}", self.0)
        }
    }

    impl std::error::Error for FakeHttpError {}

    /// Build an `AsyncHttpClient` closure that answers from a fixed map
    /// of request-path → (status, JSON body).  Discovery fetches
    /// `/.well-known/openid-configuration` first, then `jwks_uri`; both
    /// must be present for a successful flow.  An unknown path yields a
    /// 404 so a misconfigured fixture fails loudly rather than hanging.
    fn fake_client(
        routes: std::collections::HashMap<String, (u16, String)>,
    ) -> impl for<'c> AsyncHttpClient<'c, Error = FakeHttpError> {
        move |req: openidconnect::HttpRequest| {
            // Key only on the path: fixtures construct absolute URLs
            // from the issuer, but matching the path keeps the helper
            // independent of the (arbitrary) issuer host.
            let path = req.uri().path().to_owned();
            let routes = routes.clone();
            async move {
                let (status, body) = routes
                    .get(&path)
                    .cloned()
                    .unwrap_or((404, "{}".to_owned()));
                openidconnect::http::Response::builder()
                    .status(status)
                    .header(
                        openidconnect::http::header::CONTENT_TYPE,
                        "application/json",
                    )
                    .body(body.into_bytes())
                    .map_err(|e| FakeHttpError(e.to_string()))
            }
        }
    }

    /// A well-formed OIDC discovery document for `issuer`, optionally
    /// advertising the `end_session_endpoint` / `revocation_endpoint`
    /// extension fields that hypershunt's `LogoutMetadata` parses.
    fn discovery_doc(issuer: &str, with_logout: bool) -> String {
        let mut doc = serde_json::json!({
            "issuer": issuer,
            "authorization_endpoint": format!("{issuer}/authorize"),
            "token_endpoint": format!("{issuer}/token"),
            "jwks_uri": format!("{issuer}/jwks"),
            "response_types_supported": ["code"],
            "subject_types_supported": ["public"],
            "id_token_signing_alg_values_supported": ["RS256"],
        });
        if with_logout {
            doc["end_session_endpoint"] =
                format!("{issuer}/logout").into();
            doc["revocation_endpoint"] =
                format!("{issuer}/revoke").into();
        }
        doc.to_string()
    }

    /// An (empty-keys) JWKS document; discovery fetches `jwks_uri` and
    /// deserialises it, but the keys themselves aren't exercised here.
    fn empty_jwks() -> String {
        serde_json::json!({ "keys": [] }).to_string()
    }

    /// Standard route map: discovery doc + JWKS, keyed by their paths.
    fn discovery_routes(
        issuer: &str,
        with_logout: bool,
    ) -> std::collections::HashMap<String, (u16, String)> {
        let mut m = std::collections::HashMap::new();
        m.insert(
            "/.well-known/openid-configuration".to_owned(),
            (200, discovery_doc(issuer, with_logout)),
        );
        m.insert("/jwks".to_owned(), (200, empty_jwks()));
        m
    }

    #[tokio::test]
    async fn run_discovery_parses_logout_extension_endpoints() {
        let issuer = "https://idp.example";
        let cfg = mock_cfg(issuer);
        let client = fake_client(discovery_routes(issuer, true));
        let (_oidc, end_session, revocation, _jwks) =
            run_discovery(&cfg, &client)
                .await
                .expect("discovery should succeed");
        // The extension fields must round-trip through hypershunt's
        // custom `LogoutMetadata` additional-metadata type.
        assert_eq!(
            end_session.map(|u| u.to_string()),
            Some("https://idp.example/logout".to_owned()),
        );
        assert_eq!(
            revocation.map(|u| u.to_string()),
            Some("https://idp.example/revoke".to_owned()),
        );
    }

    #[tokio::test]
    async fn run_discovery_missing_logout_endpoints_yields_none() {
        let issuer = "https://idp.example";
        let cfg = mock_cfg(issuer);
        let client = fake_client(discovery_routes(issuer, false));
        let (_oidc, end_session, revocation, _jwks) =
            run_discovery(&cfg, &client)
                .await
                .expect("discovery should succeed");
        assert!(end_session.is_none());
        assert!(revocation.is_none());
    }

    #[tokio::test]
    async fn run_discovery_http_error_is_err() {
        let issuer = "https://idp.example";
        let cfg = mock_cfg(issuer);
        // Discovery endpoint returns 500: the metadata fetch must fail.
        let mut routes = discovery_routes(issuer, true);
        routes.insert(
            "/.well-known/openid-configuration".to_owned(),
            (500, "{}".to_owned()),
        );
        let client = fake_client(routes);
        assert!(run_discovery(&cfg, &client).await.is_err());
    }

    #[tokio::test]
    async fn run_discovery_malformed_json_is_err() {
        let issuer = "https://idp.example";
        let cfg = mock_cfg(issuer);
        let mut routes = discovery_routes(issuer, true);
        routes.insert(
            "/.well-known/openid-configuration".to_owned(),
            (200, "{ this is not json".to_owned()),
        );
        let client = fake_client(routes);
        assert!(run_discovery(&cfg, &client).await.is_err());
    }

    #[tokio::test]
    async fn run_discovery_issuer_mismatch_is_err() {
        // OIDC requires the discovery doc's `issuer` to equal the
        // requested issuer URL; a mismatch must be rejected.
        let issuer = "https://idp.example";
        let cfg = mock_cfg(issuer);
        let mut routes = discovery_routes(issuer, true);
        routes.insert(
            "/.well-known/openid-configuration".to_owned(),
            (200, discovery_doc("https://evil.example", true)),
        );
        let client = fake_client(routes);
        assert!(run_discovery(&cfg, &client).await.is_err());
    }

    #[test]
    fn missing_groups_claim_returns_empty() {
        let claims = serde_json::json!({});
        assert!(extract_groups_claim("groups", &claims).is_empty());
    }

    #[test]
    fn missing_username_claim_falls_back_to_default() {
        let claims = serde_json::json!({});
        let s =
            extract_string_claim("preferred_username", &claims, "alice");
        assert_eq!(s, "alice");
    }

    // Build an OidcProvider without contacting the network, sufficient
    // for exercising the in-memory refresh store directly.  Discovery
    // and the OAuth client are sidestepped: tests only touch
    // `refreshes` via the refresh_count() helper and the public
    // `refresh()` failure paths exercised through unit code that
    // doesn't require an IdP.
    pub(crate) fn provider_for_store_with_end_session(
        ttl: Duration,
        end_session: url::Url,
    ) -> Arc<OidcProvider> {
        let p = provider_for_store(ttl);
        p.end_session_url.store(Arc::new(Some(end_session)));
        p
    }

    pub(crate) fn provider_for_store(ttl: Duration) -> Arc<OidcProvider> {
        // Use a minimal OidcClient that won't be invoked: the refresh
        // tests below only insert/inspect entries and verify
        // eviction.  Building a real client requires discovery, which
        // we intentionally avoid in unit tests.
        let cfg = crate::config::OidcConfig {
            issuer: "https://idp.example".into(),
            client_id: "id".into(),
            client_secret: None,
            redirect_uri: "https://app.example/cb".into(),
            scopes: vec!["openid".into()],
            username_claim: "sub".into(),
            groups_claim: "groups".into(),
            login_path: "/oidc/login".into(),
            callback_path: "/oidc/callback".into(),
            state_ttl_secs: 60,
            refresh: true,
            refresh_ttl_secs: ttl.as_secs(),
            refresh_cookie_name: "__hypershunt_oidc_refresh".into(),
            logout_path: "/oidc/logout".into(),
            post_logout_uri: "/".into(),
            idp_logout: true,
            userinfo: false,
            discovery_refresh_secs: 0,
            discovery_retry: true,
            backchannel_logout_enabled: true,
            backchannel_logout_path:
                "/oidc/backchannel-logout".into(),
            backchannel_max_iat_skew_secs: 120,
            backchannel_jti_ttl_secs: 300,
            bearer: false,
            bearer_audiences: vec![],
            bearer_cache_size: 16,
            revoke_on_logout: true,
            require_iss: false,
            resources: vec![],
        };
        let client = dummy_client(&cfg);
        Arc::new(OidcProvider {
            client: ArcSwap::new(Arc::new(Some(Arc::new(client)))),
            state_ttl: Duration::from_secs(cfg.state_ttl_secs),
            refresh_ttl: ttl,
            metrics: Arc::new(Metrics::new()),
            cfg,
            states: Mutex::new(HashMap::new()),
            refreshes: Mutex::new(HashMap::new()),
            end_session_url: ArcSwap::new(Arc::new(None)),
            revocation_url: ArcSwap::new(Arc::new(None)),
            jwks: ArcSwap::new(Arc::new(None)),
            seen_jtis: Mutex::new(HashMap::new()),
            bearer_cache: Mutex::new(lru::LruCache::new(
                NonZeroUsize::new(16).unwrap(),
            )),
            http_client: build_http_client().unwrap(),
        })
    }

    /// Build a never-network-called `OidcClient` for unit tests.
    /// v4's typestate requires the token/userinfo markers to be
    /// `EndpointMaybeSet`, which only `from_provider_metadata` produces,
    /// so we synthesize a minimal provider-metadata document offline and
    /// run it through the exact same builder chain as production.
    fn dummy_client(cfg: &crate::config::OidcConfig) -> OidcClient {
        use openidconnect::core::{
            CoreJwsSigningAlgorithm, CoreResponseType,
            CoreSubjectIdentifierType,
        };
        let issuer = IssuerUrl::new(cfg.issuer.clone()).unwrap();
        let metadata = HypershuntProviderMetadata::new(
            issuer,
            openidconnect::AuthUrl::new(
                "https://idp.example/authorize".into(),
            )
            .unwrap(),
            openidconnect::JsonWebKeySetUrl::new(
                "https://idp.example/jwks".into(),
            )
            .unwrap(),
            vec![openidconnect::ResponseTypes::new(vec![
                CoreResponseType::Code,
            ])],
            vec![CoreSubjectIdentifierType::Public],
            vec![CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256],
            LogoutMetadata {
                end_session_endpoint: None,
                revocation_endpoint: None,
            },
        )
        .set_token_endpoint(Some(
            openidconnect::TokenUrl::new(
                "https://idp.example/token".into(),
            )
            .unwrap(),
        ))
        .set_jwks(openidconnect::JsonWebKeySet::new(vec![]));
        OidcClientFromMetadata::from_provider_metadata(
            metadata,
            ClientId::new(cfg.client_id.clone()),
            None,
        )
        .set_redirect_uri(
            RedirectUrl::new(cfg.redirect_uri.clone()).unwrap(),
        )
        .set_revocation_url(openidconnect::RevocationUrl::new(
            "https://idp.example/revoke".into(),
        )
        .unwrap())
    }

    // -- Mock IdP -------------------------------------------------
    //
    // A minimal in-process OpenID Provider speaking just enough of
    // the protocol for run_discovery / complete_login / refresh /
    // revoke_refresh_token to complete over plain HTTP on loopback:
    // discovery document, ES256 JWKS, token endpoint, revocation
    // endpoint.  The authorization endpoint is never contacted (the
    // test plays the browser and jumps straight to the callback).

    pub(crate) struct MockIdpState {
        /// Nonce the next id_token must echo; the test extracts it
        /// from the begin_login URL, exactly as a real IdP would
        /// receive it in the authorization request.
        pub(crate) nonce: Option<String>,
        /// When true the token endpoint rotates the refresh token on
        /// every grant; when false it omits the refresh_token field
        /// on refresh grants (the "TTL slide" arm).
        pub(crate) rotate_refresh: bool,
        /// Count of /revoke hits.
        pub(crate) revocations: u32,
        /// Monotonic counter for minted refresh tokens.
        pub(crate) token_seq: u32,
    }

    pub(crate) struct MockIdp {
        pub(crate) issuer: String,
        pub(crate) state: Arc<std::sync::Mutex<MockIdpState>>,
    }

    impl MockIdp {
        pub(crate) async fn spawn() -> MockIdp {
            use base64::Engine as _;
            use base64::engine::general_purpose::URL_SAFE_NO_PAD;
            use rsa::traits::PublicKeyParts as _;

            let listener =
                tokio::net::TcpListener::bind("127.0.0.1:0")
                    .await
                    .unwrap();
            let issuer =
                format!("http://{}", listener.local_addr().unwrap());

            // RS256: the only algorithm openidconnect's default
            // id_token_verifier accepts.  Keygen is slow, so share
            // one key across all tests in the process.
            static RSA_KEY: std::sync::OnceLock<rsa::RsaPrivateKey> =
                std::sync::OnceLock::new();
            let private = RSA_KEY
                .get_or_init(|| {
                    rsa::RsaPrivateKey::new(&mut rand_core::OsRng, 2048)
                        .unwrap()
                })
                .clone();
            let signing_key = Arc::new(
                rsa::pkcs1v15::SigningKey::<sha2::Sha256>::new(
                    private.clone(),
                ),
            );
            let public = private.to_public_key();
            let jwks = serde_json::json!({
                "keys": [{
                    "kty": "RSA", "alg": "RS256",
                    "use": "sig", "kid": "test-key",
                    "n": URL_SAFE_NO_PAD
                        .encode(public.n().to_bytes_be()),
                    "e": URL_SAFE_NO_PAD
                        .encode(public.e().to_bytes_be()),
                }]
            })
            .to_string();

            let state = Arc::new(std::sync::Mutex::new(MockIdpState {
                nonce: None,
                rotate_refresh: true,
                revocations: 0,
                token_seq: 0,
            }));

            let iss = issuer.clone();
            let st = state.clone();
            tokio::spawn(async move {
                loop {
                    let Ok((stream, _)) = listener.accept().await
                    else {
                        return;
                    };
                    let iss = iss.clone();
                    let st = st.clone();
                    let jwks = jwks.clone();
                    let key = signing_key.clone();
                    tokio::spawn(async move {
                        let svc = hyper::service::service_fn(
                            move |req: hyper::Request<
                                hyper::body::Incoming,
                            >| {
                                let iss = iss.clone();
                                let st = st.clone();
                                let jwks = jwks.clone();
                                let key = key.clone();
                                async move {
                                    let path = req.uri().path().to_owned();
                                    let body = match path.as_str() {
                                        "/.well-known/openid-configuration" => {
                                            serde_json::json!({
                                                "issuer": iss,
                                                "authorization_endpoint":
                                                    format!("{iss}/authorize"),
                                                "token_endpoint":
                                                    format!("{iss}/token"),
                                                "jwks_uri":
                                                    format!("{iss}/jwks"),
                                                "end_session_endpoint":
                                                    format!("{iss}/logout"),
                                                "revocation_endpoint":
                                                    format!("{iss}/revoke"),
                                                "response_types_supported":
                                                    ["code"],
                                                "subject_types_supported":
                                                    ["public"],
                                                // Must match the alg
                                                // the mock actually
                                                // signs with (RS256):
                                                // v4's id_token verifier
                                                // restricts accepted
                                                // algs to those the
                                                // discovery doc
                                                // advertises.
                                                "id_token_signing_alg_values_supported":
                                                    ["RS256"],
                                            })
                                            .to_string()
                                        }
                                        "/jwks" => jwks,
                                        "/token" => {
                                            let (nonce, seq, rotate, is_refresh);
                                            {
                                                use http_body_util::BodyExt as _;
                                                let form = req
                                                    .into_body()
                                                    .collect()
                                                    .await
                                                    .unwrap()
                                                    .to_bytes();
                                                let form = String::from_utf8_lossy(&form)
                                                    .into_owned();
                                                is_refresh = form
                                                    .contains("grant_type=refresh_token");
                                                let mut s = st.lock().unwrap();
                                                s.token_seq += 1;
                                                nonce = s.nonce.clone();
                                                seq = s.token_seq;
                                                rotate = s.rotate_refresh;
                                            }
                                            let now = std::time::SystemTime::now()
                                                .duration_since(std::time::UNIX_EPOCH)
                                                .unwrap()
                                                .as_secs() as i64;
                                            let mut claims = serde_json::json!({
                                                "iss": iss,
                                                "aud": "client-1",
                                                "sub": "alice",
                                                "iat": now,
                                                "exp": now + 3600,
                                                "preferred_username": "alice-pref",
                                                "groups": ["devs"],
                                                "sid": "idp-sess-1",
                                            });
                                            // Echo the nonce only on the
                                            // initial code grant; refresh
                                            // responses carry none, like
                                            // real IdPs.
                                            if !is_refresh
                                                && let Some(n) = nonce
                                            {
                                                claims["nonce"] =
                                                    n.into();
                                            }
                                            use base64::Engine as _;
                                            use base64::engine::general_purpose::URL_SAFE_NO_PAD;
                                            use rsa::signature::{
                                                SignatureEncoding as _,
                                                Signer as _,
                                            };
                                            let header = URL_SAFE_NO_PAD.encode(
                                                br#"{"alg":"RS256","kid":"test-key"}"#,
                                            );
                                            let payload = URL_SAFE_NO_PAD
                                                .encode(claims.to_string());
                                            let signing_input =
                                                format!("{header}.{payload}");
                                            let sig = key
                                                .sign(signing_input.as_bytes());
                                            let id_token = format!(
                                                "{signing_input}.{}",
                                                URL_SAFE_NO_PAD
                                                    .encode(sig.to_bytes())
                                            );
                                            let mut resp = serde_json::json!({
                                                "access_token":
                                                    format!("at-{seq}"),
                                                "token_type": "Bearer",
                                                "expires_in": 3600,
                                                "id_token": id_token,
                                            });
                                            if !is_refresh || rotate {
                                                resp["refresh_token"] =
                                                    format!("rt-{seq}").into();
                                            }
                                            resp.to_string()
                                        }
                                        "/revoke" => {
                                            st.lock().unwrap().revocations += 1;
                                            String::new()
                                        }
                                        _ => String::new(),
                                    };
                                    Ok::<_, std::convert::Infallible>(
                                        hyper::Response::builder()
                                            .header(
                                                "content-type",
                                                "application/json",
                                            )
                                            .body(
                                                http_body_util::Full::new(
                                                    bytes::Bytes::from(body),
                                                ),
                                            )
                                            .unwrap(),
                                    )
                                }
                            },
                        );
                        let _ = hyper::server::conn::http1::Builder::new()
                            .serve_connection(
                                hyper_util::rt::TokioIo::new(stream),
                                svc,
                            )
                            .await;
                    });
                }
            });

            MockIdp { issuer, state }
        }
    }

    pub(crate) fn mock_cfg(issuer: &str) -> crate::config::OidcConfig {
        let mut cfg = provider_for_store(Duration::from_secs(60))
            .cfg
            .clone();
        cfg.issuer = issuer.to_owned();
        cfg.client_id = "client-1".into();
        cfg.username_claim = "preferred_username".into();
        cfg.refresh = true;
        cfg.refresh_ttl_secs = 60;
        cfg
    }

    /// Poll until background discovery completes.
    async fn await_ready(p: &Arc<OidcProvider>) {
        for _ in 0..200 {
            if p.is_ready() {
                return;
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
        panic!("provider never became ready against the mock IdP");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn full_login_refresh_revoke_flow_against_mock_idp() {
        let idp = MockIdp::spawn().await;
        let metrics = Arc::new(Metrics::new());
        let p = OidcProvider::new(mock_cfg(&idp.issuer), metrics.clone());
        await_ready(&p).await;

        // Discovery surfaced the optional endpoints.
        assert!(p.end_session_url().is_some());
        assert_eq!(
            metrics
                .oidc_discoveries
                .load(std::sync::atomic::Ordering::Relaxed),
            1
        );

        // Browser leg: begin_login mints state + nonce; hand the
        // nonce to the IdP the way the authorization request would.
        let (auth_url, state_id) = p
            .begin_login("/after".into(), IdpHints::default())
            .expect("ready provider must build a login URL");
        let nonce = auth_url
            .query_pairs()
            .find(|(k, _)| k == "nonce")
            .map(|(_, v)| v.into_owned())
            .expect("auth URL must carry a nonce");
        idp.state.lock().unwrap().nonce = Some(nonce);

        // Callback leg.
        let (ident, return_to, sid) = p
            .complete_login("any-code".into(), &state_id)
            .await
            .expect("token exchange against mock IdP");
        assert_eq!(ident.username, "alice-pref");
        assert_eq!(ident.groups, vec!["devs".to_string()]);
        assert_eq!(return_to, "/after");
        let sid = sid.expect("refresh enabled -> sid cookie value");

        // State is single-use: replaying the callback fails.
        let err = p
            .complete_login("any-code".into(), &state_id)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("unknown or expired"), "got: {err}");

        // Refresh with rotation: the IdP returns a new refresh
        // token, so the session is re-keyed under a new sid.
        let (ident2, sid2) = p.refresh(&sid).await.unwrap();
        assert_eq!(ident2.username, "alice-pref");
        assert_ne!(sid2, sid, "rotation must re-key the session");
        assert_eq!(p.refresh_count(), 1, "old sid replaced, not added");

        // Refresh without rotation: same sid slides forward.
        idp.state.lock().unwrap().rotate_refresh = false;
        let (_, sid3) = p.refresh(&sid2).await.unwrap();
        assert_eq!(sid3, sid2, "no rotation -> sid unchanged");

        // Unknown sid is rejected.
        assert!(p.refresh("no-such-sid").await.is_err());

        // Best-effort revocation: openidconnect refuses to build a
        // revocation request against a plain-http endpoint
        // (InsecureUrl), which is exactly what the loopback mock
        // serves -- so this exercises the documented graceful-skip
        // arm: no panic, no failure metric, logout never blocked on
        // the IdP.  The https success path stays integration-only.
        p.revoke_refresh_token(RefreshToken::new("rt-1".into()));
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert_eq!(idp.state.lock().unwrap().revocations, 0);
        assert_eq!(
            metrics
                .oidc_revocation_failures
                .load(std::sync::atomic::Ordering::Relaxed),
            0,
            "skip must not be recorded as a failure"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn expired_state_is_rejected_at_callback() {
        let idp = MockIdp::spawn().await;
        let mut cfg = mock_cfg(&idp.issuer);
        cfg.state_ttl_secs = 0; // every state is born expired
        let p = OidcProvider::new(cfg, Arc::new(Metrics::new()));
        await_ready(&p).await;

        let (_, state_id) = p
            .begin_login("/".into(), IdpHints::default())
            .unwrap();
        tokio::time::sleep(Duration::from_millis(20)).await;
        let err = p
            .complete_login("code".into(), &state_id)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("state expired"), "got: {err}");
    }

    #[test]
    fn evict_expired_drops_stale_states_and_refreshes() {
        let p = provider_for_store(Duration::from_secs(60));
        // One live and one expired entry in each store.  StateEntry
        // freshness is judged from `created` against state_ttl (60s
        // in this fixture); RefreshEntry from its absolute deadline.
        let (_, live_state) = {
            // begin_login needs no IdP: the dummy client is enough
            // to mint a state entry.
            p.begin_login("/x".into(), IdpHints::default()).unwrap()
        };
        p.states.lock().unwrap().insert(
            "stale".into(),
            StateEntry {
                pkce_verifier: openidconnect::PkceCodeVerifier::new(
                    "v".repeat(43),
                ),
                nonce: Nonce::new("n".into()),
                return_to: "/".into(),
                created: Instant::now() - Duration::from_secs(3600),
            },
        );
        p.refreshes.lock().unwrap().insert(
            "live".into(),
            RefreshEntry {
                refresh_token: RefreshToken::new("rt".into()),
                expires_at: Instant::now() + Duration::from_secs(60),
                id_token: String::new(),
                subject: "alice".into(),
                idp_sid: None,
            },
        );
        p.refreshes.lock().unwrap().insert(
            "dead".into(),
            RefreshEntry {
                refresh_token: RefreshToken::new("rt".into()),
                expires_at: Instant::now() - Duration::from_secs(1),
                id_token: String::new(),
                subject: "alice".into(),
                idp_sid: None,
            },
        );

        p.evict_expired();

        let states = p.states.lock().unwrap();
        assert!(states.contains_key(&live_state));
        assert!(!states.contains_key("stale"));
        drop(states);
        let refreshes = p.refreshes.lock().unwrap();
        assert!(refreshes.contains_key("live"));
        assert!(!refreshes.contains_key("dead"));
    }

    #[test]
    fn provider_new_starts_in_not_ready_state() {
        // Issuer points at a non-routable address so background
        // discovery cannot succeed before this synchronous assert
        // runs.  The contract under test: new() is synchronous and
        // returns a provider that is_ready() == false until the
        // background bootstrap completes.
        let cfg = crate::config::OidcConfig {
            issuer: "https://127.0.0.1:1/".into(),
            client_id: "id".into(),
            client_secret: None,
            redirect_uri: "https://app.example/cb".into(),
            scopes: vec!["openid".into()],
            username_claim: "sub".into(),
            groups_claim: "groups".into(),
            login_path: "/oidc/login".into(),
            callback_path: "/oidc/callback".into(),
            state_ttl_secs: 60,
            refresh: false,
            refresh_ttl_secs: 60,
            refresh_cookie_name: "__hypershunt_oidc_refresh".into(),
            logout_path: "/oidc/logout".into(),
            post_logout_uri: "/".into(),
            idp_logout: false,
            userinfo: false,
            discovery_refresh_secs: 0,
            // Disable retry so the background task exits promptly
            // when discovery fails -- prevents the test runtime
            // from spinning on retries.
            discovery_retry: false,
            backchannel_logout_enabled: false,
            backchannel_logout_path:
                "/oidc/backchannel-logout".into(),
            backchannel_max_iat_skew_secs: 120,
            backchannel_jti_ttl_secs: 300,
            bearer: false,
            bearer_audiences: vec![],
            bearer_cache_size: 16,
            revoke_on_logout: true,
            require_iss: false,
            resources: vec![],
        };
        // OidcProvider::new spawns a tokio task, so we need a runtime.
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        rt.block_on(async {
            let p = OidcProvider::new(cfg, Arc::new(Metrics::new()));
            assert!(!p.is_ready());
            assert!(p.client().is_none());
        });
    }

    #[test]
    fn userinfo_merge_disabled_returns_id_token_values() {
        // With userinfo off, the helper must short-circuit before
        // touching the network -- the dummy OidcClient stored on
        // provider_for_store would fail any real call.
        let p = provider_for_store(Duration::from_secs(60));
        let client = p.client().expect("test provider has a client");
        let access = openidconnect::AccessToken::new("at".into());
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let (user, groups) = rt.block_on(p.merge_userinfo(
            &client,
            &access,
            "alice",
            vec!["devs".into()],
        ));
        assert_eq!(user, "alice");
        assert_eq!(groups, vec!["devs".to_string()]);
    }

    #[test]
    fn extract_groups_claim_from_json_array_and_string() {
        // Array form (Keycloak/Authelia).
        let v = serde_json::json!({"groups": ["admins", "devs"]});
        assert_eq!(
            extract_groups_claim_from_json("groups", &v),
            vec!["admins", "devs"],
        );
        // Space-delimited string form (some SAML-style IdPs).
        let v = serde_json::json!({"groups": "admins devs"});
        assert_eq!(
            extract_groups_claim_from_json("groups", &v),
            vec!["admins", "devs"],
        );
        // Missing.
        let v = serde_json::json!({});
        assert!(extract_groups_claim_from_json("groups", &v).is_empty());
    }

    #[test]
    fn refresh_store_evicts_expired_entries() {
        let p = provider_for_store(Duration::from_millis(1));
        p.refreshes.lock().expect("oidc refresh mutex").insert(
            "sid".into(),
            RefreshEntry {
                refresh_token: RefreshToken::new("rt".into()),
                // Already in the past.
                expires_at: Instant::now() - Duration::from_secs(1),
                id_token: "test".into(),
                subject: "alice".into(),
                idp_sid: None,
            },
        );
        assert_eq!(p.refresh_count(), 1);
        p.evict_expired();
        assert_eq!(p.refresh_count(), 0);
    }

    #[test]
    fn take_logout_session_returns_stored_id_token() {
        let p = provider_for_store(Duration::from_secs(60));
        p.refreshes.lock().expect("oidc refresh mutex").insert(
            "sid".into(),
            RefreshEntry {
                refresh_token: RefreshToken::new("rt".into()),
                expires_at: Instant::now() + Duration::from_secs(60),
                id_token: "the-id-token".into(),
                subject: "alice".into(),
                idp_sid: None,
            },
        );
        let (id_tok, refresh_tok) =
            p.take_logout_session("sid").expect("first call");
        assert_eq!(id_tok, "the-id-token");
        assert_eq!(refresh_tok.secret(), "rt");
        // Second call returns None: pop semantics.
        assert!(p.take_logout_session("sid").is_none());
        assert_eq!(p.refresh_count(), 0);
    }

    #[test]
    fn bearer_cache_returns_stored_identity() {
        // Direct exercise of the cache short-circuit: insert an
        // entry by hand and confirm validate_bearer_token returns
        // it without touching the JWS parser (the entry sits under
        // the SHA-256 of the token bytes, so any token string that
        // hashes to the same key works).
        let p = provider_for_store(Duration::from_secs(60));
        let token = "anything";
        let key: [u8; 32] = sha2::Sha256::digest(token.as_bytes()).into();
        let id = Identity {
            username: "alice".into(),
            groups: vec!["devs".into()],
        };
        let future_exp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 600;
        p.bearer_cache.lock().expect("oidc bearer cache mutex").put(
            key,
            BearerCacheEntry {
                identity: id.clone(),
                expires_at: future_exp,
            },
        );
        let got = p.validate_bearer_token(token).expect("cache hit");
        assert_eq!(got.username, id.username);
        assert_eq!(got.groups, id.groups);
    }

    #[test]
    fn bearer_cache_evicts_expired_entry_on_lookup() {
        let p = provider_for_store(Duration::from_secs(60));
        let token = "anything";
        let key: [u8; 32] = sha2::Sha256::digest(token.as_bytes()).into();
        p.bearer_cache.lock().expect("oidc bearer cache mutex").put(
            key,
            BearerCacheEntry {
                identity: Identity {
                    username: "alice".into(),
                    groups: vec![],
                },
                // Already past.
                expires_at: 0,
            },
        );
        // The validator should NOT return the expired entry; it
        // tries to parse "anything" as a JWS and fails -- which is
        // an error, not a cache hit.  Either way, the cache entry
        // must be gone afterwards.
        assert!(p.validate_bearer_token(token).is_err());
        assert!(p.bearer_cache.lock().expect("oidc bearer cache mutex").peek(&key).is_none());
    }

    #[test]
    fn revoke_no_op_when_disabled_in_config() {
        // With revoke_on_logout=false the spawn path must not even
        // touch metrics.  Easy black-box check: arrange the no-op
        // condition and confirm the counter stays at zero.
        let p = provider_for_store(Duration::from_secs(60));
        // The test helper builds cfg with revoke_on_logout=true;
        // mutate just this field via an unsafe interior-mutability
        // pattern would be heavy.  Instead build a sibling provider
        // with the field flipped.
        let mut cfg_disabled = p.cfg.clone();
        cfg_disabled.revoke_on_logout = false;
        let p_off = Arc::new(OidcProvider {
            client: ArcSwap::new(Arc::new(p.client.load_full().as_ref().clone())),
            state_ttl: Duration::from_secs(60),
            refresh_ttl: Duration::from_secs(60),
            metrics: Arc::new(crate::metrics::Metrics::new()),
            cfg: cfg_disabled,
            states: Mutex::new(HashMap::new()),
            refreshes: Mutex::new(HashMap::new()),
            end_session_url: ArcSwap::new(Arc::new(None)),
            revocation_url: ArcSwap::new(Arc::new(None)),
            jwks: ArcSwap::new(Arc::new(None)),
            seen_jtis: Mutex::new(HashMap::new()),
            bearer_cache: Mutex::new(lru::LruCache::new(
                NonZeroUsize::new(16).unwrap(),
            )),
            http_client: build_http_client().unwrap(),
        });
        // No tokio runtime needed: the early-return branch fires
        // before any spawn.
        p_off.revoke_refresh_token(RefreshToken::new("rt".into()));
        assert_eq!(
            p_off
                .metrics
                .oidc_revocations
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            p_off
                .metrics
                .oidc_revocation_failures
                .load(std::sync::atomic::Ordering::Relaxed),
            0
        );
    }

    #[test]
    fn issuer_strips_trailing_slash() {
        let mut p = provider_for_store(Duration::from_secs(60));
        // Force a trailing slash on the configured issuer and
        // confirm the accessor returns the trimmed form.
        Arc::get_mut(&mut p).unwrap().cfg.issuer =
            "https://idp.example/".into();
        assert_eq!(p.issuer(), "https://idp.example");
    }

    #[test]
    fn record_jti_rejects_replay() {
        let p = provider_for_store(Duration::from_secs(60));
        assert!(p.record_jti("jti-1"));
        assert!(!p.record_jti("jti-1"));
        // A different jti is still accepted.
        assert!(p.record_jti("jti-2"));
    }

    #[test]
    fn idp_hints_pairs_filters_none_and_preserves_order() {
        let h = IdpHints {
            login_hint: Some("alice@example".into()),
            prompt: None,
            max_age: Some("0".into()),
            acr_values: None,
            ui_locales: Some("fr".into()),
        };
        let pairs: Vec<_> = h.pairs().collect();
        assert_eq!(
            pairs,
            vec![
                ("login_hint", "alice@example"),
                ("max_age", "0"),
                ("ui_locales", "fr"),
            ],
        );
    }

    #[test]
    fn refresh_store_keeps_live_entries() {
        let p = provider_for_store(Duration::from_secs(60));
        p.refreshes.lock().expect("oidc refresh mutex").insert(
            "sid".into(),
            RefreshEntry {
                refresh_token: RefreshToken::new("rt".into()),
                expires_at: Instant::now() + Duration::from_secs(60),
                id_token: "test".into(),
                subject: "alice".into(),
                idp_sid: None,
            },
        );
        p.evict_expired();
        assert_eq!(p.refresh_count(), 1);
    }
}