use std::collections::{HashMap, HashSet};
use serde_json::{Map, Value};
use crate::{IdentityError, Result};
use super::options::ValidationOptions;
const MAX_NUMERIC_DATE: i64 = 1 << 53;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Audience(pub Vec<String>);
impl Audience {
fn from_value(value: &Value) -> Result<Self> {
match value {
Value::Null => Ok(Audience(Vec::new())),
Value::String(s) => Ok(Audience(vec![s.clone()])),
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
match item {
Value::String(s) => out.push(s.clone()),
_ => {
return Err(IdentityError::Validation(
"claim \"aud\" invalid: array must contain only strings"
.to_string(),
));
}
}
}
Ok(Audience(out))
}
_ => Err(IdentityError::Validation(
"claim \"aud\" invalid: must be a string or array of strings".to_string(),
)),
}
}
pub fn contains(&self, s: &str) -> bool {
self.0.iter().any(|v| v == s)
}
pub fn values(&self) -> &[String] {
&self.0
}
}
#[derive(Clone, Debug)]
pub struct Claims {
pub issuer: Option<String>,
pub subject: Option<String>,
pub audience: Audience,
pub expiry: Option<i64>,
pub not_before: Option<i64>,
pub issued_at: Option<i64>,
pub id: Option<String>,
pub nonce: Option<String>,
pub authorized_party: Option<String>,
pub extra: HashMap<String, Value>,
present: HashSet<String>,
meaningful: HashSet<String>,
}
const MODELLED_CLAIMS: &[&str] = &[
"iss", "sub", "aud", "exp", "nbf", "iat", "jti", "nonce", "azp",
];
impl Claims {
pub(crate) fn from_value(value: Value) -> Result<Self> {
let Value::Object(map) = value else {
return Err(IdentityError::Deserialization(
"JWT claims payload is not a JSON object".to_string(),
));
};
Self::from_map(map)
}
pub fn from_json(value: Value) -> Result<Self> {
Self::from_value(value)
}
fn from_map(map: Map<String, Value>) -> Result<Self> {
let present: HashSet<String> = map.keys().cloned().collect();
let meaningful: HashSet<String> = map
.iter()
.filter(|(_, v)| is_meaningful_value(v))
.map(|(k, _)| k.clone())
.collect();
let issuer = string_claim(&map, "iss")?;
let subject = string_claim(&map, "sub")?;
let audience = match map.get("aud") {
Some(v) => Audience::from_value(v)?,
None => Audience::default(),
};
let expiry = numeric_date_claim(&map, "exp")?;
let not_before = numeric_date_claim(&map, "nbf")?;
let issued_at = numeric_date_claim(&map, "iat")?;
let id = string_claim(&map, "jti")?;
let nonce = string_claim(&map, "nonce")?;
let authorized_party = string_claim(&map, "azp")?;
let modelled: HashSet<&str> = MODELLED_CLAIMS.iter().copied().collect();
let extra: HashMap<String, Value> = map
.into_iter()
.filter(|(k, _)| !modelled.contains(k.as_str()))
.collect();
Ok(Claims {
issuer,
subject,
audience,
expiry,
not_before,
issued_at,
id,
nonce,
authorized_party,
extra,
present,
meaningful,
})
}
pub fn has(&self, claim: &str) -> bool {
self.present.contains(claim)
}
pub(crate) fn has_meaningful(&self, claim: &str) -> bool {
self.meaningful.contains(claim)
}
pub fn get(&self, claim: &str) -> Option<&Value> {
self.extra.get(claim)
}
pub fn get_str(&self, claim: &str) -> Option<&str> {
self.extra.get(claim).and_then(Value::as_str)
}
pub(crate) fn validate(&self, opts: &ValidationOptions, now_unix: i64) -> Result<()> {
let skew = i64::try_from(opts.clock_skew.as_secs()).unwrap_or(i64::MAX);
if self.issued_at.is_none() {
return Err(claim_err("iat", "required claim is missing"));
}
match self.expiry {
None if opts.require_exp => {
return Err(claim_err("exp", "required claim is missing"));
}
Some(exp) if now_unix.saturating_sub(skew) >= exp => {
return Err(claim_err(
"exp",
&format!("token expired at {exp} (now {now_unix}, skew {skew}s)"),
));
}
_ => {}
}
match self.not_before {
None if opts.require_nbf => {
return Err(claim_err("nbf", "required claim is missing"));
}
Some(nbf) if now_unix.saturating_add(skew) < nbf => {
return Err(claim_err("nbf", "token is not yet valid"));
}
_ => {}
}
if let Some(expected) = &opts.expected_issuer {
let actual = self.issuer.as_deref().unwrap_or_default();
if actual != expected {
return Err(claim_err(
"iss",
&format!("expected {expected:?}, got {actual:?}"),
));
}
}
if let Some(expected) = &opts.expected_audience
&& !self.audience.contains(expected)
{
return Err(claim_err(
"aud",
&format!(
"does not contain expected audience {expected:?} (token audiences: {:?})",
self.audience.values()
),
));
}
if let Some(client_id) = &opts.expected_audience {
match &self.authorized_party {
Some(azp) if azp != client_id => {
return Err(claim_err(
"azp",
&format!("authorized party {azp:?} does not match client {client_id:?}"),
));
}
None if self.audience.values().len() > 1 => {
return Err(claim_err(
"azp",
"token with multiple audiences must carry an azp claim",
));
}
_ => {}
}
}
if let Some(expected) = &opts.expected_nonce {
match &self.nonce {
None => return Err(claim_err("nonce", "required nonce claim is missing")),
Some(actual) if actual != expected => {
return Err(claim_err("nonce", "nonce does not match expected value"));
}
Some(_) => {}
}
}
for claim in &opts.required_claims {
if !self.meaningful.contains(claim) {
return Err(claim_err(claim, "required claim is missing or empty"));
}
}
Ok(())
}
}
fn claim_err(claim: &str, reason: &str) -> IdentityError {
IdentityError::Validation(format!("claim {claim:?} invalid: {reason}"))
}
fn string_claim(map: &Map<String, Value>, name: &str) -> Result<Option<String>> {
match map.get(name) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(claim_err(name, "must be a string")),
}
}
fn numeric_date_claim(map: &Map<String, Value>, name: &str) -> Result<Option<i64>> {
let Some(value) = map.get(name) else {
return Ok(None);
};
if let Some(secs) = value.as_i64() {
if secs.unsigned_abs() > MAX_NUMERIC_DATE as u64 {
return Err(claim_err(name, "numeric date is out of range"));
}
return Ok(Some(secs));
}
let Some(secs) = value.as_f64() else {
return Err(claim_err(name, "must be a numeric date"));
};
if !secs.is_finite() || secs.abs() > MAX_NUMERIC_DATE as f64 {
return Err(claim_err(name, "numeric date is out of range"));
}
Ok(Some(secs.trunc() as i64))
}
fn is_meaningful_value(value: &Value) -> bool {
match value {
Value::Null => false,
Value::String(s) => !s.is_empty(),
Value::Array(a) => !a.is_empty(),
Value::Object(o) => !o.is_empty(),
_ => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
const NOW: i64 = 1_700_000_000;
fn claims(value: Value) -> Claims {
Claims::from_value(value).expect("valid claims object")
}
#[test]
fn accepts_valid_registered_claims() {
let c = claims(serde_json::json!({
"iss": "https://issuer.example.com",
"sub": "user-1",
"aud": "test-client",
"exp": NOW + 3600,
"nbf": NOW - 10,
"iat": NOW - 10,
}));
let opts = ValidationOptions::builder()
.issuer("https://issuer.example.com")
.audience("test-client")
.build();
c.validate(&opts, NOW).expect("valid token passes");
}
#[test]
fn rejects_missing_iat() {
let c = claims(serde_json::json!({ "exp": NOW + 3600 }));
let err = c
.validate(&ValidationOptions::new(), NOW)
.expect_err("missing iat rejected");
assert!(err.to_string().contains("iat"), "{err}");
}
#[test]
fn rejects_expired() {
let c = claims(serde_json::json!({ "exp": NOW - 3600, "iat": NOW - 7200 }));
let err = c
.validate(&ValidationOptions::new(), NOW)
.expect_err("expired rejected");
assert!(err.to_string().contains("expired"), "{err}");
}
#[test]
fn tolerates_clock_skew() {
let c = claims(serde_json::json!({ "exp": NOW - 30, "iat": NOW - 3600 }));
let opts = ValidationOptions::builder()
.clock_skew(Duration::from_secs(60))
.build();
c.validate(&opts, NOW).expect("within skew passes");
}
#[test]
fn rejects_not_yet_valid() {
let c = claims(serde_json::json!({
"exp": NOW + 3600,
"nbf": NOW + 3600,
"iat": NOW,
}));
let err = c
.validate(&ValidationOptions::new(), NOW)
.expect_err("nbf in future rejected");
assert!(err.to_string().contains("nbf"), "{err}");
}
#[test]
fn rejects_wrong_issuer() {
let c = claims(serde_json::json!({
"iss": "https://evil.example.com",
"exp": NOW + 3600,
"iat": NOW,
}));
let opts = ValidationOptions::builder()
.issuer("https://issuer.example.com")
.build();
let err = c.validate(&opts, NOW).expect_err("wrong issuer rejected");
assert!(err.to_string().contains("iss"), "{err}");
}
#[test]
fn rejects_wrong_or_absent_audience() {
let opts = ValidationOptions::builder().audience("test-client").build();
let wrong = claims(serde_json::json!({
"aud": ["other-client"],
"exp": NOW + 3600,
"iat": NOW,
}));
let err = wrong.validate(&opts, NOW).expect_err("wrong aud rejected");
assert!(err.to_string().contains("aud"), "{err}");
let absent = claims(serde_json::json!({ "exp": NOW + 3600, "iat": NOW }));
absent
.validate(&opts, NOW)
.expect_err("absent aud rejected when expected");
}
#[test]
fn validates_nonce_when_expected() {
let opts = ValidationOptions::builder().expected_nonce("n-123").build();
let mismatch = claims(serde_json::json!({
"nonce": "other",
"exp": NOW + 3600,
"iat": NOW,
}));
mismatch
.validate(&opts, NOW)
.expect_err("nonce mismatch rejected");
let matching = claims(serde_json::json!({
"nonce": "n-123",
"exp": NOW + 3600,
"iat": NOW,
}));
matching
.validate(&opts, NOW)
.expect("matching nonce passes");
}
#[test]
fn multi_audience_requires_matching_azp() {
let opts = ValidationOptions::builder().audience("test-client").build();
let ok = claims(serde_json::json!({
"aud": ["test-client", "other-rp"],
"azp": "test-client",
"exp": NOW + 3600,
"iat": NOW,
}));
ok.validate(&opts, NOW)
.expect("multi-aud with correct azp passes");
let no_azp = claims(serde_json::json!({
"aud": ["test-client", "other-rp"],
"exp": NOW + 3600,
"iat": NOW,
}));
let err = no_azp
.validate(&opts, NOW)
.expect_err("multi-aud without azp rejected");
assert!(err.to_string().contains("azp"), "{err}");
let wrong_azp = claims(serde_json::json!({
"aud": ["test-client", "other-rp"],
"azp": "other-rp",
"exp": NOW + 3600,
"iat": NOW,
}));
let err = wrong_azp
.validate(&opts, NOW)
.expect_err("multi-aud with wrong azp rejected");
assert!(err.to_string().contains("azp"), "{err}");
}
#[test]
fn present_azp_must_match_client() {
let opts = ValidationOptions::builder().audience("test-client").build();
let wrong = claims(serde_json::json!({
"aud": "test-client",
"azp": "attacker",
"exp": NOW + 3600,
"iat": NOW,
}));
let err = wrong
.validate(&opts, NOW)
.expect_err("single-aud wrong azp rejected");
assert!(err.to_string().contains("azp"), "{err}");
let right = claims(serde_json::json!({
"aud": "test-client",
"azp": "test-client",
"exp": NOW + 3600,
"iat": NOW,
}));
right
.validate(&opts, NOW)
.expect("single-aud matching azp passes");
let none = claims(serde_json::json!({
"aud": "test-client",
"exp": NOW + 3600,
"iat": NOW,
}));
none.validate(&opts, NOW)
.expect("single-aud without azp passes");
}
#[test]
fn azp_not_enforced_without_expected_audience() {
let c = claims(serde_json::json!({
"aud": ["a", "b"],
"exp": NOW + 3600,
"iat": NOW,
}));
c.validate(&ValidationOptions::new(), NOW)
.expect("no expected audience -> azp not enforced");
}
#[test]
fn enforces_custom_required_claims() {
let c = claims(serde_json::json!({ "exp": NOW + 3600, "iat": NOW }));
let opts = ValidationOptions::builder()
.required_claims(["scope"])
.build();
let err = c
.validate(&opts, NOW)
.expect_err("missing required claim rejected");
assert!(err.to_string().contains("scope"), "{err}");
let with = claims(serde_json::json!({
"exp": NOW + 3600,
"iat": NOW,
"scope": "openid",
}));
with.validate(&opts, NOW).expect("present required claim");
}
#[test]
fn parses_audience_forms_and_extra_claims() {
let single = claims(serde_json::json!({ "aud": "a", "iat": NOW, "exp": NOW + 1 }));
assert_eq!(single.audience.values(), ["a"]);
let many = claims(serde_json::json!({
"aud": ["a", "b"],
"iat": NOW,
"exp": NOW + 1,
"email": "user@example.com",
}));
assert!(many.audience.contains("b"));
assert_eq!(many.get_str("email"), Some("user@example.com"));
assert!(many.has("email") && many.has("aud"));
assert!(!many.has("groups"));
}
#[test]
fn rejects_null_audience_element() {
let err =
Claims::from_value(serde_json::json!({ "aud": ["a", null] })).expect_err("null aud");
assert!(err.to_string().contains("aud"), "{err}");
}
#[test]
fn rejects_out_of_range_numeric_date() {
let huge = (MAX_NUMERIC_DATE as f64) * 2.0;
let err = Claims::from_value(serde_json::json!({ "exp": huge, "iat": NOW }))
.expect_err("out-of-range exp");
assert!(err.to_string().contains("exp"), "{err}");
}
#[test]
fn rejects_large_integer_numeric_date_precisely() {
let just_over = MAX_NUMERIC_DATE + 1;
let err = Claims::from_value(serde_json::json!({ "exp": just_over, "iat": NOW }))
.expect_err("out-of-range integer exp");
assert!(err.to_string().contains("exp"), "{err}");
}
#[test]
fn require_exp_false_allows_missing_exp() {
let opts = ValidationOptions::builder().require_exp(false).build();
let no_exp = claims(serde_json::json!({ "iat": NOW }));
no_exp.validate(&opts, NOW).expect("missing exp tolerated");
let expired = claims(serde_json::json!({ "exp": NOW - 3600, "iat": NOW - 7200 }));
expired
.validate(&opts, NOW)
.expect_err("present-but-expired exp still rejected");
}
#[test]
fn require_nbf_true_rejects_missing_nbf() {
let opts = ValidationOptions::builder().require_nbf(true).build();
let c = claims(serde_json::json!({ "exp": NOW + 3600, "iat": NOW }));
let err = c.validate(&opts, NOW).expect_err("missing nbf rejected");
assert!(err.to_string().contains("nbf"), "{err}");
}
#[test]
fn expired_error_includes_exp_value() {
let exp = NOW - 3600;
let c = claims(serde_json::json!({ "exp": exp, "iat": NOW - 7200 }));
let err = c
.validate(&ValidationOptions::new(), NOW)
.expect_err("expired rejected");
assert!(err.to_string().contains(&exp.to_string()), "{err}");
}
#[test]
fn audience_error_lists_actual_values() {
let opts = ValidationOptions::builder().audience("test-client").build();
let c = claims(serde_json::json!({
"aud": ["other-a", "other-b"],
"exp": NOW + 3600,
"iat": NOW,
}));
let err = c.validate(&opts, NOW).expect_err("aud mismatch rejected");
let msg = err.to_string();
assert!(msg.contains("test-client"), "expected value missing: {msg}");
assert!(msg.contains("other-a"), "actual value missing: {msg}");
}
#[test]
fn required_claim_rejects_null_or_empty_value() {
let opts = ValidationOptions::builder()
.required_claims(["scope"])
.build();
for empty in [
serde_json::json!(null),
serde_json::json!(""),
serde_json::json!([]),
serde_json::json!({}),
] {
let c = claims(serde_json::json!({
"exp": NOW + 3600,
"iat": NOW,
"scope": empty,
}));
c.validate(&opts, NOW)
.expect_err("null/empty required claim rejected");
}
}
#[test]
fn expected_empty_nonce_requires_presence() {
let opts = ValidationOptions::builder().expected_nonce("").build();
let absent = claims(serde_json::json!({ "exp": NOW + 3600, "iat": NOW }));
absent
.validate(&opts, NOW)
.expect_err("absent nonce rejected when expected");
let present = claims(serde_json::json!({
"nonce": "",
"exp": NOW + 3600,
"iat": NOW,
}));
present
.validate(&opts, NOW)
.expect("present empty nonce matches expected empty nonce");
}
}