Skip to main content

identity_kit/resolver/
jwks.rs

1//! `JwksResolver`: the keys of an HTTPS issuer, from its JWT VC issuer metadata.
2
3use core::fmt;
4use std::collections::HashMap;
5use std::sync::{Arc, PoisonError, RwLock};
6use std::time::{Duration, Instant};
7
8use serde::Deserialize;
9use serde_json::Value;
10use url::Url;
11
12use super::{KeyReference, KeyResolutionError, KeyResolver, KeyRole};
13use crate::jose::Jwk;
14use crate::methods::web::{HttpClient, HttpError, fetchable};
15
16/// Resolves a [`KeyReference::Jwks`] through the JWT VC issuer metadata of the issuer (SD-JWT VC
17/// §3.5); every other reference is [`Unsupported`](KeyResolutionError::Unsupported).
18///
19/// For an issuer `https://host[:port][/path]` it fetches
20/// `https://host[:port]/.well-known/jwt-vc-issuer[/path]` (a trailing `/` of the path dropped),
21/// requires the metadata's `issuer` to be the issuer, takes its `jwks`, or fetches its
22/// `jwks_uri`, and returns the one key whose `kid` is the reference's. Issuer and `jwks_uri`
23/// must be `https`, unless the client [allows plain `http`](HttpClient::allows_plain_http) for
24/// them, and the issuer has no query, fragment or credentials. The key set of an
25/// issuer is cached for a time to live ([`DEFAULT_TTL`](Self::DEFAULT_TTL) unless set with
26/// [`with_ttl`](Self::with_ttl)), so a rotated key is found once its entry expires.
27///
28/// The issuer comes from the token, so the client fetches whatever a token names: `client` must
29/// enforce the protections `ReqwestClient` (feature `reqwest`) does (HTTPS only, no redirects,
30/// no non-public addresses after name resolution, a body limit and a timeout), or resolution
31/// becomes a request forgery primitive. Resolving says nothing about whether the issuer is
32/// trusted; that stays the application's policy.
33///
34/// # Examples
35///
36/// ```
37/// use identity_kit::methods::web::{HttpClient, HttpError, HttpResponse};
38/// use identity_kit::resolver::{JwksResolver, KeyReference, KeyResolver as _, KeyRole};
39/// use url::Url;
40///
41/// /// Serves the metadata of `https://example.com/issuer`.
42/// struct Served;
43///
44/// #[async_trait::async_trait]
45/// impl HttpClient for Served {
46///     async fn get(&self, url: &Url) -> Result<HttpResponse, HttpError> {
47///         assert_eq!(url.as_str(), "https://example.com/.well-known/jwt-vc-issuer/issuer");
48///         Ok(HttpResponse::new(200, r#"{
49///           "issuer": "https://example.com/issuer",
50///           "jwks": { "keys": [{
51///             "kid": "key-1", "kty": "OKP", "crv": "Ed25519",
52///             "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"
53///           }]}
54///         }"#))
55///     }
56/// }
57///
58/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
59/// let resolver = JwksResolver::new(Served);
60/// let reference = KeyReference::Jwks {
61///     issuer: Url::parse("https://example.com/issuer")?,
62///     kid: "key-1".to_owned(),
63/// };
64/// let key = resolver.resolve_key(&reference, KeyRole::Issuer).await?;
65/// assert_eq!(key.crv(), Some("Ed25519"));
66/// # Ok::<(), Box<dyn std::error::Error>>(())
67/// # })?;
68/// # Ok::<(), Box<dyn std::error::Error>>(())
69/// ```
70pub struct JwksResolver<C> {
71    client: C,
72    ttl: Duration,
73    capacity: usize,
74    cache: RwLock<HashMap<Url, Entry>>,
75}
76
77/// The key set of one issuer and when it expires.
78struct Entry {
79    keys: Arc<[Value]>,
80    expires_at: Option<Instant>,
81}
82
83impl Entry {
84    fn is_live(&self, now: Instant) -> bool {
85        self.expires_at.is_none_or(|expires_at| expires_at > now)
86    }
87}
88
89/// The members of JWT VC issuer metadata this resolver reads.
90#[derive(Deserialize)]
91struct Metadata {
92    issuer: String,
93    #[serde(default)]
94    jwks: Option<KeySet>,
95    #[serde(default)]
96    jwks_uri: Option<String>,
97}
98
99/// A JWK set (RFC 7517 §5), its keys left as JSON so that a key of a type this crate does not
100/// read does not spoil the others.
101#[derive(Deserialize)]
102struct KeySet {
103    keys: Vec<Value>,
104}
105
106impl<C> JwksResolver<C> {
107    /// How long [`new`](Self::new) keeps an issuer's key set: five minutes.
108    pub const DEFAULT_TTL: Duration = Duration::from_mins(5);
109
110    /// How many issuers [`new`](Self::new) keeps key sets of.
111    pub const DEFAULT_CAPACITY: usize = 256;
112
113    /// A resolver fetching with `client`, keeping key sets for
114    /// [`DEFAULT_TTL`](Self::DEFAULT_TTL).
115    pub fn new(client: C) -> Self {
116        Self {
117            client,
118            ttl: Self::DEFAULT_TTL,
119            capacity: Self::DEFAULT_CAPACITY,
120            cache: RwLock::new(HashMap::new()),
121        }
122    }
123
124    /// This resolver keeping key sets for `ttl`; zero keeps none.
125    #[must_use]
126    pub fn with_ttl(mut self, ttl: Duration) -> Self {
127        self.ttl = ttl;
128        self
129    }
130
131    /// This resolver keeping the key sets of at most `capacity` issuers (at least one).
132    #[must_use]
133    pub fn with_capacity(mut self, capacity: usize) -> Self {
134        self.capacity = capacity.max(1);
135        self
136    }
137
138    /// How long a key set is kept.
139    pub fn ttl(&self) -> Duration {
140        self.ttl
141    }
142
143    /// The HTTP client.
144    pub fn client(&self) -> &C {
145        &self.client
146    }
147
148    /// The cached key set of `issuer`, if live.
149    fn cached(&self, issuer: &Url) -> Option<Arc<[Value]>> {
150        let cache = self.cache.read().unwrap_or_else(PoisonError::into_inner);
151        cache
152            .get(issuer)
153            .filter(|entry| entry.is_live(Instant::now()))
154            .map(|entry| Arc::clone(&entry.keys))
155    }
156
157    /// Keeps `keys` as the key set of `issuer`, evicting expired entries and then the one that
158    /// expires soonest when full.
159    fn store(&self, issuer: &Url, keys: Arc<[Value]>) {
160        if self.ttl.is_zero() {
161            return;
162        }
163        let now = Instant::now();
164        let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner);
165        if !cache.contains_key(issuer) && cache.len() >= self.capacity {
166            cache.retain(|_, entry| entry.is_live(now));
167            if cache.len() >= self.capacity
168                && let Some(soonest) = cache
169                    .iter()
170                    .min_by_key(|(_, entry)| entry.expires_at)
171                    .map(|(issuer, _)| issuer.clone())
172            {
173                cache.remove(&soonest);
174            }
175        }
176        cache.insert(
177            issuer.clone(),
178            Entry {
179                keys,
180                expires_at: now.checked_add(self.ttl),
181            },
182        );
183    }
184}
185
186impl<C: HttpClient> JwksResolver<C> {
187    /// The key set of `issuer`, from the cache or fetched.
188    async fn key_set(&self, issuer: &Url) -> Result<Arc<[Value]>, JwksError> {
189        if let Some(keys) = self.cached(issuer) {
190            return Ok(keys);
191        }
192        let url = metadata_url(issuer)?;
193        if !fetchable(&self.client, &url) {
194            return Err(JwksError::NotHttps(issuer.clone()));
195        }
196        let metadata: Metadata = self.fetch_json(&url).await?;
197        if Url::parse(&metadata.issuer).ok().as_ref() != Some(issuer) {
198            return Err(JwksError::IssuerMismatch {
199                expected: issuer.clone(),
200                found: metadata.issuer,
201            });
202        }
203        let keys = match (metadata.jwks, metadata.jwks_uri) {
204            (Some(jwks), None) => jwks.keys,
205            (None, Some(jwks_uri)) => {
206                let jwks_uri = Url::parse(&jwks_uri).map_err(|e| JwksError::InvalidMetadata {
207                    url: url.clone(),
208                    reason: format!("`jwks_uri` {jwks_uri:?}: {e}"),
209                })?;
210                if !fetchable(&self.client, &jwks_uri) {
211                    return Err(JwksError::NotHttps(jwks_uri));
212                }
213                self.fetch_json::<KeySet>(&jwks_uri).await?.keys
214            }
215            (Some(_), Some(_)) => {
216                return Err(JwksError::InvalidMetadata {
217                    url,
218                    reason: "both `jwks` and `jwks_uri` are present".to_owned(),
219                });
220            }
221            (None, None) => {
222                return Err(JwksError::InvalidMetadata {
223                    url,
224                    reason: "neither `jwks` nor `jwks_uri` is present".to_owned(),
225                });
226            }
227        };
228        let keys: Arc<[Value]> = keys.into();
229        self.store(issuer, Arc::clone(&keys));
230        Ok(keys)
231    }
232
233    /// The JSON body at `url`, parsed.
234    async fn fetch_json<T: serde::de::DeserializeOwned>(&self, url: &Url) -> Result<T, JwksError> {
235        let response = self
236            .client
237            .get(url)
238            .await
239            .map_err(|source| JwksError::Http {
240                url: url.clone(),
241                source,
242            })?;
243        if !(200..300).contains(&response.status) {
244            return Err(JwksError::HttpStatus {
245                url: url.clone(),
246                status: response.status,
247            });
248        }
249        serde_json::from_slice(&response.body).map_err(|e| JwksError::InvalidMetadata {
250            url: url.clone(),
251            reason: e.to_string(),
252        })
253    }
254}
255
256/// `<scheme>://host[:port]/.well-known/jwt-vc-issuer[/path]` for `issuer`, whose scheme the
257/// caller checks on the result.
258fn metadata_url(issuer: &Url) -> Result<Url, JwksError> {
259    if issuer.query().is_some()
260        || issuer.fragment().is_some()
261        || issuer.host().is_none()
262        || !issuer.username().is_empty()
263        || issuer.password().is_some()
264    {
265        return Err(JwksError::InvalidIssuer(issuer.clone()));
266    }
267    let path = issuer.path().trim_end_matches('/');
268    let mut url = issuer.clone();
269    url.set_path(&format!("/.well-known/jwt-vc-issuer{path}"));
270    Ok(url)
271}
272
273/// The one key of `keys` whose `kid` is `kid`, as a public JWK.
274fn select(keys: &[Value], issuer: &Url, kid: &str) -> Result<Jwk, JwksError> {
275    let mut matching = keys
276        .iter()
277        .filter(|key| key.get("kid").and_then(Value::as_str) == Some(kid));
278    let key = matching.next().ok_or_else(|| JwksError::UnknownKid {
279        issuer: issuer.clone(),
280        kid: kid.to_owned(),
281    })?;
282    if matching.next().is_some() {
283        return Err(JwksError::DuplicateKid {
284            issuer: issuer.clone(),
285            kid: kid.to_owned(),
286        });
287    }
288    let jwk: Jwk = serde_json::from_value(key.clone()).map_err(|e| JwksError::InvalidKey {
289        kid: kid.to_owned(),
290        reason: e.to_string(),
291    })?;
292    if jwk.is_private() {
293        return Err(JwksError::InvalidKey {
294            kid: kid.to_owned(),
295            reason: "the key set publishes private material".to_owned(),
296        });
297    }
298    Ok(jwk)
299}
300
301impl<C> fmt::Debug for JwksResolver<C>
302where
303    C: fmt::Debug,
304{
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        f.debug_struct("JwksResolver")
307            .field("client", &self.client)
308            .field("ttl", &self.ttl)
309            .field("capacity", &self.capacity)
310            .finish_non_exhaustive()
311    }
312}
313
314#[async_trait::async_trait]
315impl<C: HttpClient> KeyResolver for JwksResolver<C> {
316    async fn resolve_key(&self, key: &KeyReference, _: KeyRole) -> Result<Jwk, KeyResolutionError> {
317        let KeyReference::Jwks { issuer, kid } = key else {
318            return Err(KeyResolutionError::unsupported(key));
319        };
320        let keys = self.key_set(issuer).await?;
321        Ok(select(&keys, issuer, kid)?)
322    }
323}
324
325/// Why a [`JwksResolver`] found no key.
326#[derive(Debug, thiserror::Error)]
327#[non_exhaustive]
328pub enum JwksError {
329    /// The issuer or `jwks_uri` is not an `https` URL.
330    #[error("`{0}` is not an HTTPS URL")]
331    NotHttps(Url),
332    /// The issuer has a query, a fragment or credentials, or no host.
333    #[error(
334        "`{0}` is not an issuer identifier: it has a query, a fragment or credentials, or no host"
335    )]
336    InvalidIssuer(Url),
337    /// The [`HttpClient`] got no response.
338    #[error("fetching `{url}` failed: {source}")]
339    Http {
340        /// The URL fetched.
341        url: Url,
342        /// Why there was no response.
343        #[source]
344        source: HttpError,
345    },
346    /// The server answered with a status other than `2xx`.
347    #[error("fetching `{url}` returned HTTP {status}")]
348    HttpStatus {
349        /// The URL fetched.
350        url: Url,
351        /// The status code.
352        status: u16,
353    },
354    /// The metadata or key set is not what SD-JWT VC §3.5 and RFC 7517 §5 describe.
355    #[error("`{url}`: {reason}")]
356    InvalidMetadata {
357        /// The URL fetched.
358        url: Url,
359        /// What is wrong with the body.
360        reason: String,
361    },
362    /// The metadata names another issuer.
363    #[error("the metadata of `{expected}` names the issuer {found:?}")]
364    IssuerMismatch {
365        /// The issuer whose metadata was fetched.
366        expected: Url,
367        /// The `issuer` the metadata names.
368        found: String,
369    },
370    /// No key of the issuer has the `kid`.
371    #[error("issuer `{issuer}` has no key `{kid}`")]
372    UnknownKid {
373        /// The issuer.
374        issuer: Url,
375        /// The `kid`.
376        kid: String,
377    },
378    /// Several keys of the issuer have the `kid`, so it names none of them.
379    #[error("issuer `{issuer}` has several keys `{kid}`")]
380    DuplicateKid {
381        /// The issuer.
382        issuer: Url,
383        /// The `kid`.
384        kid: String,
385    },
386    /// The key is not a public JWK this crate reads.
387    #[error("key `{kid}`: {reason}")]
388    InvalidKey {
389        /// The `kid`.
390        kid: String,
391        /// What is wrong with it.
392        reason: String,
393    },
394}
395
396impl From<JwksError> for KeyResolutionError {
397    fn from(error: JwksError) -> Self {
398        Self::new(error)
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn an_entry_expires_at_its_instant() {
408        let now = Instant::now();
409        let entry = Entry {
410            keys: Arc::from([]),
411            expires_at: Some(now),
412        };
413        assert!(entry.is_live(now.checked_sub(Duration::from_nanos(1)).unwrap()));
414        assert!(!entry.is_live(now));
415    }
416}