Skip to main content

rs_identity_model/token/
mod.rs

1//! Token endpoint client: client credentials, authorization code, PKCE,
2//! token exchange.
3//!
4//! [`TokenClient`] performs the OAuth 2.0 client credentials grant
5//! (RFC 6749 §4.4), the authorization code grant (RFC 6749 §4.1.3) — the
6//! latter with optional PKCE (RFC 7636) — and the token exchange grant
7//! (RFC 8693), whose per-call parameters are carried by
8//! [`TokenExchangeRequest`]. Client authentication is
9//! `client_secret_basic` (default) or `client_secret_post` (RFC 6749 §2.3).
10//! Successful responses decode into a typed [`TokenResponse`] (RFC 6749 §5.1);
11//! error responses become an [`IdentityError::TokenEndpoint`] (RFC 6749 §5.2).
12//!
13//! [`PkceChallenge`] and [`authorization_url`] implement the PKCE transform and
14//! authorization request (RFC 7636 §4.1–§4.3).
15//!
16//! Behavioural contract: `spec/vectors/client-credentials.json`
17//! (`CC-001`..`CC-006`), `spec/vectors/authorization-code.json`
18//! (`ACG-001`..`ACG-005`), and `spec/vectors/token-exchange.json`
19//! (`EXCH-001`..`EXCH-006`); see also `spec/capabilities.md`.
20//!
21//! ```no_run
22//! # async fn run() -> rs_identity_model::Result<()> {
23//! use rs_identity_model::TokenClient;
24//!
25//! let client = TokenClient::builder()
26//!     .client_id("my-client")
27//!     .client_secret("my-secret")
28//!     .token_endpoint("https://issuer.example.com/token")
29//!     .build()?;
30//! let token = client.client_credentials(Some("api")).await?;
31//! println!("access_token = {}", token.access_token);
32//! # Ok(())
33//! # }
34//! ```
35
36mod exchange;
37mod pkce;
38mod response;
39
40use std::collections::HashMap;
41use std::time::Duration;
42
43use reqwest::Client as HttpClient;
44use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
45
46use crate::client_auth::{OAuthErrorBody, basic_auth_header, body_snippet, read_capped_body};
47use crate::{IdentityError, Result};
48
49pub use exchange::{
50    TOKEN_TYPE_ACCESS_TOKEN, TOKEN_TYPE_ID_TOKEN, TOKEN_TYPE_JWT, TOKEN_TYPE_REFRESH_TOKEN,
51    TOKEN_TYPE_SAML1, TOKEN_TYPE_SAML2, TOKEN_TYPE_URIS, TokenExchangeRequest,
52};
53pub use pkce::{
54    CHALLENGE_METHOD_S256, PkceChallenge, authorization_url, s256_challenge, valid_code_verifier,
55};
56pub use response::TokenResponse;
57
58/// The `client_credentials` grant type (RFC 6749 §4.4).
59const GRANT_CLIENT_CREDENTIALS: &str = "client_credentials";
60/// The `authorization_code` grant type (RFC 6749 §4.1.3).
61const GRANT_AUTHORIZATION_CODE: &str = "authorization_code";
62/// The token exchange grant type URI (RFC 8693 §2.1).
63const GRANT_TOKEN_EXCHANGE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
64
65/// Default per-request timeout so a hung endpoint cannot block indefinitely.
66const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
67
68/// Placeholder printed in place of secret material in `Debug` output (#24).
69const REDACTED: &str = "<redacted>";
70
71/// Parameters owned by the grant and client-authentication logic on **every**
72/// grant. They can never be set or overridden via
73/// [`TokenClientBuilder::extra_param`], so that caller-supplied extras cannot
74/// contradict the request's identity or grant shape.
75///
76/// `resource`, `audience`, and `requested_token_type` are deliberately absent
77/// here: they are non-identity target/output hints a caller may legitimately
78/// want to supply on a grant that does not model them (e.g. an RFC 8707
79/// `resource` on the client credentials grant), so they stay available as
80/// extras there. On the token exchange grant they ARE owned — it sources them
81/// from [`TokenExchangeRequest`] — so it additionally reserves
82/// [`EXCHANGE_RESERVED_PARAMS`].
83const RESERVED_PARAMS: &[&str] = &[
84    "grant_type",
85    "client_id",
86    "client_secret",
87    "code",
88    "redirect_uri",
89    "code_verifier",
90    "scope",
91    "subject_token",
92    "subject_token_type",
93    "actor_token",
94    "actor_token_type",
95];
96
97/// Targeting parameters reserved on the token exchange grant only, on top of
98/// [`RESERVED_PARAMS`].
99///
100/// The exchange sources all three from [`TokenExchangeRequest`] (RFC 8693
101/// §2.1), so an extra param must not be able to inject one the request left
102/// unset, nor override one it pinned. Skipping keys already present in the form
103/// is not enough on its own: when the request omits a value, nothing puts the
104/// key in the form and an extra would slip through — silently retargeting the
105/// exchange at another resource server or asking for a different token type,
106/// with no check that the returned `issued_token_type` is what was requested.
107///
108/// [`TokenClient::token_exchange`] therefore *rejects* an extra param naming one
109/// of these rather than dropping it: extras are client-wide, so a silent drop
110/// would take away a restriction the caller believes is still in force, on one
111/// grant only and with nothing said about it. The skip in
112/// [`TokenClient::do_request`] stays as defence in depth.
113const EXCHANGE_RESERVED_PARAMS: &[&str] = &["requested_token_type", "resource", "audience"];
114
115/// Normalises an extra-param key before it is matched against the reserved
116/// lists.
117///
118/// The match is on the normalised form because the guard has to hold for the
119/// server, not for Rust: a form parser that folds case or trims surrounding
120/// whitespace reads `"Audience"` and `" audience"` as `audience`, so an
121/// exact-byte comparison would wave those spellings straight through the guard
122/// it documents.
123fn normalize_param_key(key: &str) -> String {
124    key.trim().to_ascii_lowercase()
125}
126
127/// How client credentials are presented to the token endpoint (RFC 6749 §2.3).
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub enum ClientAuthMethod {
130    /// Send `client_id` and `client_secret` in an HTTP Basic `Authorization`
131    /// header (RFC 6749 §2.3.1). This is the default.
132    #[default]
133    ClientSecretBasic,
134    /// Send `client_id` and `client_secret` as form parameters in the request
135    /// body (RFC 6749 §2.3.1).
136    ClientSecretPost,
137}
138
139/// An async OAuth 2.0 token endpoint client.
140///
141/// Construct one with [`TokenClient::builder`]. A single client should be
142/// reused across calls so the underlying connection pool is shared.
143pub struct TokenClient {
144    http: HttpClient,
145    token_endpoint: String,
146    client_id: String,
147    client_secret: Option<String>,
148    auth_method: ClientAuthMethod,
149    extra_params: HashMap<String, String>,
150    timeout: Duration,
151    allow_http: bool,
152}
153
154// A hand-written Debug that never prints the client secret (#24). Presence of
155// the secret is shown as `Some("<redacted>")` / `None` so a confidential vs.
156// public client is still distinguishable in logs.
157impl std::fmt::Debug for TokenClient {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        f.debug_struct("TokenClient")
160            .field("token_endpoint", &self.token_endpoint)
161            .field("client_id", &self.client_id)
162            .field(
163                "client_secret",
164                &self.client_secret.as_ref().map(|_| REDACTED),
165            )
166            .field("auth_method", &self.auth_method)
167            .field("extra_params", &self.extra_params)
168            .field("timeout", &self.timeout)
169            .field("allow_http", &self.allow_http)
170            .finish_non_exhaustive()
171    }
172}
173
174impl TokenClient {
175    /// Returns a builder for configuring a [`TokenClient`].
176    pub fn builder() -> TokenClientBuilder {
177        TokenClientBuilder::new()
178    }
179
180    /// Performs the OAuth 2.0 client credentials grant (RFC 6749 §4.4, CC-001):
181    /// POSTs `grant_type=client_credentials` to the token endpoint and returns
182    /// the typed [`TokenResponse`].
183    ///
184    /// Authentication uses the configured [`ClientAuthMethod`]
185    /// (`client_secret_basic` by default). When `scope` is `Some`, it is sent
186    /// as a single space-delimited `scope` parameter (CC-005).
187    ///
188    /// # Errors
189    ///
190    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response
191    ///   (CC-004).
192    /// - [`IdentityError::Http`] — a transport failure or non-OAuth error body.
193    /// - [`IdentityError::Deserialization`] — a 2xx body that is not a valid
194    ///   token response.
195    pub async fn client_credentials(&self, scope: Option<&str>) -> Result<TokenResponse> {
196        let mut form: Vec<(String, String)> = vec![(
197            "grant_type".to_string(),
198            GRANT_CLIENT_CREDENTIALS.to_string(),
199        )];
200        if let Some(scope) = scope {
201            form.push(("scope".to_string(), scope.to_string()));
202        }
203        self.do_request(form, self.client_secret.as_deref(), &[])
204            .await
205    }
206
207    /// Performs the OAuth 2.0 authorization code grant (RFC 6749 §4.1.3,
208    /// ACG-001): POSTs `grant_type=authorization_code` with `code`,
209    /// `redirect_uri`, and (when configured) `client_id` to the token endpoint
210    /// and returns the typed [`TokenResponse`].
211    ///
212    /// When `code_verifier` is `Some`, it is validated against RFC 7636 §4.1
213    /// and sent as the `code_verifier` parameter (ACG-004). A configured client
214    /// secret still authenticates the request via the configured method; a
215    /// public client (no secret) is identified by `client_id` in the body.
216    ///
217    /// # Errors
218    ///
219    /// - [`IdentityError::Validation`] — a `code_verifier` outside the 43–128
220    ///   unreserved-character range.
221    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response
222    ///   (ACG-005).
223    /// - [`IdentityError::Http`] / [`IdentityError::Deserialization`] — as for
224    ///   [`client_credentials`](TokenClient::client_credentials).
225    pub async fn exchange_code(
226        &self,
227        code: &str,
228        redirect_uri: &str,
229        code_verifier: Option<&str>,
230    ) -> Result<TokenResponse> {
231        if let Some(verifier) = code_verifier
232            && !valid_code_verifier(verifier)
233        {
234            return Err(IdentityError::Validation(
235                "code_verifier must be 43-128 unreserved characters".to_string(),
236            ));
237        }
238
239        let mut form: Vec<(String, String)> = vec![
240            (
241                "grant_type".to_string(),
242                GRANT_AUTHORIZATION_CODE.to_string(),
243            ),
244            ("code".to_string(), code.to_string()),
245        ];
246        if !redirect_uri.is_empty() {
247            form.push(("redirect_uri".to_string(), redirect_uri.to_string()));
248        }
249        if let Some(verifier) = code_verifier {
250            form.push(("code_verifier".to_string(), verifier.to_string()));
251        }
252        self.do_request(form, self.client_secret.as_deref(), &[])
253            .await
254    }
255
256    /// Performs the OAuth 2.0 token exchange grant (RFC 8693 §2.1, EXCH-001):
257    /// POSTs `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with
258    /// the parameters of `request` to the token endpoint and returns the typed
259    /// [`TokenResponse`], including the RFC 8693 §2.2 `issued_token_type`.
260    ///
261    /// A [`TokenExchangeRequest`] carrying only a subject token requests an
262    /// **impersonation** token; one that also carries an actor token requests a
263    /// **delegation** token (RFC 8693 §1.1, EXCH-002). The type URIs are sent
264    /// verbatim (RFC 8693 §3, EXCH-003), and `resource` / `audience` are sent as
265    /// repeated parameters when more than one target is named (EXCH-004).
266    ///
267    /// Authentication uses the configured [`ClientAuthMethod`]
268    /// (`client_secret_basic` by default), exactly as for the other grants.
269    /// The exchange owns its `requested_token_type`, `resource`, and `audience`
270    /// parameters, so a [`TokenClientBuilder::extra_param`] carrying one of
271    /// those keys is an error rather than something to drop: `extra_param` is
272    /// client-wide, and quietly dropping an `audience` the caller set to pin
273    /// every token to one API would relax that restriction on this grant alone.
274    ///
275    /// ```no_run
276    /// # async fn run() -> rs_identity_model::Result<()> {
277    /// use rs_identity_model::{TOKEN_TYPE_ACCESS_TOKEN, TokenClient, TokenExchangeRequest};
278    ///
279    /// let client = TokenClient::builder()
280    ///     .client_id("my-client")
281    ///     .client_secret("my-secret")
282    ///     .token_endpoint("https://issuer.example.com/token")
283    ///     .build()?;
284    /// let issued = client
285    ///     .token_exchange(
286    ///         &TokenExchangeRequest::new("subject.tok", TOKEN_TYPE_ACCESS_TOKEN)
287    ///             .audience("https://api.example.com"),
288    ///     )
289    ///     .await?;
290    /// println!("issued a {:?}", issued.issued_token_type);
291    /// # Ok(())
292    /// # }
293    /// ```
294    ///
295    /// # Errors
296    ///
297    /// - [`IdentityError::Validation`] — `request` is missing a REQUIRED
298    ///   RFC 8693 §2.1 parameter, or a [`TokenClientBuilder::extra_param`] key
299    ///   names a parameter this grant owns
300    ///   (`requested_token_type`, `resource`, `audience`). No request is sent.
301    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response
302    ///   (RFC 8693 §2.2.2, RFC 6749 §5.2, EXCH-006).
303    /// - [`IdentityError::Http`] — a transport failure, a non-OAuth error body,
304    ///   or a 2xx body missing the REQUIRED `access_token`, `token_type`, or
305    ///   `issued_token_type`.
306    /// - [`IdentityError::Deserialization`] — a 2xx body that is not a valid
307    ///   token response. An explicit JSON `null` falls here rather than under
308    ///   the missing-field errors above: `#[serde(default)]` fills in only an
309    ///   *absent* key, so `"token_type": null` fails to deserialize before any
310    ///   of those checks run.
311    pub async fn token_exchange(&self, request: &TokenExchangeRequest) -> Result<TokenResponse> {
312        request.validate()?;
313        // An extra param naming a parameter the exchange owns is rejected, not
314        // dropped. `extra_param` lives on [`TokenClientBuilder`], so it is
315        // client-wide and shared with `client_credentials` and `exchange_code`:
316        // dropping one here would take away a restriction the caller believes
317        // is in force — an `audience` that pinned tokens to one API would
318        // vanish on this grant alone, the AS could issue a broader token, and
319        // nothing would say which grant lost it. Keys are sorted so the message
320        // names the same key on every run when several collide.
321        let mut colliding: Vec<&str> = self
322            .extra_params
323            .keys()
324            .map(String::as_str)
325            .filter(|key| EXCHANGE_RESERVED_PARAMS.contains(&normalize_param_key(key).as_str()))
326            .collect();
327        colliding.sort_unstable();
328        if let Some(key) = colliding.first() {
329            return Err(IdentityError::Validation(format!(
330                "token exchange: extra param {key:?} names a parameter this grant owns; \
331                 set it with TokenExchangeRequest::resource, ::audience, or \
332                 ::requested_token_type instead"
333            )));
334        }
335
336        let mut form: Vec<(String, String)> = vec![
337            ("grant_type".to_string(), GRANT_TOKEN_EXCHANGE.to_string()),
338            ("subject_token".to_string(), request.subject_token.clone()),
339            (
340                "subject_token_type".to_string(),
341                request.subject_token_type.clone(),
342            ),
343        ];
344        // RFC 8693 §2.1 forbids the half-pair `actor_token` without
345        // `actor_token_type`. Both halves are destructured together so the
346        // forbidden form is unrepresentable here, rather than merely unreachable
347        // because validate() ran first: reading the type separately would emit
348        // `actor_token_type=` the moment the two fields disagreed.
349        if let (Some(actor_token), Some(actor_token_type)) = (
350            request.actor_token.as_deref(),
351            request.actor_token_type.as_deref(),
352        ) {
353            form.push(("actor_token".to_string(), actor_token.to_string()));
354            form.push(("actor_token_type".to_string(), actor_token_type.to_string()));
355        }
356        // Empty optional parameters are skipped rather than sent as `key=`: an
357        // empty value is not a request for anything, and a server is free to
358        // read it as a malformed parameter and reject the whole exchange.
359        if let Some(requested) = request
360            .requested_token_type
361            .as_deref()
362            .filter(|t| !t.is_empty())
363        {
364            form.push(("requested_token_type".to_string(), requested.to_string()));
365        }
366        if let Some(scope) = request.scope.as_deref().filter(|s| !s.is_empty()) {
367            form.push(("scope".to_string(), scope.to_string()));
368        }
369        // resource and audience MAY each appear more than once (RFC 8693 §2.1),
370        // which the ordered pair list preserves and a map would collapse.
371        for resource in request.resources.iter().filter(|r| !r.is_empty()) {
372            form.push(("resource".to_string(), resource.clone()));
373        }
374        for audience in request.audiences.iter().filter(|a| !a.is_empty()) {
375            form.push(("audience".to_string(), audience.clone()));
376        }
377
378        let token = self
379            .do_request(
380                form,
381                self.client_secret.as_deref(),
382                EXCHANGE_RESERVED_PARAMS,
383            )
384            .await?;
385        // token_type is REQUIRED in a successful token response
386        // (RFC 6749 §5.1), and `spec/vectors/token-exchange.json` lists it
387        // among the exchange's required fields. It deserializes with a default
388        // of "", so an omitted one has to be caught here rather than left to
389        // surface as an empty string the caller may put straight into an
390        // Authorization header.
391        if token.token_type.is_empty() {
392            return Err(IdentityError::Http(format!(
393                "token exchange response from {} is missing token_type",
394                self.token_endpoint
395            )));
396        }
397        // issued_token_type is REQUIRED in a successful exchange response
398        // (RFC 8693 §2.2); a 200 that omits it is non-conformant and is
399        // rejected rather than handed back with the field silently empty.
400        if !token
401            .issued_token_type
402            .as_deref()
403            .is_some_and(|t| !t.is_empty())
404        {
405            return Err(IdentityError::Http(format!(
406                "token exchange response from {} is missing issued_token_type",
407                self.token_endpoint
408            )));
409        }
410        Ok(token)
411    }
412
413    /// Applies client authentication and extra parameters, POSTs `form` as
414    /// `application/x-www-form-urlencoded`, and decodes the response: a 2xx body
415    /// into [`TokenResponse`], otherwise an OAuth error body into
416    /// [`IdentityError::TokenEndpoint`] (status checked before decode).
417    ///
418    /// `grant_reserved` names parameters this particular grant owns on top of
419    /// [`RESERVED_PARAMS`]; extras matching them are dropped rather than sent.
420    /// Grants that can say so more usefully reject the collision before calling
421    /// in (as [`TokenClient::token_exchange`] does) — the drop here is defence
422    /// in depth, not the primary guard. Both lists are matched on
423    /// [`normalize_param_key`].
424    async fn do_request(
425        &self,
426        mut form: Vec<(String, String)>,
427        client_secret: Option<&str>,
428        grant_reserved: &[&str],
429    ) -> Result<TokenResponse> {
430        // Require an https endpoint unless http was explicitly allowed.
431        let scheme = self.token_endpoint.to_ascii_lowercase();
432        let scheme_ok =
433            scheme.starts_with("https://") || (self.allow_http && scheme.starts_with("http://"));
434        if !scheme_ok {
435            return Err(IdentityError::Configuration(format!(
436                "token endpoint {:?} must use https (enable allow_http for development)",
437                self.token_endpoint
438            )));
439        }
440
441        // Client authentication (RFC 6749 §2.3). A Basic header is built for the
442        // request; post/public credentials go in the form body.
443        let mut basic_header: Option<String> = None;
444        match client_secret {
445            // Public client: identify via client_id in the body.
446            None => {
447                if !self.client_id.is_empty() {
448                    form.push(("client_id".to_string(), self.client_id.clone()));
449                }
450            }
451            Some(secret) => match self.auth_method {
452                ClientAuthMethod::ClientSecretPost => {
453                    form.push(("client_id".to_string(), self.client_id.clone()));
454                    form.push(("client_secret".to_string(), secret.to_string()));
455                }
456                ClientAuthMethod::ClientSecretBasic => {
457                    basic_header = Some(basic_auth_header(&self.client_id, secret));
458                }
459            },
460        }
461
462        // Extra params are applied last but never override reserved grant or
463        // client-auth parameters (whether or not already present — on the Basic
464        // path client_id is absent from the body yet must not be injectable).
465        for (key, value) in &self.extra_params {
466            let normalized = normalize_param_key(key);
467            if RESERVED_PARAMS.contains(&normalized.as_str())
468                || grant_reserved.contains(&normalized.as_str())
469                || form.iter().any(|(k, _)| k == key)
470            {
471                continue;
472            }
473            form.push((key.clone(), value.clone()));
474        }
475
476        let mut request = self
477            .http
478            .post(&self.token_endpoint)
479            .timeout(self.timeout)
480            .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
481            .header(ACCEPT, "application/json")
482            .form(&form);
483        if let Some(header) = basic_header {
484            request = request.header(AUTHORIZATION, header);
485        }
486
487        let response = request
488            .send()
489            .await
490            .map_err(|e| IdentityError::Http(format!("post {}: {e}", self.token_endpoint)))?;
491
492        let status = response.status();
493        let body = read_capped_body(response).await?;
494
495        // Status before decode: a non-2xx response is an OAuth error
496        // (RFC 6749 §5.2, CC-004 / ACG-005).
497        if !status.is_success() {
498            if let Ok(err) = serde_json::from_slice::<OAuthErrorBody>(&body)
499                && !err.error.is_empty()
500            {
501                return Err(IdentityError::TokenEndpoint {
502                    error: err.error,
503                    description: err.error_description,
504                    error_uri: err.error_uri,
505                    status: status.as_u16(),
506                });
507            }
508            return Err(IdentityError::Http(format!(
509                "token request to {} failed: HTTP {} with non-OAuth body: {}",
510                self.token_endpoint,
511                status.as_u16(),
512                body_snippet(&body)
513            )));
514        }
515
516        let token: TokenResponse = serde_json::from_slice(&body).map_err(|e| {
517            IdentityError::Deserialization(format!(
518                "parse token response from {}: {e}",
519                self.token_endpoint
520            ))
521        })?;
522        if token.access_token.is_empty() {
523            return Err(IdentityError::Http(format!(
524                "token response from {} is missing access_token",
525                self.token_endpoint
526            )));
527        }
528        Ok(token)
529    }
530}
531
532/// Builder for [`TokenClient`]. Obtain one via [`TokenClient::builder`].
533#[derive(Default)]
534pub struct TokenClientBuilder {
535    http: Option<HttpClient>,
536    token_endpoint: Option<String>,
537    client_id: Option<String>,
538    client_secret: Option<String>,
539    auth_method: ClientAuthMethod,
540    extra_params: HashMap<String, String>,
541    timeout: Duration,
542    allow_http: bool,
543}
544
545// Redacting Debug: the builder holds the client secret before the client is
546// built, so it must not print it either (#24).
547impl std::fmt::Debug for TokenClientBuilder {
548    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
549        f.debug_struct("TokenClientBuilder")
550            .field("token_endpoint", &self.token_endpoint)
551            .field("client_id", &self.client_id)
552            .field(
553                "client_secret",
554                &self.client_secret.as_ref().map(|_| REDACTED),
555            )
556            .field("auth_method", &self.auth_method)
557            .field("extra_params", &self.extra_params)
558            .field("timeout", &self.timeout)
559            .field("allow_http", &self.allow_http)
560            .finish_non_exhaustive()
561    }
562}
563
564impl TokenClientBuilder {
565    fn new() -> Self {
566        Self::default()
567    }
568
569    /// Sets the client identifier (required).
570    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
571        self.client_id = Some(client_id.into());
572        self
573    }
574
575    /// Sets the client secret. Omit (or pass an empty string) for a public
576    /// client (authorization code grant), which is then identified by
577    /// `client_id` in the request body.
578    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
579        self.client_secret = Some(client_secret.into());
580        self
581    }
582
583    /// Sets the token endpoint URL (required).
584    pub fn token_endpoint(mut self, token_endpoint: impl Into<String>) -> Self {
585        self.token_endpoint = Some(token_endpoint.into());
586        self
587    }
588
589    /// Selects the client authentication method (RFC 6749 §2.3). The default is
590    /// [`ClientAuthMethod::ClientSecretBasic`].
591    pub fn auth_method(mut self, method: ClientAuthMethod) -> Self {
592        self.auth_method = method;
593        self
594    }
595
596    /// Adds a single extra form parameter for provider-specific extensions
597    /// (e.g. an RFC 8707 `resource` or an `audience` on a grant that does not
598    /// model them). Reserved grant/auth parameters are never overridden.
599    ///
600    /// Extras are client-wide, so they apply to every grant this client
601    /// performs. [`token_exchange`] additionally owns `requested_token_type`,
602    /// `resource`, and `audience` — it takes those from its
603    /// [`TokenExchangeRequest`] — and fails with [`IdentityError::Validation`]
604    /// rather than silently ignoring an extra that names one of them. Keys are
605    /// compared case-insensitively and ignoring surrounding whitespace.
606    ///
607    /// [`token_exchange`]: TokenClient::token_exchange
608    pub fn extra_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
609        self.extra_params.insert(key.into(), value.into());
610        self
611    }
612
613    /// Adds multiple extra form parameters. See [`extra_param`].
614    ///
615    /// [`extra_param`]: TokenClientBuilder::extra_param
616    pub fn extra_params(mut self, params: HashMap<String, String>) -> Self {
617        self.extra_params.extend(params);
618        self
619    }
620
621    /// Uses `client` for token requests instead of a default
622    /// [`reqwest::Client`], letting callers share a connection pool or supply
623    /// custom transport configuration (CC-006).
624    pub fn http_client(mut self, client: HttpClient) -> Self {
625        self.http = Some(client);
626        self
627    }
628
629    /// Bounds each token request with a per-request timeout. A non-positive
630    /// duration is ignored and the default (30s) is retained.
631    pub fn timeout(mut self, timeout: Duration) -> Self {
632        if !timeout.is_zero() {
633            self.timeout = timeout;
634        }
635        self
636    }
637
638    /// Permits an `http://` token endpoint, which is otherwise rejected.
639    /// Intended for local development and integration tests against non-TLS
640    /// providers; do not enable in production.
641    pub fn allow_http(mut self, allow: bool) -> Self {
642        self.allow_http = allow;
643        self
644    }
645
646    /// Builds the [`TokenClient`].
647    ///
648    /// # Errors
649    ///
650    /// [`IdentityError::Configuration`] if `client_id` or `token_endpoint` is
651    /// missing or empty (AC-6).
652    pub fn build(self) -> Result<TokenClient> {
653        let client_id = self.client_id.unwrap_or_default();
654        if client_id.is_empty() {
655            return Err(IdentityError::Configuration(
656                "client_id is required".to_string(),
657            ));
658        }
659        let token_endpoint = self.token_endpoint.unwrap_or_default();
660        if token_endpoint.is_empty() {
661            return Err(IdentityError::Configuration(
662                "token_endpoint is required".to_string(),
663            ));
664        }
665        Ok(TokenClient {
666            http: self.http.unwrap_or_else(crate::http::secure_client),
667            token_endpoint,
668            client_id,
669            // An empty secret is a public client, not a confidential client
670            // with an empty password: matching the Go reference, it is
671            // identified by client_id in the body rather than a Basic header
672            // carrying `id:` (RFC 6749 §2.3.1).
673            client_secret: self.client_secret.filter(|s| !s.is_empty()),
674            auth_method: self.auth_method,
675            extra_params: self.extra_params,
676            timeout: if self.timeout.is_zero() {
677                DEFAULT_TIMEOUT
678            } else {
679                self.timeout
680            },
681            allow_http: self.allow_http,
682        })
683    }
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689    use base64::Engine;
690    use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
691    use wiremock::matchers::{header_exists, method, path};
692    use wiremock::{Mock, MockServer, Request, ResponseTemplate};
693
694    /// A minimal successful token response body.
695    const SUCCESS_BODY: &str =
696        r#"{"access_token":"at-abc","token_type":"Bearer","expires_in":3600}"#;
697
698    /// Mounts a single POST handler on `/token` returning `template`.
699    async fn mount_token(server: &MockServer, template: ResponseTemplate) {
700        Mock::given(method("POST"))
701            .and(path("/token"))
702            .respond_with(template)
703            .mount(server)
704            .await;
705    }
706
707    /// Parses a request's form body into key/value pairs.
708    fn form_of(req: &Request) -> HashMap<String, String> {
709        url::form_urlencoded::parse(&req.body)
710            .into_owned()
711            .collect()
712    }
713
714    fn client(endpoint: &str) -> TokenClientBuilder {
715        TokenClient::builder()
716            .client_id("client-1")
717            .client_secret("s3cr3t")
718            .token_endpoint(endpoint)
719            .allow_http(true)
720    }
721
722    // CC-001: a client credentials grant returns a typed response.
723    #[tokio::test]
724    async fn client_credentials_returns_typed_response() {
725        let server = MockServer::start().await;
726        mount_token(
727            &server,
728            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
729        )
730        .await;
731
732        let token = client(&format!("{}/token", server.uri()))
733            .build()
734            .unwrap()
735            .client_credentials(None)
736            .await
737            .expect("grant succeeds");
738
739        assert_eq!(token.access_token, "at-abc");
740        assert_eq!(token.token_type, "Bearer");
741        assert_eq!(token.expires_in, 3600);
742    }
743
744    // CC-002: client_secret_basic is the default — a Basic header is sent and no
745    // credentials appear in the body.
746    #[tokio::test]
747    async fn client_secret_basic_is_default() {
748        let server = MockServer::start().await;
749        Mock::given(method("POST"))
750            .and(path("/token"))
751            .and(header_exists("authorization"))
752            .respond_with(ResponseTemplate::new(200).set_body_string(SUCCESS_BODY))
753            .mount(&server)
754            .await;
755
756        client(&format!("{}/token", server.uri()))
757            .build()
758            .unwrap()
759            .client_credentials(None)
760            .await
761            .expect("grant succeeds");
762
763        let requests = server.received_requests().await.unwrap();
764        let req = requests.last().unwrap();
765        let auth = req.headers.get("authorization").unwrap().to_str().unwrap();
766        // "client-1":"s3cr3t" form-urlencoded then base64: no reserved chars,
767        // so it equals base64("client-1:s3cr3t").
768        assert_eq!(
769            auth,
770            format!("Basic {}", BASE64_STANDARD.encode("client-1:s3cr3t"))
771        );
772        let form = form_of(req);
773        assert!(!form.contains_key("client_id"), "no client_id in body");
774        assert!(
775            !form.contains_key("client_secret"),
776            "no client_secret in body"
777        );
778        assert_eq!(
779            form.get("grant_type").map(String::as_str),
780            Some("client_credentials")
781        );
782    }
783
784    // CC-003: client_secret_post places credentials in the body and sets no
785    // Basic header.
786    #[tokio::test]
787    async fn client_secret_post_uses_body() {
788        let server = MockServer::start().await;
789        mount_token(
790            &server,
791            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
792        )
793        .await;
794
795        client(&format!("{}/token", server.uri()))
796            .auth_method(ClientAuthMethod::ClientSecretPost)
797            .build()
798            .unwrap()
799            .client_credentials(None)
800            .await
801            .expect("grant succeeds");
802
803        let requests = server.received_requests().await.unwrap();
804        let req = requests.last().unwrap();
805        assert!(
806            req.headers.get("authorization").is_none(),
807            "no Basic header"
808        );
809        let form = form_of(req);
810        assert_eq!(form.get("client_id").map(String::as_str), Some("client-1"));
811        assert_eq!(
812            form.get("client_secret").map(String::as_str),
813            Some("s3cr3t")
814        );
815    }
816
817    // CC-004 / ACG-005: a non-2xx OAuth error body maps to TokenEndpoint.
818    #[tokio::test]
819    async fn error_response_maps_to_token_endpoint() {
820        let server = MockServer::start().await;
821        let body = r#"{"error":"invalid_client","error_description":"bad secret","error_uri":"https://err.example/1"}"#;
822        mount_token(&server, ResponseTemplate::new(401).set_body_string(body)).await;
823
824        let err = client(&format!("{}/token", server.uri()))
825            .build()
826            .unwrap()
827            .client_credentials(None)
828            .await
829            .expect_err("error response must fail");
830
831        match err {
832            IdentityError::TokenEndpoint {
833                error,
834                description,
835                error_uri,
836                status,
837            } => {
838                assert_eq!(error, "invalid_client");
839                assert_eq!(description.as_deref(), Some("bad secret"));
840                assert_eq!(error_uri.as_deref(), Some("https://err.example/1"));
841                assert_eq!(status, 401);
842            }
843            other => panic!("expected TokenEndpoint, got {other:?}"),
844        }
845    }
846
847    // A non-2xx response without a recognisable OAuth body is a plain Http error.
848    #[tokio::test]
849    async fn non_oauth_error_body_maps_to_http() {
850        let server = MockServer::start().await;
851        mount_token(
852            &server,
853            ResponseTemplate::new(500).set_body_string("upstream boom"),
854        )
855        .await;
856
857        let err = client(&format!("{}/token", server.uri()))
858            .build()
859            .unwrap()
860            .client_credentials(None)
861            .await
862            .expect_err("500 must fail");
863
864        assert!(matches!(err, IdentityError::Http(_)), "{err:?}");
865    }
866
867    // CC-005: WithScopes sends a single space-delimited scope parameter.
868    #[tokio::test]
869    async fn scope_is_space_delimited() {
870        let server = MockServer::start().await;
871        mount_token(
872            &server,
873            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
874        )
875        .await;
876
877        client(&format!("{}/token", server.uri()))
878            .build()
879            .unwrap()
880            .client_credentials(Some("a b"))
881            .await
882            .expect("grant succeeds");
883
884        let requests = server.received_requests().await.unwrap();
885        let form = form_of(requests.last().unwrap());
886        assert_eq!(form.get("scope").map(String::as_str), Some("a b"));
887    }
888
889    // CC-006: extra params appear in the body and the supplied http client is
890    // used; reserved params cannot be overridden.
891    #[tokio::test]
892    async fn extra_params_applied_reserved_guarded() {
893        let server = MockServer::start().await;
894        mount_token(
895            &server,
896            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
897        )
898        .await;
899
900        let custom = reqwest::Client::builder().build().unwrap();
901        client(&format!("{}/token", server.uri()))
902            .http_client(custom)
903            .extra_param("resource", "urn:test:api")
904            // reserved: must be ignored, not override the grant type.
905            .extra_param("grant_type", "hacked")
906            .build()
907            .unwrap()
908            .client_credentials(None)
909            .await
910            .expect("grant succeeds");
911
912        let requests = server.received_requests().await.unwrap();
913        let form = form_of(requests.last().unwrap());
914        assert_eq!(
915            form.get("resource").map(String::as_str),
916            Some("urn:test:api")
917        );
918        assert_eq!(
919            form.get("grant_type").map(String::as_str),
920            Some("client_credentials"),
921            "reserved grant_type must not be overridden"
922        );
923    }
924
925    // ACG-001 / ACG-004: exchange_code sends grant, code, redirect_uri, and
926    // code_verifier.
927    #[tokio::test]
928    async fn exchange_code_sends_expected_form() {
929        let server = MockServer::start().await;
930        mount_token(
931            &server,
932            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
933        )
934        .await;
935
936        // Public client: build without a secret.
937        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
938        TokenClient::builder()
939            .client_id("public-client")
940            .token_endpoint(format!("{}/token", server.uri()))
941            .allow_http(true)
942            .build()
943            .unwrap()
944            .exchange_code("auth-code-1", "https://app.example/cb", Some(verifier))
945            .await
946            .expect("exchange succeeds");
947
948        let requests = server.received_requests().await.unwrap();
949        let req = requests.last().unwrap();
950        assert!(
951            req.headers.get("authorization").is_none(),
952            "public client has no Basic header"
953        );
954        let form = form_of(req);
955        assert_eq!(
956            form.get("grant_type").map(String::as_str),
957            Some("authorization_code")
958        );
959        assert_eq!(form.get("code").map(String::as_str), Some("auth-code-1"));
960        assert_eq!(
961            form.get("redirect_uri").map(String::as_str),
962            Some("https://app.example/cb")
963        );
964        assert_eq!(
965            form.get("code_verifier").map(String::as_str),
966            Some(verifier)
967        );
968        assert_eq!(
969            form.get("client_id").map(String::as_str),
970            Some("public-client")
971        );
972    }
973
974    // CC-002: an empty client_secret is a public client, not a confidential
975    // client with an empty password — no Basic header, client_id in the body
976    // (parity with the Go reference).
977    #[tokio::test]
978    async fn empty_client_secret_is_public_client() {
979        let server = MockServer::start().await;
980        mount_token(
981            &server,
982            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
983        )
984        .await;
985
986        TokenClient::builder()
987            .client_id("public-client")
988            .client_secret("")
989            .token_endpoint(format!("{}/token", server.uri()))
990            .allow_http(true)
991            .build()
992            .unwrap()
993            .client_credentials(None)
994            .await
995            .expect("grant succeeds");
996
997        let requests = server.received_requests().await.unwrap();
998        let req = requests.last().unwrap();
999        assert!(
1000            req.headers.get("authorization").is_none(),
1001            "empty secret must not send a Basic header"
1002        );
1003        let form = form_of(req);
1004        assert_eq!(
1005            form.get("client_id").map(String::as_str),
1006            Some("public-client"),
1007            "public client is identified by client_id in the body"
1008        );
1009        assert!(
1010            !form.contains_key("client_secret"),
1011            "no empty client_secret in body"
1012        );
1013    }
1014
1015    // AC-2: an invalid code_verifier is rejected before any request is sent.
1016    #[tokio::test]
1017    async fn exchange_code_rejects_invalid_verifier() {
1018        let client = TokenClient::builder()
1019            .client_id("public-client")
1020            .token_endpoint("https://issuer.example/token")
1021            .build()
1022            .unwrap();
1023        let err = client
1024            .exchange_code("code", "https://app/cb", Some("too-short"))
1025            .await
1026            .expect_err("short verifier must error");
1027        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
1028    }
1029
1030    // AC-6: the builder rejects missing required fields.
1031    #[test]
1032    fn builder_requires_client_id_and_endpoint() {
1033        let missing_id = TokenClient::builder()
1034            .token_endpoint("https://issuer.example/token")
1035            .build();
1036        assert!(matches!(missing_id, Err(IdentityError::Configuration(_))));
1037
1038        let missing_endpoint = TokenClient::builder().client_id("c").build();
1039        assert!(matches!(
1040            missing_endpoint,
1041            Err(IdentityError::Configuration(_))
1042        ));
1043
1044        let ok = TokenClient::builder()
1045            .client_id("c")
1046            .token_endpoint("https://issuer.example/token")
1047            .build();
1048        assert!(ok.is_ok());
1049    }
1050
1051    // The default (https-only) endpoint gate rejects an http endpoint.
1052    #[tokio::test]
1053    async fn https_required_by_default() {
1054        let client = TokenClient::builder()
1055            .client_id("c")
1056            .client_secret("s")
1057            .token_endpoint("http://insecure.example/token")
1058            .build()
1059            .unwrap();
1060        let err = client
1061            .client_credentials(None)
1062            .await
1063            .expect_err("http endpoint must be rejected");
1064        assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
1065    }
1066
1067    // CC-002: Basic credentials with reserved characters are form-urlencoded
1068    // before base64 (RFC 6749 §2.3.1).
1069    #[test]
1070    fn basic_auth_header_urlencodes_credentials() {
1071        let header = basic_auth_header("id with space", "p@ss:word");
1072        let expected = format!(
1073            "Basic {}",
1074            BASE64_STANDARD.encode("id+with+space:p%40ss%3Aword")
1075        );
1076        assert_eq!(header, expected);
1077    }
1078
1079    // #24: neither the client nor its builder prints the client secret in Debug
1080    // output; the secret's presence is shown without its value.
1081    #[test]
1082    fn debug_redacts_client_secret() {
1083        let builder = TokenClient::builder()
1084            .client_id("client-1")
1085            .client_secret("s3cr3t-value")
1086            .token_endpoint("https://issuer.example/token");
1087        let builder_dbg = format!("{builder:?}");
1088        assert!(
1089            !builder_dbg.contains("s3cr3t-value"),
1090            "builder leaked secret: {builder_dbg}"
1091        );
1092        assert!(builder_dbg.contains(REDACTED), "no marker: {builder_dbg}");
1093
1094        let client = builder.build().unwrap();
1095        let client_dbg = format!("{client:?}");
1096        assert!(
1097            !client_dbg.contains("s3cr3t-value"),
1098            "client leaked secret: {client_dbg}"
1099        );
1100        assert!(client_dbg.contains(REDACTED), "no marker: {client_dbg}");
1101        // client_id is not secret and stays visible for diagnostics.
1102        assert!(client_dbg.contains("client-1"), "{client_dbg}");
1103    }
1104
1105    // A public client (no secret) shows client_secret: None, not a marker.
1106    #[test]
1107    fn debug_public_client_shows_no_secret() {
1108        let client = TokenClient::builder()
1109            .client_id("public")
1110            .token_endpoint("https://issuer.example/token")
1111            .build()
1112            .unwrap();
1113        assert!(format!("{client:?}").contains("client_secret: None"));
1114    }
1115
1116    // ---- RFC 8693 token exchange (EXCH-001..EXCH-006) --------------------
1117    //
1118    // These drive the same shared conformance fixtures the cross-language
1119    // contract (spec/vectors/token-exchange.json) references and the Go
1120    // reference replays, so the two implementations cannot drift apart on the
1121    // wire format or the parsed response.
1122
1123    /// Reads a shared conformance fixture from
1124    /// `spec/test-fixtures/token-exchange`. Unit tests run with `rust/` as the
1125    /// working directory.
1126    fn exchange_fixture(name: &str) -> String {
1127        let path = format!("../spec/test-fixtures/token-exchange/{name}");
1128        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read fixture {path}: {e}"))
1129    }
1130
1131    /// Parses a request's form body into ordered key/value pairs, preserving
1132    /// the repeated `resource` / `audience` parameters a `HashMap` collapses.
1133    fn form_pairs(req: &Request) -> Vec<(String, String)> {
1134        url::form_urlencoded::parse(&req.body)
1135            .into_owned()
1136            .collect()
1137    }
1138
1139    /// All values sent for `key`, in order.
1140    fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> {
1141        pairs
1142            .iter()
1143            .filter(|(k, _)| k == key)
1144            .map(|(_, v)| v.clone())
1145            .collect()
1146    }
1147
1148    /// The single request the server received, for asserting what was sent.
1149    async fn only_request(server: &MockServer) -> Request {
1150        let requests = server.received_requests().await.unwrap();
1151        assert_eq!(requests.len(), 1, "expected exactly one request");
1152        requests.into_iter().next().unwrap()
1153    }
1154
1155    /// A server replaying `fixture` with HTTP 200 and a client pointed at it.
1156    async fn exchange_server(fixture: &str) -> MockServer {
1157        let server = MockServer::start().await;
1158        mount_token(
1159            &server,
1160            ResponseTemplate::new(200).set_body_string(exchange_fixture(fixture)),
1161        )
1162        .await;
1163        server
1164    }
1165
1166    fn exchange_client(server: &MockServer) -> TokenClient {
1167        client(&format!("{}/token", server.uri())).build().unwrap()
1168    }
1169
1170    // EXCH-001: an impersonation exchange POSTs the token-exchange grant with
1171    // only the subject token, and parses the issued-token trio from the 200.
1172    #[tokio::test]
1173    async fn token_exchange_impersonation_returns_issued_token_trio() {
1174        let server = exchange_server("exchange-impersonation-success.json").await;
1175
1176        let issued = exchange_client(&server)
1177            .token_exchange(&TokenExchangeRequest::new(
1178                "subject-tok",
1179                TOKEN_TYPE_ACCESS_TOKEN,
1180            ))
1181            .await
1182            .expect("exchange succeeds");
1183
1184        let pairs = form_pairs(&only_request(&server).await);
1185        let form: HashMap<String, String> = pairs.iter().cloned().collect();
1186        assert_eq!(form.get("grant_type").unwrap(), GRANT_TOKEN_EXCHANGE);
1187        assert_eq!(form.get("subject_token").unwrap(), "subject-tok");
1188        assert_eq!(
1189            form.get("subject_token_type").unwrap(),
1190            TOKEN_TYPE_ACCESS_TOKEN
1191        );
1192        // Impersonation carries no actor token (RFC 8693 §1.1).
1193        assert!(!form.contains_key("actor_token"), "{form:?}");
1194        assert!(!form.contains_key("actor_token_type"), "{form:?}");
1195
1196        assert!(!issued.access_token.is_empty());
1197        assert_eq!(
1198            issued.issued_token_type.as_deref(),
1199            Some(TOKEN_TYPE_ACCESS_TOKEN)
1200        );
1201        assert_eq!(issued.token_type, "Bearer");
1202        assert_eq!(issued.expires_in, 3600);
1203    }
1204
1205    // EXCH-002: a delegation exchange sends both the subject and the actor
1206    // token with their types (RFC 8693 §1.1, §2.1).
1207    #[tokio::test]
1208    async fn token_exchange_delegation_sends_actor_token() {
1209        let server = exchange_server("exchange-delegation-success.json").await;
1210
1211        let issued = exchange_client(&server)
1212            .token_exchange(
1213                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1214                    .actor_token("actor-tok", TOKEN_TYPE_JWT),
1215            )
1216            .await
1217            .expect("delegation exchange succeeds");
1218
1219        let pairs = form_pairs(&only_request(&server).await);
1220        let form: HashMap<String, String> = pairs.iter().cloned().collect();
1221        assert_eq!(form.get("subject_token").unwrap(), "subject-tok");
1222        assert_eq!(form.get("actor_token").unwrap(), "actor-tok");
1223        assert_eq!(form.get("actor_token_type").unwrap(), TOKEN_TYPE_JWT);
1224        assert!(!issued.access_token.is_empty());
1225        assert!(issued.issued_token_type.is_some());
1226    }
1227
1228    // EXCH-003: each of the six RFC 8693 §3 token type URIs is serialized
1229    // verbatim as subject_token_type, with no abbreviation or normalisation.
1230    #[tokio::test]
1231    async fn token_exchange_serializes_all_token_type_uris_verbatim() {
1232        for uri in TOKEN_TYPE_URIS {
1233            let server = exchange_server("exchange-impersonation-success.json").await;
1234            exchange_client(&server)
1235                .token_exchange(&TokenExchangeRequest::new("subject-tok", uri))
1236                .await
1237                .unwrap_or_else(|e| panic!("exchange with {uri}: {e}"));
1238
1239            let pairs = form_pairs(&only_request(&server).await);
1240            assert_eq!(
1241                form_all(&pairs, "subject_token_type"),
1242                vec![uri.to_string()],
1243                "subject_token_type must be sent verbatim"
1244            );
1245        }
1246    }
1247
1248    // EXCH-004: requested_token_type, audience, and resource all reach the
1249    // request body.
1250    #[tokio::test]
1251    async fn token_exchange_sends_requested_type_audience_and_resource() {
1252        let server = exchange_server("exchange-impersonation-success.json").await;
1253
1254        exchange_client(&server)
1255            .token_exchange(
1256                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1257                    .requested_token_type(TOKEN_TYPE_ACCESS_TOKEN)
1258                    .audience("https://api.example.com")
1259                    .resource("https://rs.example.com")
1260                    .scope("https://api.example.com/read"),
1261            )
1262            .await
1263            .expect("exchange succeeds");
1264
1265        let pairs = form_pairs(&only_request(&server).await);
1266        let form: HashMap<String, String> = pairs.iter().cloned().collect();
1267        assert_eq!(
1268            form.get("requested_token_type").unwrap(),
1269            TOKEN_TYPE_ACCESS_TOKEN
1270        );
1271        assert_eq!(form.get("audience").unwrap(), "https://api.example.com");
1272        assert_eq!(form.get("resource").unwrap(), "https://rs.example.com");
1273        assert_eq!(form.get("scope").unwrap(), "https://api.example.com/read");
1274    }
1275
1276    // EXCH-004 (repeatable): resource and audience MAY each appear more than
1277    // once (RFC 8693 §2.1); every value is sent as its own parameter rather
1278    // than joined or collapsed to the last one.
1279    #[tokio::test]
1280    async fn token_exchange_repeats_resource_and_audience() {
1281        let server = exchange_server("exchange-impersonation-success.json").await;
1282
1283        exchange_client(&server)
1284            .token_exchange(
1285                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1286                    .resource("https://rs1.example.com")
1287                    .resource("https://rs2.example.com")
1288                    .audience("aud-a")
1289                    .audience("aud-b"),
1290            )
1291            .await
1292            .expect("exchange succeeds");
1293
1294        let pairs = form_pairs(&only_request(&server).await);
1295        assert_eq!(
1296            form_all(&pairs, "resource"),
1297            ["https://rs1.example.com", "https://rs2.example.com"]
1298        );
1299        assert_eq!(form_all(&pairs, "audience"), ["aud-a", "aud-b"]);
1300    }
1301
1302    // EXCH-005: a success whose token_type is N_A — the issued token is not
1303    // usable as a bearer token (RFC 8693 §2.2.1) — parses without error.
1304    #[tokio::test]
1305    async fn token_exchange_accepts_n_a_token_type() {
1306        let server = exchange_server("exchange-n_a-token-type.json").await;
1307
1308        let issued = exchange_client(&server)
1309            .token_exchange(&TokenExchangeRequest::new(
1310                "subject-tok",
1311                TOKEN_TYPE_ACCESS_TOKEN,
1312            ))
1313            .await
1314            .expect("N_A token type is accepted");
1315
1316        assert_eq!(issued.token_type, "N_A");
1317        assert_eq!(issued.issued_token_type.as_deref(), Some(TOKEN_TYPE_SAML2));
1318        assert!(!issued.access_token.is_empty());
1319        assert_eq!(issued.expires_in, 60);
1320    }
1321
1322    // EXCH-006: an HTTP 400 OAuth error body surfaces as a typed
1323    // TokenEndpoint error carrying the code, description, and status
1324    // (RFC 8693 §2.2.2, RFC 6749 §5.2).
1325    #[tokio::test]
1326    async fn token_exchange_error_maps_to_token_endpoint() {
1327        let server = MockServer::start().await;
1328        mount_token(
1329            &server,
1330            ResponseTemplate::new(400)
1331                .set_body_string(exchange_fixture("exchange-error-invalid-grant.json")),
1332        )
1333        .await;
1334
1335        let err = exchange_client(&server)
1336            .token_exchange(&TokenExchangeRequest::new(
1337                "expired-tok",
1338                TOKEN_TYPE_ACCESS_TOKEN,
1339            ))
1340            .await
1341            .expect_err("an error response must fail");
1342
1343        match err {
1344            IdentityError::TokenEndpoint {
1345                error,
1346                description,
1347                status,
1348                ..
1349            } => {
1350                assert_eq!(error, "invalid_grant");
1351                assert!(description.is_some_and(|d| d.contains("subject_token")));
1352                assert_eq!(status, 400);
1353            }
1354            other => panic!("expected TokenEndpoint, got {other:?}"),
1355        }
1356    }
1357
1358    // RFC 8693 §2.1 REQUIRED: an empty subject_token fails locally and no
1359    // request reaches the endpoint.
1360    #[tokio::test]
1361    async fn token_exchange_missing_subject_token_sends_nothing() {
1362        let server = exchange_server("exchange-impersonation-success.json").await;
1363
1364        let err = exchange_client(&server)
1365            .token_exchange(&TokenExchangeRequest::new("", TOKEN_TYPE_ACCESS_TOKEN))
1366            .await
1367            .expect_err("empty subject_token must fail");
1368
1369        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
1370        assert!(
1371            server.received_requests().await.unwrap().is_empty(),
1372            "no request may be sent for an invalid exchange"
1373        );
1374    }
1375
1376    // RFC 8693 §2.1 REQUIRED: an empty subject_token_type fails locally.
1377    #[tokio::test]
1378    async fn token_exchange_missing_subject_token_type_sends_nothing() {
1379        let server = exchange_server("exchange-impersonation-success.json").await;
1380
1381        let err = exchange_client(&server)
1382            .token_exchange(&TokenExchangeRequest::new("subject-tok", ""))
1383            .await
1384            .expect_err("empty subject_token_type must fail");
1385
1386        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
1387        assert!(server.received_requests().await.unwrap().is_empty());
1388    }
1389
1390    // RFC 8693 §2.1: actor_token_type is REQUIRED whenever actor_token is
1391    // present, so a typeless actor token fails before the wire.
1392    #[tokio::test]
1393    async fn token_exchange_actor_token_requires_its_type() {
1394        let server = exchange_server("exchange-delegation-success.json").await;
1395
1396        let err = exchange_client(&server)
1397            .token_exchange(
1398                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1399                    .actor_token("actor-tok", ""),
1400            )
1401            .await
1402            .expect_err("actor_token without a type must fail");
1403
1404        assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
1405        assert!(server.received_requests().await.unwrap().is_empty());
1406    }
1407
1408    // Extra params must not be able to rewrite the exchange's identity: the
1409    // subject and actor tokens, their types, and the grant itself are reserved.
1410    #[tokio::test]
1411    async fn token_exchange_extra_params_cannot_override_identity() {
1412        let server = exchange_server("exchange-delegation-success.json").await;
1413
1414        client(&format!("{}/token", server.uri()))
1415            .extra_param("subject_token", "evil-subject")
1416            .extra_param("subject_token_type", "evil-type")
1417            .extra_param("actor_token", "evil-actor")
1418            .extra_param("actor_token_type", "evil-actor-type")
1419            .extra_param("grant_type", "evil-grant")
1420            .build()
1421            .unwrap()
1422            .token_exchange(
1423                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1424                    .actor_token("actor-tok", TOKEN_TYPE_JWT),
1425            )
1426            .await
1427            .expect("exchange succeeds");
1428
1429        let pairs = form_pairs(&only_request(&server).await);
1430        assert_eq!(form_all(&pairs, "grant_type"), [GRANT_TOKEN_EXCHANGE]);
1431        assert_eq!(form_all(&pairs, "subject_token"), ["subject-tok"]);
1432        assert_eq!(
1433            form_all(&pairs, "subject_token_type"),
1434            [TOKEN_TYPE_ACCESS_TOKEN]
1435        );
1436        assert_eq!(form_all(&pairs, "actor_token"), ["actor-tok"]);
1437        assert_eq!(form_all(&pairs, "actor_token_type"), [TOKEN_TYPE_JWT]);
1438    }
1439
1440    // An extra param that is NOT reserved and not already set by the exchange
1441    // still reaches the body — reserving the identity parameters must not
1442    // disable the extension point (RFC 8707 resource on another grant, etc.).
1443    #[tokio::test]
1444    async fn token_exchange_passes_through_unreserved_extra_params() {
1445        let server = exchange_server("exchange-impersonation-success.json").await;
1446
1447        client(&format!("{}/token", server.uri()))
1448            .extra_param("acr_values", "urn:example:loa2")
1449            .build()
1450            .unwrap()
1451            .token_exchange(&TokenExchangeRequest::new(
1452                "subject-tok",
1453                TOKEN_TYPE_ACCESS_TOKEN,
1454            ))
1455            .await
1456            .expect("exchange succeeds");
1457
1458        let pairs = form_pairs(&only_request(&server).await);
1459        assert_eq!(form_all(&pairs, "acr_values"), ["urn:example:loa2"]);
1460    }
1461
1462    // The default client authentication is client_secret_basic: credentials
1463    // travel in the Authorization header, never in the exchange body.
1464    #[tokio::test]
1465    async fn token_exchange_uses_client_secret_basic_by_default() {
1466        let server = exchange_server("exchange-impersonation-success.json").await;
1467
1468        exchange_client(&server)
1469            .token_exchange(&TokenExchangeRequest::new(
1470                "subject-tok",
1471                TOKEN_TYPE_ACCESS_TOKEN,
1472            ))
1473            .await
1474            .expect("exchange succeeds");
1475
1476        let request = only_request(&server).await;
1477        let header = request
1478            .headers
1479            .get("authorization")
1480            .expect("Basic header")
1481            .to_str()
1482            .unwrap()
1483            .to_string();
1484        let encoded = header.strip_prefix("Basic ").expect("Basic scheme");
1485        let decoded = String::from_utf8(BASE64_STANDARD.decode(encoded).unwrap()).unwrap();
1486        assert_eq!(decoded, "client-1:s3cr3t");
1487
1488        let pairs = form_pairs(&request);
1489        assert!(form_all(&pairs, "client_id").is_empty(), "{pairs:?}");
1490        assert!(form_all(&pairs, "client_secret").is_empty(), "{pairs:?}");
1491    }
1492
1493    // client_secret_post puts the credentials in the exchange body instead,
1494    // with no Authorization header.
1495    #[tokio::test]
1496    async fn token_exchange_supports_client_secret_post() {
1497        let server = exchange_server("exchange-impersonation-success.json").await;
1498
1499        client(&format!("{}/token", server.uri()))
1500            .auth_method(ClientAuthMethod::ClientSecretPost)
1501            .build()
1502            .unwrap()
1503            .token_exchange(&TokenExchangeRequest::new(
1504                "subject-tok",
1505                TOKEN_TYPE_ACCESS_TOKEN,
1506            ))
1507            .await
1508            .expect("exchange succeeds");
1509
1510        let request = only_request(&server).await;
1511        assert!(request.headers.get("authorization").is_none());
1512        let pairs = form_pairs(&request);
1513        assert_eq!(form_all(&pairs, "client_id"), ["client-1"]);
1514        assert_eq!(form_all(&pairs, "client_secret"), ["s3cr3t"]);
1515    }
1516
1517    // An http:// endpoint is refused unless allow_http was set, and nothing is
1518    // sent over the cleartext connection.
1519    #[tokio::test]
1520    async fn token_exchange_requires_https() {
1521        let server = exchange_server("exchange-impersonation-success.json").await;
1522
1523        let err = TokenClient::builder()
1524            .client_id("client-1")
1525            .client_secret("s3cr3t")
1526            .token_endpoint(format!("{}/token", server.uri()))
1527            .build()
1528            .unwrap()
1529            .token_exchange(&TokenExchangeRequest::new(
1530                "subject-tok",
1531                TOKEN_TYPE_ACCESS_TOKEN,
1532            ))
1533            .await
1534            .expect_err("http endpoint must be refused");
1535
1536        assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
1537        assert!(server.received_requests().await.unwrap().is_empty());
1538    }
1539
1540    // RFC 8693 §2.2 REQUIRED: a 200 that omits issued_token_type is
1541    // non-conformant and is rejected, not returned with the field empty.
1542    #[tokio::test]
1543    async fn token_exchange_rejects_response_without_issued_token_type() {
1544        let server = MockServer::start().await;
1545        mount_token(
1546            &server,
1547            ResponseTemplate::new(200)
1548                .set_body_string(r#"{"access_token":"issued-tok","token_type":"Bearer"}"#),
1549        )
1550        .await;
1551
1552        let err = exchange_client(&server)
1553            .token_exchange(&TokenExchangeRequest::new(
1554                "subject-tok",
1555                TOKEN_TYPE_ACCESS_TOKEN,
1556            ))
1557            .await
1558            .expect_err("a missing issued_token_type must fail");
1559
1560        match err {
1561            IdentityError::Http(message) => {
1562                assert!(message.contains("issued_token_type"), "{message}");
1563            }
1564            other => panic!("expected Http, got {other:?}"),
1565        }
1566    }
1567
1568    // RFC 8693 §2.2 REQUIRED: a 200 without access_token is rejected rather
1569    // than returned as a success with no token. `access_token` is a required
1570    // field of [`TokenResponse`], so an omitted one fails in deserialization;
1571    // a present-but-empty one fails the explicit emptiness check in
1572    // `do_request`. Both are rejections, and this asserts both paths.
1573    #[tokio::test]
1574    async fn token_exchange_rejects_response_without_access_token() {
1575        let omitted =
1576            format!(r#"{{"issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}","token_type":"Bearer"}}"#);
1577        let empty = format!(
1578            r#"{{"access_token":"","issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}","token_type":"Bearer"}}"#
1579        );
1580
1581        for body in [omitted, empty] {
1582            let server = MockServer::start().await;
1583            mount_token(
1584                &server,
1585                ResponseTemplate::new(200).set_body_string(body.clone()),
1586            )
1587            .await;
1588
1589            let err = exchange_client(&server)
1590                .token_exchange(&TokenExchangeRequest::new(
1591                    "subject-tok",
1592                    TOKEN_TYPE_ACCESS_TOKEN,
1593                ))
1594                .await
1595                .expect_err("a missing access_token must fail");
1596
1597            match err {
1598                IdentityError::Deserialization(message) | IdentityError::Http(message) => {
1599                    assert!(message.contains("access_token"), "{body}: {message}");
1600                }
1601                other => panic!("{body}: expected a rejection naming access_token, got {other:?}"),
1602            }
1603        }
1604    }
1605
1606    // RFC 6749 §5.1 REQUIRED (and spec/vectors/token-exchange.json
1607    // required_fields): a 200 that omits token_type — or sends it empty — is
1608    // rejected. `TokenResponse::token_type` defaults to "", so without this
1609    // check the caller would get Ok back holding an empty token type.
1610    #[tokio::test]
1611    async fn token_exchange_rejects_response_without_token_type() {
1612        let omitted = format!(
1613            r#"{{"access_token":"issued-tok","issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}"}}"#
1614        );
1615        let empty = format!(
1616            r#"{{"access_token":"issued-tok","token_type":"","issued_token_type":"{TOKEN_TYPE_ACCESS_TOKEN}"}}"#
1617        );
1618
1619        for body in [omitted, empty] {
1620            let server = MockServer::start().await;
1621            mount_token(
1622                &server,
1623                ResponseTemplate::new(200).set_body_string(body.clone()),
1624            )
1625            .await;
1626
1627            let err = exchange_client(&server)
1628                .token_exchange(&TokenExchangeRequest::new(
1629                    "subject-tok",
1630                    TOKEN_TYPE_ACCESS_TOKEN,
1631                ))
1632                .await
1633                .expect_err("a missing token_type must fail");
1634
1635            match err {
1636                // "missing token_type", not "token_type": the latter is also
1637                // satisfied by the adjacent "is missing issued_token_type"
1638                // message, so it would not tell the two checks apart.
1639                IdentityError::Http(message) => {
1640                    assert!(message.contains("missing token_type"), "{body}: {message}");
1641                }
1642                other => panic!("{body}: expected Http, got {other:?}"),
1643            }
1644        }
1645    }
1646
1647    // RFC 8693 §1.1: an actor token that is present but empty — in either half
1648    // of the pair — is rejected locally. Dropping it instead would post a
1649    // subject-only request, downgrading the delegation the caller asked for
1650    // into an impersonation without a word.
1651    #[tokio::test]
1652    async fn token_exchange_empty_actor_token_sends_nothing() {
1653        for (actor_token, actor_token_type) in [("", TOKEN_TYPE_JWT), ("actor-tok", ""), ("", "")] {
1654            let server = exchange_server("exchange-delegation-success.json").await;
1655
1656            let err = exchange_client(&server)
1657                .token_exchange(
1658                    &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1659                        .actor_token(actor_token, actor_token_type),
1660                )
1661                .await
1662                .expect_err("an empty half of the actor pair must fail");
1663
1664            assert!(
1665                matches!(err, IdentityError::Validation(_)),
1666                "({actor_token:?}, {actor_token_type:?}): {err:?}"
1667            );
1668            assert!(
1669                server.received_requests().await.unwrap().is_empty(),
1670                "no request may be sent for ({actor_token:?}, {actor_token_type:?})"
1671            );
1672        }
1673    }
1674
1675    // An optional parameter set to the empty string is omitted, not sent as a
1676    // bare `key=`: an empty value requests nothing and a server may treat it as
1677    // a malformed parameter and reject the exchange outright.
1678    #[tokio::test]
1679    async fn token_exchange_omits_empty_optional_parameters() {
1680        let server = exchange_server("exchange-impersonation-success.json").await;
1681
1682        exchange_client(&server)
1683            .token_exchange(
1684                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1685                    .requested_token_type("")
1686                    .scope("")
1687                    .resource("")
1688                    .audience(""),
1689            )
1690            .await
1691            .expect("exchange succeeds");
1692
1693        let pairs = form_pairs(&only_request(&server).await);
1694        for key in ["requested_token_type", "scope", "resource", "audience"] {
1695            assert!(
1696                form_all(&pairs, key).is_empty(),
1697                "empty {key} must not be sent: {pairs:?}"
1698            );
1699        }
1700    }
1701
1702    // Only the empty entries are dropped — a list mixing empty and real values
1703    // still sends the real ones, in order.
1704    #[tokio::test]
1705    async fn token_exchange_keeps_non_empty_entries_when_dropping_empty_ones() {
1706        let server = exchange_server("exchange-impersonation-success.json").await;
1707
1708        exchange_client(&server)
1709            .token_exchange(
1710                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1711                    .resource("")
1712                    .resource("https://rs.example.com")
1713                    .audience("aud-a")
1714                    .audience(""),
1715            )
1716            .await
1717            .expect("exchange succeeds");
1718
1719        let pairs = form_pairs(&only_request(&server).await);
1720        assert_eq!(form_all(&pairs, "resource"), ["https://rs.example.com"]);
1721        assert_eq!(form_all(&pairs, "audience"), ["aud-a"]);
1722    }
1723
1724    // The exchange owns requested_token_type, resource, and audience, and says
1725    // so loudly: an extra param naming one fails the call before anything is
1726    // sent. Dropping it instead would be a silent loss of a restriction —
1727    // extra_param is client-wide, so a caller who set `audience` to pin every
1728    // token to one API would get a broader token back from this grant alone,
1729    // with nothing to say which grant discarded it.
1730    #[tokio::test]
1731    async fn token_exchange_extra_params_cannot_inject_targeting_params() {
1732        // The bare request never names the parameters; the second names them as
1733        // empty strings, which are dropped from the form — neither shape may
1734        // leave an opening for an extra to fill.
1735        let requests = [
1736            TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN),
1737            TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1738                .requested_token_type("")
1739                .audience("")
1740                .resource(""),
1741        ];
1742
1743        // The keys are written out here rather than iterated from
1744        // EXCHANGE_RESERVED_PARAMS on purpose: driving the cases from the
1745        // constant under test lets a shrunk constant silently shrink the test.
1746        // Drop "audience" from it and this would stay green while `audience`
1747        // became injectable again; empty it and the body would never run at
1748        // all. The constant is pinned separately, by
1749        // exchange_reserved_params_cover_every_targeting_parameter.
1750        for request in requests {
1751            for key in ["requested_token_type", "resource", "audience"] {
1752                let server = exchange_server("exchange-impersonation-success.json").await;
1753
1754                let err = client(&format!("{}/token", server.uri()))
1755                    .extra_param(key, "https://evil.example.com")
1756                    .build()
1757                    .unwrap()
1758                    .token_exchange(&request)
1759                    .await
1760                    .expect_err("an extra param naming an owned parameter must fail");
1761
1762                match err {
1763                    IdentityError::Validation(message) => {
1764                        assert!(message.contains(key), "{key}: {message}");
1765                        assert!(message.contains("TokenExchangeRequest"), "{key}: {message}");
1766                    }
1767                    other => panic!("{key}: expected Validation, got {other:?}"),
1768                }
1769                assert!(
1770                    server.received_requests().await.unwrap().is_empty(),
1771                    "{key}: no request may be sent"
1772                );
1773            }
1774        }
1775    }
1776
1777    // Pins the constant the test above deliberately does not read. Between the
1778    // two, removing a key from EXCHANGE_RESERVED_PARAMS fails loudly here while
1779    // the injection test keeps exercising all three; order is not pinned
1780    // because it carries no meaning.
1781    #[test]
1782    fn exchange_reserved_params_cover_every_targeting_parameter() {
1783        let mut reserved = EXCHANGE_RESERVED_PARAMS.to_vec();
1784        reserved.sort_unstable();
1785        assert_eq!(reserved, ["audience", "requested_token_type", "resource"]);
1786    }
1787
1788    // ...nor override one the request did pin. Note what this test is and is
1789    // not: it is a regression guard, not coverage of EXCHANGE_RESERVED_PARAMS.
1790    // Before the collision was rejected outright this case already passed,
1791    // because do_request skips a key that is already in the form — it was green
1792    // with and without the constant. What it pins now is that agreeing with the
1793    // request does not buy an extra param a pass: the call fails, so a caller
1794    // whose client-wide extra contradicts a grant finds out.
1795    #[tokio::test]
1796    async fn token_exchange_extra_params_cannot_override_targeting_params() {
1797        let server = exchange_server("exchange-impersonation-success.json").await;
1798
1799        let err = client(&format!("{}/token", server.uri()))
1800            .extra_param("requested_token_type", TOKEN_TYPE_ID_TOKEN)
1801            .extra_param("audience", "https://evil.example.com")
1802            .extra_param("resource", "https://evil-rs.example.com")
1803            .build()
1804            .unwrap()
1805            .token_exchange(
1806                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1807                    .requested_token_type(TOKEN_TYPE_ACCESS_TOKEN)
1808                    .audience("https://api.example.com")
1809                    .resource("https://rs.example.com"),
1810            )
1811            .await
1812            .expect_err("a colliding extra param must fail even when the request pins it");
1813
1814        match err {
1815            // Keys are reported in sorted order, so "audience" is named first
1816            // every run rather than whichever the HashMap yielded first.
1817            IdentityError::Validation(message) => {
1818                assert!(message.contains("audience"), "{message}");
1819            }
1820            other => panic!("expected Validation, got {other:?}"),
1821        }
1822        assert!(
1823            server.received_requests().await.unwrap().is_empty(),
1824            "no request may be sent"
1825        );
1826    }
1827
1828    // Reserving three keys on the exchange must not become "the exchange drops
1829    // every extra": a key the grant does not own still reaches the body, next
1830    // to the targeting parameters the request itself pinned. Nothing else pins
1831    // this for the exchange path, so an over-broad guard would pass the suite.
1832    #[tokio::test]
1833    async fn token_exchange_sends_non_reserved_extra_param() {
1834        let server = exchange_server("exchange-impersonation-success.json").await;
1835
1836        client(&format!("{}/token", server.uri()))
1837            .extra_param("tenant", "t1")
1838            .build()
1839            .unwrap()
1840            .token_exchange(
1841                &TokenExchangeRequest::new("subject-tok", TOKEN_TYPE_ACCESS_TOKEN)
1842                    .audience("https://api.example.com"),
1843            )
1844            .await
1845            .expect("exchange succeeds");
1846
1847        let pairs = form_pairs(&only_request(&server).await);
1848        assert_eq!(form_all(&pairs, "tenant"), ["t1"]);
1849        assert_eq!(form_all(&pairs, "audience"), ["https://api.example.com"]);
1850    }
1851
1852    // The reserved lists are matched on a normalised key. A server whose form
1853    // parser folds case or trims whitespace reads "Audience" and " audience" as
1854    // `audience`, so an exact-byte match would hand it the very parameter the
1855    // guard claims cannot be injected.
1856    #[tokio::test]
1857    async fn token_exchange_reserved_extras_are_matched_normalised() {
1858        for key in [
1859            "Audience",
1860            " audience",
1861            "REQUESTED_TOKEN_TYPE",
1862            "\tresource ",
1863        ] {
1864            let server = exchange_server("exchange-impersonation-success.json").await;
1865
1866            let err = client(&format!("{}/token", server.uri()))
1867                .extra_param(key, "https://evil.example.com")
1868                .build()
1869                .unwrap()
1870                .token_exchange(&TokenExchangeRequest::new(
1871                    "subject-tok",
1872                    TOKEN_TYPE_ACCESS_TOKEN,
1873                ))
1874                .await
1875                .expect_err("a case- or whitespace-variant reserved key must fail");
1876
1877            assert!(
1878                matches!(err, IdentityError::Validation(_)),
1879                "{key:?}: {err:?}"
1880            );
1881            assert!(
1882                server.received_requests().await.unwrap().is_empty(),
1883                "{key:?}: no request may be sent"
1884            );
1885        }
1886    }
1887
1888    // The same normalisation covers RESERVED_PARAMS, which every grant applies:
1889    // a variant spelling must not reach the body, where a case-folding or
1890    // trimming server would read it as the reserved parameter it imitates.
1891    #[tokio::test]
1892    async fn reserved_extras_are_matched_normalised() {
1893        let server = MockServer::start().await;
1894        mount_token(
1895            &server,
1896            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
1897        )
1898        .await;
1899
1900        client(&format!("{}/token", server.uri()))
1901            .extra_param("Grant_Type", "evil-grant")
1902            .extra_param(" scope", "evil-scope")
1903            .extra_param("CLIENT_ID", "evil-client")
1904            .build()
1905            .unwrap()
1906            .client_credentials(None)
1907            .await
1908            .expect("grant succeeds");
1909
1910        let pairs = form_pairs(&only_request(&server).await);
1911        assert_eq!(form_all(&pairs, "grant_type"), ["client_credentials"]);
1912        for key in [
1913            "Grant_Type",
1914            " scope",
1915            "CLIENT_ID",
1916            "scope",
1917            "client_id",
1918            "client_secret",
1919        ] {
1920            assert!(
1921                form_all(&pairs, key).is_empty(),
1922                "{key:?} must not be sent: {pairs:?}"
1923            );
1924        }
1925    }
1926
1927    // The `grant_reserved` arm of the do_request skip is the one arm no public
1928    // caller can reach: token_exchange — the only grant that passes a non-empty
1929    // list — rejects a colliding extra param outright, and the other two pass
1930    // `&[]`, so the arm never decides anything the suite above can observe.
1931    // That is why it is exercised here by calling do_request directly. Left to
1932    // the public API, weakening the skip to
1933    // `reserved || (grant_reserved && already_in_form)` keeps every other test
1934    // green while gutting the arm for exactly the case the list exists for: a
1935    // grant-owned parameter the request left unset is in no form to collide
1936    // with, so `already_in_form` is false and the extra would be appended to
1937    // the wire — silently retargeting the exchange at another resource server,
1938    // which is what reserving the key was for. Sending `audience` as a
1939    // client-wide extra is legitimate on the grants that do not own it, and
1940    // client_credentials_still_allows_targeting_extra_params pins that, so the
1941    // drop has to be keyed on the grant rather than on the key alone.
1942    #[tokio::test]
1943    async fn grant_reserved_extra_absent_from_the_form_is_dropped() {
1944        let server = MockServer::start().await;
1945        mount_token(
1946            &server,
1947            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
1948        )
1949        .await;
1950
1951        let token_client = client(&format!("{}/token", server.uri()))
1952            .extra_param("audience", "https://evil.example.com")
1953            .extra_param("tenant", "t1")
1954            .build()
1955            .unwrap();
1956
1957        // The form deliberately carries no `audience` — the exchange omits an
1958        // empty one — so the "already in the form" arm cannot stand in for the
1959        // grant_reserved arm under test.
1960        token_client
1961            .do_request(
1962                vec![("grant_type".to_string(), GRANT_TOKEN_EXCHANGE.to_string())],
1963                token_client.client_secret.as_deref(),
1964                EXCHANGE_RESERVED_PARAMS,
1965            )
1966            .await
1967            .expect("request succeeds");
1968
1969        let pairs = form_pairs(&only_request(&server).await);
1970        assert!(
1971            form_all(&pairs, "audience").is_empty(),
1972            "a grant-reserved extra the form does not already carry must not be \
1973             sent at all: {pairs:?}"
1974        );
1975        // Positive control: extras are applied on this very call, so the
1976        // assertion above cannot pass merely because none were.
1977        assert_eq!(form_all(&pairs, "tenant"), ["t1"]);
1978        assert_eq!(form_all(&pairs, "grant_type"), [GRANT_TOKEN_EXCHANGE]);
1979    }
1980
1981    // Regression guard for the documented rationale, not coverage of
1982    // EXCHANGE_RESERVED_PARAMS: this passed before the constant existed too,
1983    // when client credentials had no grant_reserved list at all. What it guards
1984    // is the `&[]` this grant passes to do_request — the three targeting
1985    // parameters are reserved on the EXCHANGE path only, and a grant that does
1986    // not model them (client credentials has no RFC 8707 resource of its own)
1987    // must still be able to send them as extras. It fails if someone widens the
1988    // reservation to every grant.
1989    #[tokio::test]
1990    async fn client_credentials_still_allows_targeting_extra_params() {
1991        let server = MockServer::start().await;
1992        mount_token(
1993            &server,
1994            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
1995        )
1996        .await;
1997
1998        client(&format!("{}/token", server.uri()))
1999            .extra_param("resource", "https://rs.example.com")
2000            .extra_param("audience", "https://api.example.com")
2001            .extra_param("requested_token_type", TOKEN_TYPE_ACCESS_TOKEN)
2002            .build()
2003            .unwrap()
2004            .client_credentials(None)
2005            .await
2006            .expect("grant succeeds");
2007
2008        let pairs = form_pairs(&only_request(&server).await);
2009        assert_eq!(form_all(&pairs, "resource"), ["https://rs.example.com"]);
2010        assert_eq!(form_all(&pairs, "audience"), ["https://api.example.com"]);
2011        assert_eq!(
2012            form_all(&pairs, "requested_token_type"),
2013            [TOKEN_TYPE_ACCESS_TOKEN]
2014        );
2015    }
2016
2017    // Mirror image of the test above for the third grant_reserved call site.
2018    // exchange_code passes `&[]` as well and nothing else pins it: handing it
2019    // EXCHANGE_RESERVED_PARAMS by mistake would silently drop an RFC 8707
2020    // `resource` or `audience` from the authorization code grant, and every
2021    // other test in the suite would stay green.
2022    #[tokio::test]
2023    async fn exchange_code_still_allows_targeting_extra_params() {
2024        let server = MockServer::start().await;
2025        mount_token(
2026            &server,
2027            ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
2028        )
2029        .await;
2030
2031        client(&format!("{}/token", server.uri()))
2032            .extra_param("resource", "https://rs.example.com")
2033            .extra_param("audience", "https://api.example.com")
2034            .extra_param("requested_token_type", TOKEN_TYPE_ACCESS_TOKEN)
2035            .build()
2036            .unwrap()
2037            .exchange_code("auth-code-1", "https://app.example/cb", None)
2038            .await
2039            .expect("grant succeeds");
2040
2041        let pairs = form_pairs(&only_request(&server).await);
2042        assert_eq!(form_all(&pairs, "resource"), ["https://rs.example.com"]);
2043        assert_eq!(form_all(&pairs, "audience"), ["https://api.example.com"]);
2044        assert_eq!(
2045            form_all(&pairs, "requested_token_type"),
2046            [TOKEN_TYPE_ACCESS_TOKEN]
2047        );
2048    }
2049
2050    // The issued_token_type is a modelled field, so it must not also be left
2051    // sitting in `extra` where a caller could read a stale duplicate.
2052    #[tokio::test]
2053    async fn token_exchange_issued_token_type_is_not_duplicated_in_extra() {
2054        let server = exchange_server("exchange-impersonation-success.json").await;
2055
2056        let issued = exchange_client(&server)
2057            .token_exchange(&TokenExchangeRequest::new(
2058                "subject-tok",
2059                TOKEN_TYPE_ACCESS_TOKEN,
2060            ))
2061            .await
2062            .expect("exchange succeeds");
2063
2064        assert!(
2065            !issued.extra.contains_key("issued_token_type"),
2066            "{:?}",
2067            issued.extra
2068        );
2069    }
2070}