Skip to main content

identity_kit/methods/web/
mod.rs

1//! `did:web`: a DID document served over HTTPS by a web origin.
2//!
3//! The [did:web method] maps a DID to the URL of its document: `did:web:example.com` is served
4//! at `https://example.com/.well-known/did.json`, and `did:web:example.com%3A8443:user:alice`
5//! at `https://example.com:8443/user/alice/did.json` (a port is percent-encoded as `%3A`, path
6//! segments are separated by `:`). [`document_url`] implements that mapping and
7//! [`did_from_url`] its inverse. The document is fetched through an [`HttpClient`] the caller
8//! injects; [`ReqwestClient`] (feature `reqwest`) is a hardened default that speaks HTTPS only,
9//! follows no redirect, refuses non-public addresses and caps the response size.
10//!
11//! The method is updated by republishing the document and deactivated by removing it; neither
12//! has an API, so [`DidWeb`] as a [`DidProducer`] builds the document to publish and nothing
13//! more.
14//!
15//! [did:web method]: https://w3c-ccg.github.io/did-method-web/
16
17use core::fmt;
18use core::fmt::Write as _;
19use std::error::Error;
20use std::sync::Arc;
21
22use url::{Host, Url};
23
24use crate::did::{
25    Context, Did, DidDocument, MethodType, ResolutionError, ResolutionErrorKind, ResolutionOptions,
26    ResolutionResult, VerificationMaterial, VerificationMethod, VerificationRelationship,
27};
28use crate::jose::Jwk;
29use crate::resolver::{DidProducer, DidResolver, Hosting, MethodCapabilities, ProduceError};
30
31use super::check_accept;
32
33#[cfg(feature = "reqwest")]
34mod client;
35
36#[cfg(feature = "reqwest")]
37#[cfg_attr(docsrs, doc(cfg(feature = "reqwest")))]
38pub use client::ReqwestClient;
39#[cfg(feature = "local-network")]
40#[cfg_attr(docsrs, doc(cfg(feature = "local-network")))]
41pub use client::{LocalNetwork, ReqwestClientBuilder};
42
43/// The method name, `web`.
44pub const METHOD: &str = "web";
45
46/// The `@context` of a document [`DidWeb`] produces.
47pub const CONTEXT: [&str; 2] = [
48    Context::DID_V1,
49    "https://w3id.org/security/suites/jws-2020/v1",
50];
51
52// ---------------------------------------------------------------------------------------------
53// HTTP
54// ---------------------------------------------------------------------------------------------
55
56/// What [`DidWeb`] needs from HTTP: a `GET` of a URL.
57///
58/// Implement it over the HTTP client of the application so `did:web` resolution shares its
59/// connection pool, proxy and TLS settings. The implementation decides the security policy:
60/// [`ReqwestClient`] is the one this crate ships.
61///
62/// Every URL a client is given comes from untrusted input (a DID, a credential's status list
63/// reference), so an implementation must refuse what [`ReqwestClient`] refuses, or weigh the
64/// consequence: plain `http`, redirects, hosts that resolve to loopback, private, link-local or
65/// other non-public addresses, unbounded bodies and unbounded waits.
66///
67/// A client follows no redirect itself: it returns the 3xx response, with its `Location` in
68/// [`HttpResponse::location`]. A caller that follows redirects, such as the status list check
69/// of the `sd-jwt` feature, fetches each target with a new call, so that every hop goes
70/// through the client's rules.
71#[async_trait::async_trait]
72pub trait HttpClient: Send + Sync {
73    /// Fetches `url`, returning the status and the body of the response.
74    ///
75    /// # Errors
76    ///
77    /// Any failure to get a response: a refused URL, a network or TLS error, a timeout, a body
78    /// over the client's limit. An HTTP error status is a response, not an error.
79    async fn get(&self, url: &Url) -> Result<HttpResponse, HttpError>;
80
81    /// Fetches `url` asking for a body of `media_type`, sent as the `Accept` header.
82    ///
83    /// The default calls [`get`](Self::get) and sends no `Accept` header; [`ReqwestClient`]
84    /// sends it. Implement it when a server negotiates the content type.
85    ///
86    /// # Errors
87    ///
88    /// As [`get`](Self::get).
89    async fn get_accepting(&self, url: &Url, media_type: &str) -> Result<HttpResponse, HttpError> {
90        let _ = media_type;
91        self.get(url).await
92    }
93
94    /// Whether this client may fetch `url` over plain `http`.
95    ///
96    /// The fetch helpers built on this trait (the DID configuration of `domain_linkage`, the
97    /// presentations of `linked_vp`, the key sets of `JwksResolver` and the status list
98    /// redirects) refuse a URL that is not `https` before sending a request, unless this
99    /// returns `true` for an `http` URL. The client still decides in [`get`](Self::get): a
100    /// `true` here lets the request reach it, nothing more.
101    ///
102    /// The default is `false`. [`ReqwestClient`] returns `true` only when built for local
103    /// development and tests, with the `local-network` feature.
104    fn allows_plain_http(&self, url: &Url) -> bool {
105        let _ = url;
106        false
107    }
108}
109
110/// Whether `http` may be asked for `url`: an `https` URL, or an `http` URL the client
111/// [allows](HttpClient::allows_plain_http).
112#[cfg(any(
113    feature = "jwks",
114    feature = "status-list",
115    feature = "domain-linkage",
116    feature = "linked-vp"
117))]
118pub(crate) fn fetchable<C: HttpClient + ?Sized>(http: &C, url: &Url) -> bool {
119    match url.scheme() {
120        "https" => true,
121        "http" => http.allows_plain_http(url),
122        _ => false,
123    }
124}
125
126// Implements `HttpClient` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
127// A method added to the trait is added here too: one with a default body would still compile
128// if left out, and calls through these wrappers would then run the default, not `T`'s
129// override. `clippy::missing_trait_methods` turns that omission into an error.
130macro_rules! forward_http_client {
131    ($($t:ty),* $(,)?) => {$(
132        #[async_trait::async_trait]
133        #[deny(clippy::missing_trait_methods)]
134        impl<T: HttpClient + ?Sized> HttpClient for $t {
135            async fn get(&self, url: &Url) -> Result<HttpResponse, HttpError> {
136                (**self).get(url).await
137            }
138
139            async fn get_accepting(
140                &self,
141                url: &Url,
142                media_type: &str,
143            ) -> Result<HttpResponse, HttpError> {
144                (**self).get_accepting(url, media_type).await
145            }
146
147            fn allows_plain_http(&self, url: &Url) -> bool {
148                (**self).allows_plain_http(url)
149            }
150        }
151    )*};
152}
153
154forward_http_client!(&T, Box<T>, Arc<T>);
155
156/// An HTTP response: the status code, the body and, for a redirect, its target.
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct HttpResponse {
160    /// The status code, `200` for a served document.
161    pub status: u16,
162    /// The body, which a `did:web` resolver parses as JSON.
163    pub body: Vec<u8>,
164    /// The `Location` header of a 3xx response, as sent: possibly relative to the requested
165    /// URL. `None` for any other response.
166    pub location: Option<String>,
167}
168
169impl HttpResponse {
170    /// A response with `status` and `body`, and no `location`.
171    pub fn new(status: u16, body: impl Into<Vec<u8>>) -> Self {
172        Self {
173            status,
174            body: body.into(),
175            location: None,
176        }
177    }
178
179    /// This response with the `Location` header `location`.
180    #[must_use]
181    pub fn with_location(mut self, location: impl Into<String>) -> Self {
182        self.location = Some(location.into());
183        self
184    }
185}
186
187/// Why an [`HttpClient`] could not get a response.
188#[derive(Debug)]
189pub struct HttpError(Box<dyn Error + Send + Sync + 'static>);
190
191impl HttpError {
192    /// Wraps `error`.
193    pub fn new<E: Error + Send + Sync + 'static>(error: E) -> Self {
194        Self(Box::new(error))
195    }
196
197    /// An error carrying `message`.
198    pub fn msg<M: fmt::Display>(message: M) -> Self {
199        Self(message.to_string().into())
200    }
201
202    /// The wrapped error.
203    pub fn inner(&self) -> &(dyn Error + Send + Sync + 'static) {
204        self.0.as_ref()
205    }
206}
207
208impl fmt::Display for HttpError {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        fmt::Display::fmt(&self.0, f)
211    }
212}
213
214impl Error for HttpError {
215    fn source(&self) -> Option<&(dyn Error + 'static)> {
216        self.0.source()
217    }
218}
219
220impl From<Box<dyn Error + Send + Sync + 'static>> for HttpError {
221    fn from(error: Box<dyn Error + Send + Sync + 'static>) -> Self {
222        Self(error)
223    }
224}
225
226// ---------------------------------------------------------------------------------------------
227// DID <-> URL
228// ---------------------------------------------------------------------------------------------
229
230/// Why a URL has no `did:web`, or a `did:web` no document URL.
231#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
232#[non_exhaustive]
233pub enum WebError {
234    /// The URL is not an HTTPS location a `did:web` can name.
235    #[error("`{url}` cannot be a did:web: {reason}")]
236    InvalidUrl {
237        /// The URL.
238        url: Url,
239        /// What is wrong with it.
240        reason: &'static str,
241    },
242    /// The DID is not a well-formed `did:web`.
243    #[error("`{did}` is not a valid did:web: {reason}")]
244    InvalidDid {
245        /// The DID.
246        did: Did,
247        /// What is wrong with it.
248        reason: &'static str,
249    },
250}
251
252/// The directory of the document of a DID without path segments.
253const WELL_KNOWN: &str = ".well-known";
254
255/// The file name of the document.
256const DOCUMENT_FILE: &str = "did.json";
257
258/// The `did:web` whose document lives under `url`: `https://example.com` gives
259/// `did:web:example.com`, `https://example.com:8443/user/alice` gives
260/// `did:web:example.com%3A8443:user:alice`.
261///
262/// The URL must be `https`, name a domain (not an IP address) and carry no credentials, query
263/// or fragment. A trailing slash is ignored, as is the document file name that
264/// [`document_url`] appends (`/.well-known/did.json` or `/did.json`), so a document URL maps
265/// back to its DID; other path segments become `:`-separated id segments, percent-encoded where
266/// the DID syntax requires it.
267///
268/// # Errors
269///
270/// [`WebError::InvalidUrl`] when the URL breaks one of those rules.
271///
272/// # Examples
273///
274/// ```
275/// use identity_kit::methods::web::did_from_url;
276/// use url::Url;
277///
278/// let did = did_from_url(&Url::parse("https://example.com:3000/user/alice/")?)?;
279/// assert_eq!(did.as_str(), "did:web:example.com%3A3000:user:alice");
280/// let did = did_from_url(&Url::parse("https://example.com/.well-known/did.json")?)?;
281/// assert_eq!(did.as_str(), "did:web:example.com");
282/// assert!(did_from_url(&Url::parse("https://192.0.2.1/")?).is_err());
283/// # Ok::<(), Box<dyn std::error::Error>>(())
284/// ```
285pub fn did_from_url(url: &Url) -> Result<Did, WebError> {
286    let invalid = |reason| WebError::InvalidUrl {
287        url: url.clone(),
288        reason,
289    };
290    if url.scheme() != "https" {
291        return Err(invalid("the scheme must be `https`"));
292    }
293    let domain = match url.host() {
294        Some(Host::Domain(domain)) => domain,
295        Some(_) => return Err(invalid("the host must be a domain name, not an IP address")),
296        None => return Err(invalid("the URL has no host")),
297    };
298    if !domain
299        .bytes()
300        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
301    {
302        return Err(invalid("the host has characters a DID cannot carry"));
303    }
304    if !url.username().is_empty() || url.password().is_some() {
305        return Err(invalid("the URL must not carry credentials"));
306    }
307    if url.query().is_some() || url.fragment().is_some() {
308        return Err(invalid("the URL must not have a query or a fragment"));
309    }
310    let mut id = domain.to_owned();
311    if let Some(port) = url.port() {
312        let _ = write!(id, "%3A{port}");
313    }
314    let mut segments: Vec<&str> = url
315        .path_segments()
316        .map(Iterator::collect)
317        .unwrap_or_default();
318    if segments.last() == Some(&"") {
319        segments.pop();
320    }
321    if segments.last() == Some(&DOCUMENT_FILE) {
322        segments.pop();
323        if segments.as_slice() == [WELL_KNOWN] {
324            segments.clear();
325        }
326    }
327    for segment in segments {
328        if segment.is_empty() {
329            return Err(invalid("the path has an empty segment"));
330        }
331        id.push(':');
332        id.push_str(&encode_segment(segment));
333    }
334    Did::parse(&format!("did:web:{id}")).map_err(|_| invalid("the URL does not map to a DID"))
335}
336
337/// The `did:web` of the origin of `url`: as [`did_from_url`], but the URL must have no path.
338///
339/// # Errors
340///
341/// [`WebError::InvalidUrl`] when the URL has a path, or breaks a rule of [`did_from_url`].
342pub fn did_from_origin(url: &Url) -> Result<Did, WebError> {
343    if !matches!(url.path(), "" | "/") {
344        return Err(WebError::InvalidUrl {
345            url: url.clone(),
346            reason: "an origin has no path",
347        });
348    }
349    did_from_url(url)
350}
351
352/// `segment` with every byte outside the DID `idchar` set percent-encoded.
353fn encode_segment(segment: &str) -> String {
354    let bytes = segment.as_bytes();
355    let mut out = String::with_capacity(segment.len());
356    let mut i = 0;
357    while i < bytes.len() {
358        let b = bytes[i];
359        if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_') {
360            out.push(char::from(b));
361        } else if b == b'%'
362            && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit)
363            && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit)
364        {
365            out.push_str(&segment[i..i + 3]);
366            i += 3;
367            continue;
368        } else {
369            let _ = write!(out, "%{b:02X}");
370        }
371        i += 1;
372    }
373    out
374}
375
376/// The URL of the document of `did` (the Read operation's URL construction):
377/// `https://host[:port]/.well-known/did.json` for a bare domain, else
378/// `https://host[:port]/<segments>/did.json`.
379///
380/// # Errors
381///
382/// [`WebError::InvalidDid`] when `did` is not a `did:web`, names an IP address, has a
383/// malformed port, or has an empty, `.` or `..` path segment, percent-encoded or not.
384///
385/// # Examples
386///
387/// ```
388/// use identity_kit::did::Did;
389/// use identity_kit::methods::web::document_url;
390///
391/// let url = document_url(&Did::parse("did:web:example.com")?)?;
392/// assert_eq!(url.as_str(), "https://example.com/.well-known/did.json");
393///
394/// let url = document_url(&Did::parse("did:web:example.com%3A3000:user:alice")?)?;
395/// assert_eq!(url.as_str(), "https://example.com:3000/user/alice/did.json");
396/// # Ok::<(), Box<dyn std::error::Error>>(())
397/// ```
398pub fn document_url(did: &Did) -> Result<Url, WebError> {
399    let invalid = |reason| WebError::InvalidDid {
400        did: did.clone(),
401        reason,
402    };
403    if did.method() != METHOD {
404        return Err(invalid("the method is not `web`"));
405    }
406    let mut segments = did.method_specific_id().split(':');
407    let authority = percent_decode(segments.next().unwrap_or_default());
408    let (host, port) = match authority.rsplit_once(':') {
409        Some((host, port)) => (host, Some(port)),
410        None => (authority.as_str(), None),
411    };
412    if host.is_empty()
413        || !host
414            .bytes()
415            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
416    {
417        return Err(invalid("the host is not a domain name"));
418    }
419    if let Some(port) = port
420        && (port.is_empty() || port.len() > 5 || !port.bytes().all(|b| b.is_ascii_digit()))
421    {
422        return Err(invalid("the port is not a number"));
423    }
424    let mut path = String::new();
425    let mut has_segments = false;
426    for segment in segments {
427        if is_dot_segment(segment) {
428            return Err(invalid("a path segment is empty, `.` or `..`"));
429        }
430        has_segments = true;
431        path.push('/');
432        path.push_str(segment);
433    }
434    if !has_segments {
435        path.push('/');
436        path.push_str(WELL_KNOWN);
437    }
438    let port = port.map(|port| format!(":{port}")).unwrap_or_default();
439    let url = Url::parse(&format!("https://{host}{port}{path}/{DOCUMENT_FILE}"))
440        .map_err(|_| invalid("the DID does not map to a URL"))?;
441    match url.host() {
442        Some(Host::Domain(_)) => Ok(url),
443        _ => Err(invalid("the host is an IP address")),
444    }
445}
446
447/// Whether `segment` is empty, or is `.` or `..` as the URL parser reads it: a segment of `.` and
448/// `%2E` in any combination and case is a dot segment, which the parser collapses into the path
449/// before it, so `did:web:example.com:a:%2E%2E:b` would name `https://example.com/b/did.json`.
450fn is_dot_segment(segment: &str) -> bool {
451    let mut dots = 0;
452    let mut i = 0;
453    let bytes = segment.as_bytes();
454    while i < bytes.len() {
455        if bytes[i] == b'.' {
456            i += 1;
457        } else if bytes[i..]
458            .get(..3)
459            .is_some_and(|b| b.eq_ignore_ascii_case(b"%2e"))
460        {
461            i += 3;
462        } else {
463            return false;
464        }
465        dots += 1;
466    }
467    dots <= 2
468}
469
470/// Decodes the percent-encoded octets of a DID segment, which the DID syntax has checked to be
471/// complete; non-UTF-8 octets become replacement characters and fail the host check.
472#[expect(clippy::cast_possible_truncation, reason = "a hex digit is below 16")]
473fn percent_decode(s: &str) -> String {
474    let bytes = s.as_bytes();
475    let mut out = Vec::with_capacity(bytes.len());
476    let mut i = 0;
477    while i < bytes.len() {
478        match (bytes[i], bytes.get(i + 1), bytes.get(i + 2)) {
479            (b'%', Some(hi), Some(lo)) if hi.is_ascii_hexdigit() && lo.is_ascii_hexdigit() => {
480                let hex = |b: u8| (b as char).to_digit(16).unwrap_or(0) as u8;
481                out.push(hex(*hi) << 4 | hex(*lo));
482                i += 3;
483            }
484            (b, _, _) => {
485                out.push(b);
486                i += 1;
487            }
488        }
489    }
490    String::from_utf8_lossy(&out).into_owned()
491}
492
493// ---------------------------------------------------------------------------------------------
494// The method
495// ---------------------------------------------------------------------------------------------
496
497/// The `did:web` method: a [`DidResolver`] fetching documents through an [`HttpClient`], and a
498/// [`DidProducer`] building the document to publish.
499///
500/// # Examples
501///
502/// ```
503/// use identity_kit::did::Did;
504/// use identity_kit::methods::web::{DidWeb, HttpClient, HttpError, HttpResponse};
505/// use identity_kit::resolver::Resolver;
506/// use url::Url;
507///
508/// /// Serves one document from memory.
509/// struct Static(String);
510///
511/// #[async_trait::async_trait]
512/// impl HttpClient for Static {
513///     async fn get(&self, url: &Url) -> Result<HttpResponse, HttpError> {
514///         Ok(if url.as_str() == "https://example.com/.well-known/did.json" {
515///             HttpResponse::new(200, self.0.as_bytes())
516///         } else {
517///             HttpResponse::new(404, Vec::new())
518///         })
519///     }
520/// }
521///
522/// # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
523/// let document = r#"{"id": "did:web:example.com"}"#.to_owned();
524/// let resolver = Resolver::builder().with(DidWeb::new(Static(document))).build();
525/// let did = Did::parse("did:web:example.com")?;
526/// assert_eq!(resolver.resolve_document(&did).await?.id, did);
527/// # Ok::<(), Box<dyn std::error::Error>>(())
528/// # })?;
529/// # Ok::<(), Box<dyn std::error::Error>>(())
530/// ```
531#[derive(Debug, Clone)]
532pub struct DidWeb<C> {
533    client: C,
534}
535
536impl<C: HttpClient> DidWeb<C> {
537    /// The method fetching documents with `client`.
538    pub const fn new(client: C) -> Self {
539        Self { client }
540    }
541
542    /// The HTTP client.
543    pub const fn client(&self) -> &C {
544        &self.client
545    }
546}
547
548#[async_trait::async_trait]
549impl<C: HttpClient> DidResolver for DidWeb<C> {
550    fn method(&self) -> &'static str {
551        METHOD
552    }
553
554    /// Fetches the document of `did` from [`document_url`] and checks that its `id` is `did`.
555    ///
556    /// # Errors
557    ///
558    /// A [`ResolutionError`] whose kind is:
559    ///
560    /// - [`InvalidDid`](ResolutionErrorKind::InvalidDid) when `did` has no document URL, caused
561    ///   by the [`WebError`].
562    /// - [`NotFound`](ResolutionErrorKind::NotFound) on a `404` or `410` response.
563    /// - [`InternalError`](ResolutionErrorKind::InternalError) when the client fails, caused by
564    ///   its [`HttpError`], or when it returns any other non-success status, which the detail
565    ///   names.
566    /// - [`InvalidDidDocument`](ResolutionErrorKind::InvalidDidDocument) when the body is not a
567    ///   DID document, caused by the [`serde_json::Error`], or is the document of another DID,
568    ///   which the detail names.
569    /// - [`RepresentationNotSupported`](ResolutionErrorKind::RepresentationNotSupported) for an
570    ///   `accept` that is not JSON.
571    async fn resolve(
572        &self,
573        did: &Did,
574        options: &ResolutionOptions,
575    ) -> Result<ResolutionResult, ResolutionError> {
576        check_accept(options)?;
577        let url = document_url(did).map_err(|error| {
578            ResolutionError::new(ResolutionErrorKind::InvalidDid).with_source(error)
579        })?;
580        let response = self.client.get(&url).await.map_err(|error| {
581            ResolutionError::new(ResolutionErrorKind::InternalError)
582                .with_detail(format!("fetching `{url}` failed"))
583                .with_source(error)
584        })?;
585        let kind = match response.status {
586            200..=299 => None,
587            404 | 410 => Some(ResolutionErrorKind::NotFound),
588            _ => Some(ResolutionErrorKind::InternalError),
589        };
590        if let Some(kind) = kind {
591            return Err(ResolutionError::new(kind).with_detail(format!(
592                "`{url}` responded with HTTP status {}",
593                response.status
594            )));
595        }
596        let document: DidDocument = serde_json::from_slice(&response.body).map_err(|error| {
597            ResolutionError::new(ResolutionErrorKind::InvalidDidDocument)
598                .with_detail(format!("the body of `{url}` is not a DID document"))
599                .with_source(error)
600        })?;
601        if document.id != *did {
602            return Err(
603                ResolutionError::new(ResolutionErrorKind::InvalidDidDocument).with_detail(format!(
604                    "`{url}` holds the document of `{}`, not `{did}`",
605                    document.id
606                )),
607            );
608        }
609        Ok(ResolutionResult::new(document))
610    }
611}
612
613#[async_trait::async_trait]
614impl<C: HttpClient> DidProducer for DidWeb<C> {
615    /// The HTTPS URL the document will be served under, as [`did_from_url`] reads it.
616    type Params = Url;
617
618    fn method(&self) -> &'static str {
619        METHOD
620    }
621
622    /// Hosted on the web, any number of keys, updated by republishing; fragments come from the
623    /// keys.
624    fn capabilities(&self) -> MethodCapabilities {
625        MethodCapabilities::new(Hosting::Web).with_updatable(true)
626    }
627
628    /// The document to publish at `url` for `keys`.
629    ///
630    /// Each key becomes a `JsonWebKey2020` verification method whose fragment is the key's
631    /// `kid`, or `key-<index>` when it has none. A key with `use` `enc`, or an X25519 key, is
632    /// referenced from `keyAgreement`; every other key from `authentication`,
633    /// `assertionMethod`, `capabilityInvocation` and `capabilityDelegation`. The document's
634    /// `@context` is [`CONTEXT`].
635    ///
636    /// # Errors
637    ///
638    /// - [`ProduceError::NoKeys`] without a key.
639    /// - [`ProduceError::InvalidParams`] when `url` has no `did:web` (see [`did_from_url`]).
640    /// - [`ProduceError::UnsupportedKey`] for a `kid` that is not a valid fragment.
641    /// - [`ProduceError::Document`] for two keys with the same `kid`.
642    async fn produce(&self, keys: &[Jwk], url: Url) -> Result<DidDocument, ProduceError> {
643        if keys.is_empty() {
644            return Err(ProduceError::NoKeys);
645        }
646        let did = did_from_url(&url).map_err(|error| ProduceError::InvalidParams {
647            reason: "the URL is not a `did:web` location".to_owned(),
648            source: Some(Box::new(error)),
649        })?;
650        let mut builder = DidDocument::builder(did.clone()).context(Context::uris(CONTEXT));
651        for (index, key) in keys.iter().enumerate() {
652            let id = match key.kid() {
653                Some(kid) => {
654                    did.join(&format!("#{kid}"))
655                        .map_err(|error| ProduceError::UnsupportedKey {
656                            index,
657                            reason: format!("`kid` {kid:?} is not a valid DID URL fragment"),
658                            source: Some(Box::new(error)),
659                        })?
660                }
661                None => did.to_url().with_fragment(&format!("key-{index}")),
662            };
663            let relationships: &[VerificationRelationship] =
664                if key.key_use() == Some("enc") || key.crv() == Some("X25519") {
665                    &[VerificationRelationship::KeyAgreement]
666                } else {
667                    &[
668                        VerificationRelationship::Authentication,
669                        VerificationRelationship::AssertionMethod,
670                        VerificationRelationship::CapabilityInvocation,
671                        VerificationRelationship::CapabilityDelegation,
672                    ]
673                };
674            let method = VerificationMethod::new(
675                id,
676                MethodType::JSON_WEB_KEY_2020,
677                did.clone(),
678                VerificationMaterial::jwk(key),
679            );
680            builder = builder.verification_method(method, relationships.iter().copied());
681        }
682        Ok(builder.build()?)
683    }
684}