Skip to main content

structured_proxy/auth/
jwks.rs

1//! JWKS fetching and key cache.
2//!
3//! Keys are fetched from the configured JWKS URI and cached by `kid`. An unknown
4//! `kid` triggers a refresh (throttled), which is how key rotation is picked up.
5//! The cached set also ages out: a lookup after [`JwksCache::with_max_age`]
6//! refetches it, so a key the provider has removed stops verifying tokens even
7//! when no request ever names an unknown `kid`.
8
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12
13use jsonwebtoken::jwk::{AlgorithmParameters, EllipticCurve, Jwk, JwkSet, KeyAlgorithm};
14use jsonwebtoken::{Algorithm, DecodingKey};
15use tokio::sync::{Mutex, RwLock};
16
17/// A decoding key plus the signature algorithm it is valid for.
18#[derive(Clone)]
19pub struct VerifyingKey {
20    pub key: Arc<DecodingKey>,
21    pub algorithm: Algorithm,
22}
23
24/// The keys of the last successful fetch.
25#[derive(Default)]
26struct KeySet {
27    keys: HashMap<String, VerifyingKey>,
28    /// When they were fetched; `None` before the first fetch.
29    fetched: Option<Instant>,
30}
31
32/// Fetches and caches JWKS keys by `kid`.
33pub struct JwksCache {
34    uri: String,
35    client: reqwest::Client,
36    set: RwLock<KeySet>,
37    last_refresh: Mutex<Option<Instant>>,
38    max_age: Duration,
39    min_refresh_interval: Duration,
40}
41
42/// Minimum spacing between refreshes, so a flood of bogus `kid`s cannot hammer
43/// the JWKS endpoint.
44pub(crate) const MIN_REFRESH_INTERVAL: Duration = Duration::from_secs(60);
45
46/// Default age after which the cached keys are refetched: the `cache_duration`
47/// Envoy's `remote_jwks` uses.
48pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(300);
49
50/// Bound the worst-case latency of a slow/stalled JWKS endpoint.
51const JWKS_HTTP_TIMEOUT: Duration = Duration::from_secs(5);
52
53impl JwksCache {
54    /// Create a cache for `uri` (keys are loaded lazily on first lookup), whose
55    /// keys are refetched after [`DEFAULT_MAX_AGE`].
56    pub fn new(uri: String) -> Self {
57        let client = reqwest::Client::builder()
58            .timeout(JWKS_HTTP_TIMEOUT)
59            // Hand reqwest a fully preconfigured rustls backend rather than
60            // relying on a process-global default provider: no install ordering
61            // constraint, no global side effect, safe for library/test callers.
62            .tls_backend_preconfigured(crate::tls::client_config())
63            .build()
64            .unwrap_or_default();
65        Self {
66            uri,
67            client,
68            set: RwLock::new(KeySet::default()),
69            last_refresh: Mutex::new(None),
70            max_age: DEFAULT_MAX_AGE,
71            min_refresh_interval: MIN_REFRESH_INTERVAL,
72        }
73    }
74
75    /// Refetch the keys once they are older than `max_age`. Refreshes stay
76    /// at least a minute apart, so a shorter age behaves as one minute.
77    pub fn with_max_age(mut self, max_age: Duration) -> Self {
78        self.max_age = max_age;
79        self
80    }
81
82    #[cfg(test)]
83    fn with_min_refresh_interval(mut self, interval: Duration) -> Self {
84        self.min_refresh_interval = interval;
85        self
86    }
87
88    /// Resolve the verifying key for `kid`, refreshing from the JWKS endpoint
89    /// once (throttled) if it is not cached or the cached keys are too old.
90    pub async fn key_for(&self, kid: &str) -> Option<VerifyingKey> {
91        {
92            let set = self.set.read().await;
93            if set.fetched.is_some_and(|t| t.elapsed() < self.max_age) {
94                if let Some(key) = set.keys.get(kid) {
95                    return Some(key.clone());
96                }
97            }
98        }
99        if let Err(reason) = self.refresh().await {
100            tracing::debug!(%reason, "JWKS not refetched; using the keys already known");
101        }
102        // Answer from the current set whatever the refresh did: another
103        // request may have replaced it meanwhile, and a key it dropped must
104        // not survive in an earlier copy. An unreachable endpoint leaves the
105        // set as it was, so the keys already known keep working: failing every
106        // token while the provider is down would turn its outage into ours.
107        self.set.read().await.keys.get(kid).cloned()
108    }
109
110    /// Fetch the JWKS and replace the cache. Throttled by the minimum refresh
111    /// interval unless no fetch has succeeded yet (first load); a provider
112    /// that answered with no keys has been loaded.
113    async fn refresh(&self) -> Result<(), String> {
114        // The refresh slot is held until the new set is in place: a lookup
115        // that arrives meanwhile waits for it, then finds the refresh throttled
116        // and answers from the new set, never from the aged one a removed key
117        // may still sit in. Only lookups that need a refresh wait; a fresh key
118        // is served before the slot is touched.
119        let mut last = self.last_refresh.lock().await;
120        if let Some(t) = *last {
121            let loaded = self.set.read().await.fetched.is_some();
122            if loaded && t.elapsed() < self.min_refresh_interval {
123                return Err("refresh throttled".to_string());
124            }
125        }
126        *last = Some(Instant::now());
127
128        let response = self
129            .client
130            .get(&self.uri)
131            .send()
132            .await
133            .and_then(reqwest::Response::error_for_status)
134            .map_err(|e| format!("JWKS fetch failed: {e}"))?;
135        let set: JwkSet = response
136            .json()
137            .await
138            .map_err(|e| format!("JWKS decode failed: {e}"))?;
139
140        *self.set.write().await = KeySet {
141            keys: parse_jwks(&set),
142            fetched: Some(Instant::now()),
143        };
144        Ok(())
145    }
146}
147
148/// Build the `kid → VerifyingKey` map from a JWK set, skipping keys without a
149/// `kid`, symmetric keys, or those that fail to convert.
150fn parse_jwks(set: &JwkSet) -> HashMap<String, VerifyingKey> {
151    let mut map = HashMap::new();
152    for jwk in &set.keys {
153        let Some(kid) = jwk.common.key_id.clone() else {
154            continue;
155        };
156        let Some(algorithm) = algorithm_for(jwk) else {
157            continue;
158        };
159        if let Ok(key) = DecodingKey::from_jwk(jwk) {
160            map.insert(
161                kid,
162                VerifyingKey {
163                    key: Arc::new(key),
164                    algorithm,
165                },
166            );
167        }
168    }
169    map
170}
171
172/// Pick the signature algorithm for a key.
173///
174/// The JWK's explicit `alg` is authoritative (so ES384 / RS512 / PS256 keys are
175/// not mis-pinned). Without it, fall back to the key type and EC curve.
176/// Symmetric keys (`OctetKey`) and unsupported variants are rejected.
177fn algorithm_for(jwk: &Jwk) -> Option<Algorithm> {
178    if let Some(alg) = jwk.common.key_algorithm.and_then(key_algorithm_to_alg) {
179        return Some(alg);
180    }
181    match &jwk.algorithm {
182        AlgorithmParameters::RSA(_) => Some(Algorithm::RS256),
183        AlgorithmParameters::EllipticCurve(ec) => match ec.curve {
184            EllipticCurve::P256 => Some(Algorithm::ES256),
185            EllipticCurve::P384 => Some(Algorithm::ES384),
186            // P-521 (ES512) is not supported by the verifier.
187            _ => None,
188        },
189        AlgorithmParameters::OctetKeyPair(_) => Some(Algorithm::EdDSA),
190        AlgorithmParameters::OctetKey(_) => None,
191        // The enum is non-exhaustive: key types added upstream are not
192        // verifiable here until they are mapped explicitly.
193        _ => None,
194    }
195}
196
197/// Map a JWK signature `alg` to a verifier algorithm, rejecting symmetric and
198/// encryption algorithms (only asymmetric signatures are usable from a JWKS).
199fn key_algorithm_to_alg(ka: KeyAlgorithm) -> Option<Algorithm> {
200    Some(match ka {
201        KeyAlgorithm::ES256 => Algorithm::ES256,
202        KeyAlgorithm::ES384 => Algorithm::ES384,
203        KeyAlgorithm::RS256 => Algorithm::RS256,
204        KeyAlgorithm::RS384 => Algorithm::RS384,
205        KeyAlgorithm::RS512 => Algorithm::RS512,
206        KeyAlgorithm::PS256 => Algorithm::PS256,
207        KeyAlgorithm::PS384 => Algorithm::PS384,
208        KeyAlgorithm::PS512 => Algorithm::PS512,
209        KeyAlgorithm::EdDSA => Algorithm::EdDSA,
210        _ => return None,
211    })
212}
213
214#[cfg(test)]
215mod tests;