rs-identity-model 0.6.0

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
//! OAuth 2.0 Token Revocation (RFC 7009).
//!
//! Revoking a token tells the authorization server to invalidate it and, at the
//! server's discretion, related tokens issued from the same grant. The request
//! is a client-authenticated `application/x-www-form-urlencoded` POST carrying
//! the `token` to revoke and an optional `token_type_hint`.
//!
//! ## The response tells you nothing about the token
//!
//! RFC 7009 §2.2 requires the server to answer HTTP 200 whether the token was
//! valid, already expired, already revoked, or never existed. That is a privacy
//! property, not an oversight: a response that differed would let an attacker
//! probe the endpoint to learn which token values are live. This client mirrors
//! it — [`RevocationClient::revoke`] returns `Ok(())` for any 200, and callers
//! must not read success as evidence that the token existed (`REV-001`).
//!
//! ## Example
//!
//! ```no_run
//! # use rs_identity_model::revocation::RevocationClient;
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let client = RevocationClient::builder()
//!     .client_id("my-client")
//!     .client_secret("my-secret")
//!     .revocation_endpoint("https://issuer.example.com/oauth2/revoke")
//!     .build()?;
//!
//! client.revoke("the-token", Some("refresh_token")).await?;
//! # Ok(())
//! # }
//! ```
//!
//! Conformance: `spec/vectors/revocation.json` (`REV-001` … `REV-005`).

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::token::ClientAuthMethod;
use crate::{IdentityError, Result};

/// 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.
const REDACTED: &str = "<redacted>";

/// Form parameters owned by the request and client-authentication logic. They
/// can never be set or overridden via [`RevocationClientBuilder::extra_param`],
/// so caller-supplied extras cannot contradict the request's identity or the
/// token being revoked.
const RESERVED_PARAMS: &[&str] = &["token", "token_type_hint", "client_id", "client_secret"];

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

impl std::fmt::Debug for RevocationClient {
    /// Redacts `client_secret` so a client cannot leak credentials into logs.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RevocationClient")
            .field("revocation_endpoint", &self.revocation_endpoint)
            .field("client_id", &self.client_id)
            .field("client_secret", &REDACTED)
            .field("auth_method", &self.auth_method)
            .field("extra_params", &self.extra_params)
            .field("timeout", &self.timeout)
            .field("allow_http", &self.allow_http)
            .finish()
    }
}

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

    /// Revokes a token (RFC 7009 §2.1, `REV-001`).
    ///
    /// POSTs `token` to the revocation endpoint as
    /// `application/x-www-form-urlencoded` and authenticates the client.
    ///
    /// `token_type_hint` is the optional `token_type_hint` parameter, typically
    /// `"access_token"` or `"refresh_token"` (`REV-002`). The server MAY use it
    /// to optimise lookup but MUST still accept the request if it is wrong, so
    /// an incorrect hint is not an error. Pass `None` (or an empty string) to
    /// omit it.
    ///
    /// # Success says nothing about the token
    ///
    /// Any HTTP 200 yields `Ok(())`, whether the body is empty or an empty JSON
    /// object, and regardless of whether the token was valid, expired, already
    /// revoked, or unknown (RFC 7009 §2.2). Treating `Ok(())` as proof the token
    /// existed would reintroduce exactly the token-scanning oracle the RFC
    /// closes.
    ///
    /// # Errors
    ///
    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response, such
    ///   as HTTP 400 `unsupported_token_type` (`REV-003`) or HTTP 401
    ///   `invalid_client` (`REV-004`).
    /// - [`IdentityError::Http`] — a transport failure or a non-OAuth error body.
    /// - [`IdentityError::Configuration`] — a non-https endpoint without
    ///   `allow_http`.
    pub async fn revoke(&self, token: &str, token_type_hint: Option<&str>) -> Result<()> {
        // Require an https endpoint unless http was explicitly allowed. The
        // token is in the request body, so a cleartext post would disclose it.
        let scheme = self.revocation_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!(
                "revocation endpoint {:?} must use https (enable allow_http for development)",
                self.revocation_endpoint
            )));
        }

        let mut form: Vec<(String, String)> = vec![("token".to_string(), token.to_string())];
        // token_type_hint is optional; an empty hint is treated as unset.
        if let Some(hint) = token_type_hint
            && !hint.is_empty()
        {
            form.push(("token_type_hint".to_string(), hint.to_string()));
        }

        // Client authentication (RFC 7009 §2.1, RFC 6749 §2.3). A Basic header
        // is built for the request; post credentials go in the form body. The
        // builder guarantees both credentials are non-empty.
        let mut basic_header: Option<String> = None;
        match self.auth_method {
            ClientAuthMethod::ClientSecretPost => {
                form.push(("client_id".to_string(), self.client_id.clone()));
                form.push(("client_secret".to_string(), self.client_secret.clone()));
            }
            ClientAuthMethod::ClientSecretBasic => {
                basic_header = Some(basic_auth_header(&self.client_id, &self.client_secret));
            }
        }

        // Extra params are applied last but never override reserved request 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.revocation_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.revocation_endpoint)))?;

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

        // A 200 is success regardless of body content (RFC 7009 §2.2). The body
        // is deliberately not parsed: servers send an empty body, an empty JSON
        // object, or occasionally whitespace, and none of it carries meaning.
        if status.is_success() {
            return Ok(());
        }

        // Non-2xx is an OAuth error (RFC 7009 §2.2.1, RFC 6749 §5.2) —
        // REV-003 unsupported_token_type, REV-004 invalid_client.
        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(),
            });
        }
        Err(IdentityError::Http(format!(
            "revocation request to {} failed: HTTP {} with non-OAuth body: {}",
            self.revocation_endpoint,
            status.as_u16(),
            body_snippet(&body)
        )))
    }
}

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

impl std::fmt::Debug for RevocationClientBuilder {
    /// Redacts `client_secret` so a half-built client cannot leak credentials.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RevocationClientBuilder")
            .field("revocation_endpoint", &self.revocation_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()
    }
}

impl RevocationClientBuilder {
    /// Creates an empty builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the OAuth 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 OAuth client secret. Required — RFC 7009 §2.1 requires the
    /// revocation endpoint to authenticate the client.
    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client_secret = Some(client_secret.into());
        self
    }

    /// Sets the revocation endpoint URL. Required.
    ///
    /// This is the `revocation_endpoint` member of the authorization server's
    /// metadata document (RFC 8414 §2, `REV-005`), so it can be taken straight
    /// from [`crate::discovery::ProviderMetadata::revocation_endpoint`] rather
    /// than configured by hand.
    pub fn revocation_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.revocation_endpoint = Some(endpoint.into());
        self
    }

    /// Selects the client-authentication method. Defaults to
    /// `client_secret_basic`.
    pub fn auth_method(mut self, method: ClientAuthMethod) -> Self {
        self.auth_method = method;
        self
    }

    /// Adds one extra form parameter. Reserved parameters are ignored — see
    /// [`RevocationClient::revoke`].
    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 several extra form parameters.
    pub fn extra_params(mut self, params: HashMap<String, String>) -> Self {
        self.extra_params.extend(params);
        self
    }

    /// Supplies a pre-configured HTTP client. Defaults to the crate's secure
    /// client, which refuses https-to-http redirect downgrades.
    pub fn http_client(mut self, client: HttpClient) -> Self {
        self.http = Some(client);
        self
    }

    /// Sets the per-request timeout. Zero means the 30-second default.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Permits a plain-http revocation endpoint. Development only: the token
    /// being revoked travels in the request body.
    pub fn allow_http(mut self, allow: bool) -> Self {
        self.allow_http = allow;
        self
    }

    /// Builds the client.
    ///
    /// # Errors
    ///
    /// [`IdentityError::Configuration`] if `client_id`, `client_secret`, or
    /// `revocation_endpoint` is missing or empty.
    pub fn build(self) -> Result<RevocationClient> {
        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 client_secret = self.client_secret.unwrap_or_default();
        if client_secret.is_empty() {
            return Err(IdentityError::Configuration(
                "client_secret is required: the revocation endpoint requires client authentication with both client_id and client_secret (RFC 7009 §2.1)"
                    .to_string(),
            ));
        }
        let revocation_endpoint = self.revocation_endpoint.unwrap_or_default();
        if revocation_endpoint.is_empty() {
            return Err(IdentityError::Configuration(
                "revocation_endpoint is required".to_string(),
            ));
        }
        Ok(RevocationClient {
            http: self.http.unwrap_or_else(crate::http::secure_client),
            revocation_endpoint,
            client_id,
            client_secret,
            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 crate::ProviderMetadata;
    use wiremock::matchers::{header, header_exists, method, path};
    use wiremock::{Mock, MockServer, Request, ResponseTemplate};

    /// 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) -> RevocationClientBuilder {
        RevocationClient::builder()
            .client_id("rs-client")
            .client_secret("rs-secret")
            .revocation_endpoint(endpoint)
            .allow_http(true)
    }

    async fn mount(server: &MockServer, template: ResponseTemplate) {
        Mock::given(method("POST"))
            .and(path("/revoke"))
            .respond_with(template)
            .mount(server)
            .await;
    }

    // REV-001: a 200 with an empty body is success, and the request is a POST
    // carrying `token` as form-encoded content.
    #[tokio::test]
    async fn revoke_posts_token_and_succeeds_on_empty_200() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect("empty 200 is success");

        let req = &server.received_requests().await.unwrap()[0];
        assert_eq!(req.method.as_str(), "POST");
        let form = form_of(req);
        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
        assert!(!form.contains_key("token_type_hint"));
    }

    // REV-001: an empty JSON object is equally a success. Some servers send
    // `{}` rather than a zero-length body; neither carries meaning.
    #[tokio::test]
    async fn empty_json_object_body_is_success() {
        let server = MockServer::start().await;
        mount(
            &server,
            ResponseTemplate::new(200).set_body_raw("{}", "application/json"),
        )
        .await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect("empty JSON object is success");
    }

    // REV-001, the privacy property: the result MUST NOT differ between a valid
    // token and an expired, already-revoked, or entirely unknown one. If this
    // ever regresses, the endpoint becomes a token-scanning oracle.
    #[tokio::test]
    async fn response_is_identical_for_unknown_and_valid_tokens() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;
        let endpoint = format!("{}/revoke", server.uri());
        let c = client(&endpoint).build().unwrap();

        for token in ["a-live-token", "an-expired-token", "never-existed-at-all"] {
            assert!(
                c.revoke(token, None).await.is_ok(),
                "revoking {token:?} must be indistinguishable from any other token"
            );
        }
    }

    // REV-002: the hint is sent as token_type_hint, alongside token.
    #[tokio::test]
    async fn token_type_hint_is_sent() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", Some("refresh_token"))
            .await
            .unwrap();

        let form = form_of(&server.received_requests().await.unwrap()[0]);
        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
        assert_eq!(
            form.get("token_type_hint").map(String::as_str),
            Some("refresh_token")
        );
    }

    // REV-002: an empty hint is treated as unset rather than sent blank.
    #[tokio::test]
    async fn empty_hint_is_omitted() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", Some(""))
            .await
            .unwrap();

        let form = form_of(&server.received_requests().await.unwrap()[0]);
        assert!(!form.contains_key("token_type_hint"));
    }

    // REV-002: a wrong hint MUST NOT fail the request — the server may ignore
    // it and revoke anyway.
    #[tokio::test]
    async fn incorrect_hint_still_succeeds() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .build()
            .unwrap()
            .revoke("an-access-token", Some("refresh_token"))
            .await
            .expect("an incorrect hint must not fail the request");
    }

    // REV-003: HTTP 400 unsupported_token_type surfaces as a typed error
    // carrying the code, description, uri, and status.
    #[tokio::test]
    async fn unsupported_token_type_is_typed() {
        let server = MockServer::start().await;
        mount(
            &server,
            ResponseTemplate::new(400).set_body_raw(
                r#"{"error":"unsupported_token_type","error_description":"cannot revoke this type","error_uri":"https://issuer.example/e"}"#,
                "application/json",
            ),
        )
        .await;

        let endpoint = format!("{}/revoke", server.uri());
        let err = client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect_err("400 must surface as an error");

        match err {
            IdentityError::TokenEndpoint {
                error,
                description,
                error_uri,
                status,
            } => {
                assert_eq!(error, "unsupported_token_type");
                assert_eq!(description.as_deref(), Some("cannot revoke this type"));
                assert_eq!(error_uri.as_deref(), Some("https://issuer.example/e"));
                assert_eq!(status, 400);
            }
            other => panic!("expected TokenEndpoint, got {other:?}"),
        }
    }

    // REV-004: HTTP 401 invalid_client surfaces as a typed error.
    #[tokio::test]
    async fn invalid_client_is_typed() {
        let server = MockServer::start().await;
        mount(
            &server,
            ResponseTemplate::new(401)
                .set_body_raw(r#"{"error":"invalid_client"}"#, "application/json"),
        )
        .await;

        let endpoint = format!("{}/revoke", server.uri());
        let err = client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect_err("401 must surface as an error");

        match err {
            IdentityError::TokenEndpoint { error, status, .. } => {
                assert_eq!(error, "invalid_client");
                assert_eq!(status, 401);
            }
            other => panic!("expected TokenEndpoint, got {other:?}"),
        }
    }

    // REV-005: the endpoint comes straight off the discovery document.
    #[tokio::test]
    async fn endpoint_resolves_from_discovery() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;
        let endpoint = format!("{}/revoke", server.uri());

        let metadata: ProviderMetadata = serde_json::from_str(&format!(
            r#"{{"issuer":"{}","revocation_endpoint":"{}"}}"#,
            server.uri(),
            endpoint
        ))
        .expect("metadata parses");

        let resolved = metadata
            .revocation_endpoint
            .as_deref()
            .expect("revocation_endpoint present in discovery");
        assert_eq!(resolved, endpoint);

        client(resolved)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect("discovery-resolved endpoint works");
    }

    // client_secret_basic is the default and sends an Authorization header
    // rather than credentials in the body.
    #[tokio::test]
    async fn client_secret_basic_is_default() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/revoke"))
            .and(header_exists(AUTHORIZATION))
            .and(header(CONTENT_TYPE, "application/x-www-form-urlencoded"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&server)
            .await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .unwrap();

        let form = form_of(&server.received_requests().await.unwrap()[0]);
        assert!(!form.contains_key("client_secret"));
    }

    // client_secret_post places credentials in the body instead.
    #[tokio::test]
    async fn client_secret_post_uses_body() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .auth_method(ClientAuthMethod::ClientSecretPost)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .unwrap();

        let req = &server.received_requests().await.unwrap()[0];
        assert!(req.headers.get(AUTHORIZATION).is_none());
        let form = form_of(req);
        assert_eq!(form.get("client_id").map(String::as_str), Some("rs-client"));
        assert_eq!(
            form.get("client_secret").map(String::as_str),
            Some("rs-secret")
        );
    }

    // Extra params cannot overwrite the token, the hint, or client credentials
    // — on the Basic path client_id is absent from the body and must stay so.
    #[tokio::test]
    async fn extra_params_cannot_override_reserved() {
        let server = MockServer::start().await;
        mount(&server, ResponseTemplate::new(200)).await;

        let endpoint = format!("{}/revoke", server.uri());
        client(&endpoint)
            .extra_param("token", "attacker-token")
            .extra_param("client_id", "attacker")
            .extra_param("resource", "https://api.example")
            .build()
            .unwrap()
            .revoke("tok-1", Some("access_token"))
            .await
            .unwrap();

        let form = form_of(&server.received_requests().await.unwrap()[0]);
        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
        assert!(!form.contains_key("client_id"));
        assert_eq!(
            form.get("resource").map(String::as_str),
            Some("https://api.example")
        );
    }

    // A non-OAuth error body still fails, but as a transport-level error that
    // quotes a snippet rather than pretending it parsed.
    #[tokio::test]
    async fn non_oauth_error_body_is_http_error() {
        let server = MockServer::start().await;
        mount(
            &server,
            ResponseTemplate::new(500).set_body_raw("<html>boom</html>", "text/html"),
        )
        .await;

        let endpoint = format!("{}/revoke", server.uri());
        let err = client(&endpoint)
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect_err("500 must fail");
        assert!(matches!(err, IdentityError::Http(_)), "got {err:?}");
    }

    // A plain-http endpoint is refused unless allow_http was set: the token
    // travels in the body.
    #[tokio::test]
    async fn http_endpoint_refused_without_allow_http() {
        let err = RevocationClient::builder()
            .client_id("rs-client")
            .client_secret("rs-secret")
            .revocation_endpoint("http://issuer.example/revoke")
            .build()
            .unwrap()
            .revoke("tok-1", None)
            .await
            .expect_err("plain http must be refused");
        assert!(
            matches!(err, IdentityError::Configuration(_)),
            "got {err:?}"
        );
    }

    #[test]
    fn build_requires_credentials_and_endpoint() {
        assert!(RevocationClient::builder().build().is_err());
        assert!(
            RevocationClient::builder()
                .client_id("id")
                .revocation_endpoint("https://e/revoke")
                .build()
                .is_err(),
            "client_secret is required"
        );
        assert!(
            RevocationClient::builder()
                .client_id("id")
                .client_secret("s")
                .build()
                .is_err(),
            "revocation_endpoint is required"
        );
    }

    #[test]
    fn debug_redacts_client_secret() {
        let c = RevocationClient::builder()
            .client_id("rs-client")
            .client_secret("super-secret")
            .revocation_endpoint("https://issuer.example/revoke")
            .build()
            .unwrap();
        let rendered = format!("{c:?}");
        assert!(!rendered.contains("super-secret"), "{rendered}");
        assert!(rendered.contains(REDACTED));

        let b = RevocationClient::builder().client_secret("super-secret");
        assert!(!format!("{b:?}").contains("super-secret"));
    }
}