use std::sync::Arc;
use std::time::{Duration, Instant};
use jsonwebtoken::jwk::JwkSet;
use tokio::sync::RwLock;
use tracing::{debug, info};
const JWKS_CACHE_TTL: Duration = Duration::from_secs(300);
#[derive(Clone, Debug, Default)]
pub struct AuthMode {
pub api_key: bool,
pub jwt: Option<JwtConfig>,
}
#[derive(Clone, Debug)]
pub struct JwtConfig {
pub issuer: String,
pub audience: Option<String>,
pub jwks_cache: Arc<JwksCache>,
}
impl AuthMode {
pub fn no_auth() -> Self {
Self::default()
}
pub fn jwt(issuer: String, audience: Option<String>) -> Self {
Self {
api_key: false,
jwt: Some(JwtConfig::new(issuer, audience)),
}
}
pub fn api_key() -> Self {
Self {
api_key: true,
jwt: None,
}
}
pub fn combined(issuer: String, audience: Option<String>) -> Self {
Self {
api_key: true,
jwt: Some(JwtConfig::new(issuer, audience)),
}
}
pub fn is_enabled(&self) -> bool {
self.api_key || self.jwt.is_some()
}
pub fn describe(&self) -> String {
match (self.jwt.as_ref(), self.api_key) {
(None, false) => "no-auth (open access)".to_string(),
(None, true) => "api-key".to_string(),
(Some(c), false) => format!("jwt (issuer: {})", c.issuer),
(Some(c), true) => format!("jwt (issuer: {}) + api-key", c.issuer),
}
}
}
impl JwtConfig {
pub fn new(issuer: String, audience: Option<String>) -> Self {
Self {
jwks_cache: Arc::new(JwksCache::new(issuer.clone())),
issuer,
audience,
}
}
}
pub struct JwksCache {
issuer: String,
cache: RwLock<Option<CachedJwks>>,
http: reqwest::Client,
}
struct CachedJwks {
jwks: JwkSet,
fetched_at: Instant,
}
impl std::fmt::Debug for JwksCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JwksCache")
.field("issuer", &self.issuer)
.finish()
}
}
impl JwksCache {
pub fn new(issuer: String) -> Self {
Self {
issuer,
cache: RwLock::new(None),
http: reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.build()
.expect("building JWKS HTTP client"),
}
}
pub fn with_jwks(issuer: String, jwks: JwkSet) -> Self {
Self {
issuer,
cache: RwLock::new(Some(CachedJwks {
jwks,
fetched_at: Instant::now(),
})),
http: reqwest::Client::new(),
}
}
pub async fn get_jwks(&self) -> anyhow::Result<JwkSet> {
{
let cache = self.cache.read().await;
if let Some(ref cached) = *cache
&& cached.fetched_at.elapsed() < JWKS_CACHE_TTL
{
return Ok(cached.jwks.clone());
}
}
self.refresh().await
}
pub async fn refresh(&self) -> anyhow::Result<JwkSet> {
let jwks_uri = self.discover_jwks_uri().await?;
debug!("Fetching JWKS from {jwks_uri}");
let jwks: JwkSet = self.http.get(&jwks_uri).send().await?.json().await?;
info!(
"Fetched {} keys from JWKS endpoint",
jwks.keys.len()
);
let mut cache = self.cache.write().await;
*cache = Some(CachedJwks {
jwks: jwks.clone(),
fetched_at: Instant::now(),
});
Ok(jwks)
}
async fn discover_jwks_uri(&self) -> anyhow::Result<String> {
let discovery_url = format!(
"{}/.well-known/openid-configuration",
self.issuer.trim_end_matches('/')
);
let resp: serde_json::Value = self
.http
.get(&discovery_url)
.send()
.await?
.json()
.await?;
resp.get("jwks_uri")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or_else(|| anyhow::anyhow!("OIDC discovery response missing jwks_uri"))
}
pub async fn find_key(&self, kid: &str) -> anyhow::Result<jsonwebtoken::DecodingKey> {
let jwks = self.get_jwks().await?;
if let Some(key) = find_key_in_set(&jwks, kid) {
return Ok(key);
}
debug!("kid '{kid}' not in JWKS cache, refreshing");
let jwks = self.refresh().await?;
find_key_in_set(&jwks, kid)
.ok_or_else(|| anyhow::anyhow!("No key with kid '{kid}' in JWKS"))
}
pub async fn find_any_key(
&self,
alg: jsonwebtoken::Algorithm,
) -> anyhow::Result<jsonwebtoken::DecodingKey> {
let jwks = self.get_jwks().await?;
for key in &jwks.keys {
if let Ok(dk) = jsonwebtoken::DecodingKey::from_jwk(key) {
let _ = alg;
return Ok(dk);
}
}
anyhow::bail!("No suitable key found in JWKS for algorithm {alg:?}")
}
}
fn find_key_in_set(
jwks: &JwkSet,
kid: &str,
) -> Option<jsonwebtoken::DecodingKey> {
jwks.keys
.iter()
.find(|k| k.common.key_id.as_deref() == Some(kid))
.and_then(|k| jsonwebtoken::DecodingKey::from_jwk(k).ok())
}