mod pkce;
mod response;
use std::collections::HashMap;
use std::time::Duration;
use reqwest::Client as HttpClient;
use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE};
use crate::client_auth::{OAuthErrorBody, basic_auth_header, body_snippet, read_capped_body};
use crate::{IdentityError, Result};
pub use pkce::{
CHALLENGE_METHOD_S256, PkceChallenge, authorization_url, s256_challenge, valid_code_verifier,
};
pub use response::TokenResponse;
const GRANT_CLIENT_CREDENTIALS: &str = "client_credentials";
const GRANT_AUTHORIZATION_CODE: &str = "authorization_code";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const REDACTED: &str = "<redacted>";
const RESERVED_PARAMS: &[&str] = &[
"grant_type",
"client_id",
"client_secret",
"code",
"redirect_uri",
"code_verifier",
"scope",
];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClientAuthMethod {
#[default]
ClientSecretBasic,
ClientSecretPost,
}
pub struct TokenClient {
http: HttpClient,
token_endpoint: String,
client_id: String,
client_secret: Option<String>,
auth_method: ClientAuthMethod,
extra_params: HashMap<String, String>,
timeout: Duration,
allow_http: bool,
}
impl std::fmt::Debug for TokenClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenClient")
.field("token_endpoint", &self.token_endpoint)
.field("client_id", &self.client_id)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| REDACTED),
)
.field("auth_method", &self.auth_method)
.field("extra_params", &self.extra_params)
.field("timeout", &self.timeout)
.field("allow_http", &self.allow_http)
.finish_non_exhaustive()
}
}
impl TokenClient {
pub fn builder() -> TokenClientBuilder {
TokenClientBuilder::new()
}
pub async fn client_credentials(&self, scope: Option<&str>) -> Result<TokenResponse> {
let mut form: Vec<(String, String)> = vec![(
"grant_type".to_string(),
GRANT_CLIENT_CREDENTIALS.to_string(),
)];
if let Some(scope) = scope {
form.push(("scope".to_string(), scope.to_string()));
}
self.do_request(form, self.client_secret.as_deref()).await
}
pub async fn exchange_code(
&self,
code: &str,
redirect_uri: &str,
code_verifier: Option<&str>,
) -> Result<TokenResponse> {
if let Some(verifier) = code_verifier
&& !valid_code_verifier(verifier)
{
return Err(IdentityError::Validation(
"code_verifier must be 43-128 unreserved characters".to_string(),
));
}
let mut form: Vec<(String, String)> = vec![
(
"grant_type".to_string(),
GRANT_AUTHORIZATION_CODE.to_string(),
),
("code".to_string(), code.to_string()),
];
if !redirect_uri.is_empty() {
form.push(("redirect_uri".to_string(), redirect_uri.to_string()));
}
if let Some(verifier) = code_verifier {
form.push(("code_verifier".to_string(), verifier.to_string()));
}
self.do_request(form, self.client_secret.as_deref()).await
}
async fn do_request(
&self,
mut form: Vec<(String, String)>,
client_secret: Option<&str>,
) -> Result<TokenResponse> {
let scheme = self.token_endpoint.to_ascii_lowercase();
let scheme_ok =
scheme.starts_with("https://") || (self.allow_http && scheme.starts_with("http://"));
if !scheme_ok {
return Err(IdentityError::Configuration(format!(
"token endpoint {:?} must use https (enable allow_http for development)",
self.token_endpoint
)));
}
let mut basic_header: Option<String> = None;
match client_secret {
None => {
if !self.client_id.is_empty() {
form.push(("client_id".to_string(), self.client_id.clone()));
}
}
Some(secret) => match self.auth_method {
ClientAuthMethod::ClientSecretPost => {
form.push(("client_id".to_string(), self.client_id.clone()));
form.push(("client_secret".to_string(), secret.to_string()));
}
ClientAuthMethod::ClientSecretBasic => {
basic_header = Some(basic_auth_header(&self.client_id, secret));
}
},
}
for (key, value) in &self.extra_params {
if RESERVED_PARAMS.contains(&key.as_str()) || form.iter().any(|(k, _)| k == key) {
continue;
}
form.push((key.clone(), value.clone()));
}
let mut request = self
.http
.post(&self.token_endpoint)
.timeout(self.timeout)
.header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(ACCEPT, "application/json")
.form(&form);
if let Some(header) = basic_header {
request = request.header(AUTHORIZATION, header);
}
let response = request
.send()
.await
.map_err(|e| IdentityError::Http(format!("post {}: {e}", self.token_endpoint)))?;
let status = response.status();
let body = read_capped_body(response).await?;
if !status.is_success() {
if let Ok(err) = serde_json::from_slice::<OAuthErrorBody>(&body)
&& !err.error.is_empty()
{
return Err(IdentityError::TokenEndpoint {
error: err.error,
description: err.error_description,
error_uri: err.error_uri,
status: status.as_u16(),
});
}
return Err(IdentityError::Http(format!(
"token request to {} failed: HTTP {} with non-OAuth body: {}",
self.token_endpoint,
status.as_u16(),
body_snippet(&body)
)));
}
let token: TokenResponse = serde_json::from_slice(&body).map_err(|e| {
IdentityError::Deserialization(format!(
"parse token response from {}: {e}",
self.token_endpoint
))
})?;
if token.access_token.is_empty() {
return Err(IdentityError::Http(format!(
"token response from {} is missing access_token",
self.token_endpoint
)));
}
Ok(token)
}
}
#[derive(Default)]
pub struct TokenClientBuilder {
http: Option<HttpClient>,
token_endpoint: Option<String>,
client_id: Option<String>,
client_secret: Option<String>,
auth_method: ClientAuthMethod,
extra_params: HashMap<String, String>,
timeout: Duration,
allow_http: bool,
}
impl std::fmt::Debug for TokenClientBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenClientBuilder")
.field("token_endpoint", &self.token_endpoint)
.field("client_id", &self.client_id)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| REDACTED),
)
.field("auth_method", &self.auth_method)
.field("extra_params", &self.extra_params)
.field("timeout", &self.timeout)
.field("allow_http", &self.allow_http)
.finish_non_exhaustive()
}
}
impl TokenClientBuilder {
fn new() -> Self {
Self::default()
}
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 token_endpoint(mut self, token_endpoint: impl Into<String>) -> Self {
self.token_endpoint = Some(token_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 {
if !timeout.is_zero() {
self.timeout = timeout;
}
self
}
pub fn allow_http(mut self, allow: bool) -> Self {
self.allow_http = allow;
self
}
pub fn build(self) -> Result<TokenClient> {
let client_id = self.client_id.unwrap_or_default();
if client_id.is_empty() {
return Err(IdentityError::Configuration(
"client_id is required".to_string(),
));
}
let token_endpoint = self.token_endpoint.unwrap_or_default();
if token_endpoint.is_empty() {
return Err(IdentityError::Configuration(
"token_endpoint is required".to_string(),
));
}
Ok(TokenClient {
http: self.http.unwrap_or_else(crate::http::secure_client),
token_endpoint,
client_id,
client_secret: self.client_secret.filter(|s| !s.is_empty()),
auth_method: self.auth_method,
extra_params: self.extra_params,
timeout: if self.timeout.is_zero() {
DEFAULT_TIMEOUT
} else {
self.timeout
},
allow_http: self.allow_http,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use wiremock::matchers::{header_exists, method, path};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};
const SUCCESS_BODY: &str =
r#"{"access_token":"at-abc","token_type":"Bearer","expires_in":3600}"#;
async fn mount_token(server: &MockServer, template: ResponseTemplate) {
Mock::given(method("POST"))
.and(path("/token"))
.respond_with(template)
.mount(server)
.await;
}
fn form_of(req: &Request) -> HashMap<String, String> {
url::form_urlencoded::parse(&req.body)
.into_owned()
.collect()
}
fn client(endpoint: &str) -> TokenClientBuilder {
TokenClient::builder()
.client_id("client-1")
.client_secret("s3cr3t")
.token_endpoint(endpoint)
.allow_http(true)
}
#[tokio::test]
async fn client_credentials_returns_typed_response() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
)
.await;
let token = client(&format!("{}/token", server.uri()))
.build()
.unwrap()
.client_credentials(None)
.await
.expect("grant succeeds");
assert_eq!(token.access_token, "at-abc");
assert_eq!(token.token_type, "Bearer");
assert_eq!(token.expires_in, 3600);
}
#[tokio::test]
async fn client_secret_basic_is_default() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/token"))
.and(header_exists("authorization"))
.respond_with(ResponseTemplate::new(200).set_body_string(SUCCESS_BODY))
.mount(&server)
.await;
client(&format!("{}/token", server.uri()))
.build()
.unwrap()
.client_credentials(None)
.await
.expect("grant succeeds");
let requests = server.received_requests().await.unwrap();
let req = requests.last().unwrap();
let auth = req.headers.get("authorization").unwrap().to_str().unwrap();
assert_eq!(
auth,
format!("Basic {}", BASE64_STANDARD.encode("client-1:s3cr3t"))
);
let form = form_of(req);
assert!(!form.contains_key("client_id"), "no client_id in body");
assert!(
!form.contains_key("client_secret"),
"no client_secret in body"
);
assert_eq!(
form.get("grant_type").map(String::as_str),
Some("client_credentials")
);
}
#[tokio::test]
async fn client_secret_post_uses_body() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
)
.await;
client(&format!("{}/token", server.uri()))
.auth_method(ClientAuthMethod::ClientSecretPost)
.build()
.unwrap()
.client_credentials(None)
.await
.expect("grant succeeds");
let requests = server.received_requests().await.unwrap();
let req = requests.last().unwrap();
assert!(
req.headers.get("authorization").is_none(),
"no Basic header"
);
let form = form_of(req);
assert_eq!(form.get("client_id").map(String::as_str), Some("client-1"));
assert_eq!(
form.get("client_secret").map(String::as_str),
Some("s3cr3t")
);
}
#[tokio::test]
async fn error_response_maps_to_token_endpoint() {
let server = MockServer::start().await;
let body = r#"{"error":"invalid_client","error_description":"bad secret","error_uri":"https://err.example/1"}"#;
mount_token(&server, ResponseTemplate::new(401).set_body_string(body)).await;
let err = client(&format!("{}/token", server.uri()))
.build()
.unwrap()
.client_credentials(None)
.await
.expect_err("error response must fail");
match err {
IdentityError::TokenEndpoint {
error,
description,
error_uri,
status,
} => {
assert_eq!(error, "invalid_client");
assert_eq!(description.as_deref(), Some("bad secret"));
assert_eq!(error_uri.as_deref(), Some("https://err.example/1"));
assert_eq!(status, 401);
}
other => panic!("expected TokenEndpoint, got {other:?}"),
}
}
#[tokio::test]
async fn non_oauth_error_body_maps_to_http() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(500).set_body_string("upstream boom"),
)
.await;
let err = client(&format!("{}/token", server.uri()))
.build()
.unwrap()
.client_credentials(None)
.await
.expect_err("500 must fail");
assert!(matches!(err, IdentityError::Http(_)), "{err:?}");
}
#[tokio::test]
async fn scope_is_space_delimited() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
)
.await;
client(&format!("{}/token", server.uri()))
.build()
.unwrap()
.client_credentials(Some("a b"))
.await
.expect("grant succeeds");
let requests = server.received_requests().await.unwrap();
let form = form_of(requests.last().unwrap());
assert_eq!(form.get("scope").map(String::as_str), Some("a b"));
}
#[tokio::test]
async fn extra_params_applied_reserved_guarded() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
)
.await;
let custom = reqwest::Client::builder().build().unwrap();
client(&format!("{}/token", server.uri()))
.http_client(custom)
.extra_param("resource", "urn:test:api")
.extra_param("grant_type", "hacked")
.build()
.unwrap()
.client_credentials(None)
.await
.expect("grant succeeds");
let requests = server.received_requests().await.unwrap();
let form = form_of(requests.last().unwrap());
assert_eq!(
form.get("resource").map(String::as_str),
Some("urn:test:api")
);
assert_eq!(
form.get("grant_type").map(String::as_str),
Some("client_credentials"),
"reserved grant_type must not be overridden"
);
}
#[tokio::test]
async fn exchange_code_sends_expected_form() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
)
.await;
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
TokenClient::builder()
.client_id("public-client")
.token_endpoint(format!("{}/token", server.uri()))
.allow_http(true)
.build()
.unwrap()
.exchange_code("auth-code-1", "https://app.example/cb", Some(verifier))
.await
.expect("exchange succeeds");
let requests = server.received_requests().await.unwrap();
let req = requests.last().unwrap();
assert!(
req.headers.get("authorization").is_none(),
"public client has no Basic header"
);
let form = form_of(req);
assert_eq!(
form.get("grant_type").map(String::as_str),
Some("authorization_code")
);
assert_eq!(form.get("code").map(String::as_str), Some("auth-code-1"));
assert_eq!(
form.get("redirect_uri").map(String::as_str),
Some("https://app.example/cb")
);
assert_eq!(
form.get("code_verifier").map(String::as_str),
Some(verifier)
);
assert_eq!(
form.get("client_id").map(String::as_str),
Some("public-client")
);
}
#[tokio::test]
async fn empty_client_secret_is_public_client() {
let server = MockServer::start().await;
mount_token(
&server,
ResponseTemplate::new(200).set_body_string(SUCCESS_BODY),
)
.await;
TokenClient::builder()
.client_id("public-client")
.client_secret("")
.token_endpoint(format!("{}/token", server.uri()))
.allow_http(true)
.build()
.unwrap()
.client_credentials(None)
.await
.expect("grant succeeds");
let requests = server.received_requests().await.unwrap();
let req = requests.last().unwrap();
assert!(
req.headers.get("authorization").is_none(),
"empty secret must not send a Basic header"
);
let form = form_of(req);
assert_eq!(
form.get("client_id").map(String::as_str),
Some("public-client"),
"public client is identified by client_id in the body"
);
assert!(
!form.contains_key("client_secret"),
"no empty client_secret in body"
);
}
#[tokio::test]
async fn exchange_code_rejects_invalid_verifier() {
let client = TokenClient::builder()
.client_id("public-client")
.token_endpoint("https://issuer.example/token")
.build()
.unwrap();
let err = client
.exchange_code("code", "https://app/cb", Some("too-short"))
.await
.expect_err("short verifier must error");
assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
}
#[test]
fn builder_requires_client_id_and_endpoint() {
let missing_id = TokenClient::builder()
.token_endpoint("https://issuer.example/token")
.build();
assert!(matches!(missing_id, Err(IdentityError::Configuration(_))));
let missing_endpoint = TokenClient::builder().client_id("c").build();
assert!(matches!(
missing_endpoint,
Err(IdentityError::Configuration(_))
));
let ok = TokenClient::builder()
.client_id("c")
.token_endpoint("https://issuer.example/token")
.build();
assert!(ok.is_ok());
}
#[tokio::test]
async fn https_required_by_default() {
let client = TokenClient::builder()
.client_id("c")
.client_secret("s")
.token_endpoint("http://insecure.example/token")
.build()
.unwrap();
let err = client
.client_credentials(None)
.await
.expect_err("http endpoint must be rejected");
assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
}
#[test]
fn basic_auth_header_urlencodes_credentials() {
let header = basic_auth_header("id with space", "p@ss:word");
let expected = format!(
"Basic {}",
BASE64_STANDARD.encode("id+with+space:p%40ss%3Aword")
);
assert_eq!(header, expected);
}
#[test]
fn debug_redacts_client_secret() {
let builder = TokenClient::builder()
.client_id("client-1")
.client_secret("s3cr3t-value")
.token_endpoint("https://issuer.example/token");
let builder_dbg = format!("{builder:?}");
assert!(
!builder_dbg.contains("s3cr3t-value"),
"builder leaked secret: {builder_dbg}"
);
assert!(builder_dbg.contains(REDACTED), "no marker: {builder_dbg}");
let client = builder.build().unwrap();
let client_dbg = format!("{client:?}");
assert!(
!client_dbg.contains("s3cr3t-value"),
"client leaked secret: {client_dbg}"
);
assert!(client_dbg.contains(REDACTED), "no marker: {client_dbg}");
assert!(client_dbg.contains("client-1"), "{client_dbg}");
}
#[test]
fn debug_public_client_shows_no_secret() {
let client = TokenClient::builder()
.client_id("public")
.token_endpoint("https://issuer.example/token")
.build()
.unwrap();
assert!(format!("{client:?}").contains("client_secret: None"));
}
}