mod response;
use std::time::Duration;
use reqwest::Client as HttpClient;
use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
use crate::{IdentityError, Result};
pub use response::{Address, UserInfoResponse};
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_BODY_BYTES: usize = 1 << 20;
pub struct UserInfoClient {
http: HttpClient,
userinfo_endpoint: String,
timeout: Duration,
allow_http: bool,
}
impl UserInfoClient {
pub fn builder() -> UserInfoClientBuilder {
UserInfoClientBuilder::new()
}
pub async fn fetch(&self, access_token: &str) -> Result<UserInfoResponse> {
self.fetch_inner(access_token, None).await
}
pub async fn fetch_with_subject(
&self,
access_token: &str,
expected_sub: &str,
) -> Result<UserInfoResponse> {
self.fetch_inner(access_token, Some(expected_sub)).await
}
async fn fetch_inner(
&self,
access_token: &str,
expected_sub: Option<&str>,
) -> Result<UserInfoResponse> {
let scheme = self.userinfo_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!(
"userinfo endpoint {:?} must use https (enable allow_http for development)",
self.userinfo_endpoint
)));
}
if access_token.is_empty() {
return Err(IdentityError::Configuration(
"access token is required".to_string(),
));
}
let response = self
.http
.get(&self.userinfo_endpoint)
.timeout(self.timeout)
.header(AUTHORIZATION, format!("Bearer {access_token}"))
.header(ACCEPT, "application/json")
.send()
.await
.map_err(|e| IdentityError::Http(format!("get {}: {e}", self.userinfo_endpoint)))?;
let status = response.status();
let www_authenticate = response
.headers()
.get(WWW_AUTHENTICATE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let content_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let body = read_capped_body(response).await?;
if !status.is_success() {
return Err(IdentityError::UserInfo {
status: status.as_u16(),
www_authenticate,
body: body_snippet(&body),
});
}
if let Some(ct) = content_type.as_deref()
&& media_type_is_jwt(ct)
{
return Err(IdentityError::Validation(
"signed/encrypted UserInfo (application/jwt) is not supported".to_string(),
));
}
let userinfo: UserInfoResponse = serde_json::from_slice(&body).map_err(|e| {
IdentityError::Deserialization(format!(
"parse userinfo response from {}: {e}",
self.userinfo_endpoint
))
})?;
if userinfo.sub.is_empty() {
return Err(IdentityError::Validation(
"userinfo response is missing the sub claim".to_string(),
));
}
if let Some(expected) = expected_sub
&& userinfo.sub != expected
{
return Err(IdentityError::Validation(
"sub mismatch between ID token and UserInfo".to_string(),
));
}
Ok(userinfo)
}
}
fn media_type_is_jwt(content_type: &str) -> bool {
content_type
.split(';')
.next()
.map(|mt| mt.trim().eq_ignore_ascii_case("application/jwt"))
.unwrap_or(false)
}
async fn read_capped_body(mut response: reqwest::Response) -> Result<Vec<u8>> {
let mut body = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|e| IdentityError::Http(format!("read userinfo response: {e}")))?
{
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err(IdentityError::Http(format!(
"userinfo response exceeds {MAX_BODY_BYTES} bytes"
)));
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn body_snippet(body: &[u8]) -> String {
const MAX: usize = 200;
let text = String::from_utf8_lossy(body);
let text = text.trim().replace('\n', " ");
if text.chars().count() > MAX {
format!("{}…", text.chars().take(MAX).collect::<String>())
} else {
text
}
}
#[derive(Default)]
pub struct UserInfoClientBuilder {
http: Option<HttpClient>,
userinfo_endpoint: Option<String>,
timeout: Duration,
allow_http: bool,
}
impl UserInfoClientBuilder {
fn new() -> Self {
Self::default()
}
pub fn userinfo_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.userinfo_endpoint = Some(endpoint.into());
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<UserInfoClient> {
let userinfo_endpoint = self.userinfo_endpoint.unwrap_or_default();
if userinfo_endpoint.is_empty() {
return Err(IdentityError::Configuration(
"userinfo_endpoint is required".to_string(),
));
}
Ok(UserInfoClient {
http: self.http.unwrap_or_else(crate::http::secure_client),
userinfo_endpoint,
timeout: if self.timeout.is_zero() {
DEFAULT_TIMEOUT
} else {
self.timeout
},
allow_http: self.allow_http,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
const STANDARD_CLAIMS: &str =
include_str!("../../../spec/test-fixtures/userinfo/standard-claims.json");
fn client(endpoint: &str) -> UserInfoClient {
UserInfoClient::builder()
.userinfo_endpoint(endpoint)
.allow_http(true)
.build()
.unwrap()
}
#[tokio::test]
async fn fetch_sends_bearer_and_returns_typed_claims() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.and(header("authorization", "Bearer at-xyz"))
.and(header("accept", "application/json"))
.respond_with(ResponseTemplate::new(200).set_body_string(STANDARD_CLAIMS))
.mount(&server)
.await;
let resp = client(&format!("{}/userinfo", server.uri()))
.fetch("at-xyz")
.await
.expect("fetch succeeds");
assert_eq!(resp.sub, "248289761001");
assert_eq!(resp.name.as_deref(), Some("Jane Doe"));
assert_eq!(resp.email.as_deref(), Some("janedoe@example.com"));
assert_eq!(resp.email_verified, Some(true));
assert!(resp.address.is_some());
assert_eq!(resp.updated_at, Some(1_700_000_000));
}
#[tokio::test]
async fn fetch_preserves_custom_claims() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(ResponseTemplate::new(200).set_body_string(STANDARD_CLAIMS))
.mount(&server)
.await;
let resp = client(&format!("{}/userinfo", server.uri()))
.fetch("tok")
.await
.expect("fetch succeeds");
assert_eq!(
resp.claims().get("department").and_then(|v| v.as_str()),
Some("Engineering")
);
assert!(!resp.claims().contains_key("email"));
}
#[tokio::test]
async fn fetch_with_matching_subject_succeeds() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(ResponseTemplate::new(200).set_body_string(STANDARD_CLAIMS))
.mount(&server)
.await;
let resp = client(&format!("{}/userinfo", server.uri()))
.fetch_with_subject("tok", "248289761001")
.await
.expect("matching sub succeeds");
assert_eq!(resp.sub, "248289761001");
}
#[tokio::test]
async fn fetch_with_mismatched_subject_errors() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(ResponseTemplate::new(200).set_body_string(STANDARD_CLAIMS))
.mount(&server)
.await;
let err = client(&format!("{}/userinfo", server.uri()))
.fetch_with_subject("tok", "someone-else")
.await
.expect_err("mismatch must error");
match err {
IdentityError::Validation(msg) => {
assert_eq!(msg, "sub mismatch between ID token and UserInfo");
}
other => panic!("expected Validation, got {other:?}"),
}
}
#[tokio::test]
async fn handles_401_with_challenge() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(
ResponseTemplate::new(401)
.insert_header("WWW-Authenticate", "Bearer error=\"invalid_token\"")
.set_body_string("unauthorized"),
)
.mount(&server)
.await;
let err = client(&format!("{}/userinfo", server.uri()))
.fetch("bogus")
.await
.expect_err("401 must fail");
match err {
IdentityError::UserInfo {
status,
www_authenticate,
..
} => {
assert_eq!(status, 401);
assert_eq!(
www_authenticate.as_deref(),
Some("Bearer error=\"invalid_token\"")
);
}
other => panic!("expected UserInfo, got {other:?}"),
}
}
#[tokio::test]
async fn handles_403() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(ResponseTemplate::new(403).set_body_string("forbidden"))
.mount(&server)
.await;
let err = client(&format!("{}/userinfo", server.uri()))
.fetch("tok")
.await
.expect_err("403 must fail");
match err {
IdentityError::UserInfo { status, .. } => assert_eq!(status, 403),
other => panic!("expected UserInfo, got {other:?}"),
}
}
#[tokio::test]
async fn handles_500_non_json() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(ResponseTemplate::new(500).set_body_string("upstream boom"))
.mount(&server)
.await;
let err = client(&format!("{}/userinfo", server.uri()))
.fetch("tok")
.await
.expect_err("500 must fail");
match err {
IdentityError::UserInfo { status, body, .. } => {
assert_eq!(status, 500);
assert!(body.contains("upstream boom"), "body snippet: {body}");
}
other => panic!("expected UserInfo, got {other:?}"),
}
}
#[tokio::test]
async fn missing_sub_is_validation_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"name":"No Sub"}"#))
.mount(&server)
.await;
let err = client(&format!("{}/userinfo", server.uri()))
.fetch("tok")
.await
.expect_err("missing sub must fail");
assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
}
#[tokio::test]
async fn rejects_application_jwt_response() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(
ResponseTemplate::new(200)
.set_body_raw("eyJ.signed.jwt".as_bytes(), "application/jwt"),
)
.mount(&server)
.await;
let err = client(&format!("{}/userinfo", server.uri()))
.fetch("tok")
.await
.expect_err("application/jwt must be rejected");
assert!(matches!(err, IdentityError::Validation(_)), "{err:?}");
}
#[tokio::test]
async fn timeout_bounds_slow_endpoint() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/userinfo"))
.respond_with(
ResponseTemplate::new(200)
.set_body_string(STANDARD_CLAIMS)
.set_delay(Duration::from_secs(2)),
)
.mount(&server)
.await;
let custom = reqwest::Client::builder().build().unwrap();
let client = UserInfoClient::builder()
.userinfo_endpoint(format!("{}/userinfo", server.uri()))
.http_client(custom)
.timeout(Duration::from_millis(50))
.allow_http(true)
.build()
.unwrap();
let err = client
.fetch("tok")
.await
.expect_err("slow endpoint times out");
assert!(matches!(err, IdentityError::Http(_)), "{err:?}");
}
#[test]
fn builder_requires_endpoint() {
assert!(matches!(
UserInfoClient::builder().build(),
Err(IdentityError::Configuration(_))
));
}
#[tokio::test]
async fn empty_access_token_is_rejected() {
let err = UserInfoClient::builder()
.userinfo_endpoint("https://issuer.example/userinfo")
.build()
.unwrap()
.fetch("")
.await
.expect_err("empty token must fail");
assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
}
#[tokio::test]
async fn https_required_by_default() {
let err = UserInfoClient::builder()
.userinfo_endpoint("http://insecure.example/userinfo")
.build()
.unwrap()
.fetch("tok")
.await
.expect_err("http endpoint must be rejected");
assert!(matches!(err, IdentityError::Configuration(_)), "{err:?}");
}
}