use std::collections::HashMap;
use std::sync::RwLock;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, jwk};
use serde_json::Value;
use super::{AuthError, Authenticator, Principal, Scopes};
use crate::model::ClientId;
#[derive(Debug, Clone)]
pub struct JwtConfig {
pub jwks_url: String,
pub token_url: String,
pub issuer: Option<String>,
pub audiences: Vec<String>,
pub client_id_claims: Vec<String>,
pub scope_claims: Vec<String>,
pub leeway: Duration,
pub refresh_after: Duration,
pub min_refresh_interval: Duration,
pub timeout: Duration,
}
impl JwtConfig {
pub fn new(jwks_url: impl Into<String>, token_url: impl Into<String>) -> Self {
Self {
jwks_url: jwks_url.into(),
token_url: token_url.into(),
issuer: None,
audiences: Vec::new(),
client_id_claims: vec!["azp".into(), "client_id".into(), "sub".into()],
scope_claims: vec!["scope".into(), "scp".into()],
leeway: Duration::from_secs(60),
refresh_after: Duration::from_secs(15 * 60),
min_refresh_interval: Duration::from_secs(30),
timeout: Duration::from_secs(10),
}
}
pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = Some(issuer.into());
self
}
pub fn with_audiences<I: Into<String>>(
mut self,
audiences: impl IntoIterator<Item = I>,
) -> Self {
self.audiences = audiences.into_iter().map(Into::into).collect();
self
}
pub fn with_client_id_claims<I: Into<String>>(
mut self,
claims: impl IntoIterator<Item = I>,
) -> Self {
self.client_id_claims = claims.into_iter().map(Into::into).collect();
self
}
}
#[derive(Clone)]
struct VerifyingKey {
key: DecodingKey,
algorithm: Algorithm,
}
struct KeyCache {
keys: HashMap<String, VerifyingKey>,
fetched_at: Option<Instant>,
attempted_at: Option<Instant>,
}
pub struct JwtAuthenticator {
config: JwtConfig,
http: reqwest::Client,
cache: RwLock<KeyCache>,
}
impl std::fmt::Debug for JwtAuthenticator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JwtAuthenticator")
.field("jwks_url", &self.config.jwks_url)
.field("issuer", &self.config.issuer)
.finish_non_exhaustive()
}
}
impl JwtAuthenticator {
pub fn new(config: JwtConfig) -> Result<Self, AuthError> {
crate::crypto::install_crypto_provider();
let http = reqwest::Client::builder()
.timeout(config.timeout)
.build()
.map_err(|e| AuthError::Unavailable(e.to_string()))?;
Ok(Self {
config,
http,
cache: RwLock::new(KeyCache {
keys: HashMap::new(),
fetched_at: None,
attempted_at: None,
}),
})
}
async fn key_for(&self, kid: &str) -> Result<VerifyingKey, AuthError> {
{
let cache = self.cache.read().unwrap_or_else(|e| e.into_inner());
let held = cache.keys.get(kid).cloned();
let fresh = cache
.fetched_at
.is_some_and(|at| at.elapsed() < self.config.refresh_after);
if fresh && let Some(key) = held {
return Ok(key);
}
if cache
.attempted_at
.is_some_and(|at| at.elapsed() < self.config.min_refresh_interval)
{
if let Some(key) = held {
return Ok(key);
}
return Err(if fresh {
AuthError::Invalid
} else {
AuthError::Unavailable(format!(
"the key set from {} is stale and could not be refreshed",
self.config.jwks_url
))
});
}
}
self.refresh().await?;
self.cache
.read()
.unwrap_or_else(|e| e.into_inner())
.keys
.get(kid)
.cloned()
.ok_or(AuthError::Invalid)
}
async fn refresh(&self) -> Result<(), AuthError> {
self.cache
.write()
.unwrap_or_else(|e| e.into_inner())
.attempted_at = Some(Instant::now());
let response = self
.http
.get(&self.config.jwks_url)
.send()
.await
.map_err(|e| AuthError::Unavailable(e.to_string()))?;
if !response.status().is_success() {
return Err(AuthError::Unavailable(format!(
"{} returned {}",
self.config.jwks_url,
response.status()
)));
}
let set: jwk::JwkSet = response
.json()
.await
.map_err(|e| AuthError::Unavailable(format!("unreadable JWKS: {e}")))?;
let mut keys = HashMap::new();
for key in &set.keys {
let Some(kid) = key.common.key_id.clone() else {
continue;
};
if !usable_for_verification(key) {
tracing::debug!(%kid, "ignoring a JWKS key its publisher did not offer for signatures");
continue;
}
let Some(algorithm) = algorithm_of(key) else {
tracing::warn!(%kid, "ignoring a JWKS key whose algorithm is unusable here");
continue;
};
match DecodingKey::from_jwk(key) {
Ok(decoding) => {
keys.insert(
kid,
VerifyingKey {
key: decoding,
algorithm,
},
);
}
Err(e) => tracing::warn!(%kid, error = %e, "ignoring an unreadable JWKS key"),
}
}
if keys.is_empty() {
return Err(AuthError::Unavailable(format!(
"{} published no usable keys",
self.config.jwks_url
)));
}
let mut cache = self.cache.write().unwrap_or_else(|e| e.into_inner());
cache.keys = keys;
cache.fetched_at = Some(Instant::now());
Ok(())
}
fn principal(&self, claims: &Value) -> Result<Principal, AuthError> {
let client_id = self
.config
.client_id_claims
.iter()
.find_map(|name| claims.get(name).and_then(Value::as_str))
.and_then(|raw| ClientId::new(raw).ok());
let scopes = self
.config
.scope_claims
.iter()
.find_map(|name| claims.get(name))
.map(scopes_of)
.unwrap_or_default();
Ok(Principal { client_id, scopes })
}
}
fn usable_for_verification(key: &jwk::Jwk) -> bool {
use jwk::PublicKeyUse;
if let Some(declared) = &key.common.public_key_use
&& !matches!(declared, PublicKeyUse::Signature)
{
return false;
}
match &key.common.key_operations {
Some(ops) if !ops.is_empty() => ops
.iter()
.any(|op| matches!(op, jwk::KeyOperations::Verify | jwk::KeyOperations::Sign)),
_ => true,
}
}
fn algorithm_of(key: &jwk::Jwk) -> Option<Algorithm> {
use jwk::{AlgorithmParameters, EllipticCurve, KeyAlgorithm};
if let Some(declared) = key.common.key_algorithm {
return match declared {
KeyAlgorithm::RS256 => Some(Algorithm::RS256),
KeyAlgorithm::RS384 => Some(Algorithm::RS384),
KeyAlgorithm::RS512 => Some(Algorithm::RS512),
KeyAlgorithm::PS256 => Some(Algorithm::PS256),
KeyAlgorithm::PS384 => Some(Algorithm::PS384),
KeyAlgorithm::PS512 => Some(Algorithm::PS512),
KeyAlgorithm::ES256 => Some(Algorithm::ES256),
KeyAlgorithm::ES384 => Some(Algorithm::ES384),
KeyAlgorithm::EdDSA => Some(Algorithm::EdDSA),
_ => None,
};
}
match &key.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,
}
}
fn scopes_of(value: &Value) -> Scopes {
match value {
Value::String(s) => Scopes::parse(s),
Value::Array(items) => Scopes::new(
items
.iter()
.filter_map(Value::as_str)
.filter_map(|s| s.parse().ok()),
),
_ => Scopes::none(),
}
}
#[async_trait]
impl Authenticator for JwtAuthenticator {
async fn authenticate(&self, bearer: Option<&str>) -> Result<Principal, AuthError> {
let token = bearer.ok_or(AuthError::Missing)?;
let header = jsonwebtoken::decode_header(token).map_err(|_| AuthError::Invalid)?;
let kid = header.kid.ok_or(AuthError::Invalid)?;
let key = self.key_for(&kid).await?;
let mut validation = Validation::new(key.algorithm);
validation.leeway = self.config.leeway.as_secs();
validation.validate_nbf = true;
if let Some(issuer) = &self.config.issuer {
validation.set_issuer(&[issuer]);
validation.required_spec_claims.insert("iss".to_string());
}
if self.config.audiences.is_empty() {
validation.validate_aud = false;
} else {
validation.set_audience(&self.config.audiences);
validation.required_spec_claims.insert("aud".to_string());
}
match jsonwebtoken::decode::<Value>(token, &key.key, &validation) {
Ok(data) => self.principal(&data.claims),
Err(e) => Err(match e.kind() {
jsonwebtoken::errors::ErrorKind::ExpiredSignature => AuthError::Expired,
_ => AuthError::Invalid,
}),
}
}
fn token_url(&self) -> String {
self.config.token_url.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn jwk_from(value: serde_json::Value) -> jwk::Jwk {
serde_json::from_value(value).unwrap()
}
#[test]
fn a_symmetric_key_in_a_jwks_is_refused() {
let key = jwk_from(json!({
"kty": "oct",
"kid": "shared",
"alg": "HS256",
"k": "c2VjcmV0"
}));
assert_eq!(algorithm_of(&key), None);
}
#[test]
fn the_algorithm_comes_from_the_key() {
let rsa = jwk_from(json!({
"kty": "RSA", "kid": "a", "alg": "RS256",
"n": "xGOr-H7A-PWG8kUJmXH-1ZDdYLXY0KsCcHfe1UwqhBrbjXPaMYcnbYbXOVEfHZ1Zsxq",
"e": "AQAB"
}));
assert_eq!(algorithm_of(&rsa), Some(Algorithm::RS256));
let bare = jwk_from(json!({
"kty": "EC", "kid": "b", "crv": "P-256",
"x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
"y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
}));
assert_eq!(algorithm_of(&bare), Some(Algorithm::ES256));
}
#[test]
fn scopes_are_read_from_either_shape() {
let from_string = scopes_of(&json!("read_all write_events openid"));
assert!(from_string.contains(super::super::Scope::ReadAll));
assert!(from_string.contains(super::super::Scope::WriteEvents));
assert_eq!(
from_string.as_slice().len(),
2,
"unknown scopes are ignored"
);
let from_array = scopes_of(&json!(["read_targets", "read_ven_objects"]));
assert_eq!(from_array.as_slice().len(), 2);
assert!(scopes_of(&json!(42)).is_empty());
}
#[test]
fn the_client_id_claim_is_configurable() {
let auth = JwtAuthenticator::new(
JwtConfig::new("https://sso.example/jwks", "https://sso.example/token")
.with_client_id_claims(["azp", "sub"]),
)
.unwrap();
let keycloak = auth
.principal(&json!({"sub": "uuid-1", "azp": "ven-7", "scope": "read_targets"}))
.unwrap();
assert_eq!(keycloak.client_id.unwrap().as_str(), "ven-7");
let plain = auth.principal(&json!({"sub": "ven-9"})).unwrap();
assert_eq!(plain.client_id.unwrap().as_str(), "ven-9");
assert!(plain.scopes.is_empty());
}
#[tokio::test]
async fn a_token_without_a_kid_is_refused_without_a_network_call() {
let auth = JwtAuthenticator::new(JwtConfig::new(
"http://127.0.0.1:1/jwks",
"http://127.0.0.1:1/token",
))
.unwrap();
let token = "eyJhbGciOiJub25lIn0.e30.";
assert_eq!(
auth.authenticate(Some(token)).await.unwrap_err(),
AuthError::Invalid
);
assert_eq!(
auth.authenticate(None).await.unwrap_err(),
AuthError::Missing
);
}
}