identity_kit/resolver/mod.rs
1//! DID resolution and production: the [`DidResolver`] and [`DidProducer`] traits a DID method
2//! implements, the [`Resolver`] registry that routes a DID to the resolver of its method, an
3//! optional TTL [`DocumentCache`], and DID URL dereferencing. Beside DIDs, finding the key a
4//! token was signed with: [`KeyReference`] and [`KeyResolver`].
5//!
6//! The module ships no DID method. Each method is a type implementing [`DidResolver`] and/or
7//! [`DidProducer`], registered with [`ResolverBuilder::with`]; adding one needs no change here.
8//!
9//! # Resolution
10//!
11//! [`Resolver::resolve`] implements the DID Resolution algorithm around the method's resolver:
12//! it reports [`ResolutionErrorKind::MethodNotSupported`] for a method nobody registered, turns a
13//! result whose metadata reports an error into `Err`, refuses a document whose `id` is not the
14//! DID being resolved (nor its `canonicalId`), and serves repeated resolutions from the cache
15//! when one is configured. [`Resolver::resolve_document`] is the shortcut to the document.
16//!
17//! # Dereferencing
18//!
19//! [`Resolver::dereference`] resolves the DID of a DID URL and then selects the resource the URL
20//! names: the document itself, or the verification method or service whose `id` is the URL
21//! ([`Dereferenced`]). The `versionId` and `versionTime` DID parameters are passed to the
22//! method's resolver as resolution options; a path, any other query parameter and the
23//! `service`/`relativeRef` parameters are method-specific and reported as
24//! [`DereferenceError::MethodSpecific`]. [`Resolver::resolve_public_key`] goes one step further
25//! and returns the [`Jwk`](crate::jose::Jwk) of a verification method, optionally checked to be
26//! usable for a verification relationship, decoding `publicKeyMultibase` material as a Multikey,
27//! which is what a JWS verifier needs.
28//!
29//! # Key references
30//!
31//! A JWT names the key that signed it in one of several ways (ADR 0006), and
32//! [`KeyReference::from_jws`] reads which, in this order: a `kid` that is a DID URL
33//! (`did:…#fragment`, without a path or DID parameters); a `kid` that is a `#fragment`, joined
34//! with a DID `iss`; an `x5c` certificate chain; another `kid` with an HTTPS `iss`, naming a key
35//! of the issuer's key set; the key itself in a `jwk` header; a `jku` key set URL. A token can
36//! carry more than one of these, and which applies is the verifier's policy, not the token's:
37//! [`KeyReference::candidates`] lists them all in that order, and a validator takes the first
38//! its [`KeyResolver`] handles, so the resolvers an application configures are that policy
39//! (ADR 0008). A [`KeyResolver`] turns the reference into a key for a [`KeyRole`], the
40//! issuer's (`assertionMethod` in a DID document) or the subject's (`authentication`), at the
41//! validation time ([`KeyResolver::resolve_key_at`]):
42//!
43//! | Reference | Resolved by |
44//! |---|---|
45//! | [`KeyReference::DidUrl`] | [`Resolver`], dereferencing the verification method |
46//! | [`KeyReference::Jwk`] | [`JwkResolver`], the key itself |
47//! | [`KeyReference::Jwks`] | `JwksResolver` (feature `jwks`), the JWT VC issuer metadata of the issuer |
48//! | [`KeyReference::X509Chain`] | `X509Resolver` (feature `x509`), the chain validated against the application's trust anchors |
49//! | [`KeyReference::Jku`] | nothing in the crate yet; an application's own [`KeyResolver`] |
50//!
51//! [`CompositeKeyResolver`] tries several in order. Resolving says nothing about trust: after
52//! the signature verifies, [`KeyReference::binds_to`] checks that the key belongs to the party
53//! the token claims, which the validators of the upper layer do.
54//!
55//! # X.509
56//!
57//! With the `x509` feature, `X509Resolver` validates the certificate chain of an `x5c` header
58//! against trust anchors the application supplies (RFC 5280 §6, by `rustls-webpki`) and
59//! returns the key of its first certificate: the *Inline X.509 Certificates* mechanism of
60//! SD-JWT VC §3.5, which the OpenID4VC High Assurance Interoperability Profile 1.0 mandates.
61//! It adds what that profile requires of every `x5c`, that the signing certificate is not
62//! self-signed. The issuer of such a token is the subject of the first certificate, which
63//! `X509Certificate` reads; an `iss` claim binds only as an `https` URL whose host is a DNS
64//! name of that certificate. An issuer signs with
65//! [`CertifiedSigner`](crate::jose::CertifiedSigner), which puts its chain in the header.
66//!
67//! # Plain JWTs
68//!
69//! [`JwtValidator`] validates a JWT that is neither a credential nor a presentation, an OAuth
70//! 2.0 access token say, as RFC 7519 §7.2 and RFC 8725 describe: an allowed `alg`, the
71//! expected `typ`, the signature under the key a [`KeyResolver`] finds, that key bound to
72//! `iss` ([`IssuerBinding`]), the expected `iss` and `aud`, `exp`, `nbf` and `iat` within a
73//! leeway, and the claims the [`JwtValidationOptions`] require.
74//!
75//! # Examples
76//!
77//! A method is a type implementing [`DidResolver`]; here one that serves documents from memory.
78//!
79//! ```
80//! use std::collections::HashMap;
81//!
82//! use identity_kit::did::{
83//! Did, DidDocument, DidUrl, ResolutionError, ResolutionErrorKind, ResolutionOptions,
84//! ResolutionResult,
85//! };
86//! use identity_kit::resolver::{Dereferenced, DidResolver, Resolver};
87//!
88//! struct Static(HashMap<Did, DidDocument>);
89//!
90//! #[async_trait::async_trait]
91//! impl DidResolver for Static {
92//! fn method(&self) -> &'static str {
93//! "example"
94//! }
95//!
96//! async fn resolve(
97//! &self,
98//! did: &Did,
99//! _: &ResolutionOptions,
100//! ) -> Result<ResolutionResult, ResolutionError> {
101//! self.0.get(did).cloned().map(ResolutionResult::new).ok_or_else(|| {
102//! ResolutionError::new(ResolutionErrorKind::NotFound)
103//! .with_detail(format!("no document is stored for `{did}`"))
104//! })
105//! }
106//! }
107//!
108//! # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
109//! let document: DidDocument = serde_json::from_str(r##"{
110//! "id": "did:example:123",
111//! "verificationMethod": [{
112//! "id": "did:example:123#key-1",
113//! "type": "JsonWebKey2020",
114//! "controller": "did:example:123",
115//! "publicKeyJwk": {
116//! "kty": "OKP", "crv": "Ed25519", "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"
117//! }
118//! }],
119//! "authentication": ["#key-1"]
120//! }"##)?;
121//! let did = document.id.clone();
122//! let resolver = Resolver::builder()
123//! .with(Static(HashMap::from([(did.clone(), document)])))
124//! .cache(std::time::Duration::from_secs(60))
125//! .build();
126//!
127//! assert_eq!(resolver.resolve_document(&did).await?.id, did);
128//!
129//! let key = DidUrl::parse("did:example:123#key-1")?;
130//! let jwk = resolver.resolve_public_key(&key, None).await?;
131//! assert_eq!(jwk.crv(), Some("Ed25519"));
132//! assert!(matches!(resolver.dereference(&key).await?, Dereferenced::VerificationMethod(_)));
133//!
134//! let unknown = Did::parse("did:other:123")?;
135//! let error = resolver.resolve(&unknown).await.unwrap_err();
136//! assert_eq!(error, ResolutionErrorKind::MethodNotSupported);
137//! assert_eq!(error.detail(), Some("no resolver is registered for `did:other`"));
138//! # Ok::<(), Box<dyn std::error::Error>>(())
139//! # })?;
140//! # Ok::<(), Box<dyn std::error::Error>>(())
141//! ```
142
143use std::sync::Arc;
144
145#[cfg(doc)]
146use crate::did::ResolutionErrorKind;
147use crate::did::{Did, ResolutionError, ResolutionOptions, ResolutionResult};
148
149mod cache;
150mod dereference;
151#[cfg(feature = "jwks")]
152mod jwks;
153mod jwt;
154mod key;
155mod producer;
156mod registry;
157#[cfg(feature = "x509")]
158mod x509;
159
160pub use cache::DocumentCache;
161pub use dereference::{DereferenceError, Dereferenced};
162#[cfg(feature = "jwks")]
163#[cfg_attr(docsrs, doc(cfg(feature = "jwks")))]
164pub use jwks::{JwksError, JwksResolver};
165pub use jwt::{
166 IssuerBinding, JwtValidationError, JwtValidationOptions, JwtValidator, ValidatedJwt,
167};
168pub use key::{
169 CompositeKeyResolver, DocumentKeyResolver, JwkResolver, KeyReference, KeyReferenceError,
170 KeyResolutionError, KeyResolver, KeyRole,
171};
172pub(crate) use key::{JwsKeyError, resolve_jws_key};
173pub use producer::{DidProducer, Hosting, MethodCapabilities, ProduceError};
174pub use registry::{Resolver, ResolverBuilder};
175#[cfg(feature = "x509")]
176#[cfg_attr(docsrs, doc(cfg(feature = "x509")))]
177pub use x509::{X509Certificate, X509Error, X509Resolver};
178
179/// Resolves the DIDs of one method (DID Resolution "DID Resolution Algorithm").
180///
181/// A resolver is registered with a [`Resolver`] under [`method`](Self::method) and receives
182/// only DIDs of that method. It is `Send + Sync` and resolution is `async` because most methods
183/// fetch the document over the network or from a registry.
184///
185/// A failed resolution may be reported either as `Err`, or as an `Ok` result whose resolution
186/// metadata carries the error, which is the shape a method that builds a full
187/// [`ResolutionResult`] (a client of a remote resolver, say) produces anyway. The [`Resolver`]
188/// normalizes both to `Err`.
189#[async_trait::async_trait]
190pub trait DidResolver: Send + Sync {
191 /// The method name this resolver handles: `web` for `did:web`.
192 fn method(&self) -> &'static str;
193
194 /// Resolves `did`, whose method is [`method`](Self::method), with `options`.
195 ///
196 /// On success the result holds the document with `id` equal to `did` (or to the
197 /// `canonicalId` of the document metadata) and whatever metadata the method knows. A
198 /// deactivated DID resolves to a result without a document whose document metadata has
199 /// `deactivated: true`.
200 ///
201 /// # Errors
202 ///
203 /// A [`ResolutionError`] whose kind is [`NotFound`](ResolutionErrorKind::NotFound) for a DID
204 /// that does not exist,
205 /// [`RepresentationNotSupported`](ResolutionErrorKind::RepresentationNotSupported) for an
206 /// `accept` the method cannot produce, or [`InternalError`](ResolutionErrorKind::InternalError)
207 /// for an unexpected failure such as a network error. Attach what caused it with
208 /// [`ResolutionError::with_source`] and [`ResolutionError::with_detail`], so callers can tell
209 /// one failure from another.
210 async fn resolve(
211 &self,
212 did: &Did,
213 options: &ResolutionOptions,
214 ) -> Result<ResolutionResult, ResolutionError>;
215}
216
217// Implements `DidResolver` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
218// A method added to the trait is added here too: one with a default body would still compile
219// if left out, and calls through these wrappers would then run the default, not `T`'s
220// override. `clippy::missing_trait_methods` turns that omission into an error.
221macro_rules! forward_did_resolver {
222 ($($ty:ty),* $(,)?) => {$(
223 #[async_trait::async_trait]
224 #[deny(clippy::missing_trait_methods)]
225 impl<T: DidResolver + ?Sized> DidResolver for $ty {
226 fn method(&self) -> &'static str {
227 (**self).method()
228 }
229
230 async fn resolve(
231 &self,
232 did: &Did,
233 options: &ResolutionOptions,
234 ) -> Result<ResolutionResult, ResolutionError> {
235 (**self).resolve(did, options).await
236 }
237 }
238 )*};
239}
240
241forward_did_resolver!(&T, Box<T>, Arc<T>);