ts_token/jwks/
cache.rs

1//! A cache for JSON web keys.
2
3use core::time::Duration;
4use std::{collections::HashMap, time::Instant};
5
6use crate::{JsonWebKey, jwks::JsonWebKeySet};
7
8/// A cache for JSON web keys.
9#[derive(Debug)]
10pub struct JsonWebKeyCache {
11    /// The entries in this cache.
12    pub entries: HashMap<String, (Instant, JsonWebKey)>,
13}
14
15impl JsonWebKeyCache {
16    /// Create a new cache.
17    #[allow(clippy::new_without_default)]
18    pub fn new() -> Self {
19        Self {
20            entries: HashMap::new(),
21        }
22    }
23
24    /// Remove any stale keys.
25    pub fn remove_stale_keys(&mut self) {
26        self.entries
27            .retain(|_, (retrieved, _)| retrieved.elapsed() < Duration::from_secs(60 * 60 * 24));
28    }
29
30    /// Insert a JSON web key set into the cache.
31    pub fn insert(&mut self, jwks: JsonWebKeySet) {
32        for jwk in jwks.keys {
33            let kid = jwk.kid.clone();
34            self.entries.insert(kid, (Instant::now(), jwk));
35        }
36    }
37
38    /// Get a key by ID.
39    pub fn get(&self, kid: &str) -> Option<&JsonWebKey> {
40        self.entries.get(kid).map(|(_, jwk)| jwk)
41    }
42}