use std::collections::HashMap;
use std::sync::RwLock;
use std::time::{Duration, Instant};
use jsonwebtoken::jwk::{AlgorithmParameters, Jwk, JwkSet};
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use crate::config::Issuer;
use crate::error::{AgentError, Result};
#[derive(Debug, Clone)]
pub struct VerifiedClaims {
pub issuer_name: 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,
}
}
}
struct CachedJwks {
keys: Vec<Jwk>,
fetched_at: Instant,
}
struct JwksCache {
cache: RwLock<HashMap<String, CachedJwks>>,
http_client: reqwest::Client,
ttl: Duration,
}
impl JwksCache {
fn new() -> Self {
Self {
cache: RwLock::new(HashMap::new()),
http_client: reqwest::Client::new(),
ttl: Duration::from_secs(3600),
}
}
async fn get_key(&self, jwks_url: &str, kid: &str) -> Result<(DecodingKey, Algorithm)> {
if let Some(key) = self.find_in_cache(jwks_url, kid) {
return key;
}
self.fetch_and_cache(jwks_url).await?;
self.find_in_cache(jwks_url, kid).unwrap_or_else(|| {
Err(AgentError::JwtVerification(format!(
"kid '{kid}' not found in JWKS at {jwks_url}"
)))
})
}
fn find_in_cache(&self, jwks_url: &str, kid: &str) -> Option<Result<(DecodingKey, Algorithm)>> {
let cache = self.cache.read().ok()?;
let entry = cache.get(jwks_url)?;
if entry.fetched_at.elapsed() > self.ttl {
return None;
}
let jwk = entry
.keys
.iter()
.find(|k| k.common.key_id.as_deref() == Some(kid))?;
Some(decoding_key_from_jwk(jwk))
}
async fn fetch_and_cache(&self, jwks_url: &str) -> Result<()> {
let response = self.http_client.get(jwks_url).send().await.map_err(|e| {
AgentError::JwtVerification(format!("failed to fetch JWKS from {jwks_url}: {e}"))
})?;
let jwks: JwkSet = response.json().await.map_err(|e| {
AgentError::JwtVerification(format!("failed to parse JWKS from {jwks_url}: {e}"))
})?;
if let Ok(mut cache) = self.cache.write() {
cache.insert(
jwks_url.to_string(),
CachedJwks {
keys: jwks.keys,
fetched_at: Instant::now(),
},
);
}
Ok(())
}
}
fn decoding_key_from_jwk(jwk: &Jwk) -> Result<(DecodingKey, Algorithm)> {
match &jwk.algorithm {
AlgorithmParameters::RSA(rsa) => {
let key = DecodingKey::from_rsa_components(&rsa.n, &rsa.e)
.map_err(|e| AgentError::JwtVerification(format!("invalid RSA JWK: {e}")))?;
let alg = jwk
.common
.key_algorithm
.and_then(|a| match a {
jsonwebtoken::jwk::KeyAlgorithm::RS256 => Some(Algorithm::RS256),
jsonwebtoken::jwk::KeyAlgorithm::RS384 => Some(Algorithm::RS384),
jsonwebtoken::jwk::KeyAlgorithm::RS512 => Some(Algorithm::RS512),
jsonwebtoken::jwk::KeyAlgorithm::PS256 => Some(Algorithm::PS256),
jsonwebtoken::jwk::KeyAlgorithm::PS384 => Some(Algorithm::PS384),
jsonwebtoken::jwk::KeyAlgorithm::PS512 => Some(Algorithm::PS512),
_ => None,
})
.unwrap_or(Algorithm::RS256);
Ok((key, alg))
}
AlgorithmParameters::EllipticCurve(ec) => {
let key = DecodingKey::from_ec_components(&ec.x, &ec.y)
.map_err(|e| AgentError::JwtVerification(format!("invalid EC JWK: {e}")))?;
let alg = jwk
.common
.key_algorithm
.and_then(|a| match a {
jsonwebtoken::jwk::KeyAlgorithm::ES256 => Some(Algorithm::ES256),
jsonwebtoken::jwk::KeyAlgorithm::ES384 => Some(Algorithm::ES384),
_ => None,
})
.unwrap_or(Algorithm::ES256);
Ok((key, alg))
}
_ => Err(AgentError::JwtVerification(
"unsupported JWK algorithm type".into(),
)),
}
}
pub struct JwtVerifier {
issuers: Vec<Issuer>,
jwks_cache: JwksCache,
}
impl JwtVerifier {
pub fn new(issuers: Vec<Issuer>) -> Self {
Self {
issuers,
jwks_cache: 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_name: issuer.name.clone(),
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> {
use Algorithm::*;
const TABLE: &[(&str, Algorithm)] = &[
("RS256", RS256), ("RS384", RS384), ("RS512", RS512),
("ES256", ES256), ("ES384", ES384),
("PS256", PS256), ("PS384", PS384), ("PS512", PS512),
("HS256", HS256), ("HS384", HS384), ("HS512", HS512),
];
TABLE.iter().find(|(name, _)| *name == alg).map(|(_, a)| *a)
.ok_or_else(|| AgentError::JwtVerification(format!("unsupported algorithm: {alg}")))
}
#[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());
}
}