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. No resolver in the crate handles it yet.
59 X509Chain(Vec<Vec<u8>>),
60 /// The key `kid` names in the key set of the HTTPS issuer `issuer` (SD-JWT VC §3.5).
61 Jwks {
62 /// The issuer, the `iss` of the token.
63 issuer: Url,
64 /// The `kid` of the key in the issuer's key set.
65 kid: String,
66 },
67 /// The key set at `url`, from `jku`, and the `kid` that selects a key in it. No resolver in
68 /// the crate handles it yet.
69 Jku {
70 /// The key set URL.
71 url: Url,
72 /// The `kid`, if the token has one.
73 kid: Option<String>,
74 },
75}
76
77impl KeyReference {
78 /// Where the key of `jws` is, given the `iss` of its claims (when `iss` is a string).
79 ///
80 /// The header parameters are tried in this order, and the first that applies decides:
81 ///
82 /// 1. A `kid` that parses as a DID URL is [`DidUrl`](Self::DidUrl). A path or DID
83 /// parameters such as `versionId` are refused: they could select a document version
84 /// that still lists a retired key (ADR 0004).
85 /// 2. A `kid` starting with `#` is joined with `iss` into a [`DidUrl`](Self::DidUrl) when
86 /// `iss` is a DID, and refused otherwise.
87 /// 3. Another `kid`, with an `https` `iss`, is [`Jwks`](Self::Jwks).
88 /// 4. A `jwk` header is [`Jwk`](Self::Jwk); a private key there is refused.
89 /// 5. An `x5c` header is [`X509Chain`](Self::X509Chain), each certificate base64-decoded
90 /// but not parsed.
91 /// 6. A `jku` header is [`Jku`](Self::Jku), with the `kid` when there is one.
92 ///
93 /// A `kid` that none of the first three cases takes is an error when no `jwk`, `x5c` or
94 /// `jku` follows.
95 ///
96 /// # Errors
97 ///
98 /// A [`KeyReferenceError`]: [`Missing`](KeyReferenceError::Missing) when the header names no
99 /// key, otherwise the parameter that is wrong.
100 pub fn from_jws(jws: &CompactJws, iss: Option<&str>) -> Result<Self, KeyReferenceError> {
101 let header = jws.header();
102 let mut kid_error = None;
103 if let Some(kid) = header.kid.as_deref() {
104 match Self::from_kid(kid, iss)? {
105 Ok(reference) => return Ok(reference),
106 Err(source) => {
107 kid_error = Some(KeyReferenceError::InvalidKid {
108 kid: kid.to_owned(),
109 source,
110 });
111 }
112 }
113 }
114 if let Some(jwk) = &header.jwk {
115 if jwk.is_private() {
116 return Err(KeyReferenceError::InvalidJwk(
117 "the `jwk` header holds a private key".to_owned(),
118 ));
119 }
120 return Ok(Self::Jwk(Box::new(jwk.clone())));
121 }
122 if let Some(x5c) = header.additional.get("x5c") {
123 return x5c_chain(x5c).map(Self::X509Chain);
124 }
125 if let Some(jku) = header.additional.get("jku") {
126 let url = jku
127 .as_str()
128 .ok_or_else(|| KeyReferenceError::InvalidUrl {
129 parameter: "jku",
130 value: jku.to_string(),
131 reason: "not a string".to_owned(),
132 })
133 .and_then(|jku| parse_url("jku", jku))?;
134 return Ok(Self::Jku {
135 url,
136 kid: header.kid.clone(),
137 });
138 }
139 Err(kid_error.unwrap_or(KeyReferenceError::Missing))
140 }
141
142 /// Rules 1 to 3 of [`from_jws`](Self::from_jws): the reference `kid` makes with `iss`, or
143 /// why `kid` is not a DID URL when it makes none.
144 fn from_kid(kid: &str, iss: Option<&str>) -> Result<Result<Self, DidError>, KeyReferenceError> {
145 let not_did_url = match DidUrl::parse(kid) {
146 Ok(url) => return did_url(url).map(Ok),
147 Err(error) => error,
148 };
149 if kid.starts_with('#') {
150 let did = iss
151 .and_then(|iss| Did::parse(iss).ok())
152 .ok_or_else(|| KeyReferenceError::RelativeKidWithoutIssuer(kid.to_owned()))?;
153 let url = did
154 .join(kid)
155 .map_err(|source| KeyReferenceError::InvalidKid {
156 kid: kid.to_owned(),
157 source,
158 })?;
159 return did_url(url).map(Ok);
160 }
161 if let Some(issuer) = iss
162 .and_then(|iss| Url::parse(iss).ok())
163 .filter(|issuer| issuer.scheme() == "https")
164 {
165 return Ok(Ok(Self::Jwks {
166 issuer,
167 kid: kid.to_owned(),
168 }));
169 }
170 Ok(Err(not_did_url))
171 }
172
173 /// Whether `key`, which this reference resolved to and which verified the signature,
174 /// belongs to `party`, the issuer or holder the token claims:
175 ///
176 /// | Reference | Binds when |
177 /// |---|---|
178 /// | [`DidUrl`](Self::DidUrl) | `party` is the DID of the URL |
179 /// | [`Jwk`](Self::Jwk) | `party` is the `did:jwk` of `key`, or its RFC 7638 SHA-256 thumbprint, or absent (a SIOPv2 self-issued `sub`) |
180 /// | [`Jwks`](Self::Jwks) | `party` is the issuer URL (compared as parsed URLs) |
181 /// | [`X509Chain`](Self::X509Chain), [`Jku`](Self::Jku) | never, until the crate resolves them |
182 ///
183 /// Only a key by value can bind to no party; a validator that requires an issuer or holder
184 /// passes it.
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// use identity_kit::did::DidUrl;
190 /// use identity_kit::jose::Jwk;
191 /// use identity_kit::resolver::KeyReference;
192 ///
193 /// // RFC 8037 Appendix A.2.
194 /// let key: Jwk = serde_json::from_str(
195 /// r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
196 /// )?;
197 /// let by_value = KeyReference::Jwk(Box::new(key.clone()));
198 /// // RFC 8037 Appendix A.3.
199 /// assert!(by_value.binds_to(Some("kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"), &key));
200 /// assert!(by_value.binds_to(None, &key));
201 /// assert!(!by_value.binds_to(Some("did:example:123"), &key));
202 ///
203 /// let by_url = KeyReference::DidUrl(DidUrl::parse("did:example:123#key-1")?);
204 /// assert!(by_url.binds_to(Some("did:example:123"), &key));
205 /// assert!(!by_url.binds_to(Some("did:example:456"), &key));
206 /// assert!(!by_url.binds_to(None, &key));
207 /// # Ok::<(), Box<dyn std::error::Error>>(())
208 /// ```
209 pub fn binds_to(&self, party: Option<&str>, key: &Jwk) -> bool {
210 match (self, party) {
211 (Self::DidUrl(url), Some(party)) => {
212 Did::parse(party).is_ok_and(|did| did == *url.did())
213 }
214 (Self::Jwk(_), None) => true,
215 (Self::Jwk(_), Some(party)) => is_key_identifier(party, key),
216 (Self::Jwks { issuer, .. }, Some(party)) => {
217 Url::parse(party).is_ok_and(|party| party == *issuer)
218 }
219 _ => false,
220 }
221 }
222}
223
224impl fmt::Display for KeyReference {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 match self {
227 Self::DidUrl(url) => fmt::Display::fmt(url, f),
228 Self::Jwk(jwk) => match jwk.thumbprint_sha256() {
229 Ok(thumbprint) => write!(f, "JWK {thumbprint}"),
230 Err(_) => f.write_str("JWK"),
231 },
232 Self::X509Chain(chain) => write!(f, "`x5c` chain of {} certificates", chain.len()),
233 Self::Jwks { issuer, kid } => write!(f, "`{kid}` of issuer `{issuer}`"),
234 Self::Jku {
235 url,
236 kid: Some(kid),
237 } => write!(f, "`{kid}` of `{url}`"),
238 Self::Jku { url, kid: None } => write!(f, "the key of `{url}`"),
239 }
240 }
241}
242
243/// `url`, refused when it carries a path or DID parameters.
244fn did_url(url: DidUrl) -> Result<KeyReference, KeyReferenceError> {
245 if url.path().is_some() || url.query().is_some() {
246 return Err(KeyReferenceError::KidWithParameters(url));
247 }
248 Ok(KeyReference::DidUrl(url))
249}
250
251/// The certificates of an `x5c` header: an array of standard base64 DER (RFC 7515 §4.1.6).
252fn x5c_chain(x5c: &serde_json::Value) -> Result<Vec<Vec<u8>>, KeyReferenceError> {
253 let invalid = |reason: &str| KeyReferenceError::InvalidX5c(reason.to_owned());
254 let certificates = x5c.as_array().ok_or_else(|| invalid("not an array"))?;
255 if certificates.is_empty() {
256 return Err(invalid("the chain is empty"));
257 }
258 certificates
259 .iter()
260 .map(|certificate| {
261 let certificate = certificate
262 .as_str()
263 .ok_or_else(|| invalid("a certificate is not a string"))?;
264 STANDARD
265 .decode(certificate)
266 .map_err(|_| invalid("a certificate is not base64"))
267 })
268 .collect()
269}
270
271/// `value` of `parameter` as an absolute URL.
272fn parse_url(parameter: &'static str, value: &str) -> Result<Url, KeyReferenceError> {
273 Url::parse(value).map_err(|e| KeyReferenceError::InvalidUrl {
274 parameter,
275 value: value.to_owned(),
276 reason: e.to_string(),
277 })
278}
279
280/// Whether `party` is the `did:jwk` or the RFC 7638 SHA-256 thumbprint of `key`.
281fn is_key_identifier(party: &str, key: &Jwk) -> bool {
282 let Ok(thumbprint) = key.thumbprint_sha256() else {
283 return false;
284 };
285 if party == thumbprint {
286 return true;
287 }
288 // A `did:jwk` names the key by value, in whatever member order its creator serialized it;
289 // the thumbprint compares the required members only.
290 Did::parse(party)
291 .ok()
292 .filter(|did| did.method() == "jwk")
293 .and_then(|did| base64url::decode(did.method_specific_id()).ok())
294 .and_then(|json| serde_json::from_slice::<Jwk>(&json).ok())
295 .and_then(|jwk| jwk.thumbprint_sha256().ok())
296 .is_some_and(|named| named == thumbprint)
297}
298
299/// Why a token names no key this crate can look for.
300#[derive(Debug, thiserror::Error)]
301#[non_exhaustive]
302pub enum KeyReferenceError {
303 /// The token names no key: no `kid`, `jwk`, `x5c` or `jku` (or, in `cnf`, no `jwk`, `kid`
304 /// or `jku`).
305 #[error("the token names no key: no `kid`, `jwk`, `x5c` or `jku`")]
306 Missing,
307 /// The `kid` is a `#fragment` and `iss` is not a DID to resolve it against.
308 #[error("`kid` {0:?} is relative and `iss` is not a DID")]
309 RelativeKidWithoutIssuer(String),
310 /// The `kid` is neither a DID URL nor anything else the token resolves it with.
311 #[error("`kid` {kid:?} is not a DID URL: {source}")]
312 InvalidKid {
313 /// The `kid`.
314 kid: String,
315 /// Why it is not a DID URL.
316 #[source]
317 source: DidError,
318 },
319 /// The `kid` carries a path or DID parameters. `versionId` and `versionTime` could select a
320 /// document version that still lists a retired key, so only `did:…#fragment` keys are
321 /// accepted.
322 #[error("`kid` `{0}` carries a path or DID parameters")]
323 KidWithParameters(DidUrl),
324 /// The key by value is not usable: it holds private material, say.
325 #[error("invalid `jwk`: {0}")]
326 InvalidJwk(String),
327 /// The `x5c` header is not an array of base64 certificates.
328 #[error("invalid `x5c`: {0}")]
329 InvalidX5c(String),
330 /// A URL parameter (`jku`) is not an absolute URL.
331 #[error("`{parameter}` {value:?} is not a URL: {reason}")]
332 InvalidUrl {
333 /// The parameter.
334 parameter: &'static str,
335 /// Its value.
336 value: String,
337 /// Why it did not parse.
338 reason: String,
339 },
340 /// The confirmation names its key only by a method the crate does not resolve, such as
341 /// `x5t#S256` or `jwe`.
342 #[error("`cnf` names its key only by `{0}`, which is not supported")]
343 UnsupportedConfirmation(String),
344}
345
346/// The role a key plays in a token, which decides what a DID document must say about it.
347#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
348#[non_exhaustive]
349pub enum KeyRole {
350 /// The key signs as the issuer of a credential or status list: `assertionMethod`. The
351 /// default.
352 #[default]
353 Issuer,
354 /// The key proves possession by the subject or holder (a presentation, a key binding JWT,
355 /// an ID token): `authentication`.
356 Subject,
357}
358
359impl KeyRole {
360 /// The verification relationship a DID document must list a key of this role under.
361 pub fn relationship(self) -> VerificationRelationship {
362 match self {
363 Self::Issuer => VerificationRelationship::AssertionMethod,
364 Self::Subject => VerificationRelationship::Authentication,
365 }
366 }
367}
368
369/// Finds the public key a [`KeyReference`] names.
370///
371/// [`Resolver`] implements it for DID URLs, [`JwkResolver`] for keys by value and, with the
372/// `jwks` feature, `JwksResolver` for the key sets of HTTPS issuers;
373/// [`CompositeKeyResolver`] combines them. An application can implement it over a cache, a
374/// fixed set of trusted keys, or a reference the crate does not resolve.
375#[async_trait::async_trait]
376pub trait KeyResolver: Send + Sync {
377 /// The public key `key` names, usable in `role`.
378 ///
379 /// # Errors
380 ///
381 /// [`KeyResolutionError::Unsupported`] for a kind of reference this resolver does not
382 /// handle, which lets a [`CompositeKeyResolver`] try the next one; any other
383 /// [`KeyResolutionError`] when the key cannot be found or used.
384 async fn resolve_key(
385 &self,
386 key: &KeyReference,
387 role: KeyRole,
388 ) -> Result<Jwk, KeyResolutionError>;
389}
390
391// Implements `KeyResolver` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
392// A method added to the trait is added here too: one with a default body would still compile
393// if left out, and calls through these wrappers would then run the default, not `T`'s
394// override. `clippy::missing_trait_methods` turns that omission into an error.
395macro_rules! forward_key_resolver {
396 ($($ty:ty),* $(,)?) => {$(
397 #[async_trait::async_trait]
398 #[deny(clippy::missing_trait_methods)]
399 impl<T: KeyResolver + ?Sized> KeyResolver for $ty {
400 async fn resolve_key(
401 &self,
402 key: &KeyReference,
403 role: KeyRole,
404 ) -> Result<Jwk, KeyResolutionError> {
405 (**self).resolve_key(key, role).await
406 }
407 }
408 )*};
409}
410
411forward_key_resolver!(&T, Box<T>, Arc<T>);
412
413/// Resolves a [`KeyReference::DidUrl`] by dereferencing it to a verification method listed
414/// under the relationship of the role; every other reference is
415/// [`Unsupported`](KeyResolutionError::Unsupported).
416#[async_trait::async_trait]
417impl KeyResolver for Resolver {
418 async fn resolve_key(
419 &self,
420 key: &KeyReference,
421 role: KeyRole,
422 ) -> Result<Jwk, KeyResolutionError> {
423 match key {
424 KeyReference::DidUrl(url) => self
425 .resolve_public_key(url, Some(role.relationship()))
426 .await
427 .map_err(KeyResolutionError::from),
428 other => Err(KeyResolutionError::unsupported(other)),
429 }
430 }
431}
432
433/// Resolves a [`KeyReference::Jwk`] to its public part; every other reference is
434/// [`Unsupported`](KeyResolutionError::Unsupported).
435///
436/// Anybody can put a key in a `jwk` header, so the key says nothing about who signed: a
437/// validator accepts it only when the claimed party is that key's `did:jwk` or thumbprint
438/// ([`KeyReference::binds_to`]). Add it to a [`CompositeKeyResolver`] to accept such tokens.
439#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
440pub struct JwkResolver;
441
442#[async_trait::async_trait]
443impl KeyResolver for JwkResolver {
444 async fn resolve_key(&self, key: &KeyReference, _: KeyRole) -> Result<Jwk, KeyResolutionError> {
445 match key {
446 KeyReference::Jwk(jwk) => Ok(jwk.public()),
447 other => Err(KeyResolutionError::unsupported(other)),
448 }
449 }
450}
451
452/// Resolves a [`KeyReference::DidUrl`] against DID documents supplied by the caller, without
453/// resolving the DID again: a document resolved to read its services, or one the caller
454/// fetched or publishes itself.
455///
456/// A DID URL of one of the documents' DIDs resolves to the verification method its fragment
457/// names, which must be usable for the relationship of the role, as [`Resolver`] would:
458/// `publicKeyJwk` as it is, `publicKeyMultibase` decoded as a Multikey. Every other reference
459/// is [`Unsupported`](KeyResolutionError::Unsupported), so that a [`CompositeKeyResolver`]
460/// tries the next resolver: a DID URL of another DID, and one with a path or query, such as a
461/// `versionId`, which names a document other than the one supplied.
462///
463/// # Examples
464///
465/// The caller supplies a presentation's holder document; issuers' keys still resolve over the
466/// network.
467///
468/// ```
469/// # #[cfg(feature = "did-key")]
470/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
471/// use identity_kit::did::{DidDocument, DidUrl};
472/// use identity_kit::jose::Jwk;
473/// use identity_kit::methods::DidKey;
474/// use identity_kit::resolver::{
475/// CompositeKeyResolver, DocumentKeyResolver, KeyReference, KeyResolver as _, KeyRole,
476/// Resolver,
477/// };
478///
479/// // The holder's `did:web` document, already resolved; its key is RFC 7515 Appendix A.3's.
480/// let holder: DidDocument = serde_json::from_str(r##"{
481/// "id": "did:web:holder.example",
482/// "verificationMethod": [{
483/// "id": "did:web:holder.example#key-1",
484/// "type": "JsonWebKey",
485/// "controller": "did:web:holder.example",
486/// "publicKeyJwk": {
487/// "kty": "EC", "crv": "P-256",
488/// "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
489/// "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"
490/// }
491/// }],
492/// "authentication": ["#key-1"]
493/// }"##)?;
494/// let resolver = CompositeKeyResolver::new()
495/// .with(DocumentKeyResolver::new(holder))
496/// .with(Resolver::builder().with(DidKey::default()).build());
497///
498/// let holder_key = KeyReference::DidUrl("did:web:holder.example#key-1".parse()?);
499/// let jwk = resolver.resolve_key(&holder_key, KeyRole::Subject).await?;
500/// assert_eq!(jwk.kty(), "EC");
501/// // Listed under `authentication` only: not a key the holder issues with.
502/// assert!(resolver.resolve_key(&holder_key, KeyRole::Issuer).await.is_err());
503///
504/// // An issuer's `did:key` falls through to the `Resolver`: RFC 8037 Appendix A.2's key.
505/// let issuer = DidKey::did(&serde_json::from_str::<Jwk>(
506/// r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
507/// )?)?;
508/// let issuer_key: DidUrl = issuer.join(&format!("#{}", issuer.method_specific_id()))?;
509/// assert!(resolver.resolve_key(&KeyReference::DidUrl(issuer_key), KeyRole::Issuer).await.is_ok());
510/// # Ok::<(), Box<dyn std::error::Error>>(())
511/// # })?;
512/// # Ok::<(), Box<dyn std::error::Error>>(())
513/// ```
514#[derive(Debug, Clone, PartialEq)]
515pub struct DocumentKeyResolver {
516 documents: Vec<DidDocument>,
517}
518
519impl DocumentKeyResolver {
520 /// A resolver over `document`.
521 pub fn new(document: DidDocument) -> Self {
522 Self {
523 documents: vec![document],
524 }
525 }
526
527 /// This resolver over `document` as well. A document of a DID already supplied replaces the
528 /// earlier one.
529 #[must_use]
530 pub fn with(mut self, document: DidDocument) -> Self {
531 self.documents.retain(|supplied| supplied.id != document.id);
532 self.documents.push(document);
533 self
534 }
535
536 /// The documents it resolves against.
537 pub fn documents(&self) -> &[DidDocument] {
538 &self.documents
539 }
540}
541
542#[async_trait::async_trait]
543impl KeyResolver for DocumentKeyResolver {
544 async fn resolve_key(
545 &self,
546 key: &KeyReference,
547 role: KeyRole,
548 ) -> Result<Jwk, KeyResolutionError> {
549 let KeyReference::DidUrl(url) = key else {
550 return Err(KeyResolutionError::unsupported(key));
551 };
552 let document = self
553 .documents
554 .iter()
555 .find(|document| document.id == *url.did())
556 .filter(|_| url.path().is_none() && url.query().is_none());
557 let Some(document) = document else {
558 return Err(KeyResolutionError::unsupported(key));
559 };
560 verification_method_in(document, url, Some(role.relationship()))
561 .and_then(public_key)
562 .map_err(KeyResolutionError::from)
563 }
564}
565
566/// Resolvers tried in order: the first answer other than
567/// [`Unsupported`](KeyResolutionError::Unsupported) is the answer, an error included.
568///
569/// # Examples
570///
571/// ```
572/// # #[cfg(feature = "did-key")]
573/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
574/// use identity_kit::jose::Jwk;
575/// use identity_kit::methods::DidKey;
576/// use identity_kit::resolver::{CompositeKeyResolver, JwkResolver, KeyReference, KeyResolver as _, KeyRole, Resolver};
577///
578/// let resolver = CompositeKeyResolver::new()
579/// .with(Resolver::builder().with(DidKey::default()).build())
580/// .with(JwkResolver);
581///
582/// // RFC 8037 Appendix A.2.
583/// let key: Jwk = serde_json::from_str(
584/// r#"{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}"#,
585/// )?;
586/// let resolved = resolver.resolve_key(&KeyReference::Jwk(Box::new(key.clone())), KeyRole::Issuer).await?;
587/// assert_eq!(resolved, key);
588/// # Ok::<(), Box<dyn std::error::Error>>(())
589/// # })?;
590/// # Ok::<(), Box<dyn std::error::Error>>(())
591/// ```
592#[derive(Clone, Default)]
593pub struct CompositeKeyResolver {
594 resolvers: Vec<Arc<dyn KeyResolver>>,
595}
596
597impl CompositeKeyResolver {
598 /// A resolver with nothing to try: every reference is unsupported.
599 pub fn new() -> Self {
600 Self::default()
601 }
602
603 /// This resolver trying `resolver` after the ones added before.
604 #[must_use]
605 pub fn with(mut self, resolver: impl KeyResolver + 'static) -> Self {
606 self.resolvers.push(Arc::new(resolver));
607 self
608 }
609
610 /// This resolver trying the shared `resolver` after the ones added before.
611 #[must_use]
612 pub fn with_shared(mut self, resolver: Arc<dyn KeyResolver>) -> Self {
613 self.resolvers.push(resolver);
614 self
615 }
616
617 /// How many resolvers it tries.
618 pub fn len(&self) -> usize {
619 self.resolvers.len()
620 }
621
622 /// Whether it has no resolver to try.
623 pub fn is_empty(&self) -> bool {
624 self.resolvers.is_empty()
625 }
626}
627
628impl fmt::Debug for CompositeKeyResolver {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.debug_struct("CompositeKeyResolver")
631 .field("resolvers", &self.resolvers.len())
632 .finish()
633 }
634}
635
636#[async_trait::async_trait]
637impl KeyResolver for CompositeKeyResolver {
638 async fn resolve_key(
639 &self,
640 key: &KeyReference,
641 role: KeyRole,
642 ) -> Result<Jwk, KeyResolutionError> {
643 for resolver in &self.resolvers {
644 match resolver.resolve_key(key, role).await {
645 Err(KeyResolutionError::Unsupported(_)) => {}
646 answer => return answer,
647 }
648 }
649 Err(KeyResolutionError::unsupported(key))
650 }
651}
652
653/// Why a [`KeyResolver`] found no key.
654#[derive(Debug)]
655#[non_exhaustive]
656pub enum KeyResolutionError {
657 /// The resolver does not handle this kind of reference.
658 Unsupported(Box<KeyReference>),
659 /// The resolver handles the reference and could not find or use the key.
660 Failed(Box<dyn Error + Send + Sync + 'static>),
661}
662
663impl KeyResolutionError {
664 /// The resolver does not handle `key`.
665 pub fn unsupported(key: &KeyReference) -> Self {
666 Self::Unsupported(Box::new(key.clone()))
667 }
668
669 /// A failure caused by `error`.
670 pub fn new<E: Error + Send + Sync + 'static>(error: E) -> Self {
671 Self::Failed(Box::new(error))
672 }
673
674 /// A failure described by `message` only.
675 pub fn msg<M: fmt::Display>(message: M) -> Self {
676 Self::Failed(message.to_string().into())
677 }
678
679 /// Whether the resolver does not handle the reference.
680 pub fn is_unsupported(&self) -> bool {
681 matches!(self, Self::Unsupported(_))
682 }
683
684 /// The error that caused a failure.
685 pub fn inner(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
686 match self {
687 Self::Failed(error) => Some(&**error),
688 Self::Unsupported(_) => None,
689 }
690 }
691}
692
693impl fmt::Display for KeyResolutionError {
694 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
695 match self {
696 Self::Unsupported(reference) => write!(f, "no resolver handles {reference}"),
697 Self::Failed(error) => fmt::Display::fmt(error, f),
698 }
699 }
700}
701
702impl Error for KeyResolutionError {
703 fn source(&self) -> Option<&(dyn Error + 'static)> {
704 match self {
705 Self::Failed(error) => error.source(),
706 Self::Unsupported(_) => None,
707 }
708 }
709}
710
711impl From<DereferenceError> for KeyResolutionError {
712 fn from(error: DereferenceError) -> Self {
713 Self::new(error)
714 }
715}