1use 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#[derive(Debug, Deserialize)]
17pub struct JwksResponse {
18 pub keys: Vec<JsonWebKey>,
20}
21
22#[derive(Debug, Deserialize)]
24pub struct JsonWebKey {
25 pub kid: Option<String>,
27
28 pub kty: String,
30
31 pub alg: Option<String>,
33
34 #[serde(rename = "use")]
36 pub key_use: Option<String>,
37
38 pub n: Option<String>,
40
41 pub e: Option<String>,
43
44 pub x5c: Option<Vec<String>>,
46}
47
48struct CachedJwks {
50 keys: HashMap<String, DecodingKey>,
52 fetched_at: Instant,
54}
55
56pub struct JwksClient {
73 url: String,
75 http_client: reqwest::Client,
77 cache: Arc<RwLock<Option<CachedJwks>>>,
79 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 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 pub async fn get_key(&self, kid: &str) -> Result<DecodingKey, JwksError> {
116 {
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 debug!(kid = %kid, "JWKS cache miss, refreshing");
131 self.refresh().await?;
132
133 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 pub async fn get_any_key(&self) -> Result<DecodingKey, JwksError> {
153 {
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 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 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 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 fn parse_jwk(&self, jwk: &JsonWebKey) -> Result<Option<DecodingKey>, JwksError> {
251 match jwk.kty.as_str() {
252 "RSA" => {
253 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 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 Ok(None)
277 }
278 _ => {
279 Ok(None)
281 }
282 }
283 }
284
285 pub fn url(&self) -> &str {
287 &self.url
288 }
289}
290
291#[derive(Debug, thiserror::Error)]
293pub enum JwksError {
294 #[error("Failed to fetch JWKS: {0}")]
296 FetchFailed(String),
297
298 #[error("Failed to parse JWKS: {0}")]
300 ParseFailed(String),
301
302 #[error("Failed to parse key: {0}")]
304 KeyParseFailed(String),
305
306 #[error("Key not found: {0}")]
308 KeyNotFound(String),
309
310 #[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 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 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(), 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()); }
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, e: None, x5c: None,
371 };
372
373 let result = client.parse_jwk(&jwk);
374 assert!(result.is_ok());
375 assert!(result.unwrap().is_none()); }
377}