rs-identity-model 0.6.1

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

mod exchange;
mod pkce;
mod response;

use std::collections::HashMap;
use std::time::Duration;

use reqwest::Client as HttpClient;
use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};

use crate::client_auth::{OAuthErrorBody, basic_auth_header, body_snippet, read_capped_body};
use crate::{IdentityError, Result};

pub use exchange::{
    TOKEN_TYPE_ACCESS_TOKEN, TOKEN_TYPE_ID_TOKEN, TOKEN_TYPE_JWT, TOKEN_TYPE_REFRESH_TOKEN,
    TOKEN_TYPE_SAML1, TOKEN_TYPE_SAML2, TOKEN_TYPE_URIS, TokenExchangeRequest,
};
pub use pkce::{
    CHALLENGE_METHOD_S256, PkceChallenge, authorization_url, s256_challenge, valid_code_verifier,
};
pub use response::TokenResponse;

/// The `client_credentials` grant type (RFC 6749 §4.4).
const GRANT_CLIENT_CREDENTIALS: &str = "client_credentials";
/// The `authorization_code` grant type (RFC 6749 §4.1.3).
const GRANT_AUTHORIZATION_CODE: &str = "authorization_code";
/// The token exchange grant type URI (RFC 8693 §2.1).
const GRANT_TOKEN_EXCHANGE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";

/// Default per-request timeout so a hung endpoint cannot block indefinitely.
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Placeholder printed in place of secret material in `Debug` output (#24).
const REDACTED: &str = "<redacted>";

/// Parameters owned by the grant and client-authentication logic on **every**
/// grant. They can never be set or overridden via
/// [`TokenClientBuilder::extra_param`], so that caller-supplied extras cannot
/// contradict the request's identity or grant shape.
///
/// `resource`, `audience`, and `requested_token_type` are deliberately absent
/// here: they are non-identity target/output hints a caller may legitimately
/// want to supply on a grant that does not model them (e.g. an RFC 8707
/// `resource` on the client credentials grant), so they stay available as
/// extras there. On the token exchange grant they ARE owned — it sources them
/// from [`TokenExchangeRequest`] — so it additionally reserves
/// [`EXCHANGE_RESERVED_PARAMS`].
const RESERVED_PARAMS: &[&str] = &[
    "grant_type",
    "client_id",
    "client_secret",
    "code",
    "redirect_uri",
    "code_verifier",
    "scope",
    "subject_token",
    "subject_token_type",
    "actor_token",
    "actor_token_type",
];

/// Targeting parameters reserved on the token exchange grant only, on top of
/// [`RESERVED_PARAMS`].
///
/// The exchange sources all three from [`TokenExchangeRequest`] (RFC 8693
/// §2.1), so an extra param must not be able to inject one the request left
/// unset, nor override one it pinned. Skipping keys already present in the form
/// is not enough on its own: when the request omits a value, nothing puts the
/// key in the form and an extra would slip through — silently retargeting the
/// exchange at another resource server or asking for a different token type,
/// with no check that the returned `issued_token_type` is what was requested.
///
/// [`TokenClient::token_exchange`] therefore *rejects* an extra param naming one
/// of these rather than dropping it: extras are client-wide, so a silent drop
/// would take away a restriction the caller believes is still in force, on one
/// grant only and with nothing said about it. The skip in
/// [`TokenClient::do_request`] stays as defence in depth.
const EXCHANGE_RESERVED_PARAMS: &[&str] = &["requested_token_type", "resource", "audience"];

/// Normalises an extra-param key before it is matched against the reserved
/// lists.
///
/// The match is on the normalised form because the guard has to hold for the
/// server, not for Rust: a form parser that folds case or trims surrounding
/// whitespace reads `"Audience"` and `" audience"` as `audience`, so an
/// exact-byte comparison would wave those spellings straight through the guard
/// it documents.
fn normalize_param_key(key: &str) -> String {
    key.trim().to_ascii_lowercase()
}

/// How client credentials are presented to the token endpoint (RFC 6749 §2.3).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClientAuthMethod {
    /// Send `client_id` and `client_secret` in an HTTP Basic `Authorization`
    /// header (RFC 6749 §2.3.1). This is the default.
    #[default]
    ClientSecretBasic,
    /// Send `client_id` and `client_secret` as form parameters in the request
    /// body (RFC 6749 §2.3.1).
    ClientSecretPost,
}

/// An async OAuth 2.0 token endpoint client.
///
/// Construct one with [`TokenClient::builder`]. A single client should be
/// reused across calls so the underlying connection pool is shared.
pub struct TokenClient {
    http: HttpClient,
    token_endpoint: String,
    client_id: String,
    client_secret: Option<String>,
    auth_method: ClientAuthMethod,
    extra_params: HashMap<String, String>,
    timeout: Duration,
    allow_http: bool,
}

// A hand-written Debug that never prints the client secret (#24). Presence of
// the secret is shown as `Some("<redacted>")` / `None` so a confidential vs.
// public client is still distinguishable in logs.
impl std::fmt::Debug for TokenClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenClient")
            .field("token_endpoint", &self.token_endpoint)
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| REDACTED),
            )
            .field("auth_method", &self.auth_method)
            .field("extra_params", &self.extra_params)
            .field("timeout", &self.timeout)
            .field("allow_http", &self.allow_http)
            .finish_non_exhaustive()
    }
}

impl TokenClient {
    /// Returns a builder for configuring a [`TokenClient`].
    pub fn builder() -> TokenClientBuilder {
        TokenClientBuilder::new()
    }

    /// Performs the OAuth 2.0 client credentials grant (RFC 6749 §4.4, CC-001):
    /// POSTs `grant_type=client_credentials` to the token endpoint and returns
    /// the typed [`TokenResponse`].
    ///
    /// Authentication uses the configured [`ClientAuthMethod`]
    /// (`client_secret_basic` by default). When `scope` is `Some`, it is sent
    /// as a single space-delimited `scope` parameter (CC-005).
    ///
    /// # Errors
    ///
    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response
    ///   (CC-004).
    /// - [`IdentityError::Http`] — a transport failure or non-OAuth error body.
    /// - [`IdentityError::Deserialization`] — a 2xx body that is not a valid
    ///   token response.
    pub async fn client_credentials(&self, scope: Option<&str>) -> Result<TokenResponse> {
        let mut form: Vec<(String, String)> = vec![(
            "grant_type".to_string(),
            GRANT_CLIENT_CREDENTIALS.to_string(),
        )];
        if let Some(scope) = scope {
            form.push(("scope".to_string(), scope.to_string()));
        }
        self.do_request(form, self.client_secret.as_deref(), &[])
            .await
    }

    /// Performs the OAuth 2.0 authorization code grant (RFC 6749 §4.1.3,
    /// ACG-001): POSTs `grant_type=authorization_code` with `code`,
    /// `redirect_uri`, and (when configured) `client_id` to the token endpoint
    /// and returns the typed [`TokenResponse`].
    ///
    /// When `code_verifier` is `Some`, it is validated against RFC 7636 §4.1
    /// and sent as the `code_verifier` parameter (ACG-004). A configured client
    /// secret still authenticates the request via the configured method; a
    /// public client (no secret) is identified by `client_id` in the body.
    ///
    /// # Errors
    ///
    /// - [`IdentityError::Validation`] — a `code_verifier` outside the 43–128
    ///   unreserved-character range.
    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response
    ///   (ACG-005).
    /// - [`IdentityError::Http`] / [`IdentityError::Deserialization`] — as for
    ///   [`client_credentials`](TokenClient::client_credentials).
    pub async fn exchange_code(
        &self,
        code: &str,
        redirect_uri: &str,
        code_verifier: Option<&str>,
    ) -> Result<TokenResponse> {
        if let Some(verifier) = code_verifier
            && !valid_code_verifier(verifier)
        {
            return Err(IdentityError::Validation(
                "code_verifier must be 43-128 unreserved characters".to_string(),
            ));
        }

        let mut form: Vec<(String, String)> = vec![
            (
                "grant_type".to_string(),
                GRANT_AUTHORIZATION_CODE.to_string(),
            ),
            ("code".to_string(), code.to_string()),
        ];
        if !redirect_uri.is_empty() {
            form.push(("redirect_uri".to_string(), redirect_uri.to_string()));
        }
        if let Some(verifier) = code_verifier {
            form.push(("code_verifier".to_string(), verifier.to_string()));
        }
        self.do_request(form, self.client_secret.as_deref(), &[])
            .await
    }

    /// Performs the OAuth 2.0 token exchange grant (RFC 8693 §2.1, EXCH-001):
    /// POSTs `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with
    /// the parameters of `request` to the token endpoint and returns the typed
    /// [`TokenResponse`], including the RFC 8693 §2.2 `issued_token_type`.
    ///
    /// A [`TokenExchangeRequest`] carrying only a subject token requests an
    /// **impersonation** token; one that also carries an actor token requests a
    /// **delegation** token (RFC 8693 §1.1, EXCH-002). The type URIs are sent
    /// verbatim (RFC 8693 §3, EXCH-003), and `resource` / `audience` are sent as
    /// repeated parameters when more than one target is named (EXCH-004).
    ///
    /// Authentication uses the configured [`ClientAuthMethod`]
    /// (`client_secret_basic` by default), exactly as for the other grants.
    /// The exchange owns its `requested_token_type`, `resource`, and `audience`
    /// parameters, so a [`TokenClientBuilder::extra_param`] carrying one of
    /// those keys is an error rather than something to drop: `extra_param` is
    /// client-wide, and quietly dropping an `audience` the caller set to pin
    /// every token to one API would relax that restriction on this grant alone.
    ///
    /// ```no_run
    /// # async fn run() -> rs_identity_model::Result<()> {
    /// use rs_identity_model::{TOKEN_TYPE_ACCESS_TOKEN, TokenClient, TokenExchangeRequest};
    ///
    /// let client = TokenClient::builder()
    ///     .client_id("my-client")
    ///     .client_secret("my-secret")
    ///     .token_endpoint("https://issuer.example.com/token")
    ///     .build()?;
    /// let issued = client
    ///     .token_exchange(
    ///         &TokenExchangeRequest::new("subject.tok", TOKEN_TYPE_ACCESS_TOKEN)
    ///             .audience("https://api.example.com"),
    ///     )
    ///     .await?;
    /// println!("issued a {:?}", issued.issued_token_type);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`IdentityError::Validation`] — `request` is missing a REQUIRED
    ///   RFC 8693 §2.1 parameter, or a [`TokenClientBuilder::extra_param`] key
    ///   names a parameter this grant owns
    ///   (`requested_token_type`, `resource`, `audience`). No request is sent.
    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response
    ///   (RFC 8693 §2.2.2, RFC 6749 §5.2, EXCH-006).
    /// - [`IdentityError::Http`] — a transport failure, a non-OAuth error body,
    ///   or a 2xx body missing the REQUIRED `access_token`, `token_type`, or
    ///   `issued_token_type`.
    /// - [`IdentityError::Deserialization`] — a 2xx body that is not a valid
    ///   token response. An explicit JSON `null` falls here rather than under
    ///   the missing-field errors above: `#[serde(default)]` fills in only an
    ///   *absent* key, so `"token_type": null` fails to deserialize before any
    ///   of those checks run.
    pub async fn token_exchange(&self, request: &TokenExchangeRequest) -> Result<TokenResponse> {
        request.validate()?;
        // An extra param naming a parameter the exchange owns is rejected, not
        // dropped. `extra_param` lives on [`TokenClientBuilder`], so it is
        // client-wide and shared with `client_credentials` and `exchange_code`:
        // dropping one here would take away a restriction the caller believes
        // is in force — an `audience` that pinned tokens to one API would
        // vanish on this grant alone, the AS could issue a broader token, and
        // nothing would say which grant lost it. Keys are sorted so the message
        // names the same key on every run when several collide.
        let mut colliding: Vec<&str> = self
            .extra_params
            .keys()
            .map(String::as_str)
            .filter(|key| EXCHANGE_RESERVED_PARAMS.contains(&normalize_param_key(key).as_str()))
            .collect();
        colliding.sort_unstable();
        if let Some(key) = colliding.first() {
            return Err(IdentityError::Validation(format!(
                "token exchange: extra param {key:?} names a parameter this grant owns; \
                 set it with TokenExchangeRequest::resource, ::audience, or \
                 ::requested_token_type instead"
            )));
        }

        let mut form: Vec<(String, String)> = vec![
            ("grant_type".to_string(), GRANT_TOKEN_EXCHANGE.to_string()),
            ("subject_token".to_string(), request.subject_token.clone()),
            (
                "subject_token_type".to_string(),
                request.subject_token_type.clone(),
            ),
        ];
        // RFC 8693 §2.1 forbids the half-pair `actor_token` without
        // `actor_token_type`. Both halves are destructured together so the
        // forbidden form is unrepresentable here, rather than merely unreachable
        // because validate() ran first: reading the type separately would emit
        // `actor_token_type=` the moment the two fields disagreed.
        if let (Some(actor_token), Some(actor_token_type)) = (
            request.actor_token.as_deref(),
            request.actor_token_type.as_deref(),
        ) {
            form.push(("actor_token".to_string(), actor_token.to_string()));
            form.push(("actor_token_type".to_string(), actor_token_type.to_string()));
        }
        // Empty optional parameters are skipped rather than sent as `key=`: an
        // empty value is not a request for anything, and a server is free to
        // read it as a malformed parameter and reject the whole exchange.
        if let Some(requested) = request
            .requested_token_type
            .as_deref()
            .filter(|t| !t.is_empty())
        {
            form.push(("requested_token_type".to_string(), requested.to_string()));
        }
        if let Some(scope) = request.scope.as_deref().filter(|s| !s.is_empty()) {
            form.push(("scope".to_string(), scope.to_string()));
        }
        // resource and audience MAY each appear more than once (RFC 8693 §2.1),
        // which the ordered pair list preserves and a map would collapse.
        for resource in request.resources.iter().filter(|r| !r.is_empty()) {
            form.push(("resource".to_string(), resource.clone()));
        }
        for audience in request.audiences.iter().filter(|a| !a.is_empty()) {
            form.push(("audience".to_string(), audience.clone()));
        }

        let token = self
            .do_request(
                form,
                self.client_secret.as_deref(),
                EXCHANGE_RESERVED_PARAMS,
            )
            .await?;
        // token_type is REQUIRED in a successful token response
        // (RFC 6749 §5.1), and `spec/vectors/token-exchange.json` lists it
        // among the exchange's required fields. It deserializes with a default
        // of "", so an omitted one has to be caught here rather than left to
        // surface as an empty string the caller may put straight into an
        // Authorization header.
        if token.token_type.is_empty() {
            return Err(IdentityError::Http(format!(
                "token exchange response from {} is missing token_type",
                self.token_endpoint
            )));
        }
        // issued_token_type is REQUIRED in a successful exchange response
        // (RFC 8693 §2.2); a 200 that omits it is non-conformant and is
        // rejected rather than handed back with the field silently empty.
        if !token
            .issued_token_type
            .as_deref()
            .is_some_and(|t| !t.is_empty())
        {
            return Err(IdentityError::Http(format!(
                "token exchange response from {} is missing issued_token_type",
                self.token_endpoint
            )));
        }
        Ok(token)
    }

    /// Applies client authentication and extra parameters, POSTs `form` as
    /// `application/x-www-form-urlencoded`, and decodes the response: a 2xx body
    /// into [`TokenResponse`], otherwise an OAuth error body into
    /// [`IdentityError::TokenEndpoint`] (status checked before decode).
    ///
    /// `grant_reserved` names parameters this particular grant owns on top of
    /// [`RESERVED_PARAMS`]; extras matching them are dropped rather than sent.
    /// Grants that can say so more usefully reject the collision before calling
    /// in (as [`TokenClient::token_exchange`] does) — the drop here is defence
    /// in depth, not the primary guard. Both lists are matched on
    /// [`normalize_param_key`].
    async fn do_request(
        &self,
        mut form: Vec<(String, String)>,
        client_secret: Option<&str>,
        grant_reserved: &[&str],
    ) -> Result<TokenResponse> {
        // Require an https endpoint unless http was explicitly allowed.
        let scheme = self.token_endpoint.to_ascii_lowercase();
        let scheme_ok =
            scheme.starts_with("https://") || (self.allow_http && scheme.starts_with("http://"));
        if !scheme_ok {
            return Err(IdentityError::Configuration(format!(
                "token endpoint {:?} must use https (enable allow_http for development)",
                self.token_endpoint
            )));
        }

        // Client authentication (RFC 6749 §2.3). A Basic header is built for the
        // request; post/public credentials go in the form body.
        let mut basic_header: Option<String> = None;
        match client_secret {
            // Public client: identify via client_id in the body.
            None => {
                if !self.client_id.is_empty() {
                    form.push(("client_id".to_string(), self.client_id.clone()));
                }
            }
            Some(secret) => match self.auth_method {
                ClientAuthMethod::ClientSecretPost => {
                    form.push(("client_id".to_string(), self.client_id.clone()));
                    form.push(("client_secret".to_string(), secret.to_string()));
                }
                ClientAuthMethod::ClientSecretBasic => {
                    basic_header = Some(basic_auth_header(&self.client_id, secret));
                }
            },
        }

        // Extra params are applied last but never override reserved grant or
        // client-auth parameters (whether or not already present — on the Basic
        // path client_id is absent from the body yet must not be injectable).
        for (key, value) in &self.extra_params {
            let normalized = normalize_param_key(key);
            if RESERVED_PARAMS.contains(&normalized.as_str())
                || grant_reserved.contains(&normalized.as_str())
                || form.iter().any(|(k, _)| k == key)
            {
                continue;
            }
            form.push((key.clone(), value.clone()));
        }

        let mut request = self
            .http
            .post(&self.token_endpoint)
            .timeout(self.timeout)
            .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
            .header(ACCEPT, "application/json")
            .form(&form);
        if let Some(header) = basic_header {
            request = request.header(AUTHORIZATION, header);
        }

        let response = request
            .send()
            .await
            .map_err(|e| IdentityError::Http(format!("post {}: {e}", self.token_endpoint)))?;

        let status = response.status();
        let body = read_capped_body(response).await?;

        // Status before decode: a non-2xx response is an OAuth error
        // (RFC 6749 §5.2, CC-004 / ACG-005).
        if !status.is_success() {
            if let Ok(err) = serde_json::from_slice::<OAuthErrorBody>(&body)
                && !err.error.is_empty()
            {
                return Err(IdentityError::TokenEndpoint {
                    error: err.error,
                    description: err.error_description,
                    error_uri: err.error_uri,
                    status: status.as_u16(),
                });
            }
            return Err(IdentityError::Http(format!(
                "token request to {} failed: HTTP {} with non-OAuth body: {}",
                self.token_endpoint,
                status.as_u16(),
                body_snippet(&body)
            )));
        }

        let token: TokenResponse = serde_json::from_slice(&body).map_err(|e| {
            IdentityError::Deserialization(format!(
                "parse token response from {}: {e}",
                self.token_endpoint
            ))
        })?;
        if token.access_token.is_empty() {
            return Err(IdentityError::Http(format!(
                "token response from {} is missing access_token",
                self.token_endpoint
            )));
        }
        Ok(token)
    }
}

/// Builder for [`TokenClient`]. Obtain one via [`TokenClient::builder`].
#[derive(Default)]
pub struct TokenClientBuilder {
    http: Option<HttpClient>,
    token_endpoint: Option<String>,
    client_id: Option<String>,
    client_secret: Option<String>,
    auth_method: ClientAuthMethod,
    extra_params: HashMap<String, String>,
    timeout: Duration,
    allow_http: bool,
}

// Redacting Debug: the builder holds the client secret before the client is
// built, so it must not print it either (#24).
impl std::fmt::Debug for TokenClientBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenClientBuilder")
            .field("token_endpoint", &self.token_endpoint)
            .field("client_id", &self.client_id)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| REDACTED),
            )
            .field("auth_method", &self.auth_method)
            .field("extra_params", &self.extra_params)
            .field("timeout", &self.timeout)
            .field("allow_http", &self.allow_http)
            .finish_non_exhaustive()
    }
}

impl TokenClientBuilder {
    fn new() -> Self {
        Self::default()
    }

    /// Sets the client identifier (required).
    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }

    /// Sets the client secret. Omit (or pass an empty string) for a public
    /// client (authorization code grant), which is then identified by
    /// `client_id` in the request body.
    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client_secret = Some(client_secret.into());
        self
    }

    /// Sets the token endpoint URL (required).
    pub fn token_endpoint(mut self, token_endpoint: impl Into<String>) -> Self {
        self.token_endpoint = Some(token_endpoint.into());
        self
    }

    /// Selects the client authentication method (RFC 6749 §2.3). The default is
    /// [`ClientAuthMethod::ClientSecretBasic`].
    pub fn auth_method(mut self, method: ClientAuthMethod) -> Self {
        self.auth_method = method;
        self
    }

    /// Adds a single extra form parameter for provider-specific extensions
    /// (e.g. an RFC 8707 `resource` or an `audience` on a grant that does not
    /// model them). Reserved grant/auth parameters are never overridden.
    ///
    /// Extras are client-wide, so they apply to every grant this client
    /// performs. [`token_exchange`] additionally owns `requested_token_type`,
    /// `resource`, and `audience` — it takes those from its
    /// [`TokenExchangeRequest`] — and fails with [`IdentityError::Validation`]
    /// rather than silently ignoring an extra that names one of them. Keys are
    /// compared case-insensitively and ignoring surrounding whitespace.
    ///
    /// [`token_exchange`]: TokenClient::token_exchange
    pub fn extra_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_params.insert(key.into(), value.into());
        self
    }

    /// Adds multiple extra form parameters. See [`extra_param`].
    ///
    /// [`extra_param`]: TokenClientBuilder::extra_param
    pub fn extra_params(mut self, params: HashMap<String, String>) -> Self {
        self.extra_params.extend(params);
        self
    }

    /// Uses `client` for token requests instead of a default
    /// [`reqwest::Client`], letting callers share a connection pool or supply
    /// custom transport configuration (CC-006).
    pub fn http_client(mut self, client: HttpClient) -> Self {
        self.http = Some(client);
        self
    }

    /// Bounds each token request with a per-request timeout. A non-positive
    /// duration is ignored and the default (30s) is retained.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        if !timeout.is_zero() {
            self.timeout = timeout;
        }
        self
    }

    /// Permits an `http://` token endpoint, which is otherwise rejected.
    /// Intended for local development and integration tests against non-TLS
    /// providers; do not enable in production.
    pub fn allow_http(mut self, allow: bool) -> Self {
        self.allow_http = allow;
        self
    }

    /// Builds the [`TokenClient`].
    ///
    /// # Errors
    ///
    /// [`IdentityError::Configuration`] if `client_id` or `token_endpoint` is
    /// missing or empty (AC-6).
    pub fn build(self) -> Result<TokenClient> {
        let client_id = self.client_id.unwrap_or_default();
        if client_id.is_empty() {
            return Err(IdentityError::Configuration(
                "client_id is required".to_string(),
            ));
        }
        let token_endpoint = self.token_endpoint.unwrap_or_default();
        if token_endpoint.is_empty() {
            return Err(IdentityError::Configuration(
                "token_endpoint is required".to_string(),
            ));
        }
        Ok(TokenClient {
            http: self.http.unwrap_or_else(crate::http::secure_client),
            token_endpoint,
            client_id,
            // An empty secret is a public client, not a confidential client
            // with an empty password: matching the Go reference, it is
            // identified by client_id in the body rather than a Basic header
            // carrying `id:` (RFC 6749 §2.3.1).
            client_secret: self.client_secret.filter(|s| !s.is_empty()),
            auth_method: self.auth_method,
            extra_params: self.extra_params,
            timeout: if self.timeout.is_zero() {
                DEFAULT_TIMEOUT
            } else {
                self.timeout
            },
            allow_http: self.allow_http,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine;
    use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
    use wiremock::matchers::{header_exists, method, path};
    use wiremock::{Mock, MockServer, Request, ResponseTemplate};

    /// A minimal successful token response body.
    const SUCCESS_BODY: &str =
        r#"{"access_token":"at-abc","token_type":"Bearer","expires_in":3600}"#;

    /// Mounts a single POST handler on `/token` returning `template`.
    async fn mount_token(server: &MockServer, template: ResponseTemplate) {
        Mock::given(method("POST"))
            .and(path("/token"))
            .respond_with(template)
            .mount(server)
            .await;
    }

    /// Parses a request's form body into key/value pairs.
    fn form_of(req: &Request) -> HashMap<String, String> {
        url::form_urlencoded::parse(&req.body)
            .into_owned()
            .collect()
    }

    fn client(endpoint: &str) -> TokenClientBuilder {
        TokenClient::builder()
            .client_id("client-1")
            .client_secret("s3cr3t")
            .token_endpoint(endpoint)
            .allow_http(true)
    }

    // CC-001: a client credentials grant returns a typed response.
    #[tokio::test]
    async fn client_credentials_returns_typed_response() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        let token = client(&format!("{}/token", server.uri()))
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        assert_eq!(token.access_token, "at-abc");
        assert_eq!(token.token_type, "Bearer");
        assert_eq!(token.expires_in, 3600);
    }

    // CC-002: client_secret_basic is the default — a Basic header is sent and no
    // credentials appear in the body.
    #[tokio::test]
    async fn client_secret_basic_is_default() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/token"))
            .and(header_exists("authorization"))
            .respond_with(ResponseTemplate::new(200).set_body_string(SUCCESS_BODY))
            .mount(&server)
            .await;

        client(&format!("{}/token", server.uri()))
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        let requests = server.received_requests().await.unwrap();
        let req = requests.last().unwrap();
        let auth = req.headers.get("authorization").unwrap().to_str().unwrap();
        // "client-1":"s3cr3t" form-urlencoded then base64: no reserved chars,
        // so it equals base64("client-1:s3cr3t").
        assert_eq!(
            auth,
            format!("Basic {}", BASE64_STANDARD.encode("client-1:s3cr3t"))
        );
        let form = form_of(req);
        assert!(!form.contains_key("client_id"), "no client_id in body");
        assert!(
            !form.contains_key("client_secret"),
            "no client_secret in body"
        );
        assert_eq!(
            form.get("grant_type").map(String::as_str),
            Some("client_credentials")
        );
    }

    // CC-003: client_secret_post places credentials in the body and sets no
    // Basic header.
    #[tokio::test]
    async fn client_secret_post_uses_body() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        client(&format!("{}/token", server.uri()))
            .auth_method(ClientAuthMethod::ClientSecretPost)
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        let requests = server.received_requests().await.unwrap();
        let req = requests.last().unwrap();
        assert!(
            req.headers.get("authorization").is_none(),
            "no Basic header"
        );
        let form = form_of(req);
        assert_eq!(form.get("client_id").map(String::as_str), Some("client-1"));
        assert_eq!(
            form.get("client_secret").map(String::as_str),
            Some("s3cr3t")
        );
    }

    // CC-004 / ACG-005: a non-2xx OAuth error body maps to TokenEndpoint.
    #[tokio::test]
    async fn error_response_maps_to_token_endpoint() {
        let server = MockServer::start().await;
        let body = r#"{"error":"invalid_client","error_description":"bad secret","error_uri":"https://err.example/1"}"#;
        mount_token(&server, ResponseTemplate::new(401).set_body_string(body)).await;

        let err = client(&format!("{}/token", server.uri()))
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect_err("error response must fail");

        match err {
            IdentityError::TokenEndpoint {
                error,
                description,
                error_uri,
                status,
            } => {
                assert_eq!(error, "invalid_client");
                assert_eq!(description.as_deref(), Some("bad secret"));
                assert_eq!(error_uri.as_deref(), Some("https://err.example/1"));
                assert_eq!(status, 401);
            }
            other => panic!("expected TokenEndpoint, got {other:?}"),
        }
    }

    // A non-2xx response without a recognisable OAuth body is a plain Http error.
    #[tokio::test]
    async fn non_oauth_error_body_maps_to_http() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(500).set_body_string("upstream boom"),
        )
        .await;

        let err = client(&format!("{}/token", server.uri()))
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect_err("500 must fail");

        assert!(matches!(err, IdentityError::Http(_)), "{err:?}");
    }

    // CC-005: WithScopes sends a single space-delimited scope parameter.
    #[tokio::test]
    async fn scope_is_space_delimited() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        client(&format!("{}/token", server.uri()))
            .build()
            .unwrap()
            .client_credentials(Some("a b"))
            .await
            .expect("grant succeeds");

        let requests = server.received_requests().await.unwrap();
        let form = form_of(requests.last().unwrap());
        assert_eq!(form.get("scope").map(String::as_str), Some("a b"));
    }

    // CC-006: extra params appear in the body and the supplied http client is
    // used; reserved params cannot be overridden.
    #[tokio::test]
    async fn extra_params_applied_reserved_guarded() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        let custom = reqwest::Client::builder().build().unwrap();
        client(&format!("{}/token", server.uri()))
            .http_client(custom)
            .extra_param("resource", "urn:test:api")
            // reserved: must be ignored, not override the grant type.
            .extra_param("grant_type", "hacked")
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        let requests = server.received_requests().await.unwrap();
        let form = form_of(requests.last().unwrap());
        assert_eq!(
            form.get("resource").map(String::as_str),
            Some("urn:test:api")
        );
        assert_eq!(
            form.get("grant_type").map(String::as_str),
            Some("client_credentials"),
            "reserved grant_type must not be overridden"
        );
    }

    // ACG-001 / ACG-004: exchange_code sends grant, code, redirect_uri, and
    // code_verifier.
    #[tokio::test]
    async fn exchange_code_sends_expected_form() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        // Public client: build without a secret.
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        TokenClient::builder()
            .client_id("public-client")
            .token_endpoint(format!("{}/token", server.uri()))
            .allow_http(true)
            .build()
            .unwrap()
            .exchange_code("auth-code-1", "https://app.example/cb", Some(verifier))
            .await
            .expect("exchange succeeds");

        let requests = server.received_requests().await.unwrap();
        let req = requests.last().unwrap();
        assert!(
            req.headers.get("authorization").is_none(),
            "public client has no Basic header"
        );
        let form = form_of(req);
        assert_eq!(
            form.get("grant_type").map(String::as_str),
            Some("authorization_code")
        );
        assert_eq!(form.get("code").map(String::as_str), Some("auth-code-1"));
        assert_eq!(
            form.get("redirect_uri").map(String::as_str),
            Some("https://app.example/cb")
        );
        assert_eq!(
            form.get("code_verifier").map(String::as_str),
            Some(verifier)
        );
        assert_eq!(
            form.get("client_id").map(String::as_str),
            Some("public-client")
        );
    }

    // CC-002: an empty client_secret is a public client, not a confidential
    // client with an empty password — no Basic header, client_id in the body
    // (parity with the Go reference).
    #[tokio::test]
    async fn empty_client_secret_is_public_client() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        TokenClient::builder()
            .client_id("public-client")
            .client_secret("")
            .token_endpoint(format!("{}/token", server.uri()))
            .allow_http(true)
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        let requests = server.received_requests().await.unwrap();
        let req = requests.last().unwrap();
        assert!(
            req.headers.get("authorization").is_none(),
            "empty secret must not send a Basic header"
        );
        let form = form_of(req);
        assert_eq!(
            form.get("client_id").map(String::as_str),
            Some("public-client"),
            "public client is identified by client_id in the body"
        );
        assert!(
            !form.contains_key("client_secret"),
            "no empty client_secret in body"
        );
    }

    // AC-2: an invalid code_verifier is rejected before any request is sent.
    #[tokio::test]
    async fn exchange_code_rejects_invalid_verifier() {
        let client = TokenClient::builder()
            .client_id("public-client")
            .token_endpoint("https://issuer.example/token")
            .build()
            .unwrap();
        let err = client
            .exchange_code("code", "https://app/cb", Some("too-short"))
            .await
            .expect_err("short verifier must error");
        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
    }

    // AC-6: the builder rejects missing required fields.
    #[test]
    fn builder_requires_client_id_and_endpoint() {
        let missing_id = TokenClient::builder()
            .token_endpoint("https://issuer.example/token")
            .build();
        assert!(matches!(missing_id, Err(IdentityError::Configuration(_))));

        let missing_endpoint = TokenClient::builder().client_id("c").build();
        assert!(matches!(
            missing_endpoint,
            Err(IdentityError::Configuration(_))
        ));

        let ok = TokenClient::builder()
            .client_id("c")
            .token_endpoint("https://issuer.example/token")
            .build();
        assert!(ok.is_ok());
    }

    // The default (https-only) endpoint gate rejects an http endpoint.
    #[tokio::test]
    async fn https_required_by_default() {
        let client = TokenClient::builder()
            .client_id("c")
            .client_secret("s")
            .token_endpoint("http://insecure.example/token")
            .build()
            .unwrap();
        let err = client
            .client_credentials(None)
            .await
            .expect_err("http endpoint must be rejected");
        assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
    }

    // CC-002: Basic credentials with reserved characters are form-urlencoded
    // before base64 (RFC 6749 §2.3.1).
    #[test]
    fn basic_auth_header_urlencodes_credentials() {
        let header = basic_auth_header("id with space", "p@ss:word");
        let expected = format!(
            "Basic {}",
            BASE64_STANDARD.encode("id+with+space:p%40ss%3Aword")
        );
        assert_eq!(header, expected);
    }

    // #24: neither the client nor its builder prints the client secret in Debug
    // output; the secret's presence is shown without its value.
    #[test]
    fn debug_redacts_client_secret() {
        let builder = TokenClient::builder()
            .client_id("client-1")
            .client_secret("s3cr3t-value")
            .token_endpoint("https://issuer.example/token");
        let builder_dbg = format!("{builder:?}");
        assert!(
            !builder_dbg.contains("s3cr3t-value"),
            "builder leaked secret: {builder_dbg}"
        );
        assert!(builder_dbg.contains(REDACTED), "no marker: {builder_dbg}");

        let client = builder.build().unwrap();
        let client_dbg = format!("{client:?}");
        assert!(
            !client_dbg.contains("s3cr3t-value"),
            "client leaked secret: {client_dbg}"
        );
        assert!(client_dbg.contains(REDACTED), "no marker: {client_dbg}");
        // client_id is not secret and stays visible for diagnostics.
        assert!(client_dbg.contains("client-1"), "{client_dbg}");
    }

    // A public client (no secret) shows client_secret: None, not a marker.
    #[test]
    fn debug_public_client_shows_no_secret() {
        let client = TokenClient::builder()
            .client_id("public")
            .token_endpoint("https://issuer.example/token")
            .build()
            .unwrap();
        assert!(format!("{client:?}").contains("client_secret: None"));
    }

    // ---- RFC 8693 token exchange (EXCH-001..EXCH-006) --------------------
    //
    // These drive the same shared conformance fixtures the cross-language
    // contract (spec/vectors/token-exchange.json) references and the Go
    // reference replays, so the two implementations cannot drift apart on the
    // wire format or the parsed response.

    /// Reads a shared conformance fixture from
    /// `spec/test-fixtures/token-exchange`. Unit tests run with `rust/` as the
    /// working directory.
    fn exchange_fixture(name: &str) -> String {
        let path = format!("../spec/test-fixtures/token-exchange/{name}");
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read fixture {path}: {e}"))
    }

    /// Parses a request's form body into ordered key/value pairs, preserving
    /// the repeated `resource` / `audience` parameters a `HashMap` collapses.
    fn form_pairs(req: &Request) -> Vec<(String, String)> {
        url::form_urlencoded::parse(&req.body)
            .into_owned()
            .collect()
    }

    /// All values sent for `key`, in order.
    fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> {
        pairs
            .iter()
            .filter(|(k, _)| k == key)
            .map(|(_, v)| v.clone())
            .collect()
    }

    /// The single request the server received, for asserting what was sent.
    async fn only_request(server: &MockServer) -> Request {
        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 1, "expected exactly one request");
        requests.into_iter().next().unwrap()
    }

    /// A server replaying `fixture` with HTTP 200 and a client pointed at it.
    async fn exchange_server(fixture: &str) -> MockServer {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(exchange_fixture(fixture)),
        )
        .await;
        server
    }

    fn exchange_client(server: &MockServer) -> TokenClient {
        client(&format!("{}/token", server.uri())).build().unwrap()
    }

    // EXCH-001: an impersonation exchange POSTs the token-exchange grant with
    // only the subject token, and parses the issued-token trio from the 200.
    #[tokio::test]
    async fn token_exchange_impersonation_returns_issued_token_trio() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        let issued = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        let form: HashMap<String, String> = pairs.iter().cloned().collect();
        assert_eq!(form.get("grant_type").unwrap(), GRANT_TOKEN_EXCHANGE);
        assert_eq!(form.get("subject_token").unwrap(), "subject-tok");
        assert_eq!(
            form.get("subject_token_type").unwrap(),
            TOKEN_TYPE_ACCESS_TOKEN
        );
        // Impersonation carries no actor token (RFC 8693 §1.1).
        assert!(!form.contains_key("actor_token"), "{form:?}");
        assert!(!form.contains_key("actor_token_type"), "{form:?}");

        assert!(!issued.access_token.is_empty());
        assert_eq!(
            issued.issued_token_type.as_deref(),
            Some(TOKEN_TYPE_ACCESS_TOKEN)
        );
        assert_eq!(issued.token_type, "Bearer");
        assert_eq!(issued.expires_in, 3600);
    }

    // EXCH-002: a delegation exchange sends both the subject and the actor
    // token with their types (RFC 8693 §1.1, §2.1).
    #[tokio::test]
    async fn token_exchange_delegation_sends_actor_token() {
        let server = exchange_server("exchange-delegation-success.json").await;

        let issued = exchange_client(&server)
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .actor_token("actor-tok", TOKEN_TYPE_JWT),
            )
            .await
            .expect("delegation exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        let form: HashMap<String, String> = pairs.iter().cloned().collect();
        assert_eq!(form.get("subject_token").unwrap(), "subject-tok");
        assert_eq!(form.get("actor_token").unwrap(), "actor-tok");
        assert_eq!(form.get("actor_token_type").unwrap(), TOKEN_TYPE_JWT);
        assert!(!issued.access_token.is_empty());
        assert!(issued.issued_token_type.is_some());
    }

    // EXCH-003: each of the six RFC 8693 §3 token type URIs is serialized
    // verbatim as subject_token_type, with no abbreviation or normalisation.
    #[tokio::test]
    async fn token_exchange_serializes_all_token_type_uris_verbatim() {
        for uri in TOKEN_TYPE_URIS {
            let server = exchange_server("exchange-impersonation-success.json").await;
            exchange_client(&server)
                .token_exchange(&TokenExchangeRequest::new("subject-tok", uri))
                .await
                .unwrap_or_else(|e| panic!("exchange with {uri}: {e}"));

            let pairs = form_pairs(&only_request(&server).await);
            assert_eq!(
                form_all(&pairs, "subject_token_type"),
                vec![uri.to_string()],
                "subject_token_type must be sent verbatim"
            );
        }
    }

    // EXCH-004: requested_token_type, audience, and resource all reach the
    // request body.
    #[tokio::test]
    async fn token_exchange_sends_requested_type_audience_and_resource() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        exchange_client(&server)
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .requested_token_type(TOKEN_TYPE_ACCESS_TOKEN)
                    .audience("https://api.example.com")
                    .resource("https://rs.example.com")
                    .scope("https://api.example.com/read"),
            )
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        let form: HashMap<String, String> = pairs.iter().cloned().collect();
        assert_eq!(
            form.get("requested_token_type").unwrap(),
            TOKEN_TYPE_ACCESS_TOKEN
        );
        assert_eq!(form.get("audience").unwrap(), "https://api.example.com");
        assert_eq!(form.get("resource").unwrap(), "https://rs.example.com");
        assert_eq!(form.get("scope").unwrap(), "https://api.example.com/read");
    }

    // EXCH-004 (repeatable): resource and audience MAY each appear more than
    // once (RFC 8693 §2.1); every value is sent as its own parameter rather
    // than joined or collapsed to the last one.
    #[tokio::test]
    async fn token_exchange_repeats_resource_and_audience() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        exchange_client(&server)
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .resource("https://rs1.example.com")
                    .resource("https://rs2.example.com")
                    .audience("aud-a")
                    .audience("aud-b"),
            )
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(
            form_all(&pairs, "resource"),
            ["https://rs1.example.com", "https://rs2.example.com"]
        );
        assert_eq!(form_all(&pairs, "audience"), ["aud-a", "aud-b"]);
    }

    // EXCH-005: a success whose token_type is N_A — the issued token is not
    // usable as a bearer token (RFC 8693 §2.2.1) — parses without error.
    #[tokio::test]
    async fn token_exchange_accepts_n_a_token_type() {
        let server = exchange_server("exchange-n_a-token-type.json").await;

        let issued = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect("N_A token type is accepted");

        assert_eq!(issued.token_type, "N_A");
        assert_eq!(issued.issued_token_type.as_deref(), Some(TOKEN_TYPE_SAML2));
        assert!(!issued.access_token.is_empty());
        assert_eq!(issued.expires_in, 60);
    }

    // EXCH-006: an HTTP 400 OAuth error body surfaces as a typed
    // TokenEndpoint error carrying the code, description, and status
    // (RFC 8693 §2.2.2, RFC 6749 §5.2).
    #[tokio::test]
    async fn token_exchange_error_maps_to_token_endpoint() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(400)
                .set_body_string(exchange_fixture("exchange-error-invalid-grant.json")),
        )
        .await;

        let err = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new(
                "expired-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect_err("an error response must fail");

        match err {
            IdentityError::TokenEndpoint {
                error,
                description,
                status,
                ..
            } => {
                assert_eq!(error, "invalid_grant");
                assert!(description.is_some_and(|d| d.contains("subject_token")));
                assert_eq!(status, 400);
            }
            other => panic!("expected TokenEndpoint, got {other:?}"),
        }
    }

    // RFC 8693 §2.1 REQUIRED: an empty subject_token fails locally and no
    // request reaches the endpoint.
    #[tokio::test]
    async fn token_exchange_missing_subject_token_sends_nothing() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        let err = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new("", TOKEN_TYPE_ACCESS_TOKEN))
            .await
            .expect_err("empty subject_token must fail");

        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
        assert!(
            server.received_requests().await.unwrap().is_empty(),
            "no request may be sent for an invalid exchange"
        );
    }

    // RFC 8693 §2.1 REQUIRED: an empty subject_token_type fails locally.
    #[tokio::test]
    async fn token_exchange_missing_subject_token_type_sends_nothing() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        let err = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new("subject-tok", ""))
            .await
            .expect_err("empty subject_token_type must fail");

        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    // RFC 8693 §2.1: actor_token_type is REQUIRED whenever actor_token is
    // present, so a typeless actor token fails before the wire.
    #[tokio::test]
    async fn token_exchange_actor_token_requires_its_type() {
        let server = exchange_server("exchange-delegation-success.json").await;

        let err = exchange_client(&server)
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .actor_token("actor-tok", ""),
            )
            .await
            .expect_err("actor_token without a type must fail");

        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    // Extra params must not be able to rewrite the exchange's identity: the
    // subject and actor tokens, their types, and the grant itself are reserved.
    #[tokio::test]
    async fn token_exchange_extra_params_cannot_override_identity() {
        let server = exchange_server("exchange-delegation-success.json").await;

        client(&format!("{}/token", server.uri()))
            .extra_param("subject_token", "evil-subject")
            .extra_param("subject_token_type", "evil-type")
            .extra_param("actor_token", "evil-actor")
            .extra_param("actor_token_type", "evil-actor-type")
            .extra_param("grant_type", "evil-grant")
            .build()
            .unwrap()
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .actor_token("actor-tok", TOKEN_TYPE_JWT),
            )
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "grant_type"), [GRANT_TOKEN_EXCHANGE]);
        assert_eq!(form_all(&pairs, "subject_token"), ["subject-tok"]);
        assert_eq!(
            form_all(&pairs, "subject_token_type"),
            [TOKEN_TYPE_ACCESS_TOKEN]
        );
        assert_eq!(form_all(&pairs, "actor_token"), ["actor-tok"]);
        assert_eq!(form_all(&pairs, "actor_token_type"), [TOKEN_TYPE_JWT]);
    }

    // An extra param that is NOT reserved and not already set by the exchange
    // still reaches the body — reserving the identity parameters must not
    // disable the extension point (RFC 8707 resource on another grant, etc.).
    #[tokio::test]
    async fn token_exchange_passes_through_unreserved_extra_params() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        client(&format!("{}/token", server.uri()))
            .extra_param("acr_values", "urn:example:loa2")
            .build()
            .unwrap()
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "acr_values"), ["urn:example:loa2"]);
    }

    // The default client authentication is client_secret_basic: credentials
    // travel in the Authorization header, never in the exchange body.
    #[tokio::test]
    async fn token_exchange_uses_client_secret_basic_by_default() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect("exchange succeeds");

        let request = only_request(&server).await;
        let header = request
            .headers
            .get("authorization")
            .expect("Basic header")
            .to_str()
            .unwrap()
            .to_string();
        let encoded = header.strip_prefix("Basic ").expect("Basic scheme");
        let decoded = String::from_utf8(BASE64_STANDARD.decode(encoded).unwrap()).unwrap();
        assert_eq!(decoded, "client-1:s3cr3t");

        let pairs = form_pairs(&request);
        assert!(form_all(&pairs, "client_id").is_empty(), "{pairs:?}");
        assert!(form_all(&pairs, "client_secret").is_empty(), "{pairs:?}");
    }

    // client_secret_post puts the credentials in the exchange body instead,
    // with no Authorization header.
    #[tokio::test]
    async fn token_exchange_supports_client_secret_post() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        client(&format!("{}/token", server.uri()))
            .auth_method(ClientAuthMethod::ClientSecretPost)
            .build()
            .unwrap()
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect("exchange succeeds");

        let request = only_request(&server).await;
        assert!(request.headers.get("authorization").is_none());
        let pairs = form_pairs(&request);
        assert_eq!(form_all(&pairs, "client_id"), ["client-1"]);
        assert_eq!(form_all(&pairs, "client_secret"), ["s3cr3t"]);
    }

    // An http:// endpoint is refused unless allow_http was set, and nothing is
    // sent over the cleartext connection.
    #[tokio::test]
    async fn token_exchange_requires_https() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        let err = TokenClient::builder()
            .client_id("client-1")
            .client_secret("s3cr3t")
            .token_endpoint(format!("{}/token", server.uri()))
            .build()
            .unwrap()
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect_err("http endpoint must be refused");

        assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    // RFC 8693 §2.2 REQUIRED: a 200 that omits issued_token_type is
    // non-conformant and is rejected, not returned with the field empty.
    #[tokio::test]
    async fn token_exchange_rejects_response_without_issued_token_type() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200)
                .set_body_string(r#"{"access_token":"issued-tok","token_type":"Bearer"}"#),
        )
        .await;

        let err = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect_err("a missing issued_token_type must fail");

        match err {
            IdentityError::Http(message) => {
                assert!(message.contains("issued_token_type"), "{message}");
            }
            other => panic!("expected Http, got {other:?}"),
        }
    }

    // RFC 8693 §2.2 REQUIRED: a 200 without access_token is rejected rather
    // than returned as a success with no token. `access_token` is a required
    // field of [`TokenResponse`], so an omitted one fails in deserialization;
    // a present-but-empty one fails the explicit emptiness check in
    // `do_request`. Both are rejections, and this asserts both paths.
    #[tokio::test]
    async fn token_exchange_rejects_response_without_access_token() {
        let omitted =
            format!(r#"{{"issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}","token_type":"Bearer"}}"#);
        let empty = format!(
            r#"{{"access_token":"","issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}","token_type":"Bearer"}}"#
        );

        for body in [omitted, empty] {
            let server = MockServer::start().await;
            mount_token(
                &server,
                ResponseTemplate::new(200).set_body_string(body.clone()),
            )
            .await;

            let err = exchange_client(&server)
                .token_exchange(&TokenExchangeRequest::new(
                    "subject-tok",
                    TOKEN_TYPE_ACCESS_TOKEN,
                ))
                .await
                .expect_err("a missing access_token must fail");

            match err {
                IdentityError::Deserialization(message) | IdentityError::Http(message) => {
                    assert!(message.contains("access_token"), "{body}: {message}");
                }
                other => panic!("{body}: expected a rejection naming access_token, got {other:?}"),
            }
        }
    }

    // RFC 6749 §5.1 REQUIRED (and spec/vectors/token-exchange.json
    // required_fields): a 200 that omits token_type — or sends it empty — is
    // rejected. `TokenResponse::token_type` defaults to "", so without this
    // check the caller would get Ok back holding an empty token type.
    #[tokio::test]
    async fn token_exchange_rejects_response_without_token_type() {
        let omitted = format!(
            r#"{{"access_token":"issued-tok","issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}"}}"#
        );
        let empty = format!(
            r#"{{"access_token":"issued-tok","token_type":"","issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}"}}"#
        );

        for body in [omitted, empty] {
            let server = MockServer::start().await;
            mount_token(
                &server,
                ResponseTemplate::new(200).set_body_string(body.clone()),
            )
            .await;

            let err = exchange_client(&server)
                .token_exchange(&TokenExchangeRequest::new(
                    "subject-tok",
                    TOKEN_TYPE_ACCESS_TOKEN,
                ))
                .await
                .expect_err("a missing token_type must fail");

            match err {
                // "missing token_type", not "token_type": the latter is also
                // satisfied by the adjacent "is missing issued_token_type"
                // message, so it would not tell the two checks apart.
                IdentityError::Http(message) => {
                    assert!(message.contains("missing token_type"), "{body}: {message}");
                }
                other => panic!("{body}: expected Http, got {other:?}"),
            }
        }
    }

    // RFC 8693 §1.1: an actor token that is present but empty — in either half
    // of the pair — is rejected locally. Dropping it instead would post a
    // subject-only request, downgrading the delegation the caller asked for
    // into an impersonation without a word.
    #[tokio::test]
    async fn token_exchange_empty_actor_token_sends_nothing() {
        for (actor_token, actor_token_type) in [("", TOKEN_TYPE_JWT), ("actor-tok", ""), ("", "")] {
            let server = exchange_server("exchange-delegation-success.json").await;

            let err = exchange_client(&server)
                .token_exchange(
                    &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                        .actor_token(actor_token, actor_token_type),
                )
                .await
                .expect_err("an empty half of the actor pair must fail");

            assert!(
                matches!(err, IdentityError::Validation(_)),
                "({actor_token:?}, {actor_token_type:?}): {err:?}"
            );
            assert!(
                server.received_requests().await.unwrap().is_empty(),
                "no request may be sent for ({actor_token:?}, {actor_token_type:?})"
            );
        }
    }

    // An optional parameter set to the empty string is omitted, not sent as a
    // bare `key=`: an empty value requests nothing and a server may treat it as
    // a malformed parameter and reject the exchange outright.
    #[tokio::test]
    async fn token_exchange_omits_empty_optional_parameters() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        exchange_client(&server)
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .requested_token_type("")
                    .scope("")
                    .resource("")
                    .audience(""),
            )
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        for key in ["requested_token_type", "scope", "resource", "audience"] {
            assert!(
                form_all(&pairs, key).is_empty(),
                "empty {key} must not be sent: {pairs:?}"
            );
        }
    }

    // Only the empty entries are dropped — a list mixing empty and real values
    // still sends the real ones, in order.
    #[tokio::test]
    async fn token_exchange_keeps_non_empty_entries_when_dropping_empty_ones() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        exchange_client(&server)
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .resource("")
                    .resource("https://rs.example.com")
                    .audience("aud-a")
                    .audience(""),
            )
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "resource"), ["https://rs.example.com"]);
        assert_eq!(form_all(&pairs, "audience"), ["aud-a"]);
    }

    // The exchange owns requested_token_type, resource, and audience, and says
    // so loudly: an extra param naming one fails the call before anything is
    // sent. Dropping it instead would be a silent loss of a restriction —
    // extra_param is client-wide, so a caller who set `audience` to pin every
    // token to one API would get a broader token back from this grant alone,
    // with nothing to say which grant discarded it.
    #[tokio::test]
    async fn token_exchange_extra_params_cannot_inject_targeting_params() {
        // The bare request never names the parameters; the second names them as
        // empty strings, which are dropped from the form — neither shape may
        // leave an opening for an extra to fill.
        let requests = [
            TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN),
            TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                .requested_token_type("")
                .audience("")
                .resource(""),
        ];

        // The keys are written out here rather than iterated from
        // EXCHANGE_RESERVED_PARAMS on purpose: driving the cases from the
        // constant under test lets a shrunk constant silently shrink the test.
        // Drop "audience" from it and this would stay green while `audience`
        // became injectable again; empty it and the body would never run at
        // all. The constant is pinned separately, by
        // exchange_reserved_params_cover_every_targeting_parameter.
        for request in requests {
            for key in ["requested_token_type", "resource", "audience"] {
                let server = exchange_server("exchange-impersonation-success.json").await;

                let err = client(&format!("{}/token", server.uri()))
                    .extra_param(key, "https://evil.example.com")
                    .build()
                    .unwrap()
                    .token_exchange(&request)
                    .await
                    .expect_err("an extra param naming an owned parameter must fail");

                match err {
                    IdentityError::Validation(message) => {
                        assert!(message.contains(key), "{key}: {message}");
                        assert!(message.contains("TokenExchangeRequest"), "{key}: {message}");
                    }
                    other => panic!("{key}: expected Validation, got {other:?}"),
                }
                assert!(
                    server.received_requests().await.unwrap().is_empty(),
                    "{key}: no request may be sent"
                );
            }
        }
    }

    // Pins the constant the test above deliberately does not read. Between the
    // two, removing a key from EXCHANGE_RESERVED_PARAMS fails loudly here while
    // the injection test keeps exercising all three; order is not pinned
    // because it carries no meaning.
    #[test]
    fn exchange_reserved_params_cover_every_targeting_parameter() {
        let mut reserved = EXCHANGE_RESERVED_PARAMS.to_vec();
        reserved.sort_unstable();
        assert_eq!(reserved, ["audience", "requested_token_type", "resource"]);
    }

    // ...nor override one the request did pin. Note what this test is and is
    // not: it is a regression guard, not coverage of EXCHANGE_RESERVED_PARAMS.
    // Before the collision was rejected outright this case already passed,
    // because do_request skips a key that is already in the form — it was green
    // with and without the constant. What it pins now is that agreeing with the
    // request does not buy an extra param a pass: the call fails, so a caller
    // whose client-wide extra contradicts a grant finds out.
    #[tokio::test]
    async fn token_exchange_extra_params_cannot_override_targeting_params() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        let err = client(&format!("{}/token", server.uri()))
            .extra_param("requested_token_type", TOKEN_TYPE_ID_TOKEN)
            .extra_param("audience", "https://evil.example.com")
            .extra_param("resource", "https://evil-rs.example.com")
            .build()
            .unwrap()
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .requested_token_type(TOKEN_TYPE_ACCESS_TOKEN)
                    .audience("https://api.example.com")
                    .resource("https://rs.example.com"),
            )
            .await
            .expect_err("a colliding extra param must fail even when the request pins it");

        match err {
            // Keys are reported in sorted order, so "audience" is named first
            // every run rather than whichever the HashMap yielded first.
            IdentityError::Validation(message) => {
                assert!(message.contains("audience"), "{message}");
            }
            other => panic!("expected Validation, got {other:?}"),
        }
        assert!(
            server.received_requests().await.unwrap().is_empty(),
            "no request may be sent"
        );
    }

    // Reserving three keys on the exchange must not become "the exchange drops
    // every extra": a key the grant does not own still reaches the body, next
    // to the targeting parameters the request itself pinned. Nothing else pins
    // this for the exchange path, so an over-broad guard would pass the suite.
    #[tokio::test]
    async fn token_exchange_sends_non_reserved_extra_param() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        client(&format!("{}/token", server.uri()))
            .extra_param("tenant", "t1")
            .build()
            .unwrap()
            .token_exchange(
                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
                    .audience("https://api.example.com"),
            )
            .await
            .expect("exchange succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "tenant"), ["t1"]);
        assert_eq!(form_all(&pairs, "audience"), ["https://api.example.com"]);
    }

    // The reserved lists are matched on a normalised key. A server whose form
    // parser folds case or trims whitespace reads "Audience" and " audience" as
    // `audience`, so an exact-byte match would hand it the very parameter the
    // guard claims cannot be injected.
    #[tokio::test]
    async fn token_exchange_reserved_extras_are_matched_normalised() {
        for key in [
            "Audience",
            " audience",
            "REQUESTED_TOKEN_TYPE",
            "\tresource ",
        ] {
            let server = exchange_server("exchange-impersonation-success.json").await;

            let err = client(&format!("{}/token", server.uri()))
                .extra_param(key, "https://evil.example.com")
                .build()
                .unwrap()
                .token_exchange(&TokenExchangeRequest::new(
                    "subject-tok",
                    TOKEN_TYPE_ACCESS_TOKEN,
                ))
                .await
                .expect_err("a case- or whitespace-variant reserved key must fail");

            assert!(
                matches!(err, IdentityError::Validation(_)),
                "{key:?}: {err:?}"
            );
            assert!(
                server.received_requests().await.unwrap().is_empty(),
                "{key:?}: no request may be sent"
            );
        }
    }

    // The same normalisation covers RESERVED_PARAMS, which every grant applies:
    // a variant spelling must not reach the body, where a case-folding or
    // trimming server would read it as the reserved parameter it imitates.
    #[tokio::test]
    async fn reserved_extras_are_matched_normalised() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        client(&format!("{}/token", server.uri()))
            .extra_param("Grant_Type", "evil-grant")
            .extra_param(" scope", "evil-scope")
            .extra_param("CLIENT_ID", "evil-client")
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "grant_type"), ["client_credentials"]);
        for key in [
            "Grant_Type",
            " scope",
            "CLIENT_ID",
            "scope",
            "client_id",
            "client_secret",
        ] {
            assert!(
                form_all(&pairs, key).is_empty(),
                "{key:?} must not be sent: {pairs:?}"
            );
        }
    }

    // The `grant_reserved` arm of the do_request skip is the one arm no public
    // caller can reach: token_exchange — the only grant that passes a non-empty
    // list — rejects a colliding extra param outright, and the other two pass
    // `&[]`, so the arm never decides anything the suite above can observe.
    // That is why it is exercised here by calling do_request directly. Left to
    // the public API, weakening the skip to
    // `reserved || (grant_reserved && already_in_form)` keeps every other test
    // green while gutting the arm for exactly the case the list exists for: a
    // grant-owned parameter the request left unset is in no form to collide
    // with, so `already_in_form` is false and the extra would be appended to
    // the wire — silently retargeting the exchange at another resource server,
    // which is what reserving the key was for. Sending `audience` as a
    // client-wide extra is legitimate on the grants that do not own it, and
    // client_credentials_still_allows_targeting_extra_params pins that, so the
    // drop has to be keyed on the grant rather than on the key alone.
    #[tokio::test]
    async fn grant_reserved_extra_absent_from_the_form_is_dropped() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        let token_client = client(&format!("{}/token", server.uri()))
            .extra_param("audience", "https://evil.example.com")
            .extra_param("tenant", "t1")
            .build()
            .unwrap();

        // The form deliberately carries no `audience` — the exchange omits an
        // empty one — so the "already in the form" arm cannot stand in for the
        // grant_reserved arm under test.
        token_client
            .do_request(
                vec![("grant_type".to_string(), GRANT_TOKEN_EXCHANGE.to_string())],
                token_client.client_secret.as_deref(),
                EXCHANGE_RESERVED_PARAMS,
            )
            .await
            .expect("request succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert!(
            form_all(&pairs, "audience").is_empty(),
            "a grant-reserved extra the form does not already carry must not be \
             sent at all: {pairs:?}"
        );
        // Positive control: extras are applied on this very call, so the
        // assertion above cannot pass merely because none were.
        assert_eq!(form_all(&pairs, "tenant"), ["t1"]);
        assert_eq!(form_all(&pairs, "grant_type"), [GRANT_TOKEN_EXCHANGE]);
    }

    // Regression guard for the documented rationale, not coverage of
    // EXCHANGE_RESERVED_PARAMS: this passed before the constant existed too,
    // when client credentials had no grant_reserved list at all. What it guards
    // is the `&[]` this grant passes to do_request — the three targeting
    // parameters are reserved on the EXCHANGE path only, and a grant that does
    // not model them (client credentials has no RFC 8707 resource of its own)
    // must still be able to send them as extras. It fails if someone widens the
    // reservation to every grant.
    #[tokio::test]
    async fn client_credentials_still_allows_targeting_extra_params() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        client(&format!("{}/token", server.uri()))
            .extra_param("resource", "https://rs.example.com")
            .extra_param("audience", "https://api.example.com")
            .extra_param("requested_token_type", TOKEN_TYPE_ACCESS_TOKEN)
            .build()
            .unwrap()
            .client_credentials(None)
            .await
            .expect("grant succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "resource"), ["https://rs.example.com"]);
        assert_eq!(form_all(&pairs, "audience"), ["https://api.example.com"]);
        assert_eq!(
            form_all(&pairs, "requested_token_type"),
            [TOKEN_TYPE_ACCESS_TOKEN]
        );
    }

    // Mirror image of the test above for the third grant_reserved call site.
    // exchange_code passes `&[]` as well and nothing else pins it: handing it
    // EXCHANGE_RESERVED_PARAMS by mistake would silently drop an RFC 8707
    // `resource` or `audience` from the authorization code grant, and every
    // other test in the suite would stay green.
    #[tokio::test]
    async fn exchange_code_still_allows_targeting_extra_params() {
        let server = MockServer::start().await;
        mount_token(
            &server,
            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
        )
        .await;

        client(&format!("{}/token", server.uri()))
            .extra_param("resource", "https://rs.example.com")
            .extra_param("audience", "https://api.example.com")
            .extra_param("requested_token_type", TOKEN_TYPE_ACCESS_TOKEN)
            .build()
            .unwrap()
            .exchange_code("auth-code-1", "https://app.example/cb", None)
            .await
            .expect("grant succeeds");

        let pairs = form_pairs(&only_request(&server).await);
        assert_eq!(form_all(&pairs, "resource"), ["https://rs.example.com"]);
        assert_eq!(form_all(&pairs, "audience"), ["https://api.example.com"]);
        assert_eq!(
            form_all(&pairs, "requested_token_type"),
            [TOKEN_TYPE_ACCESS_TOKEN]
        );
    }

    // The issued_token_type is a modelled field, so it must not also be left
    // sitting in `extra` where a caller could read a stale duplicate.
    #[tokio::test]
    async fn token_exchange_issued_token_type_is_not_duplicated_in_extra() {
        let server = exchange_server("exchange-impersonation-success.json").await;

        let issued = exchange_client(&server)
            .token_exchange(&TokenExchangeRequest::new(
                "subject-tok",
                TOKEN_TYPE_ACCESS_TOKEN,
            ))
            .await
            .expect("exchange succeeds");

        assert!(
            !issued.extra.contains_key("issued_token_type"),
            "{:?}",
            issued.extra
        );
    }
}