use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use jsonwebtoken::jwk::{AlgorithmParameters, EllipticCurve, Jwk, JwkSet, KeyAlgorithm};
use jsonwebtoken::{Algorithm, DecodingKey};
use tokio::sync::{Mutex, RwLock};
#[derive(Clone)]
pub struct VerifyingKey {
pub key: Arc<DecodingKey>,
pub algorithm: Algorithm,
}
#[derive(Default)]
struct KeySet {
keys: HashMap<String, VerifyingKey>,
fetched: Option<Instant>,
}
pub struct JwksCache {
uri: String,
client: reqwest::Client,
set: RwLock<KeySet>,
last_refresh: Mutex<Option<Instant>>,
max_age: Duration,
min_refresh_interval: Duration,
}
pub(crate) const MIN_REFRESH_INTERVAL: Duration = Duration::from_secs(60);
pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(300);
const JWKS_HTTP_TIMEOUT: Duration = Duration::from_secs(5);
impl JwksCache {
pub fn new(uri: String) -> Self {
let client = reqwest::Client::builder()
.timeout(JWKS_HTTP_TIMEOUT)
.tls_backend_preconfigured(crate::tls::client_config())
.build()
.unwrap_or_default();
Self {
uri,
client,
set: RwLock::new(KeySet::default()),
last_refresh: Mutex::new(None),
max_age: DEFAULT_MAX_AGE,
min_refresh_interval: MIN_REFRESH_INTERVAL,
}
}
pub fn with_max_age(mut self, max_age: Duration) -> Self {
self.max_age = max_age;
self
}
#[cfg(test)]
fn with_min_refresh_interval(mut self, interval: Duration) -> Self {
self.min_refresh_interval = interval;
self
}
pub async fn key_for(&self, kid: &str) -> Option<VerifyingKey> {
{
let set = self.set.read().await;
if set.fetched.is_some_and(|t| t.elapsed() < self.max_age) {
if let Some(key) = set.keys.get(kid) {
return Some(key.clone());
}
}
}
if let Err(reason) = self.refresh().await {
tracing::debug!(%reason, "JWKS not refetched; using the keys already known");
}
self.set.read().await.keys.get(kid).cloned()
}
async fn refresh(&self) -> Result<(), String> {
let mut last = self.last_refresh.lock().await;
if let Some(t) = *last {
let loaded = self.set.read().await.fetched.is_some();
if loaded && t.elapsed() < self.min_refresh_interval {
return Err("refresh throttled".to_string());
}
}
*last = Some(Instant::now());
let response = self
.client
.get(&self.uri)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| format!("JWKS fetch failed: {e}"))?;
let set: JwkSet = response
.json()
.await
.map_err(|e| format!("JWKS decode failed: {e}"))?;
*self.set.write().await = KeySet {
keys: parse_jwks(&set),
fetched: Some(Instant::now()),
};
Ok(())
}
}
fn parse_jwks(set: &JwkSet) -> HashMap<String, VerifyingKey> {
let mut map = HashMap::new();
for jwk in &set.keys {
let Some(kid) = jwk.common.key_id.clone() else {
continue;
};
let Some(algorithm) = algorithm_for(jwk) else {
continue;
};
if let Ok(key) = DecodingKey::from_jwk(jwk) {
map.insert(
kid,
VerifyingKey {
key: Arc::new(key),
algorithm,
},
);
}
}
map
}
fn algorithm_for(jwk: &Jwk) -> Option<Algorithm> {
if let Some(alg) = jwk.common.key_algorithm.and_then(key_algorithm_to_alg) {
return Some(alg);
}
match &jwk.algorithm {
AlgorithmParameters::RSA(_) => Some(Algorithm::RS256),
AlgorithmParameters::EllipticCurve(ec) => match ec.curve {
EllipticCurve::P256 => Some(Algorithm::ES256),
EllipticCurve::P384 => Some(Algorithm::ES384),
_ => None,
},
AlgorithmParameters::OctetKeyPair(_) => Some(Algorithm::EdDSA),
AlgorithmParameters::OctetKey(_) => None,
_ => None,
}
}
fn key_algorithm_to_alg(ka: KeyAlgorithm) -> Option<Algorithm> {
Some(match ka {
KeyAlgorithm::ES256 => Algorithm::ES256,
KeyAlgorithm::ES384 => Algorithm::ES384,
KeyAlgorithm::RS256 => Algorithm::RS256,
KeyAlgorithm::RS384 => Algorithm::RS384,
KeyAlgorithm::RS512 => Algorithm::RS512,
KeyAlgorithm::PS256 => Algorithm::PS256,
KeyAlgorithm::PS384 => Algorithm::PS384,
KeyAlgorithm::PS512 => Algorithm::PS512,
KeyAlgorithm::EdDSA => Algorithm::EdDSA,
_ => return None,
})
}
#[cfg(test)]
mod tests;