use std::collections::HashMap;
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use crate::config::Issuer;
use crate::error::{AgentError, Result};
use crate::jwks;
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct VerifiedClaims {
pub issuer: String,
pub issuer_name: String,
pub subject: String,
pub audience: Vec<String>,
pub claims: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Serialize, Deserialize)]
struct RawClaims {
#[serde(default)]
iss: Option<String>,
#[serde(default)]
sub: Option<String>,
#[serde(default)]
aud: Option<Audience>,
#[serde(default)]
exp: Option<u64>,
#[serde(flatten)]
extra: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
enum Audience {
Single(String),
Multiple(Vec<String>),
}
impl Audience {
fn into_vec(self) -> Vec<String> {
match self {
Audience::Single(s) => vec![s],
Audience::Multiple(v) => v,
}
}
}
pub struct JwtVerifier {
issuers: Vec<Issuer>,
jwks_cache: jwks::JwksCache,
}
impl JwtVerifier {
pub fn new(issuers: Vec<Issuer>) -> Self {
Self {
issuers,
jwks_cache: jwks::JwksCache::new(),
}
}
pub async fn verify(&self, token: &str) -> Result<VerifiedClaims> {
let header = decode_header(token).map_err(|e| {
AgentError::JwtVerification(format!("failed to decode JWT header: {e}"))
})?;
let token_kid = header.kid.as_deref();
let token_alg = header.alg;
for issuer in &self.issuers {
if let Some(ref static_keys) = issuer.static_keys {
for key in static_keys {
let key_alg = parse_algorithm(&key.alg)?;
if let Some(tk) = token_kid {
if tk != key.kid {
continue;
}
}
if key_alg != token_alg {
if token_kid.is_some() && token_kid == Some(&key.kid) {
return Err(AgentError::JwtVerification(format!(
"kid '{}' matched but algorithm mismatch: token={:?}, key={}",
key.kid, token_alg, key.alg
)));
}
continue;
}
let decoding_key = build_decoding_key(key_alg, &key.pem, &key.kid)?;
match self.try_decode(token, &decoding_key, key_alg, issuer) {
Ok(claims) => return Ok(claims),
Err(e) => {
if token_kid.is_some() && token_kid == Some(&key.kid) {
return Err(AgentError::JwtVerification(format!(
"kid '{}' matched but verification failed: {e}",
key.kid
)));
}
continue;
}
}
}
}
if let (Some(ref jwks_url), Some(kid)) = (&issuer.jwks_url, token_kid) {
match self.jwks_cache.get_key(jwks_url, kid).await {
Ok((decoding_key, jwk_alg)) => {
if jwk_alg != token_alg {
continue;
}
match self.try_decode(token, &decoding_key, jwk_alg, issuer) {
Ok(claims) => return Ok(claims),
Err(e) => {
return Err(AgentError::JwtVerification(format!(
"JWKS kid '{kid}' matched but verification failed: {e}"
)));
}
}
}
Err(_) => continue,
}
}
}
Err(AgentError::JwtVerification("no issuer matched".to_string()))
}
fn try_decode(
&self,
token: &str,
decoding_key: &DecodingKey,
alg: Algorithm,
issuer: &Issuer,
) -> std::result::Result<VerifiedClaims, String> {
let mut validation = Validation::new(alg);
validation.set_issuer(&[&issuer.issuer_url]);
if let Some(ref aud) = issuer.audience {
validation.set_audience(&[aud]);
} else {
validation.validate_aud = false;
}
validation.set_required_spec_claims(&["exp", "iss"]);
match decode::<RawClaims>(token, decoding_key, &validation) {
Ok(token_data) => {
let raw = token_data.claims;
let iss = raw.iss.unwrap_or_default();
let sub = raw.sub.unwrap_or_default();
let aud = raw.aud.map(|a| a.into_vec()).unwrap_or_default();
let mut all_claims = raw.extra;
all_claims.insert("iss".to_string(), serde_json::Value::String(iss.clone()));
all_claims.insert("sub".to_string(), serde_json::Value::String(sub.clone()));
if !aud.is_empty() {
all_claims.insert(
"aud".to_string(),
serde_json::Value::Array(
aud.iter()
.map(|a| serde_json::Value::String(a.clone()))
.collect(),
),
);
}
if let Some(exp) = raw.exp {
all_claims.insert("exp".to_string(), serde_json::Value::Number(exp.into()));
}
Ok(VerifiedClaims {
issuer: iss,
issuer_name: issuer.name.clone(),
subject: sub,
audience: aud,
claims: all_claims,
})
}
Err(e) => Err(format!("{e}")),
}
}
}
fn build_decoding_key(alg: Algorithm, pem: &str, kid: &str) -> Result<DecodingKey> {
let pem_bytes = pem.as_bytes();
let err_map = |e: jsonwebtoken::errors::Error| {
AgentError::JwtVerification(format!("invalid PEM for kid '{kid}': {e}"))
};
match alg {
Algorithm::RS256
| Algorithm::RS384
| Algorithm::RS512
| Algorithm::PS256
| Algorithm::PS384
| Algorithm::PS512 => DecodingKey::from_rsa_pem(pem_bytes).map_err(err_map),
Algorithm::ES256 | Algorithm::ES384 => DecodingKey::from_ec_pem(pem_bytes).map_err(err_map),
Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
Ok(DecodingKey::from_secret(pem_bytes))
}
_ => Err(AgentError::JwtVerification(format!(
"unsupported algorithm for key decoding: {alg:?}"
))),
}
}
fn parse_algorithm(alg: &str) -> Result<Algorithm> {
match alg {
"RS256" => Ok(Algorithm::RS256),
"RS384" => Ok(Algorithm::RS384),
"RS512" => Ok(Algorithm::RS512),
"ES256" => Ok(Algorithm::ES256),
"ES384" => Ok(Algorithm::ES384),
"PS256" => Ok(Algorithm::PS256),
"PS384" => Ok(Algorithm::PS384),
"PS512" => Ok(Algorithm::PS512),
"HS256" => Ok(Algorithm::HS256),
"HS384" => Ok(Algorithm::HS384),
"HS512" => Ok(Algorithm::HS512),
other => Err(AgentError::JwtVerification(format!(
"unsupported algorithm: {other}"
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_algorithm() {
assert_eq!(parse_algorithm("RS256").unwrap(), Algorithm::RS256);
assert_eq!(parse_algorithm("ES256").unwrap(), Algorithm::ES256);
assert!(parse_algorithm("UNKNOWN").is_err());
}
}