rs-identity-model 0.3.2

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
//! Token endpoint client: client credentials, authorization code, PKCE.
//!
//! [`TokenClient`] performs the OAuth 2.0 client credentials grant
//! (RFC 6749 §4.4) and the authorization code grant (RFC 6749 §4.1.3), the
//! latter with optional PKCE (RFC 7636). 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`) and `spec/vectors/authorization-code.json`
//! (`ACG-001`..`ACG-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 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 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";

/// 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. 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.
const RESERVED_PARAMS: &[&str] = &[
    "grant_type",
    "client_id",
    "client_secret",
    "code",
    "redirect_uri",
    "code_verifier",
    "scope",
];

/// 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
    }

    /// 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).
    async fn do_request(
        &self,
        mut form: Vec<(String, String)>,
        client_secret: Option<&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 {
            if RESERVED_PARAMS.contains(&key.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. `resource` or `audience`). Reserved grant/auth parameters are
    /// never overridden.
    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"));
    }
}