Skip to main content

identity_kit/domain_linkage/
mod.rs

1//! DIF Well Known DID Configuration: proving that the controller of an origin and the
2//! controller of a DID are the same entity.
3//!
4//! An origin publishes a [`DomainLinkageConfiguration`] at `/.well-known/did-configuration.json`
5//! ([`configuration_url`]) holding one domain linkage credential per linked DID. This crate
6//! handles the JSON Web Token proof format: [`DomainLinkageCredentialBuilder`] issues such a
7//! credential (a VCDM 1.1 [`Credential`] of type `DomainLinkageCredential` whose subject is
8//! the DID with the `origin`), and [`DomainLinkageValidator`] checks one, or a whole
9//! configuration, against the origin it was fetched from, resolving the DID's key under
10//! `assertionMethod`. Linked Data Proof entries are carried as data and not validated.
11//!
12//! The specification writes the origin with its scheme (`https://identity.foundation`), its
13//! own JWT example without (`identity.foundation`); the validator normalizes both to the
14//! `scheme://host[:port]` form, `https` when none is given, before comparing.
15//!
16//! # Fetching
17//!
18//! [`fetch_configuration`] gets the resource of an origin through an [`HttpClient`], the one
19//! `did:web` and status lists use, telling an origin that publishes no configuration
20//! ([`DomainLinkageError::NotPublished`], on `404` or `410`) apart from one whose
21//! configuration could not be fetched or read. [`DomainLinkageClient`] fetches and validates
22//! in one call, for an origin, for one DID at an origin, or for every origin a DID document
23//! lists in its `LinkedDomains` services ([`services`]), reporting per origin.
24//!
25//! # Maintaining a configuration
26//!
27//! The controller of an origin reads back the credentials it published with
28//! [`DomainLinkageConfiguration::entries`]: the DID, origin and validity period of each JWT
29//! entry ([`UnverifiedLinkage`]), read **without verifying it**, since it signed them itself.
30//! [`earliest_expiry`](DomainLinkageConfiguration::earliest_expiry) says when to renew,
31//! [`remove_origin`](DomainLinkageConfiguration::remove_origin) unlinks an origin, and
32//! [`linked_dids`](DomainLinkageConfiguration::linked_dids) is a public `Vec` for anything
33//! else, `retain` included. A configuration left without entries does not read back
34//! ([`check`](DomainLinkageConfiguration::check)): an origin that links no DID publishes no
35//! configuration.
36//!
37//! # Examples
38//!
39//! Verifying a domain: the specification's example resource, served for
40//! `https://identity.foundation`, links one `did:key`, and another origin publishes nothing.
41//!
42//! ```
43//! # #[cfg(feature = "did-key")]
44//! # {
45//! use chrono::{TimeZone as _, Utc};
46//! use identity_kit::did::Did;
47//! use identity_kit::domain_linkage::{DomainLinkageClient, DomainLinkageValidator};
48//! use identity_kit::jose::DefaultVerifier;
49//! use identity_kit::methods::DidKey;
50//! use identity_kit::methods::web::{HttpClient, HttpError, HttpResponse};
51//! use identity_kit::resolver::Resolver;
52//! use identity_kit::vc::validation::{CredentialValidationOptions, TimeOptions};
53//! use url::Url;
54//!
55//! /// Serves the example resource of `identity.foundation` and nothing else.
56//! struct Static;
57//!
58//! #[async_trait::async_trait]
59//! impl HttpClient for Static {
60//!     async fn get(&self, url: &Url) -> Result<HttpResponse, HttpError> {
61//!         Ok(match url.as_str() {
62//!             "https://identity.foundation/.well-known/did-configuration.json" => {
63//!                 # let resource = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/vectors/did_configuration/resource.json"));
64//!                 HttpResponse::new(200, resource)
65//!             }
66//!             _ => HttpResponse::new(404, Vec::new()),
67//!         })
68//!     }
69//! }
70//!
71//! # tokio::runtime::Builder::new_current_thread().build()?.block_on(async {
72//! let resolver = Resolver::builder().with(DidKey::default()).build();
73//! let client = DomainLinkageClient::new(Static, DomainLinkageValidator::new(resolver, DefaultVerifier));
74//! // The example credential is valid from 2020-12-04 to 2025-12-04.
75//! let options = CredentialValidationOptions::new()
76//!     .with_time(TimeOptions::at(Utc.with_ymd_and_hms(2021, 1, 1, 0, 0, 0).unwrap()));
77//!
78//! let report = client
79//!     .validate_origin(&Url::parse("https://identity.foundation")?, &options)
80//!     .await?;
81//! assert_eq!(
82//!     report.dids().map(Did::as_str).collect::<Vec<_>>(),
83//!     ["did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM"]
84//! );
85//!
86//! let error = client
87//!     .validate_origin(&Url::parse("https://example.com")?, &options)
88//!     .await
89//!     .unwrap_err();
90//! assert!(error.is_not_published());
91//! # Ok::<(), Box<dyn std::error::Error>>(())
92//! # })?;
93//! # }
94//! # Ok::<(), Box<dyn std::error::Error>>(())
95//! ```
96
97use core::fmt;
98use std::collections::BTreeMap;
99use std::error::Error;
100
101use chrono::{DateTime, Utc};
102use serde::{Deserialize, Deserializer, Serialize};
103use serde_json::Value;
104use url::Url;
105
106use crate::cause::cause;
107use crate::did::{Did, DidDocument, DidUrl, ResolutionError, Service, ServiceEndpoint, Uri};
108use crate::jose::{DefaultVerifier, JwsHeader, JwsVerifier, Signer};
109use crate::methods::web::{HttpClient, HttpError};
110use crate::resolver::Resolver;
111use crate::vc::validation::{
112    CredentialValidationOptions, DecodedCredential, JwtCredentialValidator, KeyReferenceError,
113    KeyResolver, ValidationError, decode_credential,
114};
115use crate::vc::{Credential, CredentialError, Jwt, JwtClaims, Subject};
116
117/// The context of the DID configuration resource and of domain linkage credentials.
118pub const CONTEXT: &str = "https://identity.foundation/.well-known/did-configuration/v1";
119
120/// The credential type, `DomainLinkageCredential`.
121pub const CREDENTIAL_TYPE: &str = "DomainLinkageCredential";
122
123/// The path of the resource under an origin.
124pub const WELL_KNOWN_PATH: &str = "/.well-known/did-configuration.json";
125
126/// The type of the DID document service listing the origins of a DID, `LinkedDomains`.
127pub const SERVICE_TYPE: &str = "LinkedDomains";
128
129/// The member of a map `serviceEndpoint` holding the origins of a `LinkedDomains` service.
130const ORIGINS: &str = "origins";
131
132/// The URL of the DID configuration resource of `origin`.
133///
134/// # Errors
135///
136/// [`DomainLinkageError::InvalidOrigin`] when `origin` has no host.
137///
138/// # Examples
139///
140/// ```
141/// use identity_kit::domain_linkage::configuration_url;
142/// use url::Url;
143///
144/// let url = configuration_url(&Url::parse("https://identity.foundation")?)?;
145/// assert_eq!(url.as_str(), "https://identity.foundation/.well-known/did-configuration.json");
146/// # Ok::<(), Box<dyn std::error::Error>>(())
147/// ```
148pub fn configuration_url(origin: &Url) -> Result<Url, DomainLinkageError> {
149    let origin = normalize_origin(origin.as_str())?;
150    Url::parse(&format!("{origin}{WELL_KNOWN_PATH}")).map_err(|e| {
151        invalid_origin(
152            &origin,
153            "its well-known URL does not parse",
154            Some(Box::new(e)),
155        )
156    })
157}
158
159/// `origin` as `scheme://host[:port]`, lowercased, with `https` assumed when no scheme is
160/// given and a path, query or fragment dropped.
161///
162/// # Errors
163///
164/// [`DomainLinkageError::InvalidOrigin`] when `origin` has no host, or one that is not an
165/// RFC 3986 host.
166pub fn normalize_origin(origin: &str) -> Result<String, DomainLinkageError> {
167    let with_scheme = if has_scheme(origin) {
168        origin.to_owned()
169    } else {
170        format!("https://{origin}")
171    };
172    let url = Url::parse(&with_scheme)
173        .map_err(|e| invalid_origin(origin, "not a URL", Some(Box::new(e))))?;
174    if url.host_str().is_none() {
175        return Err(invalid_origin(origin, "no host", None));
176    }
177    let normalized = url.origin();
178    if !normalized.is_tuple() {
179        return Err(invalid_origin(origin, "not a domain origin", None));
180    }
181    let normalized = normalized.ascii_serialization();
182    // The WHATWG URL parser accepts host characters RFC 3986 does not, such as `` ` ``.
183    Uri::parse(&normalized)
184        .map_err(|e| invalid_origin(origin, "not an RFC 3986 URI", Some(Box::new(e))))?;
185    Ok(normalized)
186}
187
188/// A [`DomainLinkageError::InvalidOrigin`] for `origin`.
189fn invalid_origin(
190    origin: &str,
191    reason: &str,
192    source: Option<Box<dyn Error + Send + Sync>>,
193) -> DomainLinkageError {
194    DomainLinkageError::InvalidOrigin {
195        origin: origin.to_owned(),
196        reason: reason.to_owned(),
197        source,
198    }
199}
200
201/// Whether `s` starts with a URI scheme (RFC 3986 §3.1) rather than a `host:port`.
202fn has_scheme(s: &str) -> bool {
203    let Some((scheme, rest)) = s.split_once(':') else {
204        return false;
205    };
206    let mut chars = scheme.chars();
207    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
208        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
209        && !rest.starts_with(|c: char| c.is_ascii_digit())
210}
211
212/// A `LinkedDomains` service of `id` listing `origins`, normalized: the origin string when
213/// there is one, `{"origins": [...]}` otherwise, the two forms the specification defines.
214///
215/// # Errors
216///
217/// [`DomainLinkageError::InvalidService`] when `origins` is empty or an origin has no host.
218///
219/// # Examples
220///
221/// ```
222/// use identity_kit::did::{DidUrl, ServiceEndpoint};
223/// use identity_kit::domain_linkage::{SERVICE_TYPE, service};
224/// use url::Url;
225///
226/// let service = service(
227///     DidUrl::parse("did:example:123#foo")?,
228///     [Url::parse("https://foo.example.com")?, Url::parse("https://identity.foundation")?],
229/// )?;
230/// assert!(service.has_type(SERVICE_TYPE));
231/// assert_eq!(
232///     serde_json::to_value(&service.service_endpoint)?,
233///     serde_json::json!({ "origins": ["https://foo.example.com", "https://identity.foundation"] })
234/// );
235/// # Ok::<(), Box<dyn std::error::Error>>(())
236/// ```
237pub fn service(
238    id: DidUrl,
239    origins: impl IntoIterator<Item = Url>,
240) -> Result<Service, DomainLinkageError> {
241    let invalid = |reason: String, source: Option<Box<dyn Error + Send + Sync>>| {
242        DomainLinkageError::InvalidService {
243            id: id.clone(),
244            reason,
245            source,
246        }
247    };
248    let origins = origins
249        .into_iter()
250        .map(|origin| {
251            normalize_origin(origin.as_str())
252                .map_err(|e| invalid(format!("origin `{origin}` is invalid"), Some(Box::new(e))))
253        })
254        .collect::<Result<Vec<_>, _>>()?;
255    let endpoint = match origins.as_slice() {
256        [] => return Err(invalid("no origin".to_owned(), None)),
257        [origin] => ServiceEndpoint::Uri(
258            Uri::parse(origin)
259                .map_err(|e| invalid(format!("`{origin}` is not a URI"), Some(Box::new(e))))?,
260        ),
261        _ => ServiceEndpoint::Map([(ORIGINS.to_owned(), Value::from(origins))].into()),
262    };
263    Ok(Service::new(id, SERVICE_TYPE, endpoint))
264}
265
266/// A `LinkedDomains` service of a DID document, with its origins.
267#[derive(Debug, Clone, PartialEq, Eq)]
268#[non_exhaustive]
269pub struct LinkedDomainsService<'a> {
270    /// The service entry.
271    pub service: &'a Service,
272    /// Its origins, normalized, in document order.
273    pub origins: Vec<Url>,
274}
275
276impl LinkedDomainsService<'_> {
277    /// The id of the service.
278    pub fn id(&self) -> &DidUrl {
279        &self.service.id
280    }
281}
282
283/// The `LinkedDomains` services of `document`, in document order, with their origins
284/// normalized as by [`normalize_origin`].
285///
286/// `serviceEndpoint` is an origin string or an object whose `origins` member is a non-empty
287/// array of origin strings, the two forms the specification defines, or an array of origins,
288/// the set form DID Core allows for any service. A service of that type whose endpoint is
289/// none of these, or holds something that is not an origin, is a
290/// [`DomainLinkageError::InvalidService`] rather than silently skipped.
291///
292/// # Examples
293///
294/// ```
295/// use identity_kit::did::DidDocument;
296/// use identity_kit::domain_linkage::services;
297/// use serde_json::json;
298///
299/// let document: DidDocument = serde_json::from_value(json!({
300///   "id": "did:example:123",
301///   "service": [
302///     {
303///       "id": "did:example:123#foo",
304///       "type": "LinkedDomains",
305///       "serviceEndpoint": { "origins": ["https://foo.example.com", "https://identity.foundation"] }
306///     },
307///     { "id": "did:example:123#bar", "type": "LinkedDomains", "serviceEndpoint": "https://bar.example.com" }
308///   ]
309/// }))?;
310/// let origins: Vec<String> = services(&document)
311///     .map(|service| service.map(|service| service.origins))
312///     .collect::<Result<Vec<_>, _>>()?
313///     .into_iter()
314///     .flatten()
315///     .map(|origin| origin.origin().ascii_serialization())
316///     .collect();
317/// assert_eq!(origins, ["https://foo.example.com", "https://identity.foundation", "https://bar.example.com"]);
318/// # Ok::<(), Box<dyn std::error::Error>>(())
319/// ```
320pub fn services(
321    document: &DidDocument,
322) -> impl Iterator<Item = Result<LinkedDomainsService<'_>, DomainLinkageError>> {
323    document
324        .service
325        .iter()
326        .filter(|service| service.has_type(SERVICE_TYPE))
327        .map(linked_domains_service)
328}
329
330/// `service` with its origins read and normalized.
331fn linked_domains_service(
332    service: &Service,
333) -> Result<LinkedDomainsService<'_>, DomainLinkageError> {
334    let invalid = |reason: String, source: Option<Box<dyn Error + Send + Sync>>| {
335        DomainLinkageError::InvalidService {
336            id: service.id.clone(),
337            reason,
338            source,
339        }
340    };
341    let origins: Vec<&str> = match &service.service_endpoint {
342        ServiceEndpoint::Map(map) => {
343            let Some(Value::Array(origins)) = map.get(ORIGINS) else {
344                return Err(invalid(
345                    format!("`serviceEndpoint` is a map without an `{ORIGINS}` array"),
346                    None,
347                ));
348            };
349            origins
350                .iter()
351                .map(|origin| {
352                    origin
353                        .as_str()
354                        .ok_or_else(|| invalid(format!("origin {origin} is not a string"), None))
355                })
356                .collect::<Result<_, _>>()?
357        }
358        endpoint => endpoint.uris().map(Uri::as_str).collect(),
359    };
360    if origins.is_empty() {
361        return Err(invalid("no origin".to_owned(), None));
362    }
363    let origins = origins
364        .into_iter()
365        .map(|origin| {
366            let normalized = normalize_origin(origin)
367                .map_err(|e| invalid(format!("origin {origin:?} is invalid"), Some(Box::new(e))))?;
368            Url::parse(&normalized)
369                .map_err(|e| invalid(format!("origin {origin:?} is not a URL"), Some(Box::new(e))))
370        })
371        .collect::<Result<_, _>>()?;
372    Ok(LinkedDomainsService { service, origins })
373}
374
375/// One entry of `linked_dids`.
376#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
377#[serde(untagged)]
378#[non_exhaustive]
379pub enum LinkedDid {
380    /// A domain linkage credential in the JSON Web Token proof format.
381    Jwt(Jwt),
382    /// A domain linkage credential in the Linked Data Proof format, carried as data. An entry
383    /// that is neither a compact JWT nor an object is a parse error, not a silently skipped
384    /// credential.
385    LinkedDataProof(serde_json::Map<String, Value>),
386}
387
388/// The DID configuration resource: `@context` and the domain linkage credentials.
389///
390/// Deserializing [checks](Self::check) it: a resource of another `@context`, or with an
391/// empty `linked_dids`, does not read.
392///
393/// # Examples
394///
395/// ```
396/// use identity_kit::domain_linkage::{DomainLinkageConfiguration, LinkedDid};
397/// use serde_json::json;
398///
399/// let configuration: DomainLinkageConfiguration = serde_json::from_value(json!({
400///   "@context": "https://identity.foundation/.well-known/did-configuration/v1",
401///   "linked_dids": [
402///     "eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg"
403///   ]
404/// }))?;
405/// assert_eq!(configuration.jwts().count(), 1);
406/// assert!(serde_json::from_value::<DomainLinkageConfiguration>(json!({
407///   "@context": "https://example.com/other", "linked_dids": []
408/// })).is_err());
409/// assert!(serde_json::from_value::<DomainLinkageConfiguration>(json!({
410///   "@context": "https://identity.foundation/.well-known/did-configuration/v1",
411///   "linked_dids": []
412/// })).is_err());
413/// # Ok::<(), serde_json::Error>(())
414/// ```
415#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
416#[non_exhaustive]
417pub struct DomainLinkageConfiguration {
418    /// `@context`, [`CONTEXT`].
419    #[serde(rename = "@context")]
420    pub context: String,
421    /// The domain linkage credentials, one per linked DID.
422    pub linked_dids: Vec<LinkedDid>,
423}
424
425impl Default for DomainLinkageConfiguration {
426    fn default() -> Self {
427        Self::new()
428    }
429}
430
431impl DomainLinkageConfiguration {
432    /// An empty configuration, to add credentials to. It does not pass
433    /// [`check`](Self::check) until it holds one.
434    pub fn new() -> Self {
435        Self {
436            context: CONTEXT.to_owned(),
437            linked_dids: Vec::new(),
438        }
439    }
440
441    /// This configuration with `credential` added.
442    #[must_use]
443    pub fn with_credential(mut self, credential: Jwt) -> Self {
444        self.linked_dids.push(LinkedDid::Jwt(credential));
445        self
446    }
447
448    /// The credentials in the JSON Web Token proof format, with their positions.
449    pub fn jwts(&self) -> impl Iterator<Item = (usize, &Jwt)> {
450        self.linked_dids
451            .iter()
452            .enumerate()
453            .filter_map(|(i, entry)| match entry {
454                LinkedDid::Jwt(jwt) => Some((i, jwt)),
455                _ => None,
456            })
457    }
458
459    /// The credentials in the JSON Web Token proof format, with their positions, each read
460    /// **without verifying it** ([`UnverifiedLinkage::from_jwt`]), or why it does not read.
461    /// Linked Data Proof entries are not among them.
462    ///
463    /// For the controller of the origin, maintaining the configuration it publishes; a
464    /// verifier validates with [`DomainLinkageValidator`].
465    pub fn entries(
466        &self,
467    ) -> impl Iterator<Item = (usize, Result<UnverifiedLinkage, DomainLinkageError>)> + '_ {
468        self.jwts()
469            .map(|(index, jwt)| (index, UnverifiedLinkage::from_jwt(jwt)))
470    }
471
472    /// The earliest expiry among the JWT credentials that read ([`entries`](Self::entries)),
473    /// or `None` when none reads or none expires: when the configuration needs renewing at
474    /// the latest.
475    pub fn earliest_expiry(&self) -> Option<DateTime<Utc>> {
476        self.entries()
477            .filter_map(|(_, entry)| entry.ok()?.expires)
478            .min()
479    }
480
481    /// Removes the JWT credentials linking `origin`, compared normalized
482    /// ([`normalize_origin`]), and returns how many it removed. Credentials that do not
483    /// read ([`entries`](Self::entries)) and Linked Data Proof entries are kept; remove them
484    /// from [`linked_dids`](Self::linked_dids) directly.
485    ///
486    /// # Errors
487    ///
488    /// [`DomainLinkageError::InvalidOrigin`] when `origin` has no host.
489    pub fn remove_origin(&mut self, origin: &Url) -> Result<usize, DomainLinkageError> {
490        let origin = normalize_origin(origin.as_str())?;
491        let before = self.linked_dids.len();
492        self.linked_dids.retain(|entry| match entry {
493            LinkedDid::Jwt(jwt) => {
494                UnverifiedLinkage::from_jwt(jwt).map_or(true, |linkage| linkage.origin != origin)
495            }
496            LinkedDid::LinkedDataProof(_) => true,
497        });
498        Ok(before - self.linked_dids.len())
499    }
500
501    /// Checks that `@context` is [`CONTEXT`] and that [`linked_dids`](Self::linked_dids) holds
502    /// at least one entry. Deserializing and the validators apply it, so a resource without
503    /// entries is malformed rather than an origin that links no DID.
504    ///
505    /// # Errors
506    ///
507    /// [`DomainLinkageError::InvalidContext`] or [`DomainLinkageError::NoEntries`].
508    pub fn check(&self) -> Result<(), DomainLinkageError> {
509        if self.context != CONTEXT {
510            return Err(DomainLinkageError::InvalidContext(self.context.clone()));
511        }
512        if self.linked_dids.is_empty() {
513            return Err(DomainLinkageError::NoEntries);
514        }
515        Ok(())
516    }
517}
518
519impl<'de> Deserialize<'de> for DomainLinkageConfiguration {
520    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
521        #[derive(Deserialize)]
522        #[serde(deny_unknown_fields)]
523        struct Raw {
524            #[serde(rename = "@context")]
525            context: String,
526            linked_dids: Vec<LinkedDid>,
527        }
528        let raw = Raw::deserialize(deserializer)?;
529        let configuration = Self {
530            context: raw.context,
531            linked_dids: raw.linked_dids,
532        };
533        configuration.check().map_err(serde::de::Error::custom)?;
534        Ok(configuration)
535    }
536}
537
538/// A domain linkage credential in the JSON Web Token proof format as its JWT says, read
539/// **without verifying it**: neither the signature nor the format rules
540/// [`DomainLinkageValidator`] enforces are checked, only what these fields need.
541///
542/// For the controller of an origin reading back credentials it signed itself, to renew them
543/// before they expire or to drop an origin's; never for deciding whether a DID and an origin
544/// are linked.
545///
546/// # Examples
547///
548/// ```
549/// use chrono::{TimeZone as _, Utc};
550/// use identity_kit::domain_linkage::UnverifiedLinkage;
551/// use identity_kit::vc::Jwt;
552///
553/// // The example JWT of the specification, whose `origin` has no scheme.
554/// # let jwt: Jwt = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/vectors/did_configuration/jwt.txt")).trim().parse()?;
555/// let linkage = UnverifiedLinkage::from_jwt(&jwt)?;
556/// assert_eq!(linkage.did.as_str(), "did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM");
557/// assert_eq!(linkage.origin, "https://identity.foundation");
558/// assert_eq!(linkage.expires, Some(Utc.with_ymd_and_hms(2025, 12, 4, 20, 12, 19).unwrap()));
559/// # Ok::<(), Box<dyn std::error::Error>>(())
560/// ```
561#[derive(Debug, Clone, PartialEq, Eq)]
562#[non_exhaustive]
563pub struct UnverifiedLinkage {
564    /// The DID the credential links: its `credentialSubject.id`.
565    pub did: Did,
566    /// The origin it links: its `credentialSubject.origin`, normalized
567    /// ([`normalize_origin`]).
568    pub origin: String,
569    /// The issuer it names, which the format requires to be [`did`](Self::did).
570    pub issuer: Uri,
571    /// When it becomes valid: `nbf`, or `issuanceDate` without one.
572    pub not_before: DateTime<Utc>,
573    /// When it expires: `exp`, or `expirationDate` without one, when either is present.
574    pub expires: Option<DateTime<Utc>>,
575}
576
577impl UnverifiedLinkage {
578    /// Reads `jwt` without verifying it.
579    ///
580    /// # Errors
581    ///
582    /// [`DomainLinkageError::Validation`] when `jwt` does not decode as a credential JWT,
583    /// [`DomainLinkageError::SubjectNotDid`] when its one subject is not a DID, and
584    /// [`DomainLinkageError::InvalidOriginProperty`] or [`DomainLinkageError::InvalidOrigin`]
585    /// when its `origin` is not one origin.
586    pub fn from_jwt(jwt: &Jwt) -> Result<Self, DomainLinkageError> {
587        let credential = decode_credential(jwt)?.credential;
588        let subject = credential
589            .subject()
590            .ok_or(DomainLinkageError::SubjectNotDid(None))?;
591        Ok(Self {
592            did: subject_did(subject)?,
593            origin: subject_origin(subject)?,
594            issuer: credential.issuer.id().clone(),
595            not_before: credential.issuance_date,
596            expires: credential.expiration_date,
597        })
598    }
599}
600
601/// Builds a domain linkage credential in the JSON Web Token proof format: a VCDM 1.1
602/// credential of type `DomainLinkageCredential` issued by `did` about `did` and `origin`,
603/// carried in the `vc` claim with `iss`, `sub`, `nbf` and `exp` and nothing else.
604///
605/// # Examples
606///
607/// ```
608/// use chrono::{TimeZone as _, Utc};
609/// use identity_kit::did::Did;
610/// use identity_kit::domain_linkage::DomainLinkageCredentialBuilder;
611/// use url::Url;
612///
613/// let did = Did::parse("did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM")?;
614/// let builder = DomainLinkageCredentialBuilder::new(
615///     did.clone(),
616///     &Url::parse("https://identity.foundation")?,
617///     Utc.with_ymd_and_hms(2020, 12, 4, 20, 12, 19).unwrap(),
618///     Utc.with_ymd_and_hms(2025, 12, 4, 20, 12, 19).unwrap(),
619/// )?;
620/// let claims = builder.jwt_claims();
621/// assert_eq!(claims.iss.as_deref(), Some(did.as_str()));
622/// assert_eq!(claims.sub, claims.iss);
623/// assert_eq!(claims.nbf, Some(1607112739));
624/// assert_eq!(claims.exp, Some(1764879139));
625/// assert_eq!(claims.additional["vc"]["credentialSubject"]["origin"], "https://identity.foundation");
626/// # Ok::<(), Box<dyn std::error::Error>>(())
627/// ```
628#[derive(Debug, Clone, PartialEq, Eq)]
629#[non_exhaustive]
630pub struct DomainLinkageCredentialBuilder {
631    /// The DID: issuer and subject of the credential.
632    pub did: Did,
633    /// The origin, normalized.
634    pub origin: String,
635    /// `issuanceDate` and `nbf`.
636    pub issuance_date: DateTime<Utc>,
637    /// `expirationDate` and `exp`.
638    pub expiration_date: DateTime<Utc>,
639}
640
641impl DomainLinkageCredentialBuilder {
642    /// A credential linking `did` and `origin`, valid from `issuance_date` to
643    /// `expiration_date`.
644    ///
645    /// # Errors
646    ///
647    /// [`DomainLinkageError::InvalidOrigin`] when `origin` has no host.
648    pub fn new(
649        did: Did,
650        origin: &Url,
651        issuance_date: DateTime<Utc>,
652        expiration_date: DateTime<Utc>,
653    ) -> Result<Self, DomainLinkageError> {
654        Ok(Self {
655            did,
656            origin: normalize_origin(origin.as_str())?,
657            issuance_date,
658            expiration_date,
659        })
660    }
661
662    /// The credential.
663    pub fn credential(&self) -> Credential {
664        let subject =
665            Subject::new(Uri::from(self.did.clone())).with_property("origin", self.origin.clone());
666        Credential::new(self.did.clone(), self.issuance_date, subject)
667            .with_context(CONTEXT)
668            .with_type(CREDENTIAL_TYPE)
669            .with_expiration_date(self.expiration_date)
670    }
671
672    /// The JWT claims: `iss` and `sub` the DID, `nbf` and `exp` the validity period, `vc` the
673    /// whole credential.
674    ///
675    /// # Panics
676    ///
677    /// Never: the credential this builder makes always serializes to JSON.
678    pub fn jwt_claims(&self) -> JwtClaims {
679        let mut claims = JwtClaims::new()
680            .with_nbf(self.issuance_date)
681            .with_exp(self.expiration_date);
682        claims.iss = Some(self.did.as_str().to_owned());
683        claims.sub = Some(self.did.as_str().to_owned());
684        claims.additional.insert(
685            "vc".to_owned(),
686            serde_json::to_value(self.credential()).expect("a credential serializes"),
687        );
688        claims
689    }
690
691    /// The credential signed with `signer` under a header of `alg` and `kid` only, `kid`
692    /// naming the verification method of the DID.
693    ///
694    /// # Errors
695    ///
696    /// [`DomainLinkageError::Validation`] with [`ValidationError::Jws`] when signing fails.
697    pub async fn sign(&self, kid: &DidUrl, signer: &dyn Signer) -> Result<Jwt, DomainLinkageError> {
698        let header = JwsHeader::new(signer.alg()).with_kid(kid.as_str());
699        let jwt = Jwt::sign(&header, &self.jwt_claims(), signer)
700            .await
701            .map_err(ValidationError::from)?;
702        Ok(jwt)
703    }
704}
705
706/// Why a domain linkage credential or configuration did not validate.
707#[derive(Debug, thiserror::Error)]
708#[non_exhaustive]
709pub enum DomainLinkageError {
710    /// An origin is not `scheme://host[:port]`. The source is the URL or URI error, when
711    /// there is one.
712    #[error("invalid origin {origin:?}: {reason}{}", cause(.source.as_ref()))]
713    InvalidOrigin {
714        /// The origin, as given.
715        origin: String,
716        /// What is wrong with it.
717        reason: String,
718        /// The underlying error.
719        source: Option<Box<dyn Error + Send + Sync>>,
720    },
721    /// The configuration's `@context` is not [`CONTEXT`].
722    #[error("`@context` is {0:?}, not `{CONTEXT}`")]
723    InvalidContext(String),
724    /// The configuration's `linked_dids` is empty.
725    #[error("`linked_dids` is empty")]
726    NoEntries,
727    /// The JWT header has a `typ`, which the format forbids.
728    #[error("header `typ` {0:?} must not be present")]
729    TypPresent(String),
730    /// The JWT header has a parameter other than `alg` and `kid`.
731    #[error("header parameter `{0}` must not be present")]
732    UnexpectedHeaderParameter(String),
733    /// The JWT payload has a claim other than `iss`, `sub`, `nbf`, `exp` and `vc`.
734    #[error("claim `{0}` must not be present")]
735    UnexpectedClaim(String),
736    /// A required claim is missing: `iss`, `sub`, `exp` or `nbf`.
737    #[error("claim `{0}` is required")]
738    MissingClaim(&'static str),
739    /// The credential has an `id`, which the format forbids.
740    #[error("the credential must not have an `id`")]
741    IdPresent,
742    /// The credential's context does not include [`CONTEXT`].
743    #[error("the credential's `@context` does not include `{CONTEXT}`")]
744    MissingContext,
745    /// The credential's type does not include [`CREDENTIAL_TYPE`].
746    #[error("the credential's `type` does not include `{CREDENTIAL_TYPE}`")]
747    MissingType,
748    /// The credential has no `expirationDate`.
749    #[error("the credential must have an `expirationDate`")]
750    MissingExpirationDate,
751    /// `credentialSubject.id` is missing or not a DID.
752    #[error("`credentialSubject.id` {0:?} is not a DID")]
753    SubjectNotDid(Option<String>),
754    /// The issuer, `iss` or `sub` differs from `credentialSubject.id`.
755    #[error("{role} `{found}` is not the subject `{subject}`")]
756    SubjectMismatch {
757        /// `issuer`, `iss` or `sub`.
758        role: &'static str,
759        /// The value found.
760        found: String,
761        /// `credentialSubject.id`.
762        subject: Did,
763    },
764    /// `credentialSubject.origin` is missing or not one string.
765    #[error("`credentialSubject.origin` {0:?} is not one origin")]
766    InvalidOriginProperty(Option<Value>),
767    /// `credentialSubject.origin` is not the origin the resource was fetched from.
768    #[error("origin {found:?} is not {expected:?}")]
769    OriginMismatch {
770        /// The normalized origin expected.
771        expected: String,
772        /// The credential's origin, normalized.
773        found: String,
774    },
775    /// The credential did not decode or validate as a credential JWT.
776    #[error(transparent)]
777    Validation(#[from] ValidationError),
778    /// The configuration holds no JWT credential for the DID.
779    #[error("the configuration holds no JWT credential for `{0}`")]
780    NoCredentialFor(Did),
781    /// No credential of the configuration validated; the error of each JWT entry by its
782    /// position.
783    #[error("no domain linkage credential validated: {}", format_errors(.0))]
784    NoValidCredential(BTreeMap<usize, DomainLinkageError>),
785    /// A `LinkedDomains` service does not list one or more origins. The source is the
786    /// [`InvalidOrigin`](Self::InvalidOrigin) error of an origin, or the URI or URL error, when
787    /// there is one.
788    #[error("service `{id}`: {reason}{}", cause(.source.as_ref()))]
789    InvalidService {
790        /// The id of the service.
791        id: DidUrl,
792        /// What is wrong with it.
793        reason: String,
794        /// The underlying error.
795        source: Option<Box<dyn Error + Send + Sync>>,
796    },
797    /// The origin is not `https`, the only scheme the resource is fetched over.
798    #[error("`{0}` is not an HTTPS origin")]
799    InsecureOrigin(String),
800    /// The [`HttpClient`] got no response.
801    #[error("fetching `{url}` failed: {source}")]
802    Http {
803        /// The URL of the resource.
804        url: Url,
805        /// Why there was no response.
806        #[source]
807        source: HttpError,
808    },
809    /// The origin publishes no DID configuration: the server answered `404` or `410`. A
810    /// legitimate state of an origin rather than a failure; see
811    /// [`is_not_published`](Self::is_not_published).
812    #[error("`{url}` publishes no DID configuration (HTTP {status})")]
813    NotPublished {
814        /// The URL of the resource.
815        url: Url,
816        /// `404` or `410`.
817        status: u16,
818    },
819    /// The server answered with a status other than `2xx`, `404` and `410`.
820    #[error("fetching `{url}` returned HTTP {status}")]
821    HttpStatus {
822        /// The URL of the resource.
823        url: Url,
824        /// The status code.
825        status: u16,
826    },
827    /// The body is not a DID configuration resource: not JSON, not of its shape, or of
828    /// another `@context`.
829    #[error("`{url}` is not a DID configuration resource: {source}")]
830    InvalidConfiguration {
831        /// The URL of the resource.
832        url: Url,
833        /// Why the body did not deserialize.
834        #[source]
835        source: serde_json::Error,
836    },
837    /// The DID did not resolve.
838    #[error("resolving the DID failed: {0}")]
839    Resolution(#[from] ResolutionError),
840    /// The origin was not fetched: the DID document lists more origins than the client's
841    /// limit, given here.
842    #[error("the DID document lists more than {0} origins")]
843    TooManyOrigins(usize),
844    /// The entry was not validated: the configuration holds more JWT entries, or more naming
845    /// the DID, than the validator's limit, given here.
846    #[error("the configuration holds more than {0} credentials to validate")]
847    TooManyCredentials(usize),
848}
849
850impl DomainLinkageError {
851    /// Whether the origin publishes no DID configuration ([`NotPublished`](Self::NotPublished)),
852    /// as opposed to a configuration that could not be fetched, read or validated.
853    pub fn is_not_published(&self) -> bool {
854        matches!(self, Self::NotPublished { .. })
855    }
856}
857
858impl From<CredentialError> for DomainLinkageError {
859    fn from(error: CredentialError) -> Self {
860        Self::Validation(error.into())
861    }
862}
863
864/// `errors` as `index: error; …`.
865fn format_errors(errors: &BTreeMap<usize, DomainLinkageError>) -> String {
866    errors
867        .iter()
868        .map(|(index, error)| format!("{index}: {error}"))
869        .collect::<Vec<_>>()
870        .join("; ")
871}
872
873/// A validated DID configuration resource: which entries linked which DIDs, and which failed.
874#[derive(Debug)]
875#[non_exhaustive]
876pub struct DomainLinkageReport {
877    /// The entries that validated, by position, with the DID each links.
878    pub linked: Vec<(usize, Did, DecodedCredential)>,
879    /// The JWT entries that failed, by position.
880    pub failed: BTreeMap<usize, DomainLinkageError>,
881}
882
883impl DomainLinkageReport {
884    /// The DIDs linked to the origin, in the order of the resource.
885    pub fn dids(&self) -> impl Iterator<Item = &Did> {
886        self.linked.iter().map(|(_, did, _)| did)
887    }
888}
889
890/// Validates domain linkage credentials and DID configuration resources (DID Configuration
891/// Resource Verification): the subject is a DID equal to the issuer, `iss` and `sub`, the
892/// one `origin` is the requested origin, the credential has an expiration date, no `id`, no
893/// extra claims or header parameters, and its signature verifies under a key of the DID
894/// listed under `assertionMethod`.
895///
896/// A configuration is written by whoever controls the origin, and every entry validated
897/// resolves its issuer's DID, so [`validate_configuration`](Self::validate_configuration) and
898/// [`validate_linkage`](Self::validate_linkage) validate at most
899/// [`max_credentials`](Self::max_credentials) entries of one configuration.
900///
901/// # Examples
902///
903/// ```
904/// # #[cfg(feature = "did-key")]
905/// # {
906/// use identity_kit::domain_linkage::DomainLinkageValidator;
907/// use identity_kit::jose::DefaultVerifier;
908/// use identity_kit::methods::DidKey;
909/// use identity_kit::resolver::Resolver;
910///
911/// let resolver = Resolver::builder().with(DidKey::default()).build();
912/// let validator = DomainLinkageValidator::new(resolver, DefaultVerifier);
913/// assert!(!validator.credential_validator().has_status_check());
914/// # }
915/// ```
916#[derive(Debug)]
917pub struct DomainLinkageValidator<R, V = DefaultVerifier> {
918    credentials: JwtCredentialValidator<R, V>,
919    max_credentials: usize,
920}
921
922impl<R, V> DomainLinkageValidator<R, V> {
923    /// The most entries of one configuration [`new`](Self::new) validates: 32.
924    pub const DEFAULT_MAX_CREDENTIALS: usize = 32;
925}
926
927impl<R: KeyResolver, V: JwsVerifier> DomainLinkageValidator<R, V> {
928    /// A validator resolving keys with `resolver` and verifying signatures with `verifier`,
929    /// validating at most [`DEFAULT_MAX_CREDENTIALS`](Self::DEFAULT_MAX_CREDENTIALS) entries
930    /// of a configuration.
931    pub fn new(resolver: R, verifier: V) -> Self {
932        Self::from_credential_validator(JwtCredentialValidator::new(resolver, verifier))
933    }
934
935    /// A validator over `credentials`, validating at most
936    /// [`DEFAULT_MAX_CREDENTIALS`](Self::DEFAULT_MAX_CREDENTIALS) entries of a configuration.
937    pub fn from_credential_validator(credentials: JwtCredentialValidator<R, V>) -> Self {
938        Self {
939            credentials,
940            max_credentials: Self::DEFAULT_MAX_CREDENTIALS,
941        }
942    }
943
944    /// This validator validating at most `max_credentials` entries of a configuration.
945    #[must_use]
946    pub fn with_max_credentials(mut self, max_credentials: usize) -> Self {
947        self.max_credentials = max_credentials;
948        self
949    }
950
951    /// The most entries of one configuration [`validate_configuration`](Self::validate_configuration)
952    /// and [`validate_linkage`](Self::validate_linkage) validate.
953    pub fn max_credentials(&self) -> usize {
954        self.max_credentials
955    }
956
957    /// The credential validator.
958    pub fn credential_validator(&self) -> &JwtCredentialValidator<R, V> {
959        &self.credentials
960    }
961
962    /// Validates `jwt` as a domain linkage credential for `origin`.
963    ///
964    /// # Errors
965    ///
966    /// The first [`DomainLinkageError`] found: the format checks first, then the signature,
967    /// issuer binding and validity period of [`JwtCredentialValidator::validate`].
968    pub async fn validate_credential(
969        &self,
970        jwt: &Jwt,
971        origin: &Url,
972        options: &CredentialValidationOptions,
973    ) -> Result<DecodedCredential, DomainLinkageError> {
974        let expected = normalize_origin(origin.as_str())?;
975        let decoded = decode_credential(jwt)?;
976        check_format(&decoded, &expected)?;
977        self.credentials.validate(jwt, options).await?;
978        Ok(decoded)
979    }
980
981    /// Validates the credential of `configuration` linking `did` to `origin`: the first JWT
982    /// entry issued by `did` that validates. Entries naming `did` past the first
983    /// [`max_credentials`](Self::max_credentials) are not validated.
984    ///
985    /// # Errors
986    ///
987    /// [`DomainLinkageError::InvalidContext`] or [`DomainLinkageError::NoEntries`] when the
988    /// configuration does not [`check`](DomainLinkageConfiguration::check),
989    /// [`DomainLinkageError::NoCredentialFor`] when no JWT entry names `did` as issuer,
990    /// [`DomainLinkageError::NoValidCredential`] with the error of each such entry otherwise,
991    /// [`DomainLinkageError::TooManyCredentials`] for those past the limit.
992    pub async fn validate_linkage(
993        &self,
994        configuration: &DomainLinkageConfiguration,
995        did: &Did,
996        origin: &Url,
997        options: &CredentialValidationOptions,
998    ) -> Result<DecodedCredential, DomainLinkageError> {
999        configuration.check()?;
1000        let mut errors = BTreeMap::new();
1001        let mut validated = 0;
1002        for (index, jwt) in configuration.jwts() {
1003            if issuer_of(jwt).as_ref() != Some(did) {
1004                continue;
1005            }
1006            if validated == self.max_credentials {
1007                errors.insert(
1008                    index,
1009                    DomainLinkageError::TooManyCredentials(self.max_credentials),
1010                );
1011                continue;
1012            }
1013            validated += 1;
1014            match self.validate_credential(jwt, origin, options).await {
1015                Ok(decoded) => return Ok(decoded),
1016                Err(error) => {
1017                    errors.insert(index, error);
1018                }
1019            }
1020        }
1021        if errors.is_empty() {
1022            return Err(DomainLinkageError::NoCredentialFor(did.clone()));
1023        }
1024        Err(DomainLinkageError::NoValidCredential(errors))
1025    }
1026
1027    /// Validates every JWT entry of `configuration` for `origin`: succeeds when at least one
1028    /// does, reporting the rest as errors. Entries past the first
1029    /// [`max_credentials`](Self::max_credentials) are not validated and report
1030    /// [`DomainLinkageError::TooManyCredentials`].
1031    ///
1032    /// # Errors
1033    ///
1034    /// [`DomainLinkageError::InvalidContext`] or [`DomainLinkageError::NoEntries`] when the
1035    /// configuration does not [`check`](DomainLinkageConfiguration::check), or
1036    /// [`DomainLinkageError::NoValidCredential`] with the error of every JWT entry.
1037    ///
1038    /// # Panics
1039    ///
1040    /// Never: a credential that validates has a DID as its issuer.
1041    pub async fn validate_configuration(
1042        &self,
1043        configuration: &DomainLinkageConfiguration,
1044        origin: &Url,
1045        options: &CredentialValidationOptions,
1046    ) -> Result<DomainLinkageReport, DomainLinkageError> {
1047        configuration.check()?;
1048        let mut linked = Vec::new();
1049        let mut failed = BTreeMap::new();
1050        for (position, (index, jwt)) in configuration.jwts().enumerate() {
1051            if position >= self.max_credentials {
1052                failed.insert(
1053                    index,
1054                    DomainLinkageError::TooManyCredentials(self.max_credentials),
1055                );
1056                continue;
1057            }
1058            match self.validate_credential(jwt, origin, options).await {
1059                Ok(decoded) => {
1060                    let did = Did::parse(decoded.credential.issuer.id().as_str())
1061                        .expect("the format check accepted the issuer as a DID");
1062                    linked.push((index, did, decoded));
1063                }
1064                Err(error) => {
1065                    failed.insert(index, error);
1066                }
1067            }
1068        }
1069        if linked.is_empty() {
1070            return Err(DomainLinkageError::NoValidCredential(failed));
1071        }
1072        Ok(DomainLinkageReport { linked, failed })
1073    }
1074}
1075
1076/// Fetches the DID configuration resource of `origin` with `http`: a `GET` of
1077/// [`configuration_url`] over HTTPS, the body deserialized as a
1078/// [`DomainLinkageConfiguration`], so it is [checked](DomainLinkageConfiguration::check) and
1079/// Linked Data Proof entries are carried as data. Nothing is validated.
1080///
1081/// # Errors
1082///
1083/// - [`DomainLinkageError::InvalidOrigin`] when `origin` has no host, and
1084///   [`DomainLinkageError::InsecureOrigin`] when it is not `https`, both without fetching;
1085/// - [`DomainLinkageError::NotPublished`] on `404` or `410`: the origin publishes no
1086///   configuration;
1087/// - [`DomainLinkageError::Http`] when there is no response, and
1088///   [`DomainLinkageError::HttpStatus`] for any other status that is not `2xx`;
1089/// - [`DomainLinkageError::InvalidConfiguration`] when the body is not a configuration, one
1090///   without entries included.
1091pub async fn fetch_configuration<C: HttpClient + ?Sized>(
1092    http: &C,
1093    origin: &Url,
1094) -> Result<DomainLinkageConfiguration, DomainLinkageError> {
1095    let url = configuration_url(origin)?;
1096    if url.scheme() != "https" {
1097        return Err(DomainLinkageError::InsecureOrigin(
1098            url.origin().ascii_serialization(),
1099        ));
1100    }
1101    let response = match http.get(&url).await {
1102        Ok(response) => response,
1103        Err(source) => return Err(DomainLinkageError::Http { url, source }),
1104    };
1105    match response.status {
1106        200..=299 => {}
1107        status @ (404 | 410) => return Err(DomainLinkageError::NotPublished { url, status }),
1108        status => return Err(DomainLinkageError::HttpStatus { url, status }),
1109    }
1110    serde_json::from_slice(&response.body)
1111        .map_err(|source| DomainLinkageError::InvalidConfiguration { url, source })
1112}
1113
1114/// What became of one origin of a `LinkedDomains` service.
1115#[derive(Debug)]
1116#[non_exhaustive]
1117pub struct LinkedDomainReport {
1118    /// The id of the service.
1119    pub service: DidUrl,
1120    /// The origin, normalized; `None` when the service entry itself is invalid.
1121    pub origin: Option<Url>,
1122    /// The domain linkage credential of the DID at that origin, validated, or why there is
1123    /// none. [`DomainLinkageError::is_not_published`] tells an origin without a configuration
1124    /// apart.
1125    pub result: Result<DecodedCredential, DomainLinkageError>,
1126}
1127
1128/// Fetches DID configuration resources with an [`HttpClient`] and validates them with a
1129/// [`DomainLinkageValidator`]: for an origin, for one DID at an origin, or for every origin a
1130/// DID document lists.
1131///
1132/// Origins come from callers and from DID documents, so the client fetches whatever a DID
1133/// controller names, and validating a whole configuration resolves every DID it names:
1134/// `http`, and the `did:web` client of the resolver, must enforce the protections
1135/// `ReqwestClient` (feature `reqwest`) does (HTTPS only, no redirects, no non-public
1136/// addresses after name resolution, a body limit and a timeout), or fetching becomes a
1137/// request forgery primitive. A DID document can also list any number of origins, so
1138/// [`validate_document`](Self::validate_document) fetches at most
1139/// [`max_origins`](Self::max_origins) of them.
1140#[derive(Debug)]
1141pub struct DomainLinkageClient<C, R, V = DefaultVerifier> {
1142    http: C,
1143    validator: DomainLinkageValidator<R, V>,
1144    max_origins: usize,
1145}
1146
1147impl<C, R, V> DomainLinkageClient<C, R, V> {
1148    /// The most origins [`new`](Self::new) fetches for one DID document: 32.
1149    pub const DEFAULT_MAX_ORIGINS: usize = 32;
1150}
1151
1152impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> DomainLinkageClient<C, R, V> {
1153    /// A client fetching with `http` and validating with `validator`, fetching at most
1154    /// [`DEFAULT_MAX_ORIGINS`](Self::DEFAULT_MAX_ORIGINS) origins of a DID document.
1155    pub fn new(http: C, validator: DomainLinkageValidator<R, V>) -> Self {
1156        Self {
1157            http,
1158            validator,
1159            max_origins: Self::DEFAULT_MAX_ORIGINS,
1160        }
1161    }
1162
1163    /// This client fetching at most `max_origins` origins of a DID document.
1164    #[must_use]
1165    pub fn with_max_origins(mut self, max_origins: usize) -> Self {
1166        self.max_origins = max_origins;
1167        self
1168    }
1169
1170    /// The most origins [`validate_document`](Self::validate_document) fetches for one
1171    /// document.
1172    pub fn max_origins(&self) -> usize {
1173        self.max_origins
1174    }
1175
1176    /// The HTTP client.
1177    pub fn http(&self) -> &C {
1178        &self.http
1179    }
1180
1181    /// The validator.
1182    pub fn validator(&self) -> &DomainLinkageValidator<R, V> {
1183        &self.validator
1184    }
1185
1186    /// The DID configuration resource of `origin`, unvalidated.
1187    ///
1188    /// # Errors
1189    ///
1190    /// As [`fetch_configuration`].
1191    pub async fn fetch_configuration(
1192        &self,
1193        origin: &Url,
1194    ) -> Result<DomainLinkageConfiguration, DomainLinkageError> {
1195        fetch_configuration(&self.http, origin).await
1196    }
1197
1198    /// Fetches the configuration of `origin` and validates every JWT entry, as
1199    /// [`DomainLinkageValidator::validate_configuration`].
1200    ///
1201    /// # Errors
1202    ///
1203    /// As [`fetch_configuration`] and
1204    /// [`validate_configuration`](DomainLinkageValidator::validate_configuration).
1205    pub async fn validate_origin(
1206        &self,
1207        origin: &Url,
1208        options: &CredentialValidationOptions,
1209    ) -> Result<DomainLinkageReport, DomainLinkageError> {
1210        let configuration = self.fetch_configuration(origin).await?;
1211        self.validator
1212            .validate_configuration(&configuration, origin, options)
1213            .await
1214    }
1215
1216    /// Fetches the configuration of `origin` and validates the credential linking `did`, as
1217    /// [`DomainLinkageValidator::validate_linkage`]. Only `did` is resolved.
1218    ///
1219    /// # Errors
1220    ///
1221    /// As [`fetch_configuration`] and
1222    /// [`validate_linkage`](DomainLinkageValidator::validate_linkage).
1223    pub async fn validate_linkage(
1224        &self,
1225        did: &Did,
1226        origin: &Url,
1227        options: &CredentialValidationOptions,
1228    ) -> Result<DecodedCredential, DomainLinkageError> {
1229        let configuration = self.fetch_configuration(origin).await?;
1230        self.validator
1231            .validate_linkage(&configuration, did, origin, options)
1232            .await
1233    }
1234
1235    /// Validates the linkage of the DID of `document` to every origin of its `LinkedDomains`
1236    /// services: one report per origin in document order, and one for each invalid service
1237    /// entry. Origins past the first [`max_origins`](Self::max_origins) are not fetched and
1238    /// report [`DomainLinkageError::TooManyOrigins`].
1239    pub async fn validate_document(
1240        &self,
1241        document: &DidDocument,
1242        options: &CredentialValidationOptions,
1243    ) -> Vec<LinkedDomainReport> {
1244        let mut reports = Vec::new();
1245        let mut fetched = 0;
1246        for service in document
1247            .service
1248            .iter()
1249            .filter(|service| service.has_type(SERVICE_TYPE))
1250        {
1251            let linked = match linked_domains_service(service) {
1252                Ok(linked) => linked,
1253                Err(error) => {
1254                    reports.push(LinkedDomainReport {
1255                        service: service.id.clone(),
1256                        origin: None,
1257                        result: Err(error),
1258                    });
1259                    continue;
1260                }
1261            };
1262            for origin in linked.origins {
1263                let result = if fetched < self.max_origins {
1264                    fetched += 1;
1265                    self.validate_linkage(&document.id, &origin, options).await
1266                } else {
1267                    Err(DomainLinkageError::TooManyOrigins(self.max_origins))
1268                };
1269                reports.push(LinkedDomainReport {
1270                    service: service.id.clone(),
1271                    origin: Some(origin),
1272                    result,
1273                });
1274            }
1275        }
1276        reports
1277    }
1278}
1279
1280impl<C: HttpClient, V: JwsVerifier> DomainLinkageClient<C, Resolver, V> {
1281    /// Resolves `did` with the validator's resolver, then validates its linkage to every
1282    /// origin its document lists, as [`validate_document`](Self::validate_document).
1283    ///
1284    /// # Errors
1285    ///
1286    /// [`DomainLinkageError::Resolution`] when `did` does not resolve to a document.
1287    pub async fn validate_did(
1288        &self,
1289        did: &Did,
1290        options: &CredentialValidationOptions,
1291    ) -> Result<Vec<LinkedDomainReport>, DomainLinkageError> {
1292        let document = self
1293            .validator
1294            .credential_validator()
1295            .resolver()
1296            .resolve_document(did)
1297            .await?;
1298        Ok(self.validate_document(&document, options).await)
1299    }
1300}
1301
1302/// The issuer DID of `jwt`, read without verifying; `None` when it has none or it is not a
1303/// DID.
1304fn issuer_of(jwt: &Jwt) -> Option<Did> {
1305    crate::vc::validation::extract_issuer(jwt).ok()
1306}
1307
1308/// The checks of the JSON Web Token proof format and of DID Configuration Resource
1309/// Verification that need no key.
1310fn check_format(
1311    decoded: &DecodedCredential,
1312    expected_origin: &str,
1313) -> Result<(), DomainLinkageError> {
1314    let header = &decoded.header;
1315    if let Some(typ) = &header.typ {
1316        return Err(DomainLinkageError::TypPresent(typ.clone()));
1317    }
1318    if header.kid.is_none() {
1319        return Err(ValidationError::KeyReference(KeyReferenceError::Missing).into());
1320    }
1321    for (name, present) in [
1322        ("cty", header.cty.is_some()),
1323        ("jwk", header.jwk.is_some()),
1324        ("crit", header.crit.is_some()),
1325    ] {
1326        if present {
1327            return Err(DomainLinkageError::UnexpectedHeaderParameter(
1328                name.to_owned(),
1329            ));
1330        }
1331    }
1332    if let Some(name) = header.additional.keys().next() {
1333        return Err(DomainLinkageError::UnexpectedHeaderParameter(name.clone()));
1334    }
1335
1336    let claims = &decoded.claims;
1337    for (name, present) in [
1338        ("aud", claims.aud.is_some()),
1339        ("iat", claims.iat.is_some()),
1340        ("jti", claims.jti.is_some()),
1341    ] {
1342        if present {
1343            return Err(DomainLinkageError::UnexpectedClaim(name.to_owned()));
1344        }
1345    }
1346    if let Some(name) = claims.additional.keys().find(|name| *name != "vc") {
1347        return Err(DomainLinkageError::UnexpectedClaim(name.clone()));
1348    }
1349    let iss = claims
1350        .iss
1351        .as_deref()
1352        .ok_or(DomainLinkageError::MissingClaim("iss"))?;
1353    let sub = claims
1354        .sub
1355        .as_deref()
1356        .ok_or(DomainLinkageError::MissingClaim("sub"))?;
1357    if claims.nbf.is_none() {
1358        return Err(DomainLinkageError::MissingClaim("nbf"));
1359    }
1360    if claims.exp.is_none() {
1361        return Err(DomainLinkageError::MissingClaim("exp"));
1362    }
1363
1364    let credential = &decoded.credential;
1365    if credential.id.is_some() {
1366        return Err(DomainLinkageError::IdPresent);
1367    }
1368    if !credential.context.contains(CONTEXT) {
1369        return Err(DomainLinkageError::MissingContext);
1370    }
1371    if !credential.has_type(CREDENTIAL_TYPE) {
1372        return Err(DomainLinkageError::MissingType);
1373    }
1374    if credential.expiration_date.is_none() {
1375        return Err(DomainLinkageError::MissingExpirationDate);
1376    }
1377    // A JWT with `sub` and several subjects does not decode as a credential, so one subject
1378    // is all that gets here.
1379    let subject = credential
1380        .subject()
1381        .ok_or(DomainLinkageError::SubjectNotDid(None))?;
1382    let subject_did = subject_did(subject)?;
1383    for (role, found) in [
1384        ("issuer", credential.issuer.id().as_str()),
1385        ("iss", iss),
1386        ("sub", sub),
1387    ] {
1388        if found != subject_did.as_str() {
1389            return Err(DomainLinkageError::SubjectMismatch {
1390                role,
1391                found: found.to_owned(),
1392                subject: subject_did,
1393            });
1394        }
1395    }
1396    let found = subject_origin(subject)?;
1397    if found != expected_origin {
1398        return Err(DomainLinkageError::OriginMismatch {
1399            expected: expected_origin.to_owned(),
1400            found,
1401        });
1402    }
1403    Ok(())
1404}
1405
1406/// The DID `credentialSubject.id` names.
1407fn subject_did(subject: &Subject) -> Result<Did, DomainLinkageError> {
1408    let id = subject.id.as_ref().map(Uri::as_str);
1409    id.and_then(|id| Did::parse(id).ok())
1410        .ok_or_else(|| DomainLinkageError::SubjectNotDid(id.map(str::to_owned)))
1411}
1412
1413/// `credentialSubject.origin`, normalized.
1414fn subject_origin(subject: &Subject) -> Result<String, DomainLinkageError> {
1415    let origin = subject.properties.get("origin");
1416    let Some(Value::String(origin)) = origin else {
1417        return Err(DomainLinkageError::InvalidOriginProperty(origin.cloned()));
1418    };
1419    normalize_origin(origin)
1420}
1421
1422impl fmt::Display for DomainLinkageConfiguration {
1423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1424        let json = serde_json::to_string(self).map_err(|_| fmt::Error)?;
1425        f.write_str(&json)
1426    }
1427}