Skip to main content

rs_identity_model/revocation/
mod.rs

1//! OAuth 2.0 Token Revocation (RFC 7009).
2//!
3//! Revoking a token tells the authorization server to invalidate it and, at the
4//! server's discretion, related tokens issued from the same grant. The request
5//! is a client-authenticated `application/x-www-form-urlencoded` POST carrying
6//! the `token` to revoke and an optional `token_type_hint`.
7//!
8//! ## The response tells you nothing about the token
9//!
10//! RFC 7009 §2.2 requires the server to answer HTTP 200 whether the token was
11//! valid, already expired, already revoked, or never existed. That is a privacy
12//! property, not an oversight: a response that differed would let an attacker
13//! probe the endpoint to learn which token values are live. This client mirrors
14//! it — [`RevocationClient::revoke`] returns `Ok(())` for any 200, and callers
15//! must not read success as evidence that the token existed (`REV-001`).
16//!
17//! ## Example
18//!
19//! ```no_run
20//! # use rs_identity_model::revocation::RevocationClient;
21//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
22//! let client = RevocationClient::builder()
23//!     .client_id("my-client")
24//!     .client_secret("my-secret")
25//!     .revocation_endpoint("https://issuer.example.com/oauth2/revoke")
26//!     .build()?;
27//!
28//! client.revoke("the-token", Some("refresh_token")).await?;
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! Conformance: `spec/vectors/revocation.json` (`REV-001` … `REV-005`).
34
35use std::collections::HashMap;
36use std::time::Duration;
37
38use reqwest::Client as HttpClient;
39use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
40
41use crate::client_auth::{OAuthErrorBody, basic_auth_header, body_snippet, read_capped_body};
42use crate::token::ClientAuthMethod;
43use crate::{IdentityError, Result};
44
45/// Default per-request timeout so a hung endpoint cannot block indefinitely.
46const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
47
48/// Placeholder printed in place of secret material in `Debug` output.
49const REDACTED: &str = "<redacted>";
50
51/// Form parameters owned by the request and client-authentication logic. They
52/// can never be set or overridden via [`RevocationClientBuilder::extra_param`],
53/// so caller-supplied extras cannot contradict the request's identity or the
54/// token being revoked.
55const RESERVED_PARAMS: &[&str] = &["token", "token_type_hint", "client_id", "client_secret"];
56
57/// An async OAuth 2.0 token revocation client (RFC 7009).
58///
59/// Construct one with [`RevocationClient::builder`]. A single client should be
60/// reused across calls so the underlying connection pool is shared.
61pub struct RevocationClient {
62    http: HttpClient,
63    revocation_endpoint: String,
64    client_id: String,
65    client_secret: String,
66    auth_method: ClientAuthMethod,
67    extra_params: HashMap<String, String>,
68    timeout: Duration,
69    allow_http: bool,
70}
71
72impl std::fmt::Debug for RevocationClient {
73    /// Redacts `client_secret` so a client cannot leak credentials into logs.
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.debug_struct("RevocationClient")
76            .field("revocation_endpoint", &self.revocation_endpoint)
77            .field("client_id", &self.client_id)
78            .field("client_secret", &REDACTED)
79            .field("auth_method", &self.auth_method)
80            // Keys only: a caller may park a client_assertion or other bearer
81            // material in an extra param, and Debug output reaches logs.
82            .field(
83                "extra_params",
84                &self.extra_params.keys().collect::<Vec<_>>(),
85            )
86            .field("timeout", &self.timeout)
87            .field("allow_http", &self.allow_http)
88            .finish()
89    }
90}
91
92impl RevocationClient {
93    /// Returns a builder for configuring a [`RevocationClient`].
94    pub fn builder() -> RevocationClientBuilder {
95        RevocationClientBuilder::new()
96    }
97
98    /// Revokes a token (RFC 7009 §2.1, `REV-001`).
99    ///
100    /// POSTs `token` to the revocation endpoint as
101    /// `application/x-www-form-urlencoded` and authenticates the client.
102    ///
103    /// `token_type_hint` is the optional `token_type_hint` parameter, typically
104    /// `"access_token"` or `"refresh_token"` (`REV-002`). The server MAY use it
105    /// to optimise lookup but MUST still accept the request if it is wrong, so
106    /// an incorrect hint is not an error. Pass `None` (or an empty string) to
107    /// omit it.
108    ///
109    /// # Success says nothing about the token
110    ///
111    /// Any HTTP 200 yields `Ok(())`, whether the body is empty or an empty JSON
112    /// object, and regardless of whether the token was valid, expired, already
113    /// revoked, or unknown (RFC 7009 §2.2). Treating `Ok(())` as proof the token
114    /// existed would reintroduce exactly the token-scanning oracle the RFC
115    /// closes.
116    ///
117    /// # Errors
118    ///
119    /// - [`IdentityError::TokenEndpoint`] — a non-2xx OAuth error response, such
120    ///   as HTTP 400 `unsupported_token_type` (`REV-003`) or HTTP 401
121    ///   `invalid_client` (`REV-004`).
122    /// - [`IdentityError::Http`] — a transport failure or a non-OAuth error body.
123    /// - [`IdentityError::Configuration`] — a non-https endpoint without
124    ///   `allow_http`.
125    pub async fn revoke(&self, token: &str, token_type_hint: Option<&str>) -> Result<()> {
126        // An empty token is a caller bug, not a revocation. RFC 7009 §2.1 makes
127        // `token` REQUIRED, and a server that treats "" as simply unknown answers
128        // 200 (§2.2) — so posting it would hand the caller Ok(()) for a request
129        // that revoked nothing. Fail here rather than let that read as success.
130        if token.is_empty() {
131            return Err(IdentityError::Configuration(
132                "token is required: refusing to send an empty revocation request, which a server would answer 200 and the caller would read as a successful revocation"
133                    .to_string(),
134            ));
135        }
136
137        // Require an https endpoint unless http was explicitly allowed. The
138        // token is in the request body, so a cleartext post would disclose it.
139        let scheme = self.revocation_endpoint.to_ascii_lowercase();
140        let scheme_ok =
141            scheme.starts_with("https://") || (self.allow_http && scheme.starts_with("http://"));
142        if !scheme_ok {
143            return Err(IdentityError::Configuration(format!(
144                "revocation endpoint {:?} must use https (enable allow_http for development)",
145                self.revocation_endpoint
146            )));
147        }
148
149        let mut form: Vec<(String, String)> = vec![("token".to_string(), token.to_string())];
150        // token_type_hint is optional; an empty hint is treated as unset.
151        if let Some(hint) = token_type_hint
152            && !hint.is_empty()
153        {
154            form.push(("token_type_hint".to_string(), hint.to_string()));
155        }
156
157        // Client authentication (RFC 7009 §2.1, RFC 6749 §2.3). A Basic header
158        // is built for the request; post credentials go in the form body. The
159        // builder guarantees both credentials are non-empty.
160        let mut basic_header: Option<String> = None;
161        match self.auth_method {
162            ClientAuthMethod::ClientSecretPost => {
163                form.push(("client_id".to_string(), self.client_id.clone()));
164                form.push(("client_secret".to_string(), self.client_secret.clone()));
165            }
166            ClientAuthMethod::ClientSecretBasic => {
167                basic_header = Some(basic_auth_header(&self.client_id, &self.client_secret));
168            }
169        }
170
171        // Extra params are applied last but never override reserved request or
172        // client-auth parameters (whether or not already present — on the Basic
173        // path client_id is absent from the body yet must not be injectable).
174        for (key, value) in &self.extra_params {
175            // Case-insensitive on a trimmed key. An exact match would let
176            // `Token` or `token ` through, and a server whose form parser folds
177            // case (ASP.NET Core's IFormCollection is OrdinalIgnoreCase) then
178            // joins the duplicates into "<real>,x", matches no stored token, and
179            // returns the anti-scanning 200 — so every revocation silently stops
180            // revoking while still reporting success.
181            let normalised = key.trim().to_ascii_lowercase();
182            if RESERVED_PARAMS.contains(&normalised.as_str())
183                || form
184                    .iter()
185                    .any(|(k, _)| k.eq_ignore_ascii_case(normalised.trim()))
186            {
187                continue;
188            }
189            form.push((key.clone(), value.clone()));
190        }
191
192        let mut request = self
193            .http
194            .post(&self.revocation_endpoint)
195            .timeout(self.timeout)
196            .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
197            .header(ACCEPT, "application/json")
198            .form(&form);
199        if let Some(header) = basic_header {
200            request = request.header(AUTHORIZATION, header);
201        }
202
203        let response = request
204            .send()
205            .await
206            .map_err(|e| IdentityError::Http(format!("post {}: {e}", self.revocation_endpoint)))?;
207
208        // reqwest fixes its redirect policy at client-build time, so unlike the
209        // Go reference — which copies the caller's client and sets CheckRedirect
210        // per request — we cannot impose a policy on a client supplied via
211        // `http_client`. Compare the response's final URL against the configured
212        // endpoint instead: if they differ, a redirect was followed. On a
213        // 301/302/303 the body was dropped and this 2xx means nothing; on a
214        // 307/308 the token (and `client_secret` on the post path) has already
215        // been replayed to that host. Detection is all that is available at that
216        // point, and it is strictly better than returning Ok. The default client
217        // follows nothing, so this only fires for caller-supplied clients.
218        if response.url().as_str() != self.revocation_endpoint.as_str() {
219            return Err(IdentityError::Http(format!(
220                "revocation request to {} was redirected to a different URL; refusing to treat the result as a revocation. \
221                 The token travels in the request body, so a followed redirect either dropped it or replayed it to another host. \
222                 Supply a client with a no-redirect policy (the default client already has one).",
223                self.revocation_endpoint
224            )));
225        }
226
227        let status = response.status();
228
229        // A 2xx is success regardless of body content (RFC 7009 §2.2), so return
230        // before touching the body. Reading it first would let a truncated
231        // chunked response or a connection reset — both common on endpoints that
232        // answer 200 and immediately close — turn a revocation the server has
233        // already performed into an Err, telling the caller the token is still
234        // live. The body carries no meaning on success: servers send nothing, an
235        // empty JSON object, or whitespace.
236        if status.is_success() {
237            return Ok(());
238        }
239
240        // Only an error response is worth reading.
241        let body = read_capped_body(response).await?;
242
243        // Non-2xx is an OAuth error (RFC 7009 §2.2.1, RFC 6749 §5.2) —
244        // REV-003 unsupported_token_type, REV-004 invalid_client.
245        if let Ok(err) = serde_json::from_slice::<OAuthErrorBody>(&body)
246            && !err.error.is_empty()
247        {
248            return Err(IdentityError::TokenEndpoint {
249                error: err.error,
250                description: err.error_description,
251                error_uri: err.error_uri,
252                status: status.as_u16(),
253            });
254        }
255        Err(IdentityError::Http(format!(
256            "revocation request to {} failed: HTTP {} with non-OAuth body: {}",
257            self.revocation_endpoint,
258            status.as_u16(),
259            body_snippet(&body)
260        )))
261    }
262}
263
264/// Builder for [`RevocationClient`]. Obtain one via
265/// [`RevocationClient::builder`].
266#[derive(Default)]
267pub struct RevocationClientBuilder {
268    http: Option<HttpClient>,
269    revocation_endpoint: Option<String>,
270    client_id: Option<String>,
271    client_secret: Option<String>,
272    auth_method: ClientAuthMethod,
273    extra_params: HashMap<String, String>,
274    timeout: Duration,
275    allow_http: bool,
276}
277
278impl std::fmt::Debug for RevocationClientBuilder {
279    /// Redacts `client_secret` so a half-built client cannot leak credentials.
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        f.debug_struct("RevocationClientBuilder")
282            .field("revocation_endpoint", &self.revocation_endpoint)
283            .field("client_id", &self.client_id)
284            .field(
285                "client_secret",
286                &self.client_secret.as_ref().map(|_| REDACTED),
287            )
288            .field("auth_method", &self.auth_method)
289            // Keys only: a caller may park a client_assertion or other bearer
290            // material in an extra param, and Debug output reaches logs.
291            .field(
292                "extra_params",
293                &self.extra_params.keys().collect::<Vec<_>>(),
294            )
295            .field("timeout", &self.timeout)
296            .field("allow_http", &self.allow_http)
297            .finish()
298    }
299}
300
301impl RevocationClientBuilder {
302    /// Creates an empty builder.
303    pub fn new() -> Self {
304        Self::default()
305    }
306
307    /// Sets the OAuth client identifier. Required.
308    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
309        self.client_id = Some(client_id.into());
310        self
311    }
312
313    /// Sets the OAuth client secret. Required — RFC 7009 §2.1 requires the
314    /// revocation endpoint to authenticate the client.
315    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
316        self.client_secret = Some(client_secret.into());
317        self
318    }
319
320    /// Sets the revocation endpoint URL. Required.
321    ///
322    /// This is the `revocation_endpoint` member of the authorization server's
323    /// metadata document (RFC 8414 §2, `REV-005`), so it can be taken straight
324    /// from [`crate::discovery::ProviderMetadata::revocation_endpoint`] rather
325    /// than configured by hand.
326    pub fn revocation_endpoint(mut self, endpoint: impl Into<String>) -> Self {
327        self.revocation_endpoint = Some(endpoint.into());
328        self
329    }
330
331    /// Selects the client-authentication method. Defaults to
332    /// `client_secret_basic`.
333    pub fn auth_method(mut self, method: ClientAuthMethod) -> Self {
334        self.auth_method = method;
335        self
336    }
337
338    /// Adds one extra form parameter. Reserved parameters are ignored — see
339    /// [`RevocationClient::revoke`].
340    pub fn extra_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
341        self.extra_params.insert(key.into(), value.into());
342        self
343    }
344
345    /// Adds several extra form parameters.
346    pub fn extra_params(mut self, params: HashMap<String, String>) -> Self {
347        self.extra_params.extend(params);
348        self
349    }
350
351    /// Supplies a pre-configured HTTP client.
352    ///
353    /// Defaults to a **non-redirecting** client. The token travels in the request
354    /// body, and following a redirect either drops it (301/302/303, where the
355    /// POST is rewritten to a GET) and reports a false success, or replays it —
356    /// with `client_secret` on the `client_secret_post` path — to the redirect
357    /// target (307/308). A caller who overrides this takes on that risk.
358    pub fn http_client(mut self, client: HttpClient) -> Self {
359        self.http = Some(client);
360        self
361    }
362
363    /// Sets the per-request timeout. Zero means the 30-second default.
364    pub fn timeout(mut self, timeout: Duration) -> Self {
365        self.timeout = timeout;
366        self
367    }
368
369    /// Permits a plain-http revocation endpoint. Development only: the token
370    /// being revoked travels in the request body.
371    pub fn allow_http(mut self, allow: bool) -> Self {
372        self.allow_http = allow;
373        self
374    }
375
376    /// Builds the client.
377    ///
378    /// # Errors
379    ///
380    /// [`IdentityError::Configuration`] if `client_id`, `client_secret`, or
381    /// `revocation_endpoint` is missing or empty.
382    pub fn build(self) -> Result<RevocationClient> {
383        let client_id = self.client_id.unwrap_or_default();
384        if client_id.is_empty() {
385            return Err(IdentityError::Configuration(
386                "client_id is required".to_string(),
387            ));
388        }
389        let client_secret = self.client_secret.unwrap_or_default();
390        if client_secret.is_empty() {
391            return Err(IdentityError::Configuration(
392                "client_secret is required: the revocation endpoint requires client authentication with both client_id and client_secret (RFC 7009 §2.1)"
393                    .to_string(),
394            ));
395        }
396        let revocation_endpoint = self.revocation_endpoint.unwrap_or_default();
397        if revocation_endpoint.is_empty() {
398            return Err(IdentityError::Configuration(
399                "revocation_endpoint is required".to_string(),
400            ));
401        }
402        // Strip credentials carried in the URL. `https://id:secret@as/revoke` is a
403        // common way to pass basic auth as one config string, and the endpoint is
404        // interpolated into every transport-error message and printed by Debug —
405        // so leaving userinfo in place would publish the secret to the log store
406        // right beside the field this type carefully redacts.
407        let revocation_endpoint = match reqwest::Url::parse(&revocation_endpoint) {
408            Ok(mut url) => {
409                if !url.username().is_empty() || url.password().is_some() {
410                    let _ = url.set_username("");
411                    let _ = url.set_password(None);
412                }
413                url.to_string()
414            }
415            // Not parseable: leave as-is so the existing scheme check produces the
416            // configuration error rather than masking it here.
417            Err(_) => revocation_endpoint,
418        };
419        Ok(RevocationClient {
420            http: self.http.unwrap_or_else(crate::http::no_redirect_client),
421            revocation_endpoint,
422            client_id,
423            client_secret,
424            auth_method: self.auth_method,
425            extra_params: self.extra_params,
426            timeout: if self.timeout.is_zero() {
427                DEFAULT_TIMEOUT
428            } else {
429                self.timeout
430            },
431            allow_http: self.allow_http,
432        })
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439    use crate::ProviderMetadata;
440    use wiremock::matchers::{header, header_exists, method, path};
441    use wiremock::{Mock, MockServer, Request, ResponseTemplate};
442
443    /// Parses a request's form body into key/value pairs.
444    fn form_of(req: &Request) -> HashMap<String, String> {
445        url::form_urlencoded::parse(&req.body)
446            .into_owned()
447            .collect()
448    }
449
450    fn client(endpoint: &str) -> RevocationClientBuilder {
451        RevocationClient::builder()
452            .client_id("rs-client")
453            .client_secret("rs-secret")
454            .revocation_endpoint(endpoint)
455            .allow_http(true)
456    }
457
458    async fn mount(server: &MockServer, template: ResponseTemplate) {
459        Mock::given(method("POST"))
460            .and(path("/revoke"))
461            .respond_with(template)
462            .mount(server)
463            .await;
464    }
465
466    // REV-001: a 200 with an empty body is success, and the request is a POST
467    // carrying `token` as form-encoded content.
468    #[tokio::test]
469    async fn revoke_posts_token_and_succeeds_on_empty_200() {
470        let server = MockServer::start().await;
471        mount(&server, ResponseTemplate::new(200)).await;
472
473        let endpoint = format!("{}/revoke", server.uri());
474        client(&endpoint)
475            .build()
476            .unwrap()
477            .revoke("tok-1", None)
478            .await
479            .expect("empty 200 is success");
480
481        let req = &server.received_requests().await.unwrap()[0];
482        assert_eq!(req.method.as_str(), "POST");
483        let form = form_of(req);
484        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
485        assert!(!form.contains_key("token_type_hint"));
486    }
487
488    // REV-001: an empty JSON object is equally a success. Some servers send
489    // `{}` rather than a zero-length body; neither carries meaning.
490    #[tokio::test]
491    async fn empty_json_object_body_is_success() {
492        let server = MockServer::start().await;
493        mount(
494            &server,
495            ResponseTemplate::new(200).set_body_raw("{}", "application/json"),
496        )
497        .await;
498
499        let endpoint = format!("{}/revoke", server.uri());
500        client(&endpoint)
501            .build()
502            .unwrap()
503            .revoke("tok-1", None)
504            .await
505            .expect("empty JSON object is success");
506    }
507
508    // REV-001, the privacy property: the result MUST NOT differ between a valid
509    // token and an expired, already-revoked, or entirely unknown one. If this
510    // ever regresses, the endpoint becomes a token-scanning oracle.
511    #[tokio::test]
512    async fn response_is_identical_for_unknown_and_valid_tokens() {
513        let server = MockServer::start().await;
514        mount(&server, ResponseTemplate::new(200)).await;
515        let endpoint = format!("{}/revoke", server.uri());
516        let c = client(&endpoint).build().unwrap();
517
518        for token in ["a-live-token", "an-expired-token", "never-existed-at-all"] {
519            assert!(
520                c.revoke(token, None).await.is_ok(),
521                "revoking {token:?} must be indistinguishable from any other token"
522            );
523        }
524    }
525
526    // REV-002: the hint is sent as token_type_hint, alongside token.
527    #[tokio::test]
528    async fn token_type_hint_is_sent() {
529        let server = MockServer::start().await;
530        mount(&server, ResponseTemplate::new(200)).await;
531
532        let endpoint = format!("{}/revoke", server.uri());
533        client(&endpoint)
534            .build()
535            .unwrap()
536            .revoke("tok-1", Some("refresh_token"))
537            .await
538            .unwrap();
539
540        let form = form_of(&server.received_requests().await.unwrap()[0]);
541        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
542        assert_eq!(
543            form.get("token_type_hint").map(String::as_str),
544            Some("refresh_token")
545        );
546    }
547
548    // REV-002: an empty hint is treated as unset rather than sent blank.
549    #[tokio::test]
550    async fn empty_hint_is_omitted() {
551        let server = MockServer::start().await;
552        mount(&server, ResponseTemplate::new(200)).await;
553
554        let endpoint = format!("{}/revoke", server.uri());
555        client(&endpoint)
556            .build()
557            .unwrap()
558            .revoke("tok-1", Some(""))
559            .await
560            .unwrap();
561
562        let form = form_of(&server.received_requests().await.unwrap()[0]);
563        assert!(!form.contains_key("token_type_hint"));
564    }
565
566    // REV-002: a wrong hint MUST NOT fail the request — the server may ignore
567    // it and revoke anyway.
568    #[tokio::test]
569    async fn incorrect_hint_still_succeeds() {
570        let server = MockServer::start().await;
571        mount(&server, ResponseTemplate::new(200)).await;
572
573        let endpoint = format!("{}/revoke", server.uri());
574        client(&endpoint)
575            .build()
576            .unwrap()
577            .revoke("an-access-token", Some("refresh_token"))
578            .await
579            .expect("an incorrect hint must not fail the request");
580    }
581
582    // REV-003: HTTP 400 unsupported_token_type surfaces as a typed error
583    // carrying the code, description, uri, and status.
584    #[tokio::test]
585    async fn unsupported_token_type_is_typed() {
586        let server = MockServer::start().await;
587        mount(
588            &server,
589            ResponseTemplate::new(400).set_body_raw(
590                r#"{"error":"unsupported_token_type","error_description":"cannot revoke this type","error_uri":"https://issuer.example/e"}"#,
591                "application/json",
592            ),
593        )
594        .await;
595
596        let endpoint = format!("{}/revoke", server.uri());
597        let err = client(&endpoint)
598            .build()
599            .unwrap()
600            .revoke("tok-1", None)
601            .await
602            .expect_err("400 must surface as an error");
603
604        match err {
605            IdentityError::TokenEndpoint {
606                error,
607                description,
608                error_uri,
609                status,
610            } => {
611                assert_eq!(error, "unsupported_token_type");
612                assert_eq!(description.as_deref(), Some("cannot revoke this type"));
613                assert_eq!(error_uri.as_deref(), Some("https://issuer.example/e"));
614                assert_eq!(status, 400);
615            }
616            other => panic!("expected TokenEndpoint, got {other:?}"),
617        }
618    }
619
620    // REV-004: HTTP 401 invalid_client surfaces as a typed error.
621    #[tokio::test]
622    async fn invalid_client_is_typed() {
623        let server = MockServer::start().await;
624        mount(
625            &server,
626            ResponseTemplate::new(401)
627                .set_body_raw(r#"{"error":"invalid_client"}"#, "application/json"),
628        )
629        .await;
630
631        let endpoint = format!("{}/revoke", server.uri());
632        let err = client(&endpoint)
633            .build()
634            .unwrap()
635            .revoke("tok-1", None)
636            .await
637            .expect_err("401 must surface as an error");
638
639        match err {
640            IdentityError::TokenEndpoint { error, status, .. } => {
641                assert_eq!(error, "invalid_client");
642                assert_eq!(status, 401);
643            }
644            other => panic!("expected TokenEndpoint, got {other:?}"),
645        }
646    }
647
648    // REV-005: the endpoint comes straight off the discovery document.
649    #[tokio::test]
650    async fn endpoint_resolves_from_discovery() {
651        let server = MockServer::start().await;
652        mount(&server, ResponseTemplate::new(200)).await;
653        let endpoint = format!("{}/revoke", server.uri());
654
655        let metadata: ProviderMetadata = serde_json::from_str(&format!(
656            r#"{{"issuer":"{}","revocation_endpoint":"{}"}}"#,
657            server.uri(),
658            endpoint
659        ))
660        .expect("metadata parses");
661
662        let resolved = metadata
663            .revocation_endpoint
664            .as_deref()
665            .expect("revocation_endpoint present in discovery");
666        assert_eq!(resolved, endpoint);
667
668        client(resolved)
669            .build()
670            .unwrap()
671            .revoke("tok-1", None)
672            .await
673            .expect("discovery-resolved endpoint works");
674    }
675
676    // client_secret_basic is the default and sends an Authorization header
677    // rather than credentials in the body.
678    #[tokio::test]
679    async fn client_secret_basic_is_default() {
680        let server = MockServer::start().await;
681        Mock::given(method("POST"))
682            .and(path("/revoke"))
683            .and(header_exists(AUTHORIZATION))
684            .and(header(CONTENT_TYPE, "application/x-www-form-urlencoded"))
685            .respond_with(ResponseTemplate::new(200))
686            .mount(&server)
687            .await;
688
689        let endpoint = format!("{}/revoke", server.uri());
690        client(&endpoint)
691            .build()
692            .unwrap()
693            .revoke("tok-1", None)
694            .await
695            .unwrap();
696
697        let form = form_of(&server.received_requests().await.unwrap()[0]);
698        assert!(!form.contains_key("client_secret"));
699    }
700
701    // client_secret_post places credentials in the body instead.
702    #[tokio::test]
703    async fn client_secret_post_uses_body() {
704        let server = MockServer::start().await;
705        mount(&server, ResponseTemplate::new(200)).await;
706
707        let endpoint = format!("{}/revoke", server.uri());
708        client(&endpoint)
709            .auth_method(ClientAuthMethod::ClientSecretPost)
710            .build()
711            .unwrap()
712            .revoke("tok-1", None)
713            .await
714            .unwrap();
715
716        let req = &server.received_requests().await.unwrap()[0];
717        assert!(req.headers.get(AUTHORIZATION).is_none());
718        let form = form_of(req);
719        assert_eq!(form.get("client_id").map(String::as_str), Some("rs-client"));
720        assert_eq!(
721            form.get("client_secret").map(String::as_str),
722            Some("rs-secret")
723        );
724    }
725
726    // Extra params cannot overwrite the token, the hint, or client credentials
727    // — on the Basic path client_id is absent from the body and must stay so.
728    #[tokio::test]
729    async fn extra_params_cannot_override_reserved() {
730        let server = MockServer::start().await;
731        mount(&server, ResponseTemplate::new(200)).await;
732
733        let endpoint = format!("{}/revoke", server.uri());
734        client(&endpoint)
735            .extra_param("token", "attacker-token")
736            .extra_param("client_id", "attacker")
737            .extra_param("resource", "https://api.example")
738            .build()
739            .unwrap()
740            .revoke("tok-1", Some("access_token"))
741            .await
742            .unwrap();
743
744        let form = form_of(&server.received_requests().await.unwrap()[0]);
745        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
746        assert!(!form.contains_key("client_id"));
747        assert_eq!(
748            form.get("resource").map(String::as_str),
749            Some("https://api.example")
750        );
751    }
752
753    // A non-OAuth error body still fails, but as a transport-level error that
754    // quotes a snippet rather than pretending it parsed.
755    #[tokio::test]
756    async fn non_oauth_error_body_is_http_error() {
757        let server = MockServer::start().await;
758        mount(
759            &server,
760            ResponseTemplate::new(500).set_body_raw("<html>boom</html>", "text/html"),
761        )
762        .await;
763
764        let endpoint = format!("{}/revoke", server.uri());
765        let err = client(&endpoint)
766            .build()
767            .unwrap()
768            .revoke("tok-1", None)
769            .await
770            .expect_err("500 must fail");
771        assert!(matches!(err, IdentityError::Http(_)), "got {err:?}");
772    }
773
774    // A plain-http endpoint is refused unless allow_http was set: the token
775    // travels in the body.
776    #[tokio::test]
777    async fn http_endpoint_refused_without_allow_http() {
778        let err = RevocationClient::builder()
779            .client_id("rs-client")
780            .client_secret("rs-secret")
781            .revocation_endpoint("http://issuer.example/revoke")
782            .build()
783            .unwrap()
784            .revoke("tok-1", None)
785            .await
786            .expect_err("plain http must be refused");
787        assert!(
788            matches!(err, IdentityError::Configuration(_)),
789            "got {err:?}"
790        );
791    }
792
793    // Adversarial (mirrors the Go reference's TestRevoke_RejectsEmptyToken):
794    // token is REQUIRED by RFC 7009 §2.1. An empty one must be rejected locally,
795    // because a lenient server answers the anti-scanning 200 for it and the
796    // caller would read that as a successful revocation. Asserting the server
797    // was never called is the point — an error raised after the request would
798    // still have leaked a malformed request to the provider.
799    #[tokio::test]
800    async fn empty_token_is_rejected_before_the_network() {
801        let server = MockServer::start().await;
802        mount(&server, ResponseTemplate::new(200)).await;
803
804        let endpoint = format!("{}/revoke", server.uri());
805        let err = client(&endpoint)
806            .build()
807            .unwrap()
808            .revoke("", Some("access_token"))
809            .await
810            .expect_err("an empty token must not be sent");
811
812        match &err {
813            IdentityError::Configuration(msg) => {
814                assert!(
815                    msg.contains("token is required"),
816                    "unexpected message: {msg}"
817                )
818            }
819            other => panic!("expected Configuration, got {other:?}"),
820        }
821        assert!(
822            server.received_requests().await.unwrap().is_empty(),
823            "empty-token revocation must be rejected before the network, but the server was called"
824        );
825    }
826
827    // A 2xx is decided on before the body is touched, so a body that cannot be
828    // read cannot turn a revocation the server already performed into an error.
829    // Modelled on a provider that answers 200 and drops the connection: the
830    // response promises more bytes than it delivers.
831    #[tokio::test]
832    async fn success_does_not_depend_on_reading_the_body() {
833        let server = MockServer::start().await;
834        mount(
835            &server,
836            ResponseTemplate::new(200)
837                .set_body_raw("", "application/json")
838                .append_header("content-length", "512"),
839        )
840        .await;
841
842        let endpoint = format!("{}/revoke", server.uri());
843        let result = client(&endpoint)
844            .build()
845            .unwrap()
846            .revoke("tok-1", None)
847            .await;
848
849        assert!(
850            result.is_ok(),
851            "a 2xx must succeed without depending on the body: {result:?}"
852        );
853    }
854
855    // A redirect is not followed. On a 302 reqwest would rewrite the POST to a
856    // GET and drop the body, so the final 200 would report success for a request
857    // whose token never arrived — a silent false success on a live token.
858    #[tokio::test]
859    async fn redirect_is_not_followed_and_is_an_error() {
860        let upstream = MockServer::start().await;
861        Mock::given(method("GET"))
862            .respond_with(ResponseTemplate::new(200))
863            .mount(&upstream)
864            .await;
865
866        let server = MockServer::start().await;
867        Mock::given(method("POST"))
868            .and(path("/revoke"))
869            .respond_with(
870                ResponseTemplate::new(302)
871                    .append_header("location", format!("{}/elsewhere", upstream.uri()).as_str()),
872            )
873            .mount(&server)
874            .await;
875
876        let endpoint = format!("{}/revoke", server.uri());
877        let err = client(&endpoint)
878            .build()
879            .unwrap()
880            .revoke("tok-1", None)
881            .await
882            .expect_err("a 3xx must not be reported as a successful revocation");
883        assert!(matches!(err, IdentityError::Http(_)), "got {err:?}");
884
885        assert!(
886            upstream.received_requests().await.unwrap().is_empty(),
887            "the redirect target must never be contacted — the token is in the body"
888        );
889    }
890
891    // A caller-supplied client that follows redirects must not be able to turn a
892    // replayed or dropped request into a reported success. Mirrors the Go
893    // reference's TestRevoke_RefusesInsecureRedirect, which passes a caller
894    // client deliberately.
895    #[tokio::test]
896    async fn caller_supplied_redirecting_client_is_still_refused() {
897        let upstream = MockServer::start().await;
898        Mock::given(method("POST"))
899            .respond_with(ResponseTemplate::new(200))
900            .mount(&upstream)
901            .await;
902        Mock::given(method("GET"))
903            .respond_with(ResponseTemplate::new(200))
904            .mount(&upstream)
905            .await;
906
907        let server = MockServer::start().await;
908        Mock::given(method("POST"))
909            .and(path("/revoke"))
910            .respond_with(
911                ResponseTemplate::new(307)
912                    .append_header("location", format!("{}/elsewhere", upstream.uri()).as_str()),
913            )
914            .mount(&server)
915            .await;
916
917        // Default reqwest policy: follows redirects. This is what a caller who
918        // needs a proxy or a custom CA ends up with.
919        let permissive = reqwest::Client::builder()
920            .build()
921            .expect("build permissive client");
922
923        let endpoint = format!("{}/revoke", server.uri());
924        let err = client(&endpoint)
925            .http_client(permissive)
926            .build()
927            .unwrap()
928            .revoke("tok-1", None)
929            .await
930            .expect_err("a followed redirect must not be reported as a revocation");
931        assert!(matches!(err, IdentityError::Http(_)), "got {err:?}");
932    }
933
934    // Reserved parameters are matched case-insensitively: `Token` must not slip
935    // past and become a duplicate the server folds together.
936    #[tokio::test]
937    async fn reserved_params_are_case_insensitive() {
938        let server = MockServer::start().await;
939        mount(&server, ResponseTemplate::new(200)).await;
940
941        let endpoint = format!("{}/revoke", server.uri());
942        client(&endpoint)
943            .extra_param("Token", "attacker")
944            .extra_param("TOKEN", "attacker")
945            .extra_param(" token ", "attacker")
946            .extra_param("Client_Secret", "attacker")
947            .build()
948            .unwrap()
949            .revoke("tok-1", None)
950            .await
951            .unwrap();
952
953        let form = form_of(&server.received_requests().await.unwrap()[0]);
954        let token_keys: Vec<_> = form
955            .keys()
956            .filter(|k| k.trim().eq_ignore_ascii_case("token"))
957            .collect();
958        assert_eq!(
959            token_keys.len(),
960            1,
961            "exactly one token parameter must reach the wire, got {form:?}"
962        );
963        assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
964        assert!(
965            !form
966                .keys()
967                .any(|k| k.trim().eq_ignore_ascii_case("client_secret")),
968            "client_secret must not be injectable on the Basic path: {form:?}"
969        );
970    }
971
972    #[test]
973    fn build_requires_credentials_and_endpoint() {
974        assert!(RevocationClient::builder().build().is_err());
975        assert!(
976            RevocationClient::builder()
977                .client_id("id")
978                .revocation_endpoint("https://e/revoke")
979                .build()
980                .is_err(),
981            "client_secret is required"
982        );
983        assert!(
984            RevocationClient::builder()
985                .client_id("id")
986                .client_secret("s")
987                .build()
988                .is_err(),
989            "revocation_endpoint is required"
990        );
991    }
992
993    #[test]
994    fn debug_redacts_client_secret() {
995        let c = RevocationClient::builder()
996            .client_id("rs-client")
997            .client_secret("super-secret")
998            .revocation_endpoint("https://issuer.example/revoke")
999            .build()
1000            .unwrap();
1001        let rendered = format!("{c:?}");
1002        assert!(!rendered.contains("super-secret"), "{rendered}");
1003        assert!(rendered.contains(REDACTED));
1004
1005        let b = RevocationClient::builder().client_secret("super-secret");
1006        assert!(!format!("{b:?}").contains("super-secret"));
1007    }
1008}