mod claims;
mod options;
use std::time::{SystemTime, UNIX_EPOCH};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
use serde::Deserialize;
use serde_json::Value;
use crate::jwks::{JsonWebKey, JwksClient};
use crate::{IdentityError, Result};
pub use claims::{Audience, Claims};
pub use options::{DEFAULT_ALLOWED_ALGORITHMS, ValidationOptions, ValidationOptionsBuilder};
#[derive(Debug, Deserialize)]
struct JoseHeader {
#[serde(default)]
alg: String,
#[serde(default)]
kid: String,
}
pub fn validate_token(
token: &str,
key: &JsonWebKey,
options: &ValidationOptions,
) -> Result<Claims> {
let token = token.trim();
let header = parse_header(token)?;
let alg = check_algorithm(&header, options)?;
let decoding_key = decoding_key_for(key)?;
let mut validation = Validation::new(alg);
validation.validate_exp = false;
validation.validate_nbf = false;
validation.validate_aud = false;
validation.required_spec_claims.clear();
validation.algorithms = vec![alg];
let token_data = decode::<Value>(token, &decoding_key, &validation).map_err(map_verify_err)?;
let claims = Claims::from_value(token_data.claims)?;
claims.validate(options, now_unix())?;
Ok(claims)
}
pub async fn validate_token_with_jwks(
token: &str,
jwks: &JwksClient,
jwks_uri: &str,
options: &ValidationOptions,
) -> Result<Claims> {
let token = token.trim();
let header = parse_header(token)?;
check_algorithm(&header, options)?;
let key = jwks.resolve_key(jwks_uri, &header.kid).await?;
validate_token(token, &key, options)
}
fn parse_header(token: &str) -> Result<JoseHeader> {
let parts: Vec<&str> = token.split('.').collect();
if parts.len() != 3 {
return Err(IdentityError::Validation(format!(
"malformed token: compact JWS must have 3 segments, got {}",
parts.len()
)));
}
if parts[0].is_empty() {
return Err(IdentityError::Validation(
"malformed token: empty header segment".to_string(),
));
}
let raw = URL_SAFE_NO_PAD
.decode(parts[0])
.map_err(|e| IdentityError::Validation(format!("malformed token: decode header: {e}")))?;
serde_json::from_slice(&raw)
.map_err(|e| IdentityError::Validation(format!("malformed token: parse header JSON: {e}")))
}
fn check_algorithm(header: &JoseHeader, options: &ValidationOptions) -> Result<Algorithm> {
if header.alg.eq_ignore_ascii_case("none") {
return Err(IdentityError::Validation(
"unsecured token with algorithm \"none\" is rejected".to_string(),
));
}
if header.alg.is_empty() {
return Err(IdentityError::Validation(
"malformed token: header is missing the \"alg\" parameter".to_string(),
));
}
if !options.allowed_algorithms.iter().any(|a| a == &header.alg) {
return Err(IdentityError::Validation(format!(
"unsupported or disallowed algorithm {:?}",
header.alg
)));
}
algorithm_from_str(&header.alg)
}
fn algorithm_from_str(alg: &str) -> Result<Algorithm> {
let mapped = match alg {
"RS256" => Algorithm::RS256,
"RS384" => Algorithm::RS384,
"RS512" => Algorithm::RS512,
"PS256" => Algorithm::PS256,
"PS384" => Algorithm::PS384,
"PS512" => Algorithm::PS512,
"ES256" => Algorithm::ES256,
"ES384" => Algorithm::ES384,
_ => {
return Err(IdentityError::Validation(format!(
"unsupported or disallowed algorithm {alg:?}"
)));
}
};
Ok(mapped)
}
fn decoding_key_for(key: &JsonWebKey) -> Result<DecodingKey> {
match key.kty.as_str() {
"RSA" => DecodingKey::from_rsa_components(&key.n, &key.e)
.map_err(|e| IdentityError::Validation(format!("convert RSA key {:?}: {e}", key.kid))),
"EC" => DecodingKey::from_ec_components(&key.x, &key.y)
.map_err(|e| IdentityError::Validation(format!("convert EC key {:?}: {e}", key.kid))),
other => Err(IdentityError::Validation(format!(
"unsupported key type {other:?}"
))),
}
}
fn map_verify_err(err: jsonwebtoken::errors::Error) -> IdentityError {
use jsonwebtoken::errors::ErrorKind;
match err.kind() {
ErrorKind::InvalidSignature => {
IdentityError::Validation("signature verification failed".to_string())
}
_ => IdentityError::Validation(format!("signature verification failed: {err}")),
}
}
fn now_unix() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::jwks::JsonWebKeySet;
use jsonwebtoken::{EncodingKey, Header};
use serde_json::json;
use std::time::Duration;
const FIXTURE_DIR: &str = "../spec/test-fixtures/validation";
const TEST_KID: &str = "test-key-1";
const TEST_ISSUER: &str = "https://issuer.example.com";
const TEST_AUDIENCE: &str = "test-client";
fn read_fixture(name: &str) -> Vec<u8> {
std::fs::read(format!("{FIXTURE_DIR}/{name}"))
.unwrap_or_else(|e| panic!("read fixture {name}: {e}"))
}
fn signing_key() -> EncodingKey {
EncodingKey::from_rsa_der(&read_fixture("signing-key.pkcs1.der"))
}
fn public_key() -> JsonWebKey {
let set = JsonWebKeySet::parse(&read_fixture("jwks.json")).expect("parse jwks fixture");
set.resolve_key(TEST_KID).expect("fixture key").clone()
}
fn mint(claims: Value) -> String {
let mut header = Header::new(Algorithm::RS256);
header.kid = Some(TEST_KID.to_string());
jsonwebtoken::encode(&header, &claims, &signing_key()).expect("sign token")
}
fn now() -> i64 {
now_unix()
}
#[test]
fn accepts_valid_rsa_token() {
let n = now();
let token = mint(json!({
"iss": TEST_ISSUER,
"sub": "user-1",
"aud": TEST_AUDIENCE,
"exp": n + 3600,
"iat": n - 5,
}));
let opts = ValidationOptions::builder()
.issuer(TEST_ISSUER)
.audience(TEST_AUDIENCE)
.build();
let claims = validate_token(&token, &public_key(), &opts).expect("valid token");
assert_eq!(claims.subject.as_deref(), Some("user-1"));
assert_eq!(claims.issuer.as_deref(), Some(TEST_ISSUER));
assert!(claims.audience.contains(TEST_AUDIENCE));
}
#[test]
fn accepts_valid_ec_token() {
use p256::elliptic_curve::sec1::ToSec1Point;
use p256::pkcs8::{EncodePrivateKey, LineEnding as P256LineEnding};
let secret = p256::SecretKey::from_slice(&[1u8; 32]).expect("valid P-256 scalar");
let pkcs8 = secret.to_pkcs8_pem(P256LineEnding::LF).expect("pkcs8 pem");
let encoding = EncodingKey::from_ec_pem(pkcs8.as_bytes()).expect("EC encoding key");
let point = secret.public_key().to_sec1_point(false);
let x = URL_SAFE_NO_PAD.encode(point.x().expect("x coordinate"));
let y = URL_SAFE_NO_PAD.encode(point.y().expect("y coordinate"));
let jwk: JsonWebKey = serde_json::from_value(json!({
"kty": "EC",
"crv": "P-256",
"x": x,
"y": y,
"kid": "ec-test",
"alg": "ES256",
}))
.expect("EC jwk");
let n = now();
let mut header = Header::new(Algorithm::ES256);
header.kid = Some("ec-test".to_string());
let claims = json!({ "iss": TEST_ISSUER, "sub": "ec-user", "exp": n + 3600, "iat": n });
let token = jsonwebtoken::encode(&header, &claims, &encoding).expect("sign ES256");
let opts = ValidationOptions::builder().issuer(TEST_ISSUER).build();
let validated = validate_token(&token, &jwk, &opts).expect("valid ES256 token");
assert_eq!(validated.subject.as_deref(), Some("ec-user"));
}
#[test]
fn rejects_alg_none_fixture() {
let token = String::from_utf8(read_fixture("alg-none-token.txt")).expect("utf8 token");
let err = validate_token(token.trim(), &public_key(), &ValidationOptions::new())
.expect_err("alg none rejected");
assert!(err.to_string().contains("none"), "{err}");
}
#[test]
fn rejects_tampered_signature() {
let n = now();
let token = mint(json!({ "iss": TEST_ISSUER, "exp": n + 3600, "iat": n }));
let (head, sig) = token.rsplit_once('.').expect("three segments");
let last = sig.chars().last().expect("non-empty signature");
let swapped = if last == 'A' { 'B' } else { 'A' };
let tampered = format!("{head}.{}{swapped}", &sig[..sig.len() - 1]);
let err = validate_token(&tampered, &public_key(), &ValidationOptions::new())
.expect_err("tampered signature rejected");
assert!(err.to_string().contains("signature"), "{err}");
}
#[test]
fn rejects_disallowed_algorithm() {
let n = now();
let token = mint(json!({ "iss": TEST_ISSUER, "exp": n + 3600, "iat": n }));
let opts = ValidationOptions::builder()
.allowed_algorithms(["ES256"])
.build();
let err = validate_token(&token, &public_key(), &opts).expect_err("RS256 disallowed");
assert!(err.to_string().contains("disallowed"), "{err}");
}
#[test]
fn rejects_malformed_token() {
let err = validate_token("not.a", &public_key(), &ValidationOptions::new())
.expect_err("two-segment token rejected");
assert!(err.to_string().contains("malformed"), "{err}");
}
#[test]
fn rejects_expired_token_end_to_end() {
let n = now();
let token = mint(json!({ "iss": TEST_ISSUER, "exp": n - 10, "iat": n - 3600 }));
let err = validate_token(&token, &public_key(), &ValidationOptions::new())
.expect_err("expired rejected");
assert!(err.to_string().contains("expired"), "{err}");
}
#[test]
fn tolerates_skew_end_to_end() {
let n = now();
let token = mint(json!({ "iss": TEST_ISSUER, "exp": n - 30, "iat": n - 3600 }));
let opts = ValidationOptions::builder()
.clock_skew(Duration::from_secs(120))
.build();
validate_token(&token, &public_key(), &opts).expect("within skew passes");
}
#[test]
fn enforces_azp_for_multi_audience_end_to_end() {
let n = now();
let opts = ValidationOptions::builder()
.issuer(TEST_ISSUER)
.audience(TEST_AUDIENCE)
.build();
let no_azp = mint(json!({
"iss": TEST_ISSUER,
"aud": [TEST_AUDIENCE, "other-rp"],
"exp": n + 3600,
"iat": n - 5,
}));
let err = validate_token(&no_azp, &public_key(), &opts)
.expect_err("multi-aud without azp rejected");
assert!(err.to_string().contains("azp"), "{err}");
let with_azp = mint(json!({
"iss": TEST_ISSUER,
"aud": [TEST_AUDIENCE, "other-rp"],
"azp": TEST_AUDIENCE,
"exp": n + 3600,
"iat": n - 5,
}));
validate_token(&with_azp, &public_key(), &opts).expect("multi-aud with correct azp passes");
}
}