Skip to main content

identity_kit/resolver/
key.rs

1//! `KeyReference`, `KeyRole` and `KeyResolver`: where a token says its key is, and the trait
2//! that finds it.
3
4use core::fmt;
5use std::error::Error;
6use std::sync::Arc;
7
8use base64::Engine as _;
9use base64::engine::general_purpose::STANDARD;
10use url::Url;
11
12use super::dereference::{public_key, verification_method_in};
13use super::{DereferenceError, Resolver};
14use crate::did::{Did, DidDocument, DidError, DidUrl, VerificationRelationship};
15use crate::jose::{CompactJws, Jwk, base64url};
16
17/// Where a token says the key that signed it is (ADR 0006).
18///
19/// A JWT names its key in one of several ways: a DID URL in `kid`, a `#fragment` in `kid`
20/// relative to a DID `iss`, a `kid` into the key set an HTTPS `iss` publishes, the key itself in
21/// a `jwk` header, a certificate chain in `x5c`, or a key set URL in `jku`.
22/// [`from_jws`](Self::from_jws) reads which from a JWS header; `sd_jwt_vc` builds one from a
23/// `cnf` claim. A [`KeyResolver`] turns it into a key.
24///
25/// Resolving a reference says nothing about trust: a key by value resolves to itself whoever
26/// made the token. Once the signature verifies, [`binds_to`](Self::binds_to) checks that the key
27/// belongs to the party the token claims.
28///
29/// # Examples
30///
31/// ```
32/// use identity_kit::jose::{CompactJws, JwtClaims};
33/// use identity_kit::resolver::{KeyReference, KeyReferenceError};
34///
35/// // {"alg":"EdDSA","kid":"#key-1"}.{"iss":"did:example:123"}
36/// let jws = CompactJws::decode(
37///     "eyJhbGciOiJFZERTQSIsImtpZCI6IiNrZXktMSJ9.eyJpc3MiOiJkaWQ6ZXhhbXBsZToxMjMifQ.c2lnbmF0dXJl",
38/// )?;
39/// let claims: JwtClaims = jws.claims()?;
40/// let reference = KeyReference::from_jws(&jws, claims.iss.as_deref())?;
41/// assert_eq!(reference.to_string(), "did:example:123#key-1");
42///
43/// // A relative `kid` needs a DID to resolve against.
44/// assert!(matches!(
45///     KeyReference::from_jws(&jws, None),
46///     Err(KeyReferenceError::RelativeKidWithoutIssuer(_))
47/// ));
48/// # Ok::<(), Box<dyn std::error::Error>>(())
49/// ```
50#[derive(Debug, Clone, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum KeyReference {
53    /// A verification method: a `kid` that is an absolute DID URL, or a `#fragment` joined with
54    /// a DID `iss`.
55    DidUrl(DidUrl),
56    /// The public key itself, from a `jwk` header or `cnf.jwk`.
57    Jwk(Box<Jwk>),
58    /// An `x5c` certificate chain, DER, leaf first. `X509Resolver` (feature `x509`) resolves
59    /// it against the application's trust anchors.
60    X509Chain(Vec<Vec<u8>>),
61    /// The key `kid` names in the key set of the HTTPS issuer `issuer` (SD-JWT VC §3.5).
62    Jwks {
63        /// The issuer, the `iss` of the token.
64        issuer: Url,
65        /// The `kid` of the key in the issuer's key set.
66        kid: String,
67    },
68    /// The key set at `url`, from `jku`, and the `kid` that selects a key in it. No resolver in
69    /// the crate handles it yet.
70    Jku {
71        /// The key set URL.
72        url: Url,
73        /// The `kid`, if the token has one.
74        kid: Option<String>,
75    },
76}
77
78impl KeyReference {
79    /// Where the key of `jws` is, given the `iss` of its claims (when `iss` is a string): the
80    /// first of the [`candidates`](Self::candidates).
81    ///
82    /// The header parameters are tried in this order, and the first that applies decides:
83    ///
84    /// 1. A `kid` that parses as a DID URL is [`DidUrl`](Self::DidUrl). A path or DID
85    ///    parameters such as `versionId` are refused: they could select a document version
86    ///    that still lists a retired key (ADR 0004).
87    /// 2. A `kid` starting with `#` is joined with `iss` into a [`DidUrl`](Self::DidUrl) when
88    ///    `iss` is a DID, and refused otherwise.
89    /// 3. An `x5c` header is [`X509Chain`](Self::X509Chain), each certificate base64-decoded
90    ///    but not parsed.
91    /// 4. Another `kid`, with an `https` `iss`, is [`Jwks`](Self::Jwks).
92    /// 5. A `jwk` header is [`Jwk`](Self::Jwk); a private key there is refused.
93    /// 6. A `jku` header is [`Jku`](Self::Jku), with the `kid` when there is one.
94    ///
95    /// A certificate chain comes before the issuer's key set and a key by value: it is in the
96    /// token, so it costs no request, and it is validated against trust anchors, where a
97    /// `jwk` header only asserts itself (ADR 0008).
98    ///
99    /// # Errors
100    ///
101    /// A [`KeyReferenceError`]: [`Missing`](KeyReferenceError::Missing) when the header names no
102    /// key, otherwise the parameter that is wrong.
103    pub fn from_jws(jws: &CompactJws, iss: Option<&str>) -> Result<Self, KeyReferenceError> {
104        Self::candidates(jws, iss).map(|mut candidates| candidates.swap_remove(0))
105    }
106
107    /// Every reference the header of `jws` makes, in the order [`from_jws`](Self::from_jws)
108    /// lists; never empty.
109    ///
110    /// A token can carry the inputs of more than one mechanism, an `x5c` chain next to a `kid`
111    /// and an HTTPS `iss`, say. Which one applies is the verifier's policy, not the token's
112    /// (SD-JWT VC §3.5): a validator asks its [`KeyResolver`] for each candidate in turn and
113    /// takes the first the resolver handles, so the resolvers an application configures are
114    /// that policy. A candidate the resolver handles and fails to resolve ends the search.
115    ///
116    /// A malformed `x5c`, `jwk` or `jku` is skipped when another parameter makes a reference,
117    /// as is a `kid` that names nothing by itself. A `kid` that is refused outright ends the
118    /// search, whatever else the header carries: a DID URL with a path or DID parameters, or a
119    /// `#fragment` without a DID `iss` to join it with.
120    ///
121    /// # Errors
122    ///
123    /// As [`from_jws`](Self::from_jws), when no parameter makes a reference.
124    pub fn candidates(jws: &CompactJws, iss: Option<&str>) -> Result<Vec<Self>, KeyReferenceError> {
125        let header = jws.header();
126        let mut candidates = Vec::new();
127        let (mut kid_error, mut error) = (None, None);
128        let mut key_set = None;
129        if let Some(kid) = header.kid.as_deref() {
130            match Self::from_kid(kid, iss)? {
131                Ok(reference @ Self::Jwks { .. }) => key_set = Some(reference),
132                Ok(reference) => candidates.push(reference),
133                Err(source) => {
134                    kid_error = Some(KeyReferenceError::InvalidKid {
135                        kid: kid.to_owned(),
136                        source,
137                    });
138                }
139            }
140        }
141        if let Some(x5c) = header.additional.get("x5c") {
142            match x5c_chain(x5c) {
143                Ok(chain) => candidates.push(Self::X509Chain(chain)),
144                Err(e) => error = error.or(Some(e)),
145            }
146        }
147        candidates.extend(key_set);
148        if let Some(jwk) = &header.jwk {
149            if jwk.is_private() {
150                error = error.or(Some(KeyReferenceError::InvalidJwk(
151                    "the `jwk` header holds a private key".to_owned(),
152                )));
153            } else {
154                candidates.push(Self::Jwk(Box::new(jwk.clone())));
155            }
156        }
157        if let Some(jku) = header.additional.get("jku") {
158            let url = jku
159                .as_str()
160                .ok_or_else(|| KeyReferenceError::InvalidUrl {
161                    parameter: "jku",
162                    value: jku.to_string(),
163                    reason: "not a string".to_owned(),
164                })
165                .and_then(|jku| parse_url("jku", jku));
166            match url {
167                Ok(url) => candidates.push(Self::Jku {
168                    url,
169                    kid: header.kid.clone(),
170                }),
171                Err(e) => error = error.or(Some(e)),
172            }
173        }
174        if candidates.is_empty() {
175            return Err(error.or(kid_error).unwrap_or(KeyReferenceError::Missing));
176        }
177        Ok(candidates)
178    }
179
180    /// The reference `kid` makes with `iss`: a [`DidUrl`](Self::DidUrl) for a DID URL or a
181    /// `#fragment` of a DID `iss`, a [`Jwks`](Self::Jwks) for another `kid` of an `https`
182    /// `iss`, or why `kid` is not a DID URL when it makes none.
183    fn from_kid(kid: &str, iss: Option<&str>) -> Result<Result<Self, DidError>, KeyReferenceError> {
184        let not_did_url = match DidUrl::parse(kid) {
185            Ok(url) => return did_url(url).map(Ok),
186            Err(error) => error,
187        };
188        if kid.starts_with('#') {
189            let did = iss
190                .and_then(|iss| Did::parse(iss).ok())
191                .ok_or_else(|| KeyReferenceError::RelativeKidWithoutIssuer(kid.to_owned()))?;
192            let url = did
193                .join(kid)
194                .map_err(|source| KeyReferenceError::InvalidKid {
195                    kid: kid.to_owned(),
196                    source,
197                })?;
198            return did_url(url).map(Ok);
199        }
200        if let Some(issuer) = iss
201            .and_then(|iss| Url::parse(iss).ok())
202            .filter(|issuer| issuer.scheme() == "https")
203        {
204            return Ok(Ok(Self::Jwks {
205                issuer,
206                kid: kid.to_owned(),
207            }));
208        }
209        Ok(Err(not_did_url))
210    }
211
212    /// Whether `key`, which this reference resolved to and which verified the signature,
213    /// belongs to `party`, the issuer or holder the token claims:
214    ///
215    /// | Reference | Binds when |
216    /// |---|---|
217    /// | [`DidUrl`](Self::DidUrl) | `party` is the DID of the URL |
218    /// | [`Jwk`](Self::Jwk) | `party` is the `did:jwk` of `key`, or its RFC 7638 SHA-256 thumbprint, or absent (a SIOPv2 self-issued `sub`) |
219    /// | [`Jwks`](Self::Jwks) | `party` is the issuer URL (compared as parsed URLs) |
220    /// | [`X509Chain`](Self::X509Chain) | with the `x509` feature: `party` is absent, or an `https` URL whose host is a DNS name of the first certificate (`X509Certificate::binds`) |
221    /// | [`Jku`](Self::Jku) | never, until the crate resolves it |
222    ///
223    /// A key by value and a certificate chain can bind to no party; a validator that requires
224    /// an issuer or holder passes it. With a certificate chain, the party that signed is the
225    /// subject of the first certificate, and a claimed `iss` is not authenticated by the chain
226    /// (SD-JWT VC §3.5): it binds only when the certificate names its host. A DID never binds
227    /// to a chain.
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// use identity_kit::did::DidUrl;
233    /// use identity_kit::jose::Jwk;
234    /// use identity_kit::resolver::KeyReference;
235    ///
236    /// // RFC 8037 Appendix A.2.
237    /// let key: Jwk = serde_json::from_str(
238    ///     r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
239    /// )?;
240    /// let by_value = KeyReference::Jwk(Box::new(key.clone()));
241    /// // RFC 8037 Appendix A.3.
242    /// assert!(by_value.binds_to(Some("kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"), &key));
243    /// assert!(by_value.binds_to(None, &key));
244    /// assert!(!by_value.binds_to(Some("did:example:123"), &key));
245    ///
246    /// let by_url = KeyReference::DidUrl(DidUrl::parse("did:example:123#key-1")?);
247    /// assert!(by_url.binds_to(Some("did:example:123"), &key));
248    /// assert!(!by_url.binds_to(Some("did:example:456"), &key));
249    /// assert!(!by_url.binds_to(None, &key));
250    /// # Ok::<(), Box<dyn std::error::Error>>(())
251    /// ```
252    pub fn binds_to(&self, party: Option<&str>, key: &Jwk) -> bool {
253        match (self, party) {
254            (Self::DidUrl(url), Some(party)) => {
255                Did::parse(party).is_ok_and(|did| did == *url.did())
256            }
257            (Self::Jwk(_), None) => true,
258            (Self::Jwk(_), Some(party)) => is_key_identifier(party, key),
259            (Self::Jwks { issuer, .. }, Some(party)) => {
260                Url::parse(party).is_ok_and(|party| party == *issuer)
261            }
262            #[cfg(feature = "x509")]
263            (Self::X509Chain(_), None) => true,
264            #[cfg(feature = "x509")]
265            (Self::X509Chain(chain), Some(party)) => chain
266                .first()
267                .and_then(|leaf| super::X509Certificate::from_der(leaf).ok())
268                .is_some_and(|leaf| leaf.binds(party)),
269            _ => false,
270        }
271    }
272}
273
274impl fmt::Display for KeyReference {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        match self {
277            Self::DidUrl(url) => fmt::Display::fmt(url, f),
278            Self::Jwk(jwk) => match jwk.thumbprint_sha256() {
279                Ok(thumbprint) => write!(f, "JWK {thumbprint}"),
280                Err(_) => f.write_str("JWK"),
281            },
282            Self::X509Chain(chain) => write!(f, "`x5c` chain of {} certificates", chain.len()),
283            Self::Jwks { issuer, kid } => write!(f, "`{kid}` of issuer `{issuer}`"),
284            Self::Jku {
285                url,
286                kid: Some(kid),
287            } => write!(f, "`{kid}` of `{url}`"),
288            Self::Jku { url, kid: None } => write!(f, "the key of `{url}`"),
289        }
290    }
291}
292
293/// `url`, refused when it carries a path or DID parameters.
294fn did_url(url: DidUrl) -> Result<KeyReference, KeyReferenceError> {
295    if url.path().is_some() || url.query().is_some() {
296        return Err(KeyReferenceError::KidWithParameters(url));
297    }
298    Ok(KeyReference::DidUrl(url))
299}
300
301/// The certificates of an `x5c` header: an array of standard base64 DER (RFC 7515 §4.1.6).
302fn x5c_chain(x5c: &serde_json::Value) -> Result<Vec<Vec<u8>>, KeyReferenceError> {
303    let invalid = |reason: &str| KeyReferenceError::InvalidX5c(reason.to_owned());
304    let certificates = x5c.as_array().ok_or_else(|| invalid("not an array"))?;
305    if certificates.is_empty() {
306        return Err(invalid("the chain is empty"));
307    }
308    certificates
309        .iter()
310        .map(|certificate| {
311            let certificate = certificate
312                .as_str()
313                .ok_or_else(|| invalid("a certificate is not a string"))?;
314            STANDARD
315                .decode(certificate)
316                .map_err(|_| invalid("a certificate is not base64"))
317        })
318        .collect()
319}
320
321/// `value` of `parameter` as an absolute URL.
322fn parse_url(parameter: &'static str, value: &str) -> Result<Url, KeyReferenceError> {
323    Url::parse(value).map_err(|e| KeyReferenceError::InvalidUrl {
324        parameter,
325        value: value.to_owned(),
326        reason: e.to_string(),
327    })
328}
329
330/// Whether `party` is the `did:jwk` or the RFC 7638 SHA-256 thumbprint of `key`.
331fn is_key_identifier(party: &str, key: &Jwk) -> bool {
332    let Ok(thumbprint) = key.thumbprint_sha256() else {
333        return false;
334    };
335    if party == thumbprint {
336        return true;
337    }
338    // A `did:jwk` names the key by value, in whatever member order its creator serialized it;
339    // the thumbprint compares the required members only.
340    Did::parse(party)
341        .ok()
342        .filter(|did| did.method() == "jwk")
343        .and_then(|did| base64url::decode(did.method_specific_id()).ok())
344        .and_then(|json| serde_json::from_slice::<Jwk>(&json).ok())
345        .and_then(|jwk| jwk.thumbprint_sha256().ok())
346        .is_some_and(|named| named == thumbprint)
347}
348
349/// Why a token names no key this crate can look for.
350#[derive(Debug, thiserror::Error)]
351#[non_exhaustive]
352pub enum KeyReferenceError {
353    /// The token names no key: no `kid`, `jwk`, `x5c` or `jku` (or, in `cnf`, no `jwk`, `kid`
354    /// or `jku`).
355    #[error("the token names no key: no `kid`, `jwk`, `x5c` or `jku`")]
356    Missing,
357    /// The `kid` is a `#fragment` and `iss` is not a DID to resolve it against.
358    #[error("`kid` {0:?} is relative and `iss` is not a DID")]
359    RelativeKidWithoutIssuer(String),
360    /// The `kid` is neither a DID URL nor anything else the token resolves it with.
361    #[error("`kid` {kid:?} is not a DID URL: {source}")]
362    InvalidKid {
363        /// The `kid`.
364        kid: String,
365        /// Why it is not a DID URL.
366        #[source]
367        source: DidError,
368    },
369    /// The `kid` carries a path or DID parameters. `versionId` and `versionTime` could select a
370    /// document version that still lists a retired key, so only `did:…#fragment` keys are
371    /// accepted.
372    #[error("`kid` `{0}` carries a path or DID parameters")]
373    KidWithParameters(DidUrl),
374    /// The key by value is not usable: it holds private material, say.
375    #[error("invalid `jwk`: {0}")]
376    InvalidJwk(String),
377    /// The `x5c` header is not an array of base64 certificates.
378    #[error("invalid `x5c`: {0}")]
379    InvalidX5c(String),
380    /// A URL parameter (`jku`) is not an absolute URL.
381    #[error("`{parameter}` {value:?} is not a URL: {reason}")]
382    InvalidUrl {
383        /// The parameter.
384        parameter: &'static str,
385        /// Its value.
386        value: String,
387        /// Why it did not parse.
388        reason: String,
389    },
390    /// The confirmation names its key only by a method the crate does not resolve, such as
391    /// `x5t#S256` or `jwe`.
392    #[error("`cnf` names its key only by `{0}`, which is not supported")]
393    UnsupportedConfirmation(String),
394}
395
396/// The role a key plays in a token, which decides what a DID document must say about it.
397#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
398#[non_exhaustive]
399pub enum KeyRole {
400    /// The key signs as the issuer of a credential or status list: `assertionMethod`. The
401    /// default.
402    #[default]
403    Issuer,
404    /// The key proves possession by the subject or holder (a presentation, a key binding JWT,
405    /// an ID token): `authentication`.
406    Subject,
407}
408
409impl KeyRole {
410    /// The verification relationship a DID document must list a key of this role under.
411    pub fn relationship(self) -> VerificationRelationship {
412        match self {
413            Self::Issuer => VerificationRelationship::AssertionMethod,
414            Self::Subject => VerificationRelationship::Authentication,
415        }
416    }
417}
418
419/// Finds the public key a [`KeyReference`] names.
420///
421/// [`Resolver`] implements it for DID URLs, [`JwkResolver`] for keys by value and, with the
422/// `jwks` feature, `JwksResolver` for the key sets of HTTPS issuers;
423/// [`CompositeKeyResolver`] combines them. An application can implement it over a cache, a
424/// fixed set of trusted keys, or a reference the crate does not resolve.
425#[async_trait::async_trait]
426pub trait KeyResolver: Send + Sync {
427    /// The public key `key` names, usable in `role`.
428    ///
429    /// # Errors
430    ///
431    /// [`KeyResolutionError::Unsupported`] for a kind of reference this resolver does not
432    /// handle, which lets a [`CompositeKeyResolver`] try the next one; any other
433    /// [`KeyResolutionError`] when the key cannot be found or used.
434    async fn resolve_key(
435        &self,
436        key: &KeyReference,
437        role: KeyRole,
438    ) -> Result<Jwk, KeyResolutionError>;
439
440    /// The public key `key` names, usable in `role` at `now`, the validation time in seconds
441    /// since the Unix epoch.
442    ///
443    /// The validators call this method, with the time they validate at. The default ignores
444    /// the time and calls [`resolve_key`](Self::resolve_key), which is right for a key that
445    /// does not depend on it; a resolver whose answer does, such as `X509Resolver` with the
446    /// validity periods of certificates, implements it.
447    ///
448    /// A resolver that wraps another one (a cache, a filter, a logger) must implement this
449    /// method too and forward it: left to the default, it would answer for the current time
450    /// whatever time the validator asked for, and a certificate chain would be validated at
451    /// the wrong one.
452    ///
453    /// # Errors
454    ///
455    /// As [`resolve_key`](Self::resolve_key).
456    async fn resolve_key_at(
457        &self,
458        key: &KeyReference,
459        role: KeyRole,
460        now: i64,
461    ) -> Result<Jwk, KeyResolutionError> {
462        let _ = now;
463        self.resolve_key(key, role).await
464    }
465}
466
467/// The key of `jws`, `iss` being the issuer its claims name, for `role` at `now`: the first of
468/// the [candidates](KeyReference::candidates) that `resolver` handles, with its reference.
469///
470/// # Errors
471///
472/// [`JwsKeyError::Reference`] when the header names no key, and [`JwsKeyError::Resolution`]
473/// with the candidate that failed, or with the first one when the resolver handles none.
474pub(crate) async fn resolve_jws_key<R: KeyResolver + ?Sized>(
475    resolver: &R,
476    jws: &CompactJws,
477    iss: Option<&str>,
478    role: KeyRole,
479    now: i64,
480) -> Result<(KeyReference, Jwk), JwsKeyError> {
481    let mut unsupported = None;
482    for reference in KeyReference::candidates(jws, iss).map_err(JwsKeyError::Reference)? {
483        match resolver.resolve_key_at(&reference, role, now).await {
484            Ok(key) => return Ok((reference, key)),
485            Err(source) if source.is_unsupported() => {
486                unsupported.get_or_insert(JwsKeyError::Resolution {
487                    key: Box::new(reference),
488                    source,
489                });
490            }
491            Err(source) => {
492                return Err(JwsKeyError::Resolution {
493                    key: Box::new(reference),
494                    source,
495                });
496            }
497        }
498    }
499    // `candidates` is never empty, so a search without a key ended on an unsupported one.
500    Err(unsupported.unwrap_or(JwsKeyError::Reference(KeyReferenceError::Missing)))
501}
502
503/// Why [`resolve_jws_key`] found no key.
504#[derive(Debug)]
505pub(crate) enum JwsKeyError {
506    /// The token names no key.
507    Reference(KeyReferenceError),
508    /// The resolver did not resolve `key`.
509    Resolution {
510        /// The reference.
511        key: Box<KeyReference>,
512        /// Why it did not resolve.
513        source: KeyResolutionError,
514    },
515}
516
517// Implements `KeyResolver` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
518// A method added to the trait is added here too: one with a default body would still compile
519// if left out, and calls through these wrappers would then run the default, not `T`'s
520// override. `clippy::missing_trait_methods` turns that omission into an error.
521macro_rules! forward_key_resolver {
522    ($($ty:ty),* $(,)?) => {$(
523        #[async_trait::async_trait]
524        #[deny(clippy::missing_trait_methods)]
525        impl<T: KeyResolver + ?Sized> KeyResolver for $ty {
526            async fn resolve_key(
527                &self,
528                key: &KeyReference,
529                role: KeyRole,
530            ) -> Result<Jwk, KeyResolutionError> {
531                (**self).resolve_key(key, role).await
532            }
533
534            async fn resolve_key_at(
535                &self,
536                key: &KeyReference,
537                role: KeyRole,
538                now: i64,
539            ) -> Result<Jwk, KeyResolutionError> {
540                (**self).resolve_key_at(key, role, now).await
541            }
542        }
543    )*};
544}
545
546forward_key_resolver!(&T, Box<T>, Arc<T>);
547
548/// Resolves a [`KeyReference::DidUrl`] by dereferencing it to a verification method listed
549/// under the relationship of the role; every other reference is
550/// [`Unsupported`](KeyResolutionError::Unsupported).
551#[async_trait::async_trait]
552impl KeyResolver for Resolver {
553    async fn resolve_key(
554        &self,
555        key: &KeyReference,
556        role: KeyRole,
557    ) -> Result<Jwk, KeyResolutionError> {
558        match key {
559            KeyReference::DidUrl(url) => self
560                .resolve_public_key(url, Some(role.relationship()))
561                .await
562                .map_err(KeyResolutionError::from),
563            other => Err(KeyResolutionError::unsupported(other)),
564        }
565    }
566}
567
568/// Resolves a [`KeyReference::Jwk`] to its public part; every other reference is
569/// [`Unsupported`](KeyResolutionError::Unsupported).
570///
571/// Anybody can put a key in a `jwk` header, so the key says nothing about who signed: a
572/// validator accepts it only when the claimed party is that key's `did:jwk` or thumbprint
573/// ([`KeyReference::binds_to`]). Add it to a [`CompositeKeyResolver`] to accept such tokens.
574#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
575pub struct JwkResolver;
576
577#[async_trait::async_trait]
578impl KeyResolver for JwkResolver {
579    async fn resolve_key(&self, key: &KeyReference, _: KeyRole) -> Result<Jwk, KeyResolutionError> {
580        match key {
581            KeyReference::Jwk(jwk) => Ok(jwk.public()),
582            other => Err(KeyResolutionError::unsupported(other)),
583        }
584    }
585}
586
587/// Resolves a [`KeyReference::DidUrl`] against DID documents supplied by the caller, without
588/// resolving the DID again: a document resolved to read its services, or one the caller
589/// fetched or publishes itself.
590///
591/// A DID URL of one of the documents' DIDs resolves to the verification method its fragment
592/// names, which must be usable for the relationship of the role, as [`Resolver`] would:
593/// `publicKeyJwk` as it is, `publicKeyMultibase` decoded as a Multikey. Every other reference
594/// is [`Unsupported`](KeyResolutionError::Unsupported), so that a [`CompositeKeyResolver`]
595/// tries the next resolver: a DID URL of another DID, and one with a path or query, such as a
596/// `versionId`, which names a document other than the one supplied.
597///
598/// # Examples
599///
600/// The caller supplies a presentation's holder document; issuers' keys still resolve over the
601/// network.
602///
603/// ```
604/// # #[cfg(feature = "did-key")]
605/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
606/// use identity_kit::did::{DidDocument, DidUrl};
607/// use identity_kit::jose::Jwk;
608/// use identity_kit::methods::DidKey;
609/// use identity_kit::resolver::{
610///     CompositeKeyResolver, DocumentKeyResolver, KeyReference, KeyResolver as _, KeyRole,
611///     Resolver,
612/// };
613///
614/// // The holder's `did:web` document, already resolved; its key is RFC 7515 Appendix A.3's.
615/// let holder: DidDocument = serde_json::from_str(r##"{
616///   "id": "did:web:holder.example",
617///   "verificationMethod": [{
618///     "id": "did:web:holder.example#key-1",
619///     "type": "JsonWebKey",
620///     "controller": "did:web:holder.example",
621///     "publicKeyJwk": {
622///       "kty": "EC", "crv": "P-256",
623///       "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
624///       "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
625///     }
626///   }],
627///   "authentication": ["#key-1"]
628/// }"##)?;
629/// let resolver = CompositeKeyResolver::new()
630///     .with(DocumentKeyResolver::new(holder))
631///     .with(Resolver::builder().with(DidKey::default()).build());
632///
633/// let holder_key = KeyReference::DidUrl("did:web:holder.example#key-1".parse()?);
634/// let jwk = resolver.resolve_key(&holder_key, KeyRole::Subject).await?;
635/// assert_eq!(jwk.kty(), "EC");
636/// // Listed under `authentication` only: not a key the holder issues with.
637/// assert!(resolver.resolve_key(&holder_key, KeyRole::Issuer).await.is_err());
638///
639/// // An issuer's `did:key` falls through to the `Resolver`: RFC 8037 Appendix A.2's key.
640/// let issuer = DidKey::did(&serde_json::from_str::<Jwk>(
641///     r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
642/// )?)?;
643/// let issuer_key: DidUrl = issuer.join(&format!("#{}", issuer.method_specific_id()))?;
644/// assert!(resolver.resolve_key(&KeyReference::DidUrl(issuer_key), KeyRole::Issuer).await.is_ok());
645/// # Ok::<(), Box<dyn std::error::Error>>(())
646/// # })?;
647/// # Ok::<(), Box<dyn std::error::Error>>(())
648/// ```
649#[derive(Debug, Clone, PartialEq)]
650pub struct DocumentKeyResolver {
651    documents: Vec<DidDocument>,
652}
653
654impl DocumentKeyResolver {
655    /// A resolver over `document`.
656    pub fn new(document: DidDocument) -> Self {
657        Self {
658            documents: vec![document],
659        }
660    }
661
662    /// This resolver over `document` as well. A document of a DID already supplied replaces the
663    /// earlier one.
664    #[must_use]
665    pub fn with(mut self, document: DidDocument) -> Self {
666        self.documents.retain(|supplied| supplied.id != document.id);
667        self.documents.push(document);
668        self
669    }
670
671    /// The documents it resolves against.
672    pub fn documents(&self) -> &[DidDocument] {
673        &self.documents
674    }
675}
676
677#[async_trait::async_trait]
678impl KeyResolver for DocumentKeyResolver {
679    async fn resolve_key(
680        &self,
681        key: &KeyReference,
682        role: KeyRole,
683    ) -> Result<Jwk, KeyResolutionError> {
684        let KeyReference::DidUrl(url) = key else {
685            return Err(KeyResolutionError::unsupported(key));
686        };
687        let document = self
688            .documents
689            .iter()
690            .find(|document| document.id == *url.did())
691            .filter(|_| url.path().is_none() && url.query().is_none());
692        let Some(document) = document else {
693            return Err(KeyResolutionError::unsupported(key));
694        };
695        verification_method_in(document, url, Some(role.relationship()))
696            .and_then(public_key)
697            .map_err(KeyResolutionError::from)
698    }
699}
700
701/// Resolvers tried in order: the first answer other than
702/// [`Unsupported`](KeyResolutionError::Unsupported) is the answer, an error included.
703///
704/// # Examples
705///
706/// ```
707/// # #[cfg(feature = "did-key")]
708/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
709/// use identity_kit::jose::Jwk;
710/// use identity_kit::methods::DidKey;
711/// use identity_kit::resolver::{CompositeKeyResolver, JwkResolver, KeyReference, KeyResolver as _, KeyRole, Resolver};
712///
713/// let resolver = CompositeKeyResolver::new()
714///     .with(Resolver::builder().with(DidKey::default()).build())
715///     .with(JwkResolver);
716///
717/// // RFC 8037 Appendix A.2.
718/// let key: Jwk = serde_json::from_str(
719///     r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
720/// )?;
721/// let resolved = resolver.resolve_key(&KeyReference::Jwk(Box::new(key.clone())), KeyRole::Issuer).await?;
722/// assert_eq!(resolved, key);
723/// # Ok::<(), Box<dyn std::error::Error>>(())
724/// # })?;
725/// # Ok::<(), Box<dyn std::error::Error>>(())
726/// ```
727#[derive(Clone, Default)]
728pub struct CompositeKeyResolver {
729    resolvers: Vec<Arc<dyn KeyResolver>>,
730}
731
732impl CompositeKeyResolver {
733    /// A resolver with nothing to try: every reference is unsupported.
734    pub fn new() -> Self {
735        Self::default()
736    }
737
738    /// This resolver trying `resolver` after the ones added before.
739    #[must_use]
740    pub fn with(mut self, resolver: impl KeyResolver + 'static) -> Self {
741        self.resolvers.push(Arc::new(resolver));
742        self
743    }
744
745    /// This resolver trying the shared `resolver` after the ones added before.
746    #[must_use]
747    pub fn with_shared(mut self, resolver: Arc<dyn KeyResolver>) -> Self {
748        self.resolvers.push(resolver);
749        self
750    }
751
752    /// How many resolvers it tries.
753    pub fn len(&self) -> usize {
754        self.resolvers.len()
755    }
756
757    /// Whether it has no resolver to try.
758    pub fn is_empty(&self) -> bool {
759        self.resolvers.is_empty()
760    }
761}
762
763impl fmt::Debug for CompositeKeyResolver {
764    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
765        f.debug_struct("CompositeKeyResolver")
766            .field("resolvers", &self.resolvers.len())
767            .finish()
768    }
769}
770
771#[async_trait::async_trait]
772impl KeyResolver for CompositeKeyResolver {
773    async fn resolve_key(
774        &self,
775        key: &KeyReference,
776        role: KeyRole,
777    ) -> Result<Jwk, KeyResolutionError> {
778        for resolver in &self.resolvers {
779            match resolver.resolve_key(key, role).await {
780                Err(KeyResolutionError::Unsupported(_)) => {}
781                answer => return answer,
782            }
783        }
784        Err(KeyResolutionError::unsupported(key))
785    }
786
787    async fn resolve_key_at(
788        &self,
789        key: &KeyReference,
790        role: KeyRole,
791        now: i64,
792    ) -> Result<Jwk, KeyResolutionError> {
793        for resolver in &self.resolvers {
794            match resolver.resolve_key_at(key, role, now).await {
795                Err(KeyResolutionError::Unsupported(_)) => {}
796                answer => return answer,
797            }
798        }
799        Err(KeyResolutionError::unsupported(key))
800    }
801}
802
803/// Why a [`KeyResolver`] found no key.
804#[derive(Debug)]
805#[non_exhaustive]
806pub enum KeyResolutionError {
807    /// The resolver does not handle this kind of reference.
808    Unsupported(Box<KeyReference>),
809    /// The resolver handles the reference and could not find or use the key.
810    Failed(Box<dyn Error + Send + Sync + 'static>),
811}
812
813impl KeyResolutionError {
814    /// The resolver does not handle `key`.
815    pub fn unsupported(key: &KeyReference) -> Self {
816        Self::Unsupported(Box::new(key.clone()))
817    }
818
819    /// A failure caused by `error`.
820    pub fn new<E: Error + Send + Sync + 'static>(error: E) -> Self {
821        Self::Failed(Box::new(error))
822    }
823
824    /// A failure described by `message` only.
825    pub fn msg<M: fmt::Display>(message: M) -> Self {
826        Self::Failed(message.to_string().into())
827    }
828
829    /// Whether the resolver does not handle the reference.
830    pub fn is_unsupported(&self) -> bool {
831        matches!(self, Self::Unsupported(_))
832    }
833
834    /// The error that caused a failure.
835    pub fn inner(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
836        match self {
837            Self::Failed(error) => Some(&**error),
838            Self::Unsupported(_) => None,
839        }
840    }
841}
842
843impl fmt::Display for KeyResolutionError {
844    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845        match self {
846            Self::Unsupported(reference) => write!(f, "no resolver handles {reference}"),
847            Self::Failed(error) => fmt::Display::fmt(error, f),
848        }
849    }
850}
851
852impl Error for KeyResolutionError {
853    fn source(&self) -> Option<&(dyn Error + 'static)> {
854        match self {
855            Self::Failed(error) => error.source(),
856            Self::Unsupported(_) => None,
857        }
858    }
859}
860
861impl From<DereferenceError> for KeyResolutionError {
862    fn from(error: DereferenceError) -> Self {
863        Self::new(error)
864    }
865}