use std::collections::HashMap;
use std::sync::RwLock;
use std::time::{Duration, Instant};
use serde::Deserialize;
use crate::RuntimeError;
pub const MAX_JWKS_BYTES: usize = 64 * 1024;
pub const MAX_KEYS: usize = 32;
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct Jwk {
pub(crate) kid: String,
pub(crate) n: String,
pub(crate) e: String,
kty: String,
alg: Option<String>,
#[serde(rename = "use")]
usage: Option<String>,
key_ops: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
struct Document {
keys: Vec<serde_json::Value>,
}
#[derive(Debug)]
pub(crate) struct KeyStore {
http: reqwest::Client,
url: String,
keys: RwLock<HashMap<String, Jwk>>,
refreshing: tokio::sync::Mutex<()>,
refreshed_at: RwLock<Option<Instant>>,
failed_at: RwLock<Option<Instant>>,
min_interval: Duration,
cache_ttl: Duration,
}
const FAILURE_COOLDOWN: Duration = Duration::from_secs(5);
struct Attempt<'a>(Option<&'a RwLock<Option<Instant>>>);
impl Attempt<'_> {
fn finish(mut self, failed: bool) {
if let Some(failed_at) = self.0.take() {
record(failed_at, failed.then(Instant::now));
}
}
}
impl Drop for Attempt<'_> {
fn drop(&mut self) {
if let Some(failed_at) = self.0.take() {
record(failed_at, Some(Instant::now()));
}
}
}
fn record(failed_at: &RwLock<Option<Instant>>, value: Option<Instant>) {
if let Ok(mut slot) = failed_at.write() {
*slot = value;
}
}
impl KeyStore {
pub(crate) fn new(
http: reqwest::Client,
url: String,
min_interval: Duration,
cache_ttl: Duration,
) -> Self {
Self {
http,
url,
keys: RwLock::new(HashMap::new()),
refreshing: tokio::sync::Mutex::new(()),
refreshed_at: RwLock::new(None),
failed_at: RwLock::new(None),
min_interval: min_interval.min(cache_ttl),
cache_ttl,
}
}
pub(crate) fn get(&self, kid: &str) -> Option<Jwk> {
if self.since_refresh()? >= self.cache_ttl {
return None;
}
self.keys.read().ok()?.get(kid).cloned()
}
fn since_refresh(&self) -> Option<Duration> {
self.refreshed_at.read().ok()?.map(|at| at.elapsed())
}
fn too_soon(&self) -> Option<Result<bool, RuntimeError>> {
if self
.since_refresh()
.is_some_and(|elapsed| elapsed < self.min_interval)
{
return Some(Ok(false));
}
let cooldown = self.min_interval.min(FAILURE_COOLDOWN);
let failed = self.failed_at.read().ok().and_then(|at| *at);
failed
.filter(|at| at.elapsed() < cooldown)
.map(|_| Err(RuntimeError::message("the JWKS refresh failed moments ago")))
}
pub(crate) async fn refresh_if_stale(&self) -> Result<bool, RuntimeError> {
if let Some(answer) = self.too_soon() {
return answer;
}
let _guard = self.refreshing.lock().await;
if let Some(answer) = self.too_soon() {
return answer;
}
self.fetch().await?;
Ok(true)
}
pub(crate) async fn refresh_now(&self) -> Result<(), RuntimeError> {
let _guard = self.refreshing.lock().await;
self.fetch().await
}
async fn fetch(&self) -> Result<(), RuntimeError> {
let attempt = Attempt(Some(&self.failed_at));
let outcome = self.download().await;
attempt.finish(outcome.is_err());
outcome
}
async fn download(&self) -> Result<(), RuntimeError> {
let response = self
.http
.get(&self.url)
.send()
.await
.map_err(|error| crate::client::send_error("fetching the JWKS", error))?;
if !response.status().is_success() {
return Err(RuntimeError::message(format!(
"the JWKS endpoint answered {}",
response.status()
)));
}
let document: Document = crate::client::json_bounded(response, MAX_JWKS_BYTES).await?;
let keys: HashMap<String, Jwk> = document
.keys
.into_iter()
.filter_map(|key| serde_json::from_value::<Jwk>(key).ok())
.filter(|key| {
key.kty == "RSA"
&& key.alg.as_deref().is_none_or(|alg| alg == "RS256")
&& key.usage.as_deref().is_none_or(|usage| usage == "sig")
&& key
.key_ops
.as_ref()
.is_none_or(|ops| ops.iter().any(|op| op == "verify"))
})
.take(MAX_KEYS)
.map(|key| (key.kid.clone(), key))
.collect();
if keys.is_empty() {
return Err(RuntimeError::message(
"the JWKS document contained no usable RSA keys",
));
}
*self
.keys
.write()
.map_err(|_| RuntimeError::message("the JWKS lock is poisoned"))? = keys;
*self
.refreshed_at
.write()
.map_err(|_| RuntimeError::message("the JWKS lock is poisoned"))? =
Some(Instant::now());
Ok(())
}
}