use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde_json::Value;
use sha2::{Digest, Sha256, Sha384, Sha512};
use subtle::ConstantTimeEq;
use crate::jwks::JwksClient;
use crate::{IdentityError, Result};
use super::claims::Claims;
use super::options::ValidationOptions;
use super::{now_unix, parse_header_alg, validate_token_with_jwks};
const EDDSA_ALGS: &[&str] = &["EdDSA", "Ed25519"];
#[derive(Clone, Debug, Default)]
pub struct IdTokenValidationOptions {
pub(crate) client_id: Option<String>,
pub(crate) nonce: Option<String>,
pub(crate) access_token: Option<String>,
pub(crate) code: Option<String>,
pub(crate) max_age: Option<i64>,
pub(crate) leeway: Duration,
pub(crate) now: Option<i64>,
}
impl IdTokenValidationOptions {
pub fn new() -> Self {
Self::default()
}
pub fn builder() -> IdTokenValidationOptionsBuilder {
IdTokenValidationOptionsBuilder::new()
}
}
#[derive(Clone, Debug, Default)]
pub struct IdTokenValidationOptionsBuilder {
inner: IdTokenValidationOptions,
}
impl IdTokenValidationOptionsBuilder {
fn new() -> Self {
Self::default()
}
pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
self.inner.client_id = Some(client_id.into());
self
}
pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
self.inner.nonce = Some(nonce.into());
self
}
pub fn access_token(mut self, access_token: impl Into<String>) -> Self {
self.inner.access_token = Some(access_token.into());
self
}
pub fn code(mut self, code: impl Into<String>) -> Self {
self.inner.code = Some(code.into());
self
}
pub fn max_age(mut self, max_age: i64) -> Self {
self.inner.max_age = Some(max_age);
self
}
pub fn leeway(mut self, leeway: Duration) -> Self {
self.inner.leeway = leeway;
self
}
pub fn now(mut self, now: i64) -> Self {
self.inner.now = Some(now);
self
}
pub fn build(self) -> IdTokenValidationOptions {
self.inner
}
}
fn digest_for_alg(bytes: &[u8], alg: Option<&str>) -> Result<Vec<u8>> {
let alg = alg.map(str::trim).unwrap_or_default();
if alg.is_empty() {
return Err(IdentityError::IdTokenValidation(
"ID token header 'alg' is required to validate at_hash/c_hash".to_string(),
));
}
if EDDSA_ALGS.contains(&alg) {
return Ok(Sha512::digest(bytes).to_vec());
}
if alg.ends_with("256") {
Ok(Sha256::digest(bytes).to_vec())
} else if alg.ends_with("384") {
Ok(Sha384::digest(bytes).to_vec())
} else if alg.ends_with("512") {
Ok(Sha512::digest(bytes).to_vec())
} else {
Err(IdentityError::IdTokenValidation(format!(
"Unsupported ID token 'alg' {alg:?} for at_hash/c_hash validation"
)))
}
}
fn left_half_hash(value: &str, alg: Option<&str>) -> Result<String> {
let digest = digest_for_alg(value.as_bytes(), alg)?;
let half = digest.len() / 2;
Ok(URL_SAFE_NO_PAD.encode(&digest[..half]))
}
fn ct_eq(a: &str, b: &str) -> bool {
a.as_bytes().ct_eq(b.as_bytes()).into()
}
fn numeric_seconds(value: &Value) -> Option<i64> {
if value.is_boolean() {
return None;
}
if let Some(i) = value.as_i64() {
return Some(i);
}
value.as_f64().map(|f| f.trunc() as i64)
}
pub fn validate_id_token_claims(
claims: &Claims,
header_alg: Option<&str>,
options: &IdTokenValidationOptions,
) -> Result<()> {
if claims.subject.as_deref().unwrap_or_default().is_empty() {
return Err(IdentityError::IdTokenValidation(
"ID token missing required 'sub' claim".to_string(),
));
}
let audiences = claims.audience.values();
let azp = claims.authorized_party.as_deref();
let azp_present = azp.is_some_and(|value| !value.is_empty());
if audiences.len() > 1 && !azp_present {
return Err(IdentityError::IdTokenValidation(
"ID token with multiple audiences must contain an 'azp' claim".to_string(),
));
}
if let (Some(azp), Some(client_id)) = (azp, options.client_id.as_deref())
&& azp != client_id
{
return Err(IdentityError::IdTokenValidation(
"ID token 'azp' claim does not match the configured client_id".to_string(),
));
}
if let Some(expected) = options.nonce.as_deref() {
let matches = claims
.nonce
.as_deref()
.is_some_and(|actual| ct_eq(actual, expected));
if !matches {
return Err(IdentityError::IdTokenValidation(
"ID token 'nonce' claim does not match the expected value".to_string(),
));
}
}
if let Some(max_age) = options.max_age {
let auth_time = claims.get("auth_time").and_then(numeric_seconds);
let Some(auth_time) = auth_time else {
return Err(IdentityError::IdTokenValidation(
"ID token missing required numeric 'auth_time' claim for max_age check".to_string(),
));
};
let now = options.now.unwrap_or_else(now_unix);
let leeway = i64::try_from(options.leeway.as_secs()).unwrap_or(i64::MAX);
if now.saturating_sub(auth_time) > max_age.saturating_add(leeway) {
return Err(IdentityError::IdTokenValidation(
"ID token 'auth_time' is older than the permitted max_age".to_string(),
));
}
}
if let Some(access_token) = options.access_token.as_deref() {
let expected = left_half_hash(access_token, header_alg)?;
let matches = claims
.get_str("at_hash")
.is_some_and(|actual| ct_eq(actual, &expected));
if !matches {
return Err(IdentityError::IdTokenValidation(
"ID token 'at_hash' claim does not match the access token".to_string(),
));
}
}
if let Some(code) = options.code.as_deref() {
let expected = left_half_hash(code, header_alg)?;
let matches = claims
.get_str("c_hash")
.is_some_and(|actual| ct_eq(actual, &expected));
if !matches {
return Err(IdentityError::IdTokenValidation(
"ID token 'c_hash' claim does not match the authorization code".to_string(),
));
}
}
Ok(())
}
pub async fn validate_id_token(
id_token: &str,
jwks: &JwksClient,
jwks_uri: &str,
base: &ValidationOptions,
profile: &IdTokenValidationOptions,
) -> Result<Claims> {
let claims = validate_token_with_jwks(id_token, jwks, jwks_uri, base).await?;
let header_alg = parse_header_alg(id_token)?;
let mut effective = profile.clone();
if effective.client_id.is_none() {
effective.client_id = base.expected_audience.clone();
}
validate_id_token_claims(&claims, header_alg.as_deref(), &effective)?;
Ok(claims)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn claims(value: Value) -> Claims {
Claims::from_json(value).expect("valid claims object")
}
fn assert_id_token_reject(err: &IdentityError, needle: &str) {
match err {
IdentityError::IdTokenValidation(msg) => {
assert!(msg.contains(needle), "message {msg:?} lacks {needle:?}");
}
other => panic!("expected IdTokenValidation, got {other:?}"),
}
}
#[test]
fn accepts_baseline_single_audience() {
let c = claims(
json!({"iss": "https://op.example.com", "sub": "248289761001", "aud": "s6BhdRkqt3"}),
);
let opts = IdTokenValidationOptions::builder()
.client_id("s6BhdRkqt3")
.build();
validate_id_token_claims(&c, Some("RS256"), &opts).expect("baseline validates");
}
#[test]
fn rejects_missing_or_empty_sub() {
let opts = IdTokenValidationOptions::new();
let absent = claims(json!({"aud": "s6BhdRkqt3"}));
assert_id_token_reject(
&validate_id_token_claims(&absent, Some("RS256"), &opts).unwrap_err(),
"required 'sub'",
);
let empty = claims(json!({"sub": "", "aud": "s6BhdRkqt3"}));
assert_id_token_reject(
&validate_id_token_claims(&empty, Some("RS256"), &opts).unwrap_err(),
"required 'sub'",
);
}
#[test]
fn enforces_azp_for_multiple_audiences() {
let cid = IdTokenValidationOptions::builder()
.client_id("s6BhdRkqt3")
.build();
let single_list = claims(json!({"sub": "u", "aud": ["s6BhdRkqt3"]}));
validate_id_token_claims(&single_list, Some("RS256"), &cid)
.expect("single-element aud list needs no azp");
let no_azp = claims(json!({"sub": "u", "aud": ["s6BhdRkqt3", "other-client-9x"]}));
assert_id_token_reject(
&validate_id_token_claims(&no_azp, Some("RS256"), &cid).unwrap_err(),
"multiple audiences must contain an 'azp'",
);
let wrong_azp = claims(
json!({"sub": "u", "aud": ["s6BhdRkqt3", "other-client-9x"], "azp": "other-client-9x"}),
);
assert_id_token_reject(
&validate_id_token_claims(&wrong_azp, Some("RS256"), &cid).unwrap_err(),
"'azp' claim does not match",
);
let right_azp = claims(
json!({"sub": "u", "aud": ["s6BhdRkqt3", "other-client-9x"], "azp": "s6BhdRkqt3"}),
);
validate_id_token_claims(&right_azp, Some("RS256"), &cid)
.expect("multi-aud with matching azp validates");
}
#[test]
fn empty_string_azp_matches_oracle_truthiness() {
let multi_empty =
claims(json!({"sub": "u", "aud": ["s6BhdRkqt3", "other-client-9x"], "azp": ""}));
assert_id_token_reject(
&validate_id_token_claims(
&multi_empty,
Some("RS256"),
&IdTokenValidationOptions::new(),
)
.unwrap_err(),
"multiple audiences must contain an 'azp'",
);
let cid = IdTokenValidationOptions::builder()
.client_id("s6BhdRkqt3")
.build();
assert_id_token_reject(
&validate_id_token_claims(&multi_empty, Some("RS256"), &cid).unwrap_err(),
"multiple audiences must contain an 'azp'",
);
let single_empty_cid = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "azp": ""}));
assert_id_token_reject(
&validate_id_token_claims(&single_empty_cid, Some("RS256"), &cid).unwrap_err(),
"'azp' claim does not match",
);
validate_id_token_claims(
&single_empty_cid,
Some("RS256"),
&IdTokenValidationOptions::new(),
)
.expect("empty azp on single audience with no client_id validates");
}
#[test]
fn validates_present_azp_for_single_audience() {
let cid = IdTokenValidationOptions::builder()
.client_id("s6BhdRkqt3")
.build();
let ok = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "azp": "s6BhdRkqt3"}));
validate_id_token_claims(&ok, Some("RS256"), &cid).expect("matching azp validates");
let bad = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "azp": "impostor-client"}));
assert_id_token_reject(
&validate_id_token_claims(&bad, Some("RS256"), &cid).unwrap_err(),
"'azp' claim does not match",
);
}
#[test]
fn enforces_nonce_binding() {
let c = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "nonce": "n-0S6_WzA2Mj"}));
let matching = IdTokenValidationOptions::builder()
.client_id("s6BhdRkqt3")
.nonce("n-0S6_WzA2Mj")
.build();
validate_id_token_claims(&c, Some("RS256"), &matching).expect("matching nonce validates");
let mismatch = IdTokenValidationOptions::builder()
.nonce("a-different-nonce")
.build();
assert_id_token_reject(
&validate_id_token_claims(&c, Some("RS256"), &mismatch).unwrap_err(),
"'nonce' claim does not match",
);
let absent = claims(json!({"sub": "u", "aud": "s6BhdRkqt3"}));
assert_id_token_reject(
&validate_id_token_claims(&absent, Some("RS256"), &matching).unwrap_err(),
"'nonce' claim does not match",
);
}
#[test]
fn enforces_auth_time_freshness() {
let within = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "auth_time": 1_699_999_900}));
let opts = IdTokenValidationOptions::builder()
.max_age(3600)
.now(1_700_000_000)
.build();
validate_id_token_claims(&within, Some("RS256"), &opts).expect("fresh auth_time validates");
let leeway_case =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "auth_time": 1_699_996_390}));
let with_leeway = IdTokenValidationOptions::builder()
.max_age(3600)
.leeway(Duration::from_secs(60))
.now(1_700_000_000)
.build();
validate_id_token_claims(&leeway_case, Some("RS256"), &with_leeway)
.expect("just-past max_age but within leeway validates");
let stale = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "auth_time": 1_699_992_800}));
assert_id_token_reject(
&validate_id_token_claims(&stale, Some("RS256"), &opts).unwrap_err(),
"'auth_time' is older than",
);
let missing = claims(json!({"sub": "u", "aud": "s6BhdRkqt3"}));
assert_id_token_reject(
&validate_id_token_claims(&missing, Some("RS256"), &opts).unwrap_err(),
"missing required numeric 'auth_time'",
);
}
#[test]
fn enforces_at_hash_rs256() {
let access_token = "jHkWEdUXMU1BwAsC4vtUsZwnNvTIxEl0z9K3vx5KntU";
let opts = IdTokenValidationOptions::builder()
.access_token(access_token)
.build();
let good =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "at_hash": "T7VF8gELfbwjUBkK04GEhg"}));
validate_id_token_claims(&good, Some("RS256"), &opts).expect("correct at_hash validates");
let bad =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "at_hash": "DyAleB7ctGQvU9M3DbMBYQ"}));
assert_id_token_reject(
&validate_id_token_claims(&bad, Some("RS256"), &opts).unwrap_err(),
"'at_hash' claim does not match",
);
let absent = claims(json!({"sub": "u", "aud": "s6BhdRkqt3"}));
assert_id_token_reject(
&validate_id_token_claims(&absent, Some("RS256"), &opts).unwrap_err(),
"'at_hash' claim does not match",
);
let unchecked = IdTokenValidationOptions::new();
validate_id_token_claims(&good, Some("RS256"), &unchecked)
.expect("at_hash unchecked without an access token");
}
#[test]
fn at_hash_hash_is_selected_by_alg() {
let es512 = IdTokenValidationOptions::builder()
.access_token("YmExYzZmZTgtZXM1MTItYWNjZXNzLXRva2VuLWV4YW1wbGU")
.build();
let good = claims(json!({
"sub": "u", "aud": "s6BhdRkqt3",
"at_hash": "2azZeYx02zZttjvAxgBshVhQxqEJ6Ku0oRgkegwI9Ww"
}));
validate_id_token_claims(&good, Some("ES512"), &es512).expect("ES512 at_hash validates");
let sha256_sized = IdTokenValidationOptions::builder()
.access_token("jHkWEdUXMU1BwAsC4vtUsZwnNvTIxEl0z9K3vx5KntU")
.build();
let mismatched =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "at_hash": "T7VF8gELfbwjUBkK04GEhg"}));
assert_id_token_reject(
&validate_id_token_claims(&mismatched, Some("ES512"), &sha256_sized).unwrap_err(),
"'at_hash' claim does not match",
);
}
#[test]
fn enforces_c_hash() {
let rs = IdTokenValidationOptions::builder()
.code("Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk")
.build();
let good =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "c_hash": "LDktKdoQak3Pk0cnXxCltA"}));
validate_id_token_claims(&good, Some("RS256"), &rs).expect("RS256 c_hash validates");
let bad =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "c_hash": "DyAleB7ctGQvU9M3DbMBYQ"}));
assert_id_token_reject(
&validate_id_token_claims(&bad, Some("RS256"), &rs).unwrap_err(),
"'c_hash' claim does not match",
);
let es = IdTokenValidationOptions::builder()
.code("Y29kZS1lczUxMi1hdXRob3JpemF0aW9uLWNvZGUtZXhhbXBsZQ")
.build();
let es_good = claims(json!({
"sub": "u", "aud": "s6BhdRkqt3",
"c_hash": "5ZRO6ySh8Y5x73OPd63wcyIunjtbSNZh9sQvDCegRDY"
}));
validate_id_token_claims(&es_good, Some("ES512"), &es).expect("ES512 c_hash validates");
}
#[test]
fn hash_check_fails_closed_on_bad_alg() {
let at = IdTokenValidationOptions::builder()
.access_token("jHkWEdUXMU1BwAsC4vtUsZwnNvTIxEl0z9K3vx5KntU")
.build();
let with_at =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "at_hash": "T7VF8gELfbwjUBkK04GEhg"}));
assert_id_token_reject(
&validate_id_token_claims(&with_at, Some("UNKNOWN"), &at).unwrap_err(),
"Unsupported ID token 'alg'",
);
assert_id_token_reject(
&validate_id_token_claims(&with_at, None, &at).unwrap_err(),
"header 'alg' is required",
);
let code = IdTokenValidationOptions::builder()
.code("Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk")
.build();
let with_code =
claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "c_hash": "LDktKdoQak3Pk0cnXxCltA"}));
assert_id_token_reject(
&validate_id_token_claims(&with_code, Some("RS999"), &code).unwrap_err(),
"Unsupported ID token 'alg'",
);
}
#[test]
fn boolean_auth_time_is_not_numeric() {
let c = claims(json!({"sub": "u", "aud": "s6BhdRkqt3", "auth_time": true}));
let opts = IdTokenValidationOptions::builder()
.max_age(3600)
.now(1_700_000_000)
.build();
assert_id_token_reject(
&validate_id_token_claims(&c, Some("RS256"), &opts).unwrap_err(),
"missing required numeric 'auth_time'",
);
}
}