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};
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const REDACTED: &str = "<redacted>";
const RESERVED_PARAMS: &[&str] = &["token", "token_type_hint", "client_id", "client_secret"];
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 {
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.keys().collect::<Vec<_>>(),
)
.field("timeout", &self.timeout)
.field("allow_http", &self.allow_http)
.finish()
}
}
impl RevocationClient {
pub fn builder() -> RevocationClientBuilder {
RevocationClientBuilder::new()
}
pub async fn revoke(&self, token: &str, token_type_hint: Option<&str>) -> Result<()> {
if token.is_empty() {
return Err(IdentityError::Configuration(
"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"
.to_string(),
));
}
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())];
if let Some(hint) = token_type_hint
&& !hint.is_empty()
{
form.push(("token_type_hint".to_string(), hint.to_string()));
}
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));
}
}
for (key, value) in &self.extra_params {
let normalised = key.trim().to_ascii_lowercase();
if RESERVED_PARAMS.contains(&normalised.as_str())
|| form
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case(normalised.trim()))
{
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)))?;
if response.url().as_str() != self.revocation_endpoint.as_str() {
return Err(IdentityError::Http(format!(
"revocation request to {} was redirected to a different URL; refusing to treat the result as a revocation. \
The token travels in the request body, so a followed redirect either dropped it or replayed it to another host. \
Supply a client with a no-redirect policy (the default client already has one).",
self.revocation_endpoint
)));
}
let status = response.status();
if status.is_success() {
return Ok(());
}
let body = read_capped_body(response).await?;
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)
)))
}
}
#[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 {
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.keys().collect::<Vec<_>>(),
)
.field("timeout", &self.timeout)
.field("allow_http", &self.allow_http)
.finish()
}
}
impl RevocationClientBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
self.client_id = Some(client_id.into());
self
}
pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
self.client_secret = Some(client_secret.into());
self
}
pub fn revocation_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.revocation_endpoint = Some(endpoint.into());
self
}
pub fn auth_method(mut self, method: ClientAuthMethod) -> Self {
self.auth_method = method;
self
}
pub fn extra_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.extra_params.insert(key.into(), value.into());
self
}
pub fn extra_params(mut self, params: HashMap<String, String>) -> Self {
self.extra_params.extend(params);
self
}
pub fn http_client(mut self, client: HttpClient) -> Self {
self.http = Some(client);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn allow_http(mut self, allow: bool) -> Self {
self.allow_http = allow;
self
}
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(),
));
}
let revocation_endpoint = match reqwest::Url::parse(&revocation_endpoint) {
Ok(mut url) => {
if !url.username().is_empty() || url.password().is_some() {
let _ = url.set_username("");
let _ = url.set_password(None);
}
url.to_string()
}
Err(_) => revocation_endpoint,
};
Ok(RevocationClient {
http: self.http.unwrap_or_else(crate::http::no_redirect_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};
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;
}
#[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"));
}
#[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");
}
#[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"
);
}
}
#[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")
);
}
#[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"));
}
#[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");
}
#[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:?}"),
}
}
#[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:?}"),
}
}
#[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");
}
#[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"));
}
#[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")
);
}
#[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")
);
}
#[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:?}");
}
#[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:?}"
);
}
#[tokio::test]
async fn empty_token_is_rejected_before_the_network() {
let server = MockServer::start().await;
mount(&server, ResponseTemplate::new(200)).await;
let endpoint = format!("{}/revoke", server.uri());
let err = client(&endpoint)
.build()
.unwrap()
.revoke("", Some("access_token"))
.await
.expect_err("an empty token must not be sent");
match &err {
IdentityError::Configuration(msg) => {
assert!(
msg.contains("token is required"),
"unexpected message: {msg}"
)
}
other => panic!("expected Configuration, got {other:?}"),
}
assert!(
server.received_requests().await.unwrap().is_empty(),
"empty-token revocation must be rejected before the network, but the server was called"
);
}
#[tokio::test]
async fn success_does_not_depend_on_reading_the_body() {
let server = MockServer::start().await;
mount(
&server,
ResponseTemplate::new(200)
.set_body_raw("", "application/json")
.append_header("content-length", "512"),
)
.await;
let endpoint = format!("{}/revoke", server.uri());
let result = client(&endpoint)
.build()
.unwrap()
.revoke("tok-1", None)
.await;
assert!(
result.is_ok(),
"a 2xx must succeed without depending on the body: {result:?}"
);
}
#[tokio::test]
async fn redirect_is_not_followed_and_is_an_error() {
let upstream = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200))
.mount(&upstream)
.await;
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/revoke"))
.respond_with(
ResponseTemplate::new(302)
.append_header("location", format!("{}/elsewhere", upstream.uri()).as_str()),
)
.mount(&server)
.await;
let endpoint = format!("{}/revoke", server.uri());
let err = client(&endpoint)
.build()
.unwrap()
.revoke("tok-1", None)
.await
.expect_err("a 3xx must not be reported as a successful revocation");
assert!(matches!(err, IdentityError::Http(_)), "got {err:?}");
assert!(
upstream.received_requests().await.unwrap().is_empty(),
"the redirect target must never be contacted — the token is in the body"
);
}
#[tokio::test]
async fn caller_supplied_redirecting_client_is_still_refused() {
let upstream = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200))
.mount(&upstream)
.await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200))
.mount(&upstream)
.await;
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/revoke"))
.respond_with(
ResponseTemplate::new(307)
.append_header("location", format!("{}/elsewhere", upstream.uri()).as_str()),
)
.mount(&server)
.await;
let permissive = reqwest::Client::builder()
.build()
.expect("build permissive client");
let endpoint = format!("{}/revoke", server.uri());
let err = client(&endpoint)
.http_client(permissive)
.build()
.unwrap()
.revoke("tok-1", None)
.await
.expect_err("a followed redirect must not be reported as a revocation");
assert!(matches!(err, IdentityError::Http(_)), "got {err:?}");
}
#[tokio::test]
async fn reserved_params_are_case_insensitive() {
let server = MockServer::start().await;
mount(&server, ResponseTemplate::new(200)).await;
let endpoint = format!("{}/revoke", server.uri());
client(&endpoint)
.extra_param("Token", "attacker")
.extra_param("TOKEN", "attacker")
.extra_param(" token ", "attacker")
.extra_param("Client_Secret", "attacker")
.build()
.unwrap()
.revoke("tok-1", None)
.await
.unwrap();
let form = form_of(&server.received_requests().await.unwrap()[0]);
let token_keys: Vec<_> = form
.keys()
.filter(|k| k.trim().eq_ignore_ascii_case("token"))
.collect();
assert_eq!(
token_keys.len(),
1,
"exactly one token parameter must reach the wire, got {form:?}"
);
assert_eq!(form.get("token").map(String::as_str), Some("tok-1"));
assert!(
!form
.keys()
.any(|k| k.trim().eq_ignore_ascii_case("client_secret")),
"client_secret must not be injectable on the Basic path: {form:?}"
);
}
#[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"));
}
}