Skip to main content

identity_kit/linked_vp/
mod.rs

1//! DIF Linked Verifiable Presentation: verifiable presentations a DID controller publishes for
2//! anyone to discover, through a `LinkedVerifiablePresentation` service in its DID document.
3//!
4//! The service entry is the normative part of the specification: `type` is
5//! [`SERVICE_TYPE`] and `serviceEndpoint` one URL or a non-empty array of them. [`service`]
6//! builds one, [`services`] reads them out of a document. Each URL serves one presentation;
7//! this crate handles it as a JSON Web Token, in two forms, and reports the JSON-LD form as
8//! unsupported:
9//!
10//! - a VCDM 1.1 presentation in the `vp` claim, its credentials as JWTs;
11//! - a VCDM 2.0 presentation secured with VC-JOSE-COSE (`typ` `vp+jwt`), the presentation the
12//!   payload, its credentials enveloped (`application/vc+jwt` or `application/vc+sd-jwt`).
13//!   [`is_vcdm2`] tells the two apart.
14//!
15//! - [`LinkedPresentationBuilder`] (VCDM 1.1) and [`LinkedPresentationV2Builder`] (VCDM 2.0)
16//!   sign a presentation for publishing: `iss` and `holder` the DID, no `aud` and no `nonce`,
17//!   which a presentation published for anyone cannot carry.
18//! - [`LinkedVpValidator`] validates one presentation for the DID whose document lists it:
19//!   holder and `iss` are that DID, the holder signed with a key of the DID under
20//!   `authentication`, `exp` holds when present, and every credential validates with its
21//!   subject the holder (the specification's SHOULD, configurable).
22//!   [`validate`](LinkedVpValidator::validate) and
23//!   [`validate_v2`](LinkedVpValidator::validate_v2) take one form each,
24//!   [`validate_any`](LinkedVpValidator::validate_any) either.
25//! - [`LinkedVpClient`] fetches what a document's services point to through an
26//!   [`HttpClient`] and validates each presentation, in either form, reporting per URL: every
27//!   linked presentation stands on its own.
28//!
29//! # What fails alone
30//!
31//! A verifier reads what someone else published, so one malformed entry does not hide the
32//! valid ones next to it:
33//!
34//! - An endpoint URI that is not a URL fails alone: [`services`] lists it in
35//!   [`LinkedVpService::invalid_urls`] and keeps the service's other URLs, and
36//!   [`LinkedVpClient::validate_document`] reports it on its own. A service fails as a whole
37//!   only when its endpoint is a map or names no URL.
38//! - An entry of the presentation's `verifiableCredential` that is not a credential JWT, or an
39//!   envelope that does not hold a credential, fails alone: [`decode`] and [`decode_v2`]
40//!   return one result per entry, and the validator reports it in
41//!   [`PresentationValidationError::credentials`] under its index, as any other credential
42//!   that does not validate. In the VCDM 2.0 form, an entry that is not an envelope at all
43//!   fails the presentation.
44//! - Everything else is the presentation's: it does not decode, its holder or signer is not
45//!   the linking DID, or its signature or time claims do not hold.
46//!
47//! # A linked presentation proves control at link time only
48//!
49//! Anyone can fetch a linked presentation and replay it, and it says nothing about who
50//! controls the DID now. A verifier must not grant access on a linked presentation alone, but
51//! ask the holder for an interactive proof of control, as the specification's security
52//! considerations require. Hashlinks (`hl=` in a URL) are passed through and not verified.
53//!
54//! # `typ`
55//!
56//! The specification does not constrain `typ`. Its example presentation carries the literal
57//! `'vp+ld+jwt'`, stray quotes included, and its credential `'vc+ld+jwt'`; the validator
58//! accepts these ([`PRESENTATION_TYP`], [`CREDENTIAL_TYP`]) next to `JWT` and no `typ`. The
59//! VCDM 1.1 builder writes `JWT`; the VCDM 2.0 builder writes `vp+jwt`, which VC-JOSE-COSE
60//! defines.
61//!
62//! # Examples
63//!
64//! The specification's example document lists two presentations, one over HTTPS and one on
65//! IPFS:
66//!
67//! ```
68//! use identity_kit::did::DidDocument;
69//! use identity_kit::linked_vp::services;
70//! use serde_json::json;
71//!
72//! let document: DidDocument = serde_json::from_value(json!({
73//!   "@context": ["https://www.w3.org/ns/did/v1", "https://identity.foundation/linked-vp/contexts/v1"],
74//!   "id": "did:example:123",
75//!   "service": [
76//!     {
77//!       "id": "did:example:123#foo",
78//!       "type": "LinkedVerifiablePresentation",
79//!       "serviceEndpoint": ["https://bar.example.com/verifiable-presentation.jsonld"]
80//!     },
81//!     {
82//!       "id": "did:example:123#baz",
83//!       "type": "LinkedVerifiablePresentation",
84//!       "serviceEndpoint": "ipfs://bafybeihkoviema7g3gxyt6la7vd5ho32ictqbilu3wnlo3rs7ewhnp7lly/verifiable-presentation.jwt"
85//!     }
86//!   ]
87//! }))?;
88//! let urls: Vec<String> = services(&document)
89//!     .map(|service| service.map(|service| service.urls[0].to_string()))
90//!     .collect::<Result<_, _>>()?;
91//! assert_eq!(urls, [
92//!     "https://bar.example.com/verifiable-presentation.jsonld",
93//!     "ipfs://bafybeihkoviema7g3gxyt6la7vd5ho32ictqbilu3wnlo3rs7ewhnp7lly/verifiable-presentation.jwt",
94//! ]);
95//! # Ok::<(), Box<dyn std::error::Error>>(())
96//! ```
97
98use std::collections::BTreeSet;
99use std::error::Error;
100
101use chrono::{DateTime, Utc};
102use url::Url;
103
104use crate::cause::cause;
105use crate::did::{Did, DidDocument, DidUrl, ResolutionError, Service, ServiceEndpoint, Uri};
106use crate::jose::{DefaultVerifier, JwsError, JwsHeader, JwsVerifier, Signer};
107use crate::methods::web::{HttpClient, HttpError, fetchable};
108use crate::resolver::Resolver;
109use crate::vc::validation::{
110    CredentialValidationOptions, DecodedCredential, DecodedPresentation, DecodedPresentationV2,
111    FailFast, JwtPresentationValidator, KeyReference, KeyResolver, PresentationValidationError,
112    PresentationValidationOptions, PresentedCredentialV2, SubjectHolderRelationship, TimeOptions,
113    ValidationError, decode_presentation_entries, decode_presentation_entries_v2, extract_holder,
114};
115use crate::vc::{
116    CredentialError, EnvelopedVc, Jwt, JwtClaims, Party, Presentation, PresentationV2,
117};
118
119/// The service type, `LinkedVerifiablePresentation`.
120pub const SERVICE_TYPE: &str = "LinkedVerifiablePresentation";
121
122/// The JSON-LD context defining [`SERVICE_TYPE`], for the `@context` of a DID document that
123/// lists linked presentations.
124pub const CONTEXT: &str = "https://identity.foundation/linked-vp/contexts/v1";
125
126/// The header `typ` values a linked presentation may carry besides `JWT`: `vp+ld+jwt`, and the
127/// literal `'vp+ld+jwt'` with the single quotes of the specification's example.
128pub const PRESENTATION_TYP: [&str; 2] = ["vp+ld+jwt", "'vp+ld+jwt'"];
129
130/// The header `typ` values a credential in a linked presentation may carry besides `JWT`:
131/// `vc+ld+jwt`, and the literal `'vc+ld+jwt'` of the specification's example.
132pub const CREDENTIAL_TYP: [&str; 2] = ["vc+ld+jwt", "'vc+ld+jwt'"];
133
134/// A `LinkedVerifiablePresentation` service of `id` pointing to `urls`.
135///
136/// # Errors
137///
138/// [`LinkedVpError::InvalidService`] when `urls` is empty or a URL is not an RFC 3986 URI.
139///
140/// # Examples
141///
142/// ```
143/// use identity_kit::did::{DidUrl, ServiceEndpoint};
144/// use identity_kit::linked_vp::{SERVICE_TYPE, service};
145/// use url::Url;
146///
147/// let service = service(
148///     DidUrl::parse("did:example:123#foo")?,
149///     [Url::parse("https://bar.example.com/verifiable-presentation.jwt")?],
150/// )?;
151/// assert!(service.has_type(SERVICE_TYPE));
152/// assert!(matches!(service.service_endpoint, ServiceEndpoint::Uri(_)));
153/// # Ok::<(), Box<dyn std::error::Error>>(())
154/// ```
155#[expect(
156    clippy::similar_names,
157    reason = "the URLs given and the URIs of the service endpoint are both needed"
158)]
159pub fn service(id: DidUrl, urls: impl IntoIterator<Item = Url>) -> Result<Service, LinkedVpError> {
160    let mut uris = Vec::new();
161    for url in urls {
162        let uri = Uri::parse(url.as_str()).map_err(|e| LinkedVpError::InvalidService {
163            id: id.clone(),
164            reason: format!("`{url}` is not a URI"),
165            source: Some(Box::new(e)),
166        })?;
167        uris.push(uri);
168    }
169    let endpoint = match <[Uri; 1]>::try_from(uris) {
170        Ok([uri]) => ServiceEndpoint::Uri(uri),
171        Err(uris) if uris.is_empty() => {
172            return Err(LinkedVpError::InvalidService {
173                id,
174                reason: "no URL".to_owned(),
175                source: None,
176            });
177        }
178        Err(uris) => ServiceEndpoint::Set(uris.into_iter().collect()),
179    };
180    Ok(Service::new(id, SERVICE_TYPE, endpoint))
181}
182
183/// A `LinkedVerifiablePresentation` service of a DID document, with its URLs.
184#[derive(Debug, Clone, PartialEq, Eq)]
185#[non_exhaustive]
186pub struct LinkedVpService<'a> {
187    /// The service entry.
188    pub service: &'a Service,
189    /// Its URLs, in document order: the endpoint URIs that parse as URLs.
190    pub urls: Vec<Url>,
191    /// The endpoint URIs that do not parse as URLs, in document order, each with why. They
192    /// do not hide the service's other URLs.
193    pub invalid_urls: Vec<(Uri, url::ParseError)>,
194}
195
196impl LinkedVpService<'_> {
197    /// The id of the service.
198    pub fn id(&self) -> &DidUrl {
199        &self.service.id
200    }
201}
202
203/// The `LinkedVerifiablePresentation` services of `document`, in document order. A service of
204/// that type whose endpoint is a map, or names no URL at all, is a
205/// [`LinkedVpError::InvalidService`] rather than silently skipped. An endpoint URI that is not
206/// a URL (`https://example.org:99999/vp`, whose port is out of range) is listed in
207/// [`LinkedVpService::invalid_urls`] and leaves the service's other URLs in place.
208pub fn services(
209    document: &DidDocument,
210) -> impl Iterator<Item = Result<LinkedVpService<'_>, LinkedVpError>> {
211    document
212        .service
213        .iter()
214        .filter(|service| service.has_type(SERVICE_TYPE))
215        .map(linked_vp_service)
216}
217
218/// `service` with its URLs parsed.
219fn linked_vp_service(service: &Service) -> Result<LinkedVpService<'_>, LinkedVpError> {
220    let invalid = |reason: String, source: Option<Box<dyn Error + Send + Sync>>| {
221        LinkedVpError::InvalidService {
222            id: service.id.clone(),
223            reason,
224            source,
225        }
226    };
227    if matches!(service.service_endpoint, ServiceEndpoint::Map(_)) {
228        return Err(invalid(
229            "`serviceEndpoint` is a map, not URLs".to_owned(),
230            None,
231        ));
232    }
233    let mut urls = Vec::new();
234    let mut invalid_urls = Vec::new();
235    for uri in service.service_endpoint.uris() {
236        match Url::parse(uri.as_str()) {
237            Ok(url) => urls.push(url),
238            Err(e) => invalid_urls.push((uri.clone(), e)),
239        }
240    }
241    if urls.is_empty() {
242        return Err(match invalid_urls.into_iter().next() {
243            Some((uri, e)) => invalid(format!("`{uri}` is not a URL"), Some(Box::new(e))),
244            None => invalid("no URL".to_owned(), None),
245        });
246    }
247    Ok(LinkedVpService {
248        service,
249        urls,
250        invalid_urls,
251    })
252}
253
254/// The report of `uri`, an endpoint URI of `service` that is not a URL.
255fn invalid_url(service: &Service, uri: &Uri, error: url::ParseError) -> LinkedPresentationReport {
256    LinkedPresentationReport {
257        service: service.id.clone(),
258        url: None,
259        result: Err(LinkedVpError::InvalidService {
260            id: service.id.clone(),
261            reason: format!("`{uri}` is not a URL"),
262            source: Some(Box::new(error)),
263        }),
264    }
265}
266
267/// Builds a linked presentation in the JSON Web Token form: a VCDM 1.1 presentation of
268/// credential JWTs held by `holder`, with `iss`, `sub` and `holder` the holder, `jti` the
269/// presentation's `id`, `iat` and `nbf` the issuance time, `exp` when an expiration is set,
270/// and neither `aud` nor `nonce`.
271///
272/// # Examples
273///
274/// ```
275/// use chrono::{TimeZone as _, Utc};
276/// use identity_kit::did::{Did, Uri};
277/// use identity_kit::linked_vp::LinkedPresentationBuilder;
278///
279/// let holder = Did::parse("did:example:123")?;
280/// let claims = LinkedPresentationBuilder::new(holder)
281///     .with_id(Uri::parse("https://bar.example.com/verifiable-presentation.jwt")?)
282///     .with_issued_at(Utc.with_ymd_and_hms(2024, 2, 8, 17, 38, 46).unwrap())
283///     .with_expiration(Utc.with_ymd_and_hms(2029, 2, 8, 17, 38, 46).unwrap())
284///     .jwt_claims()?;
285/// assert_eq!(claims.iss.as_deref(), Some("did:example:123"));
286/// assert_eq!(claims.sub, claims.iss);
287/// assert_eq!((claims.iat, claims.nbf, claims.exp), (Some(1707413926), Some(1707413926), Some(1865266726)));
288/// assert_eq!(claims.jti.as_deref(), Some("https://bar.example.com/verifiable-presentation.jwt"));
289/// assert!(claims.aud.is_none() && !claims.additional.contains_key("nonce"));
290/// # Ok::<(), Box<dyn std::error::Error>>(())
291/// ```
292#[derive(Debug, Clone, PartialEq, Eq)]
293#[non_exhaustive]
294pub struct LinkedPresentationBuilder {
295    /// The holder: the DID whose document links the presentation.
296    pub holder: Did,
297    /// The presentation's `id`, usually the URL it is published at.
298    pub id: Option<Uri>,
299    /// The credential JWTs.
300    pub credentials: Vec<Jwt>,
301    /// `iat` and `nbf`.
302    pub issued_at: DateTime<Utc>,
303    /// `exp`, if the presentation expires.
304    pub expiration: Option<DateTime<Utc>>,
305}
306
307impl LinkedPresentationBuilder {
308    /// A presentation by `holder` of no credentials, issued now, without `id` or expiration.
309    pub fn new(holder: Did) -> Self {
310        Self {
311            holder,
312            id: None,
313            credentials: Vec::new(),
314            issued_at: Utc::now(),
315            expiration: None,
316        }
317    }
318
319    /// This presentation with its `id` set.
320    #[must_use]
321    pub fn with_id(mut self, id: impl Into<Uri>) -> Self {
322        self.id = Some(id.into());
323        self
324    }
325
326    /// This presentation with `credential` added.
327    #[must_use]
328    pub fn with_credential(mut self, credential: Jwt) -> Self {
329        self.credentials.push(credential);
330        self
331    }
332
333    /// This presentation issued at `issued_at`.
334    #[must_use]
335    pub fn with_issued_at(mut self, issued_at: DateTime<Utc>) -> Self {
336        self.issued_at = issued_at;
337        self
338    }
339
340    /// This presentation expiring at `expiration`, which the specification recommends to limit
341    /// how long a published presentation stays valid.
342    #[must_use]
343    pub fn with_expiration(mut self, expiration: DateTime<Utc>) -> Self {
344        self.expiration = Some(expiration);
345        self
346    }
347
348    /// The presentation.
349    pub fn presentation(&self) -> Presentation {
350        let mut presentation = Presentation::new().with_holder(self.holder.clone());
351        if let Some(id) = &self.id {
352            presentation = presentation.with_id(id.clone());
353        }
354        self.credentials
355            .iter()
356            .fold(presentation, |presentation, credential| {
357                presentation.with_credential(credential.clone())
358            })
359    }
360
361    /// The JWT claims: the presentation's (`iss`, `jti`, `vp`) with `sub`, `iat`, `nbf` and
362    /// `exp`.
363    ///
364    /// # Errors
365    ///
366    /// A [`CredentialError`] when the presentation does not map to claims; one built here
367    /// always does.
368    pub fn jwt_claims(&self) -> Result<JwtClaims, CredentialError> {
369        let mut claims = self
370            .presentation()
371            .to_jwt_claims()?
372            .with_sub(self.holder.as_str())
373            .with_iat(self.issued_at)
374            .with_nbf(self.issued_at);
375        if let Some(expiration) = self.expiration {
376            claims = claims.with_exp(expiration);
377        }
378        Ok(claims)
379    }
380
381    /// The presentation signed with `signer` under a header of `alg`, `typ` `JWT` and `kid`,
382    /// `kid` naming a verification method of the holder, which a verifier resolves under
383    /// `authentication`.
384    ///
385    /// # Errors
386    ///
387    /// [`LinkedVpError::Validation`] with [`ValidationError::HolderMismatch`] when `kid` is not
388    /// a key of the holder, or with [`ValidationError::Jws`] when signing fails.
389    pub async fn sign(&self, kid: &DidUrl, signer: &dyn Signer) -> Result<Jwt, LinkedVpError> {
390        if kid.did() != &self.holder {
391            return Err(ValidationError::HolderMismatch {
392                holder: self.holder.clone().into(),
393                key: Box::new(KeyReference::DidUrl(kid.clone())),
394            }
395            .into());
396        }
397        let header = JwsHeader::new(signer.alg())
398            .with_typ("JWT")
399            .with_kid(kid.as_str());
400        let claims = self.jwt_claims().map_err(ValidationError::from)?;
401        let jwt = Jwt::sign(&header, &claims, signer)
402            .await
403            .map_err(ValidationError::from)?;
404        Ok(jwt)
405    }
406}
407
408/// Builds a linked presentation as a VCDM 2.0 presentation secured with VC-JOSE-COSE: the
409/// presentation is the JWT payload (`typ` `vp+jwt`), with `holder` and `iss` the holder, its
410/// credentials enveloped (`EnvelopedVerifiableCredential`, `application/vc+jwt` or
411/// `application/vc+sd-jwt`), `iat` and `nbf` the issuance time, `exp` when an expiration is
412/// set, and neither `aud` nor `nonce`.
413///
414/// A credential secured with SD-JWT is published with the disclosures its envelope holds,
415/// which anyone fetching the presentation can read.
416///
417/// # Examples
418///
419/// ```
420/// use chrono::{TimeZone as _, Utc};
421/// use identity_kit::did::{Did, Uri};
422/// use identity_kit::linked_vp::LinkedPresentationV2Builder;
423///
424/// let holder = Did::parse("did:example:123")?;
425/// let claims = LinkedPresentationV2Builder::new(holder)
426///     .with_id(Uri::parse("https://bar.example.com/verifiable-presentation.jwt")?)
427///     .with_issued_at(Utc.with_ymd_and_hms(2024, 2, 8, 17, 38, 46).unwrap())
428///     .with_expiration(Utc.with_ymd_and_hms(2029, 2, 8, 17, 38, 46).unwrap())
429///     .jwt_claims();
430/// assert_eq!(claims.iss.as_deref(), Some("did:example:123"));
431/// assert_eq!(claims.additional["holder"], "did:example:123");
432/// assert_eq!(claims.additional["type"], "VerifiablePresentation");
433/// assert_eq!((claims.iat, claims.nbf, claims.exp), (Some(1707413926), Some(1707413926), Some(1865266726)));
434/// assert!(claims.aud.is_none() && !claims.additional.contains_key("nonce"));
435/// assert!(!claims.additional.contains_key("vp"));
436/// # Ok::<(), Box<dyn std::error::Error>>(())
437/// ```
438#[derive(Debug, Clone, PartialEq, Eq)]
439#[non_exhaustive]
440pub struct LinkedPresentationV2Builder {
441    /// The holder: the DID whose document links the presentation.
442    pub holder: Did,
443    /// The presentation's `id`, usually the URL it is published at.
444    pub id: Option<Uri>,
445    /// The enveloped credentials.
446    pub credentials: Vec<EnvelopedVc>,
447    /// `iat` and `nbf`.
448    pub issued_at: DateTime<Utc>,
449    /// `exp`, if the presentation expires.
450    pub expiration: Option<DateTime<Utc>>,
451}
452
453impl LinkedPresentationV2Builder {
454    /// A presentation by `holder` of no credentials, issued now, without `id` or expiration.
455    pub fn new(holder: Did) -> Self {
456        Self {
457            holder,
458            id: None,
459            credentials: Vec::new(),
460            issued_at: Utc::now(),
461            expiration: None,
462        }
463    }
464
465    /// This presentation with its `id` set.
466    #[must_use]
467    pub fn with_id(mut self, id: impl Into<Uri>) -> Self {
468        self.id = Some(id.into());
469        self
470    }
471
472    /// This presentation with `credential` added.
473    #[must_use]
474    pub fn with_credential(mut self, credential: EnvelopedVc) -> Self {
475        self.credentials.push(credential);
476        self
477    }
478
479    /// This presentation issued at `issued_at`.
480    #[must_use]
481    pub fn with_issued_at(mut self, issued_at: DateTime<Utc>) -> Self {
482        self.issued_at = issued_at;
483        self
484    }
485
486    /// This presentation expiring at `expiration`, which the specification recommends to limit
487    /// how long a published presentation stays valid.
488    #[must_use]
489    pub fn with_expiration(mut self, expiration: DateTime<Utc>) -> Self {
490        self.expiration = Some(expiration);
491        self
492    }
493
494    /// The presentation.
495    pub fn presentation(&self) -> PresentationV2 {
496        let mut presentation = PresentationV2::new().with_holder(self.holder.clone());
497        if let Some(id) = &self.id {
498            presentation = presentation.with_id(id.clone());
499        }
500        self.credentials
501            .iter()
502            .fold(presentation, |presentation, credential| {
503                presentation.with_credential(credential.clone())
504            })
505    }
506
507    /// The JWT claims: the presentation as the payload, with `iss`, `iat`, `nbf` and `exp`.
508    pub fn jwt_claims(&self) -> JwtClaims {
509        let mut claims = self
510            .presentation()
511            .to_jwt_claims()
512            .with_iss(self.holder.as_str())
513            .with_iat(self.issued_at)
514            .with_nbf(self.issued_at);
515        if let Some(expiration) = self.expiration {
516            claims = claims.with_exp(expiration);
517        }
518        claims
519    }
520
521    /// The presentation signed with `signer` under a header of `alg`, `typ` `vp+jwt` and
522    /// `kid`, `kid` naming a verification method of the holder, which a verifier resolves
523    /// under `authentication`.
524    ///
525    /// # Errors
526    ///
527    /// [`LinkedVpError::Validation`] with [`ValidationError::HolderMismatch`] when `kid` is not
528    /// a key of the holder, or with [`ValidationError::Jws`] when signing fails.
529    pub async fn sign(&self, kid: &DidUrl, signer: &dyn Signer) -> Result<Jwt, LinkedVpError> {
530        if kid.did() != &self.holder {
531            return Err(ValidationError::HolderMismatch {
532                holder: self.holder.clone().into(),
533                key: Box::new(KeyReference::DidUrl(kid.clone())),
534            }
535            .into());
536        }
537        let header = JwsHeader::new(signer.alg())
538            .with_typ(PresentationV2::JWT_TYP)
539            .with_kid(kid.as_str());
540        let jwt = Jwt::sign(&header, &self.jwt_claims(), signer)
541            .await
542            .map_err(ValidationError::from)?;
543        Ok(jwt)
544    }
545}
546
547/// Why a linked presentation could not be found, fetched or validated.
548#[derive(Debug, thiserror::Error)]
549#[non_exhaustive]
550pub enum LinkedVpError {
551    /// A `LinkedVerifiablePresentation` service does not name one or more URLs. The source
552    /// is the URI or URL error, when there is one.
553    #[error("service `{id}`: {reason}{}", cause(.source.as_ref()))]
554    InvalidService {
555        /// The id of the service.
556        id: DidUrl,
557        /// What is wrong with it.
558        reason: String,
559        /// The underlying error.
560        source: Option<Box<dyn Error + Send + Sync>>,
561    },
562    /// A URL is not `https`: an `ipfs://` endpoint, say. Only HTTPS is fetched.
563    #[error("`{0}` is not an HTTPS URL")]
564    UnsupportedEndpoint(Url),
565    /// The [`HttpClient`] got no response.
566    #[error("fetching `{url}` failed: {source}")]
567    Http {
568        /// The URL fetched.
569        url: Url,
570        /// Why there was no response.
571        #[source]
572        source: HttpError,
573    },
574    /// The server answered with a status other than `2xx`.
575    #[error("fetching `{url}` returned HTTP {status}")]
576    HttpStatus {
577        /// The URL fetched.
578        url: Url,
579        /// The status code.
580        status: u16,
581    },
582    /// The body is a JSON object: a presentation in the JSON-LD form, which this crate does
583    /// not process.
584    #[error("`{0}` serves a JSON-LD presentation, which is not supported")]
585    UnsupportedFormat(Url),
586    /// The body is not a compact JWT. The source is the UTF-8 or [`JwsError`].
587    #[error("`{url}` does not serve a compact JWT: {reason}{}", cause(.source.as_ref()))]
588    InvalidBody {
589        /// The URL fetched.
590        url: Url,
591        /// What is wrong with the body.
592        reason: &'static str,
593        /// The underlying error.
594        source: Option<Box<dyn Error + Send + Sync>>,
595    },
596    /// The presentation's holder is not the DID whose document links it.
597    #[error("the holder `{holder}` is not `{did}`, the DID linking the presentation")]
598    HolderMismatch {
599        /// The DID linking the presentation.
600        did: Did,
601        /// The holder the presentation names.
602        holder: Did,
603    },
604    /// The presentation or some of its credentials did not validate.
605    #[error(transparent)]
606    Presentation(#[from] PresentationValidationError),
607    /// The presentation did not decode, or did not sign.
608    #[error(transparent)]
609    Validation(#[from] ValidationError),
610    /// The DID did not resolve.
611    #[error("resolving the DID failed: {0}")]
612    Resolution(#[from] ResolutionError),
613    /// The URL was not fetched: the DID document lists more URLs than the client's limit,
614    /// given here.
615    #[error("the DID document lists more than {0} presentation URLs")]
616    TooManyUrls(usize),
617}
618
619/// Options of [`LinkedVpValidator`]. The audience and nonce are fixed: a linked presentation
620/// has neither.
621#[derive(Debug, Clone, Default, PartialEq, Eq)]
622#[non_exhaustive]
623pub struct LinkedVpValidationOptions {
624    /// The validation time and leeway of the presentation JWT; `exp` is honoured when present
625    /// and not required.
626    pub time: TimeOptions,
627    /// The options every credential is validated with. [`CREDENTIAL_TYP`] is accepted on top
628    /// of their `additional_typ`.
629    pub credentials: CredentialValidationOptions,
630    /// How credential subjects must relate to the holder;
631    /// [`SubjectHolderRelationship::AlwaysSubject`] by default, as the specification
632    /// recommends.
633    pub subject_holder: SubjectHolderRelationship,
634    /// Whether to stop at the first failing credential.
635    pub fail_fast: FailFast,
636}
637
638impl LinkedVpValidationOptions {
639    /// Default options: validate now without leeway, default credential options,
640    /// [`SubjectHolderRelationship::AlwaysSubject`], [`FailFast::FirstError`].
641    pub fn new() -> Self {
642        Self::default()
643    }
644
645    /// These options with `time`, for the presentation JWT only.
646    #[must_use]
647    pub fn with_time(mut self, time: TimeOptions) -> Self {
648        self.time = time;
649        self
650    }
651
652    /// These options validating credentials with `credentials`.
653    #[must_use]
654    pub fn with_credentials(mut self, credentials: CredentialValidationOptions) -> Self {
655        self.credentials = credentials;
656        self
657    }
658
659    /// These options with `relationship`.
660    #[must_use]
661    pub fn with_subject_holder(mut self, relationship: SubjectHolderRelationship) -> Self {
662        self.subject_holder = relationship;
663        self
664    }
665
666    /// These options with `fail_fast`.
667    #[must_use]
668    pub fn with_fail_fast(mut self, fail_fast: FailFast) -> Self {
669        self.fail_fast = fail_fast;
670        self
671    }
672
673    /// The options of the underlying [`JwtPresentationValidator`]: no audience, no nonce, and
674    /// [`PRESENTATION_TYP`] and [`CREDENTIAL_TYP`] accepted.
675    pub fn presentation_options(&self) -> PresentationValidationOptions {
676        let mut credentials = self.credentials.clone();
677        credentials
678            .additional_typ
679            .extend(CREDENTIAL_TYP.map(str::to_owned));
680        let mut options = PresentationValidationOptions::new()
681            .with_time(self.time)
682            .with_subject_holder(self.subject_holder)
683            .with_credentials(credentials)
684            .with_fail_fast(self.fail_fast);
685        options
686            .additional_typ
687            .extend(PRESENTATION_TYP.map(str::to_owned));
688        options
689    }
690}
691
692/// A linked presentation decoded without verification: the presentation, and each entry of
693/// its `verifiableCredential` decoded on its own.
694#[derive(Debug)]
695#[non_exhaustive]
696pub struct DecodedLinkedPresentation {
697    /// The JWS header.
698    pub header: JwsHeader,
699    /// The claims set, `vp` included.
700    pub claims: JwtClaims,
701    /// The presentation, with `iss` and `jti` mapped back into it. Its
702    /// `verifiable_credential` holds the entries that are compact JWTs.
703    pub presentation: Presentation,
704    /// One result per entry of `verifiableCredential`, in order: the credential decoded, or why
705    /// that entry is not one.
706    pub credentials: Vec<Result<DecodedCredential, ValidationError>>,
707}
708
709impl DecodedLinkedPresentation {
710    /// The holder: `holder` of the presentation, which decoding set from `iss`.
711    pub fn holder(&self) -> Option<&Uri> {
712        self.presentation.holder.as_ref().map(Party::id)
713    }
714}
715
716/// Decodes a linked presentation and its credentials without verifying or validating
717/// anything, accepting [`PRESENTATION_TYP`] and [`CREDENTIAL_TYP`]. Each entry of
718/// `verifiableCredential` decodes on its own: one that is not a credential JWT is an error in
719/// [`DecodedLinkedPresentation::credentials`], next to the others.
720///
721/// # Errors
722///
723/// As [`decode_presentation`](crate::vc::validation::decode_presentation), for the
724/// presentation alone.
725pub fn decode(jwt: &Jwt) -> Result<DecodedLinkedPresentation, ValidationError> {
726    let presentation_typ: BTreeSet<String> = PRESENTATION_TYP.map(str::to_owned).into();
727    let credential_typ: BTreeSet<String> = CREDENTIAL_TYP.map(str::to_owned).into();
728    let (decoded, credentials) =
729        decode_presentation_entries(jwt, &presentation_typ, &credential_typ)?;
730    Ok(DecodedLinkedPresentation {
731        header: decoded.header,
732        claims: decoded.claims,
733        presentation: decoded.presentation,
734        credentials,
735    })
736}
737
738/// A VCDM 2.0 linked presentation (`vp+jwt`) decoded without verification: the presentation,
739/// and the credential of each of its envelopes decoded on its own.
740#[derive(Debug)]
741#[non_exhaustive]
742pub struct DecodedLinkedPresentationV2 {
743    /// The JWS header.
744    pub header: JwsHeader,
745    /// The claims set, which is the presentation plus any registered claims.
746    pub claims: JwtClaims,
747    /// The presentation, with `iss` and `jti` mapped into `holder` and `id` when those are
748    /// absent.
749    pub presentation: PresentationV2,
750    /// One result per entry of `verifiableCredential`, in order: the enveloped credential
751    /// decoded (a credential secured with SD-JWT with the disclosures it carries applied), or
752    /// why that envelope does not hold one.
753    pub credentials: Vec<Result<PresentedCredentialV2, ValidationError>>,
754}
755
756impl DecodedLinkedPresentationV2 {
757    /// The holder: `holder` of the presentation, or `iss` when it has none.
758    pub fn holder(&self) -> Option<&Uri> {
759        self.presentation.holder.as_ref().map(Party::id)
760    }
761}
762
763/// Decodes a VCDM 2.0 linked presentation and its enveloped credentials without verifying or
764/// validating anything, accepting [`PRESENTATION_TYP`] besides `vp+jwt`. Each envelope decodes
765/// on its own: one that does not hold a credential is an error in
766/// [`DecodedLinkedPresentationV2::credentials`], next to the others. An entry of
767/// `verifiableCredential` that is not an envelope at all fails the presentation.
768///
769/// # Errors
770///
771/// As [`decode_presentation_v2`](crate::vc::validation::decode_presentation_v2), for the
772/// presentation alone.
773pub fn decode_v2(jwt: &Jwt) -> Result<DecodedLinkedPresentationV2, ValidationError> {
774    let presentation_typ: BTreeSet<String> = PRESENTATION_TYP.map(str::to_owned).into();
775    let (decoded, credentials) = decode_presentation_entries_v2(jwt, &presentation_typ)?;
776    Ok(DecodedLinkedPresentationV2 {
777        header: decoded.header,
778        claims: decoded.claims,
779        presentation: decoded.presentation,
780        credentials,
781    })
782}
783
784/// Whether `jwt` is a VCDM 2.0 presentation rather than a VCDM 1.1 one, read without
785/// verifying anything: its `typ` is `vp+jwt`, or its payload has no `vp` claim.
786///
787/// # Errors
788///
789/// [`ValidationError::Jws`] or [`ValidationError::Payload`] when the token does not decode.
790pub fn is_vcdm2(jwt: &Jwt) -> Result<bool, ValidationError> {
791    let jws = jwt.decode()?;
792    if jws.header().typ.as_deref() == Some(PresentationV2::JWT_TYP) {
793        return Ok(true);
794    }
795    let claims: JwtClaims =
796        serde_json::from_slice(jws.payload()).map_err(ValidationError::Payload)?;
797    Ok(!claims.additional.contains_key("vp"))
798}
799
800/// A validated linked presentation, in the JSON Web Token form it was published in.
801#[derive(Debug)]
802#[non_exhaustive]
803pub enum LinkedPresentation {
804    /// A VCDM 1.1 presentation in the `vp` claim, its credentials as JWTs.
805    Vcdm11(DecodedPresentation),
806    /// A VCDM 2.0 presentation secured with VC-JOSE-COSE, its credentials enveloped.
807    Vcdm2(DecodedPresentationV2),
808}
809
810impl LinkedPresentation {
811    /// The holder of the presentation.
812    pub fn holder(&self) -> Option<&Uri> {
813        match self {
814            Self::Vcdm11(decoded) => decoded.holder(),
815            Self::Vcdm2(decoded) => decoded.holder(),
816        }
817    }
818
819    /// The VCDM 1.1 presentation, if it is one.
820    pub fn as_vcdm11(&self) -> Option<&DecodedPresentation> {
821        match self {
822            Self::Vcdm11(decoded) => Some(decoded),
823            Self::Vcdm2(_) => None,
824        }
825    }
826
827    /// The VCDM 2.0 presentation, if it is one.
828    pub fn as_vcdm2(&self) -> Option<&DecodedPresentationV2> {
829        match self {
830            Self::Vcdm11(_) => None,
831            Self::Vcdm2(decoded) => Some(decoded),
832        }
833    }
834}
835
836/// Validates linked presentations: [`JwtPresentationValidator`] with the options fixed to the
837/// specification, plus the holder and the signer being the DID that links the presentation.
838///
839/// # Examples
840///
841/// ```
842/// # #[cfg(feature = "did-key")]
843/// # {
844/// use identity_kit::jose::DefaultVerifier;
845/// use identity_kit::linked_vp::LinkedVpValidator;
846/// use identity_kit::methods::DidKey;
847/// use identity_kit::resolver::Resolver;
848///
849/// let resolver = Resolver::builder().with(DidKey::default()).build();
850/// let validator = LinkedVpValidator::new(resolver, DefaultVerifier);
851/// assert!(!validator.presentation_validator().credential_validator().has_status_check());
852/// # }
853/// ```
854#[derive(Debug)]
855pub struct LinkedVpValidator<R, V = DefaultVerifier> {
856    presentations: JwtPresentationValidator<R, V>,
857}
858
859impl<R: KeyResolver, V: JwsVerifier> LinkedVpValidator<R, V> {
860    /// A validator resolving keys with `resolver` and verifying signatures with `verifier`.
861    pub fn new(resolver: R, verifier: V) -> Self {
862        Self {
863            presentations: JwtPresentationValidator::new(resolver, verifier),
864        }
865    }
866
867    /// A validator over `presentations`, with its status check.
868    pub fn from_presentation_validator(presentations: JwtPresentationValidator<R, V>) -> Self {
869        Self { presentations }
870    }
871
872    /// The presentation validator.
873    pub fn presentation_validator(&self) -> &JwtPresentationValidator<R, V> {
874        &self.presentations
875    }
876
877    /// Validates `jwt` as a VCDM 1.1 presentation linked from the document of `did`.
878    ///
879    /// The holder, and the party the token's [`KeyReference`] names, are checked against
880    /// `did` before any key is resolved, so a presentation naming another DID never makes the
881    /// resolver fetch that DID's document: a DID URL must be of `did`, a key by value must be
882    /// the `did:jwk` of `did`, and a key set of an HTTPS issuer never belongs to a DID.
883    ///
884    /// # Errors
885    ///
886    /// [`LinkedVpError::HolderMismatch`] when the holder is not `did`, otherwise
887    /// [`LinkedVpError::Presentation`] with what [`JwtPresentationValidator::validate`]
888    /// reports; a key of another DID is a [`ValidationError::HolderMismatch`] there.
889    pub async fn validate(
890        &self,
891        jwt: &Jwt,
892        did: &Did,
893        options: &LinkedVpValidationOptions,
894    ) -> Result<DecodedPresentation, LinkedVpError> {
895        check_linking_did(jwt, did)?;
896        let decoded = self
897            .presentations
898            .validate(jwt, &options.presentation_options())
899            .await?;
900        Ok(decoded)
901    }
902
903    /// Validates `jwt` as a VCDM 2.0 presentation (`vp+jwt`) linked from the document of
904    /// `did`, with the checks of [`validate`](Self::validate) on the holder and the signing
905    /// key. Each credential is unwrapped from its envelope and validated as
906    /// [`JwtPresentationValidator::validate_v2`] does, a credential secured with SD-JWT
907    /// without a key binding: the holder's signature over the presentation proves control.
908    ///
909    /// # Errors
910    ///
911    /// As [`validate`](Self::validate), with what [`JwtPresentationValidator::validate_v2`]
912    /// reports.
913    pub async fn validate_v2(
914        &self,
915        jwt: &Jwt,
916        did: &Did,
917        options: &LinkedVpValidationOptions,
918    ) -> Result<DecodedPresentationV2, LinkedVpError> {
919        check_linking_did(jwt, did)?;
920        let decoded = self
921            .presentations
922            .validate_v2(jwt, &options.presentation_options())
923            .await?;
924        Ok(decoded)
925    }
926
927    /// Validates `jwt` as a presentation linked from the document of `did`, in whichever
928    /// JSON Web Token form it is: [`validate_v2`](Self::validate_v2) when [`is_vcdm2`], else
929    /// [`validate`](Self::validate).
930    ///
931    /// # Errors
932    ///
933    /// As [`validate`](Self::validate) and [`validate_v2`](Self::validate_v2);
934    /// [`LinkedVpError::Presentation`] when the token does not decode.
935    pub async fn validate_any(
936        &self,
937        jwt: &Jwt,
938        did: &Did,
939        options: &LinkedVpValidationOptions,
940    ) -> Result<LinkedPresentation, LinkedVpError> {
941        if is_vcdm2(jwt).map_err(PresentationValidationError::presentation)? {
942            self.validate_v2(jwt, did, options)
943                .await
944                .map(LinkedPresentation::Vcdm2)
945        } else {
946            self.validate(jwt, did, options)
947                .await
948                .map(LinkedPresentation::Vcdm11)
949        }
950    }
951}
952
953/// Checks the holder of `jwt`, and the party its [`KeyReference`] names, against `did`,
954/// without resolving any key.
955fn check_linking_did(jwt: &Jwt, did: &Did) -> Result<(), LinkedVpError> {
956    let holder = extract_holder(jwt).map_err(PresentationValidationError::presentation)?;
957    if holder != *did {
958        return Err(LinkedVpError::HolderMismatch {
959            did: did.clone(),
960            holder,
961        });
962    }
963    let jws = jwt
964        .decode()
965        .map_err(|e| PresentationValidationError::presentation(e.into()))?;
966    if let Ok(reference) = KeyReference::from_jws(&jws, Some(did.as_str())) {
967        let of_did = match &reference {
968            KeyReference::DidUrl(url) => url.did() == did,
969            KeyReference::Jwk(jwk) => reference.binds_to(Some(did.as_str()), jwk),
970            _ => false,
971        };
972        if !of_did {
973            return Err(PresentationValidationError::presentation(
974                ValidationError::HolderMismatch {
975                    holder: did.clone().into(),
976                    key: Box::new(reference),
977                },
978            )
979            .into());
980        }
981    }
982    Ok(())
983}
984
985/// What became of one URL of a `LinkedVerifiablePresentation` service.
986#[derive(Debug)]
987#[non_exhaustive]
988pub struct LinkedPresentationReport {
989    /// The id of the service.
990    pub service: DidUrl,
991    /// The URL; `None` when the service entry itself is invalid.
992    pub url: Option<Url>,
993    /// The presentation, validated, or why it was not.
994    pub result: Result<LinkedPresentation, LinkedVpError>,
995}
996
997/// Fetches the presentations a DID document links with an [`HttpClient`] and validates them
998/// with a [`LinkedVpValidator`].
999///
1000/// The URLs come from the document, so the client fetches whatever its controller names:
1001/// `http` must enforce the protections `ReqwestClient` (feature `reqwest`) does (HTTPS only,
1002/// no redirects, no non-public addresses after name resolution, a body limit and a timeout),
1003/// or fetching becomes a request forgery primitive. A DID document can also list any number of
1004/// URLs, so [`validate_document`](Self::validate_document) fetches at most
1005/// [`max_urls`](Self::max_urls) of them.
1006#[derive(Debug)]
1007pub struct LinkedVpClient<C, R, V = DefaultVerifier> {
1008    http: C,
1009    validator: LinkedVpValidator<R, V>,
1010    max_urls: usize,
1011}
1012
1013impl<C, R, V> LinkedVpClient<C, R, V> {
1014    /// The most URLs [`new`](Self::new) fetches for one DID document: 32.
1015    pub const DEFAULT_MAX_URLS: usize = 32;
1016}
1017
1018impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> LinkedVpClient<C, R, V> {
1019    /// A client fetching with `http` and validating with `validator`, fetching at most
1020    /// [`DEFAULT_MAX_URLS`](Self::DEFAULT_MAX_URLS) URLs of a DID document.
1021    pub fn new(http: C, validator: LinkedVpValidator<R, V>) -> Self {
1022        Self {
1023            http,
1024            validator,
1025            max_urls: Self::DEFAULT_MAX_URLS,
1026        }
1027    }
1028
1029    /// This client fetching at most `max_urls` URLs of a DID document.
1030    #[must_use]
1031    pub fn with_max_urls(mut self, max_urls: usize) -> Self {
1032        self.max_urls = max_urls;
1033        self
1034    }
1035
1036    /// The most URLs [`validate_document`](Self::validate_document) fetches for one document.
1037    pub fn max_urls(&self) -> usize {
1038        self.max_urls
1039    }
1040
1041    /// The HTTP client.
1042    pub fn http(&self) -> &C {
1043        &self.http
1044    }
1045
1046    /// The validator.
1047    pub fn validator(&self) -> &LinkedVpValidator<R, V> {
1048        &self.validator
1049    }
1050
1051    /// The presentation JWT at `url`, unverified: the body, trimmed, must be one compact JWT.
1052    ///
1053    /// # Errors
1054    ///
1055    /// [`LinkedVpError::UnsupportedEndpoint`] for a URL that is not `https`, without fetching,
1056    /// unless the client [allows plain `http`](HttpClient::allows_plain_http) for it;
1057    /// [`LinkedVpError::Http`] or [`LinkedVpError::HttpStatus`] when there is no `2xx`
1058    /// response; [`LinkedVpError::UnsupportedFormat`] for a JSON-LD presentation;
1059    /// [`LinkedVpError::InvalidBody`] for anything else that is not a compact JWT.
1060    pub async fn fetch(&self, url: &Url) -> Result<Jwt, LinkedVpError> {
1061        if !fetchable(&self.http, url) {
1062            return Err(LinkedVpError::UnsupportedEndpoint(url.clone()));
1063        }
1064        let response = self
1065            .http
1066            .get(url)
1067            .await
1068            .map_err(|source| LinkedVpError::Http {
1069                url: url.clone(),
1070                source,
1071            })?;
1072        if !(200..300).contains(&response.status) {
1073            return Err(LinkedVpError::HttpStatus {
1074                url: url.clone(),
1075                status: response.status,
1076            });
1077        }
1078        let invalid = |reason: &'static str, source: Box<dyn Error + Send + Sync>| {
1079            LinkedVpError::InvalidBody {
1080                url: url.clone(),
1081                reason,
1082                source: Some(source),
1083            }
1084        };
1085        let body = core::str::from_utf8(&response.body)
1086            .map_err(|e| invalid("the body is not UTF-8", Box::new(e)))?
1087            .trim();
1088        if body.starts_with('{') {
1089            return Err(LinkedVpError::UnsupportedFormat(url.clone()));
1090        }
1091        Jwt::new(body).map_err(|e: JwsError| invalid("not a compact JWS", Box::new(e)))
1092    }
1093
1094    /// Fetches and validates `url` as a presentation linked from the document of `did`, in
1095    /// either JSON Web Token form.
1096    ///
1097    /// # Errors
1098    ///
1099    /// As [`fetch`](Self::fetch) and [`LinkedVpValidator::validate_any`].
1100    pub async fn validate_url(
1101        &self,
1102        url: &Url,
1103        did: &Did,
1104        options: &LinkedVpValidationOptions,
1105    ) -> Result<LinkedPresentation, LinkedVpError> {
1106        let jwt = self.fetch(url).await?;
1107        self.validator.validate_any(&jwt, did, options).await
1108    }
1109
1110    /// Fetches and validates every presentation `document` links, one report per URL in
1111    /// document order, one for each endpoint URI that is not a URL, and one for each invalid
1112    /// service entry. URLs past the first [`max_urls`](Self::max_urls) are not fetched and
1113    /// report [`LinkedVpError::TooManyUrls`].
1114    pub async fn validate_document(
1115        &self,
1116        document: &DidDocument,
1117        options: &LinkedVpValidationOptions,
1118    ) -> Vec<LinkedPresentationReport> {
1119        let mut reports = Vec::new();
1120        let mut fetched = 0;
1121        for service in document
1122            .service
1123            .iter()
1124            .filter(|service| service.has_type(SERVICE_TYPE))
1125        {
1126            if let Err(error) = linked_vp_service(service) {
1127                reports.push(LinkedPresentationReport {
1128                    service: service.id.clone(),
1129                    url: None,
1130                    result: Err(error),
1131                });
1132                continue;
1133            }
1134            for uri in service.service_endpoint.uris() {
1135                let url = match Url::parse(uri.as_str()) {
1136                    Ok(url) => url,
1137                    Err(error) => {
1138                        reports.push(invalid_url(service, uri, error));
1139                        continue;
1140                    }
1141                };
1142                let result = if fetched < self.max_urls {
1143                    fetched += 1;
1144                    self.validate_url(&url, &document.id, options).await
1145                } else {
1146                    Err(LinkedVpError::TooManyUrls(self.max_urls))
1147                };
1148                reports.push(LinkedPresentationReport {
1149                    service: service.id.clone(),
1150                    url: Some(url),
1151                    result,
1152                });
1153            }
1154        }
1155        reports
1156    }
1157}
1158
1159impl<C: HttpClient, V: JwsVerifier> LinkedVpClient<C, Resolver, V> {
1160    /// Resolves `did` with the validator's resolver, then validates every presentation its
1161    /// document links, as [`validate_document`](Self::validate_document).
1162    ///
1163    /// # Errors
1164    ///
1165    /// [`LinkedVpError::Resolution`] when `did` does not resolve to a document.
1166    pub async fn validate_did(
1167        &self,
1168        did: &Did,
1169        options: &LinkedVpValidationOptions,
1170    ) -> Result<Vec<LinkedPresentationReport>, LinkedVpError> {
1171        let document = self
1172            .validator
1173            .presentation_validator()
1174            .credential_validator()
1175            .resolver()
1176            .resolve_document(did)
1177            .await?;
1178        Ok(self.validate_document(&document, options).await)
1179    }
1180}