Skip to main content

forge_runtime/gateway/
jwks.rs

1//! JWKS (JSON Web Key Set) client for RSA token validation.
2//!
3//! This module provides a client for fetching and caching public keys from
4//! JWKS endpoints, used by providers like Firebase, Clerk, Auth0, etc.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use jsonwebtoken::DecodingKey;
11use serde::Deserialize;
12use tokio::sync::RwLock;
13use tracing::{debug, warn};
14
15/// JWKS response structure from providers.
16#[derive(Debug, Deserialize)]
17pub struct JwksResponse {
18    /// List of JSON Web Keys.
19    pub keys: Vec<JsonWebKey>,
20}
21
22/// Individual JSON Web Key.
23#[derive(Debug, Deserialize)]
24pub struct JsonWebKey {
25    /// Key ID - used to match tokens to keys.
26    pub kid: Option<String>,
27
28    /// Key type (RSA, EC, etc.).
29    pub kty: String,
30
31    /// Algorithm (RS256, RS384, RS512, etc.).
32    pub alg: Option<String>,
33
34    /// Key use (sig = signature, enc = encryption).
35    #[serde(rename = "use")]
36    pub key_use: Option<String>,
37
38    /// RSA modulus (base64url encoded).
39    pub n: Option<String>,
40
41    /// RSA exponent (base64url encoded).
42    pub e: Option<String>,
43
44    /// X.509 certificate chain (used by Firebase).
45    pub x5c: Option<Vec<String>>,
46}
47
48/// Cached JWKS keys with TTL tracking.
49struct CachedJwks {
50    /// Map of key ID to decoding key.
51    keys: HashMap<String, DecodingKey>,
52    /// When the cache was last refreshed.
53    fetched_at: Instant,
54}
55
56/// JWKS client with automatic caching.
57///
58/// Fetches public keys from a JWKS endpoint and caches them for efficient
59/// token validation. Keys are automatically refreshed when the cache expires.
60///
61/// # Example
62///
63/// ```ignore
64/// let client = JwksClient::new(
65///     "https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com".to_string(),
66///     3600, // 1 hour cache TTL
67/// );
68///
69/// // Get key by ID from token header
70/// let key = client.get_key("abc123").await?;
71/// ```
72pub struct JwksClient {
73    /// JWKS endpoint URL.
74    url: String,
75    /// HTTP client for fetching keys.
76    http_client: reqwest::Client,
77    /// Cached keys with TTL.
78    cache: Arc<RwLock<Option<CachedJwks>>>,
79    /// Cache time-to-live.
80    cache_ttl: Duration,
81}
82
83impl std::fmt::Debug for JwksClient {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        f.debug_struct("JwksClient")
86            .field("url", &self.url)
87            .field("cache_ttl", &self.cache_ttl)
88            .finish_non_exhaustive()
89    }
90}
91
92impl JwksClient {
93    /// Create a new JWKS client.
94    ///
95    /// # Arguments
96    ///
97    /// * `url` - The JWKS endpoint URL
98    /// * `cache_ttl_secs` - How long to cache keys (in seconds)
99    pub fn new(url: String, cache_ttl_secs: u64) -> Self {
100        Self {
101            url,
102            http_client: reqwest::Client::builder()
103                .timeout(Duration::from_secs(10))
104                .build()
105                .expect("Failed to create HTTP client"),
106            cache: Arc::new(RwLock::new(None)),
107            cache_ttl: Duration::from_secs(cache_ttl_secs),
108        }
109    }
110
111    /// Get a decoding key by key ID.
112    ///
113    /// This will return a cached key if available and not expired,
114    /// otherwise it will fetch fresh keys from the JWKS endpoint.
115    pub async fn get_key(&self, kid: &str) -> Result<DecodingKey, JwksError> {
116        // Try to get from cache first
117        {
118            let cache = self.cache.read().await;
119            if let Some(ref cached) = *cache {
120                if cached.fetched_at.elapsed() < self.cache_ttl {
121                    if let Some(key) = cached.keys.get(kid) {
122                        debug!(kid = %kid, "Using cached JWKS key");
123                        return Ok(key.clone());
124                    }
125                }
126            }
127        }
128
129        // Cache miss or expired - refresh
130        debug!(kid = %kid, "JWKS cache miss, refreshing");
131        self.refresh().await?;
132
133        // Try again from refreshed cache
134        let cache = self.cache.read().await;
135        if let Some(ref cached) = *cache {
136            cached
137                .keys
138                .get(kid)
139                .cloned()
140                .ok_or_else(|| JwksError::KeyNotFound(kid.to_string()))
141        } else {
142            Err(JwksError::FetchFailed(
143                "Cache empty after refresh".to_string(),
144            ))
145        }
146    }
147
148    /// Get any available key (for tokens without kid header).
149    ///
150    /// Some providers don't include a key ID in tokens. This method
151    /// returns the first available key from the JWKS.
152    pub async fn get_any_key(&self) -> Result<DecodingKey, JwksError> {
153        // Try to get from cache first
154        {
155            let cache = self.cache.read().await;
156            if let Some(ref cached) = *cache {
157                if cached.fetched_at.elapsed() < self.cache_ttl {
158                    if let Some(key) = cached.keys.values().next() {
159                        debug!("Using first cached JWKS key (no kid specified)");
160                        return Ok(key.clone());
161                    }
162                }
163            }
164        }
165
166        // Cache miss or expired - refresh
167        debug!("JWKS cache miss for any key, refreshing");
168        self.refresh().await?;
169
170        let cache = self.cache.read().await;
171        if let Some(ref cached) = *cache {
172            cached
173                .keys
174                .values()
175                .next()
176                .cloned()
177                .ok_or(JwksError::NoKeysAvailable)
178        } else {
179            Err(JwksError::FetchFailed("No keys in JWKS".to_string()))
180        }
181    }
182
183    /// Force refresh the key cache.
184    ///
185    /// Fetches fresh keys from the JWKS endpoint regardless of cache state.
186    pub async fn refresh(&self) -> Result<(), JwksError> {
187        debug!(url = %self.url, "Fetching JWKS");
188
189        let response = self
190            .http_client
191            .get(&self.url)
192            .send()
193            .await
194            .map_err(|e| JwksError::FetchFailed(e.to_string()))?;
195
196        if !response.status().is_success() {
197            return Err(JwksError::FetchFailed(format!(
198                "HTTP {} from JWKS endpoint",
199                response.status()
200            )));
201        }
202
203        let jwks: JwksResponse = response
204            .json()
205            .await
206            .map_err(|e| JwksError::ParseFailed(e.to_string()))?;
207
208        let mut keys = HashMap::new();
209
210        for jwk in jwks.keys {
211            // Skip non-signature keys
212            if let Some(ref key_use) = jwk.key_use {
213                if key_use != "sig" {
214                    continue;
215                }
216            }
217
218            let kid = jwk.kid.clone().unwrap_or_else(|| "default".to_string());
219
220            match self.parse_jwk(&jwk) {
221                Ok(Some(key)) => {
222                    debug!(kid = %kid, kty = %jwk.kty, "Parsed JWKS key");
223                    keys.insert(kid, key);
224                }
225                Ok(None) => {
226                    debug!(kid = %kid, kty = %jwk.kty, "Skipping unsupported key type");
227                }
228                Err(e) => {
229                    warn!(kid = %kid, error = %e, "Failed to parse JWKS key");
230                }
231            }
232        }
233
234        if keys.is_empty() {
235            return Err(JwksError::NoKeysAvailable);
236        }
237
238        debug!(count = keys.len(), "Cached JWKS keys");
239
240        let mut cache = self.cache.write().await;
241        *cache = Some(CachedJwks {
242            keys,
243            fetched_at: Instant::now(),
244        });
245
246        Ok(())
247    }
248
249    /// Parse a JWK into a DecodingKey.
250    fn parse_jwk(&self, jwk: &JsonWebKey) -> Result<Option<DecodingKey>, JwksError> {
251        match jwk.kty.as_str() {
252            "RSA" => {
253                // Try X.509 certificate chain first (used by Firebase)
254                if let Some(ref x5c) = jwk.x5c {
255                    if let Some(cert) = x5c.first() {
256                        let pem = format!(
257                            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
258                            cert
259                        );
260                        return DecodingKey::from_rsa_pem(pem.as_bytes()).map(Some).map_err(
261                            |e: jsonwebtoken::errors::Error| {
262                                JwksError::KeyParseFailed(e.to_string())
263                            },
264                        );
265                    }
266                }
267
268                // Fall back to n/e components (used by Clerk, Auth0, etc.)
269                if let (Some(n), Some(e)) = (&jwk.n, &jwk.e) {
270                    return DecodingKey::from_rsa_components(n, e).map(Some).map_err(
271                        |e: jsonwebtoken::errors::Error| JwksError::KeyParseFailed(e.to_string()),
272                    );
273                }
274
275                // RSA key but missing required components
276                Ok(None)
277            }
278            _ => {
279                // Unsupported key type (EC, oct, etc.)
280                Ok(None)
281            }
282        }
283    }
284
285    /// Get the JWKS URL.
286    pub fn url(&self) -> &str {
287        &self.url
288    }
289}
290
291/// Errors that can occur when working with JWKS.
292#[derive(Debug, thiserror::Error)]
293pub enum JwksError {
294    /// Failed to fetch JWKS from endpoint.
295    #[error("Failed to fetch JWKS: {0}")]
296    FetchFailed(String),
297
298    /// Failed to parse JWKS response.
299    #[error("Failed to parse JWKS: {0}")]
300    ParseFailed(String),
301
302    /// Failed to parse individual key.
303    #[error("Failed to parse key: {0}")]
304    KeyParseFailed(String),
305
306    /// Requested key ID not found in JWKS.
307    #[error("Key not found: {0}")]
308    KeyNotFound(String),
309
310    /// No usable keys in JWKS.
311    #[error("No keys available in JWKS")]
312    NoKeysAvailable,
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    #[test]
320    fn test_parse_jwk_with_n_e() {
321        let client = JwksClient::new("http://example.com".to_string(), 3600);
322
323        // Example RSA public key components (minimal test)
324        let jwk = JsonWebKey {
325            kid: Some("test-key".to_string()),
326            kty: "RSA".to_string(),
327            alg: Some("RS256".to_string()),
328            key_use: Some("sig".to_string()),
329            // These are example values - not a real key
330            n: Some("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw".to_string()),
331            e: Some("AQAB".to_string()),
332            x5c: None,
333        };
334
335        let result = client.parse_jwk(&jwk);
336        assert!(result.is_ok());
337        assert!(result.unwrap().is_some());
338    }
339
340    #[test]
341    fn test_parse_jwk_unsupported_type() {
342        let client = JwksClient::new("http://example.com".to_string(), 3600);
343
344        let jwk = JsonWebKey {
345            kid: Some("test-key".to_string()),
346            kty: "EC".to_string(), // Unsupported
347            alg: Some("ES256".to_string()),
348            key_use: Some("sig".to_string()),
349            n: None,
350            e: None,
351            x5c: None,
352        };
353
354        let result = client.parse_jwk(&jwk);
355        assert!(result.is_ok());
356        assert!(result.unwrap().is_none()); // Should return None for unsupported types
357    }
358
359    #[test]
360    fn test_parse_jwk_missing_components() {
361        let client = JwksClient::new("http://example.com".to_string(), 3600);
362
363        let jwk = JsonWebKey {
364            kid: Some("test-key".to_string()),
365            kty: "RSA".to_string(),
366            alg: Some("RS256".to_string()),
367            key_use: Some("sig".to_string()),
368            n: None, // Missing
369            e: None, // Missing
370            x5c: None,
371        };
372
373        let result = client.parse_jwk(&jwk);
374        assert!(result.is_ok());
375        assert!(result.unwrap().is_none()); // Should return None when missing components
376    }
377}