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 the JSON Web Token form (a VCDM 1.1 presentation in the `vp` claim, its
8//! credentials as JWTs) and reports the JSON-LD form as unsupported.
9//!
10//! - [`LinkedPresentationBuilder`] signs a presentation for publishing: `iss`, `sub` and
11//! `holder` the DID, no `aud` and no `nonce`, which a presentation published for anyone
12//! cannot carry.
13//! - [`LinkedVpValidator`] validates one presentation for the DID whose document lists it:
14//! holder and `iss` are that DID, the holder signed with a key of the DID under
15//! `authentication`, `exp` holds when present, and every credential validates with its
16//! subject the holder (the specification's SHOULD, configurable).
17//! - [`LinkedVpClient`] fetches what a document's services point to through an
18//! [`HttpClient`] and validates each presentation, reporting per URL: every linked
19//! presentation stands on its own.
20//!
21//! # What fails alone
22//!
23//! A verifier reads what someone else published, so one malformed entry does not hide the
24//! valid ones next to it:
25//!
26//! - An endpoint URI that is not a URL fails alone: [`services`] lists it in
27//! [`LinkedVpService::invalid_urls`] and keeps the service's other URLs, and
28//! [`LinkedVpClient::validate_document`] reports it on its own. A service fails as a whole
29//! only when its endpoint is a map or names no URL.
30//! - An entry of the presentation's `verifiableCredential` that is not a credential JWT fails
31//! alone: [`decode`] returns one result per entry, and [`LinkedVpValidator::validate`]
32//! reports it in [`PresentationValidationError::credentials`] under its index, as any other
33//! credential that does not validate.
34//! - Everything else is the presentation's: it does not decode, its holder or signer is not
35//! the linking DID, or its signature or time claims do not hold.
36//!
37//! # A linked presentation proves control at link time only
38//!
39//! Anyone can fetch a linked presentation and replay it, and it says nothing about who
40//! controls the DID now. A verifier must not grant access on a linked presentation alone, but
41//! ask the holder for an interactive proof of control, as the specification's security
42//! considerations require. Hashlinks (`hl=` in a URL) are passed through and not verified.
43//!
44//! # `typ`
45//!
46//! The specification does not constrain `typ`. Its example presentation carries the literal
47//! `'vp+ld+jwt'`, stray quotes included, and its credential `'vc+ld+jwt'`; the validator
48//! accepts these ([`PRESENTATION_TYP`], [`CREDENTIAL_TYP`]) next to `JWT` and no `typ`. The
49//! builder writes `JWT`.
50//!
51//! # Examples
52//!
53//! The specification's example document lists two presentations, one over HTTPS and one on
54//! IPFS:
55//!
56//! ```
57//! use identity_kit::did::DidDocument;
58//! use identity_kit::linked_vp::services;
59//! use serde_json::json;
60//!
61//! let document: DidDocument = serde_json::from_value(json!({
62//! "@context": ["https://www.w3.org/ns/did/v1", "https://identity.foundation/linked-vp/contexts/v1"],
63//! "id": "did:example:123",
64//! "service": [
65//! {
66//! "id": "did:example:123#foo",
67//! "type": "LinkedVerifiablePresentation",
68//! "serviceEndpoint": ["https://bar.example.com/verifiable-presentation.jsonld"]
69//! },
70//! {
71//! "id": "did:example:123#baz",
72//! "type": "LinkedVerifiablePresentation",
73//! "serviceEndpoint": "ipfs://bafybeihkoviema7g3gxyt6la7vd5ho32ictqbilu3wnlo3rs7ewhnp7lly/verifiable-presentation.jwt"
74//! }
75//! ]
76//! }))?;
77//! let urls: Vec<String> = services(&document)
78//! .map(|service| service.map(|service| service.urls[0].to_string()))
79//! .collect::<Result<_, _>>()?;
80//! assert_eq!(urls, [
81//! "https://bar.example.com/verifiable-presentation.jsonld",
82//! "ipfs://bafybeihkoviema7g3gxyt6la7vd5ho32ictqbilu3wnlo3rs7ewhnp7lly/verifiable-presentation.jwt",
83//! ]);
84//! # Ok::<(), Box<dyn std::error::Error>>(())
85//! ```
86
87use std::collections::BTreeSet;
88use std::error::Error;
89
90use chrono::{DateTime, Utc};
91use url::Url;
92
93use crate::cause::cause;
94use crate::did::{Did, DidDocument, DidUrl, ResolutionError, Service, ServiceEndpoint, Uri};
95use crate::jose::{DefaultVerifier, JwsError, JwsHeader, JwsVerifier, Signer};
96use crate::methods::web::{HttpClient, HttpError, fetchable};
97use crate::resolver::Resolver;
98use crate::vc::validation::{
99 CredentialValidationOptions, DecodedCredential, DecodedPresentation, FailFast,
100 JwtPresentationValidator, KeyReference, KeyResolver, PresentationValidationError,
101 PresentationValidationOptions, SubjectHolderRelationship, TimeOptions, ValidationError,
102 decode_presentation_entries, extract_holder,
103};
104use crate::vc::{CredentialError, Jwt, JwtClaims, Party, Presentation};
105
106/// The service type, `LinkedVerifiablePresentation`.
107pub const SERVICE_TYPE: &str = "LinkedVerifiablePresentation";
108
109/// The JSON-LD context defining [`SERVICE_TYPE`], for the `@context` of a DID document that
110/// lists linked presentations.
111pub const CONTEXT: &str = "https://identity.foundation/linked-vp/contexts/v1";
112
113/// The header `typ` values a linked presentation may carry besides `JWT`: `vp+ld+jwt`, and the
114/// literal `'vp+ld+jwt'` with the single quotes of the specification's example.
115pub const PRESENTATION_TYP: [&str; 2] = ["vp+ld+jwt", "'vp+ld+jwt'"];
116
117/// The header `typ` values a credential in a linked presentation may carry besides `JWT`:
118/// `vc+ld+jwt`, and the literal `'vc+ld+jwt'` of the specification's example.
119pub const CREDENTIAL_TYP: [&str; 2] = ["vc+ld+jwt", "'vc+ld+jwt'"];
120
121/// A `LinkedVerifiablePresentation` service of `id` pointing to `urls`.
122///
123/// # Errors
124///
125/// [`LinkedVpError::InvalidService`] when `urls` is empty or a URL is not an RFC 3986 URI.
126///
127/// # Examples
128///
129/// ```
130/// use identity_kit::did::{DidUrl, ServiceEndpoint};
131/// use identity_kit::linked_vp::{SERVICE_TYPE, service};
132/// use url::Url;
133///
134/// let service = service(
135/// DidUrl::parse("did:example:123#foo")?,
136/// [Url::parse("https://bar.example.com/verifiable-presentation.jwt")?],
137/// )?;
138/// assert!(service.has_type(SERVICE_TYPE));
139/// assert!(matches!(service.service_endpoint, ServiceEndpoint::Uri(_)));
140/// # Ok::<(), Box<dyn std::error::Error>>(())
141/// ```
142#[expect(
143 clippy::similar_names,
144 reason = "the URLs given and the URIs of the service endpoint are both needed"
145)]
146pub fn service(id: DidUrl, urls: impl IntoIterator<Item = Url>) -> Result<Service, LinkedVpError> {
147 let mut uris = Vec::new();
148 for url in urls {
149 let uri = Uri::parse(url.as_str()).map_err(|e| LinkedVpError::InvalidService {
150 id: id.clone(),
151 reason: format!("`{url}` is not a URI"),
152 source: Some(Box::new(e)),
153 })?;
154 uris.push(uri);
155 }
156 let endpoint = match <[Uri; 1]>::try_from(uris) {
157 Ok([uri]) => ServiceEndpoint::Uri(uri),
158 Err(uris) if uris.is_empty() => {
159 return Err(LinkedVpError::InvalidService {
160 id,
161 reason: "no URL".to_owned(),
162 source: None,
163 });
164 }
165 Err(uris) => ServiceEndpoint::Set(uris.into_iter().collect()),
166 };
167 Ok(Service::new(id, SERVICE_TYPE, endpoint))
168}
169
170/// A `LinkedVerifiablePresentation` service of a DID document, with its URLs.
171#[derive(Debug, Clone, PartialEq, Eq)]
172#[non_exhaustive]
173pub struct LinkedVpService<'a> {
174 /// The service entry.
175 pub service: &'a Service,
176 /// Its URLs, in document order: the endpoint URIs that parse as URLs.
177 pub urls: Vec<Url>,
178 /// The endpoint URIs that do not parse as URLs, in document order, each with why. They
179 /// do not hide the service's other URLs.
180 pub invalid_urls: Vec<(Uri, url::ParseError)>,
181}
182
183impl LinkedVpService<'_> {
184 /// The id of the service.
185 pub fn id(&self) -> &DidUrl {
186 &self.service.id
187 }
188}
189
190/// The `LinkedVerifiablePresentation` services of `document`, in document order. A service of
191/// that type whose endpoint is a map, or names no URL at all, is a
192/// [`LinkedVpError::InvalidService`] rather than silently skipped. An endpoint URI that is not
193/// a URL (`https://example.org:99999/vp`, whose port is out of range) is listed in
194/// [`LinkedVpService::invalid_urls`] and leaves the service's other URLs in place.
195pub fn services(
196 document: &DidDocument,
197) -> impl Iterator<Item = Result<LinkedVpService<'_>, LinkedVpError>> {
198 document
199 .service
200 .iter()
201 .filter(|service| service.has_type(SERVICE_TYPE))
202 .map(linked_vp_service)
203}
204
205/// `service` with its URLs parsed.
206fn linked_vp_service(service: &Service) -> Result<LinkedVpService<'_>, LinkedVpError> {
207 let invalid = |reason: String, source: Option<Box<dyn Error + Send + Sync>>| {
208 LinkedVpError::InvalidService {
209 id: service.id.clone(),
210 reason,
211 source,
212 }
213 };
214 if matches!(service.service_endpoint, ServiceEndpoint::Map(_)) {
215 return Err(invalid(
216 "`serviceEndpoint` is a map, not URLs".to_owned(),
217 None,
218 ));
219 }
220 let mut urls = Vec::new();
221 let mut invalid_urls = Vec::new();
222 for uri in service.service_endpoint.uris() {
223 match Url::parse(uri.as_str()) {
224 Ok(url) => urls.push(url),
225 Err(e) => invalid_urls.push((uri.clone(), e)),
226 }
227 }
228 if urls.is_empty() {
229 return Err(match invalid_urls.into_iter().next() {
230 Some((uri, e)) => invalid(format!("`{uri}` is not a URL"), Some(Box::new(e))),
231 None => invalid("no URL".to_owned(), None),
232 });
233 }
234 Ok(LinkedVpService {
235 service,
236 urls,
237 invalid_urls,
238 })
239}
240
241/// The report of `uri`, an endpoint URI of `service` that is not a URL.
242fn invalid_url(service: &Service, uri: &Uri, error: url::ParseError) -> LinkedPresentationReport {
243 LinkedPresentationReport {
244 service: service.id.clone(),
245 url: None,
246 result: Err(LinkedVpError::InvalidService {
247 id: service.id.clone(),
248 reason: format!("`{uri}` is not a URL"),
249 source: Some(Box::new(error)),
250 }),
251 }
252}
253
254/// Builds a linked presentation in the JSON Web Token form: a VCDM 1.1 presentation of
255/// credential JWTs held by `holder`, with `iss`, `sub` and `holder` the holder, `jti` the
256/// presentation's `id`, `iat` and `nbf` the issuance time, `exp` when an expiration is set,
257/// and neither `aud` nor `nonce`.
258///
259/// # Examples
260///
261/// ```
262/// use chrono::{TimeZone as _, Utc};
263/// use identity_kit::did::{Did, Uri};
264/// use identity_kit::linked_vp::LinkedPresentationBuilder;
265///
266/// let holder = Did::parse("did:example:123")?;
267/// let claims = LinkedPresentationBuilder::new(holder)
268/// .with_id(Uri::parse("https://bar.example.com/verifiable-presentation.jwt")?)
269/// .with_issued_at(Utc.with_ymd_and_hms(2024, 2, 8, 17, 38, 46).unwrap())
270/// .with_expiration(Utc.with_ymd_and_hms(2029, 2, 8, 17, 38, 46).unwrap())
271/// .jwt_claims()?;
272/// assert_eq!(claims.iss.as_deref(), Some("did:example:123"));
273/// assert_eq!(claims.sub, claims.iss);
274/// assert_eq!((claims.iat, claims.nbf, claims.exp), (Some(1707413926), Some(1707413926), Some(1865266726)));
275/// assert_eq!(claims.jti.as_deref(), Some("https://bar.example.com/verifiable-presentation.jwt"));
276/// assert!(claims.aud.is_none() && !claims.additional.contains_key("nonce"));
277/// # Ok::<(), Box<dyn std::error::Error>>(())
278/// ```
279#[derive(Debug, Clone, PartialEq, Eq)]
280#[non_exhaustive]
281pub struct LinkedPresentationBuilder {
282 /// The holder: the DID whose document links the presentation.
283 pub holder: Did,
284 /// The presentation's `id`, usually the URL it is published at.
285 pub id: Option<Uri>,
286 /// The credential JWTs.
287 pub credentials: Vec<Jwt>,
288 /// `iat` and `nbf`.
289 pub issued_at: DateTime<Utc>,
290 /// `exp`, if the presentation expires.
291 pub expiration: Option<DateTime<Utc>>,
292}
293
294impl LinkedPresentationBuilder {
295 /// A presentation by `holder` of no credentials, issued now, without `id` or expiration.
296 pub fn new(holder: Did) -> Self {
297 Self {
298 holder,
299 id: None,
300 credentials: Vec::new(),
301 issued_at: Utc::now(),
302 expiration: None,
303 }
304 }
305
306 /// This presentation with its `id` set.
307 #[must_use]
308 pub fn with_id(mut self, id: impl Into<Uri>) -> Self {
309 self.id = Some(id.into());
310 self
311 }
312
313 /// This presentation with `credential` added.
314 #[must_use]
315 pub fn with_credential(mut self, credential: Jwt) -> Self {
316 self.credentials.push(credential);
317 self
318 }
319
320 /// This presentation issued at `issued_at`.
321 #[must_use]
322 pub fn with_issued_at(mut self, issued_at: DateTime<Utc>) -> Self {
323 self.issued_at = issued_at;
324 self
325 }
326
327 /// This presentation expiring at `expiration`, which the specification recommends to limit
328 /// how long a published presentation stays valid.
329 #[must_use]
330 pub fn with_expiration(mut self, expiration: DateTime<Utc>) -> Self {
331 self.expiration = Some(expiration);
332 self
333 }
334
335 /// The presentation.
336 pub fn presentation(&self) -> Presentation {
337 let mut presentation = Presentation::new().with_holder(self.holder.clone());
338 if let Some(id) = &self.id {
339 presentation = presentation.with_id(id.clone());
340 }
341 self.credentials
342 .iter()
343 .fold(presentation, |presentation, credential| {
344 presentation.with_credential(credential.clone())
345 })
346 }
347
348 /// The JWT claims: the presentation's (`iss`, `jti`, `vp`) with `sub`, `iat`, `nbf` and
349 /// `exp`.
350 ///
351 /// # Errors
352 ///
353 /// A [`CredentialError`] when the presentation does not map to claims; one built here
354 /// always does.
355 pub fn jwt_claims(&self) -> Result<JwtClaims, CredentialError> {
356 let mut claims = self
357 .presentation()
358 .to_jwt_claims()?
359 .with_sub(self.holder.as_str())
360 .with_iat(self.issued_at)
361 .with_nbf(self.issued_at);
362 if let Some(expiration) = self.expiration {
363 claims = claims.with_exp(expiration);
364 }
365 Ok(claims)
366 }
367
368 /// The presentation signed with `signer` under a header of `alg`, `typ` `JWT` and `kid`,
369 /// `kid` naming a verification method of the holder, which a verifier resolves under
370 /// `authentication`.
371 ///
372 /// # Errors
373 ///
374 /// [`LinkedVpError::Validation`] with [`ValidationError::HolderMismatch`] when `kid` is not
375 /// a key of the holder, or with [`ValidationError::Jws`] when signing fails.
376 pub async fn sign(&self, kid: &DidUrl, signer: &dyn Signer) -> Result<Jwt, LinkedVpError> {
377 if kid.did() != &self.holder {
378 return Err(ValidationError::HolderMismatch {
379 holder: self.holder.clone().into(),
380 key: Box::new(KeyReference::DidUrl(kid.clone())),
381 }
382 .into());
383 }
384 let header = JwsHeader::new(signer.alg())
385 .with_typ("JWT")
386 .with_kid(kid.as_str());
387 let claims = self.jwt_claims().map_err(ValidationError::from)?;
388 let jwt = Jwt::sign(&header, &claims, signer)
389 .await
390 .map_err(ValidationError::from)?;
391 Ok(jwt)
392 }
393}
394
395/// Why a linked presentation could not be found, fetched or validated.
396#[derive(Debug, thiserror::Error)]
397#[non_exhaustive]
398pub enum LinkedVpError {
399 /// A `LinkedVerifiablePresentation` service does not name one or more URLs. The source
400 /// is the URI or URL error, when there is one.
401 #[error("service `{id}`: {reason}{}", cause(.source.as_ref()))]
402 InvalidService {
403 /// The id of the service.
404 id: DidUrl,
405 /// What is wrong with it.
406 reason: String,
407 /// The underlying error.
408 source: Option<Box<dyn Error + Send + Sync>>,
409 },
410 /// A URL is not `https`: an `ipfs://` endpoint, say. Only HTTPS is fetched.
411 #[error("`{0}` is not an HTTPS URL")]
412 UnsupportedEndpoint(Url),
413 /// The [`HttpClient`] got no response.
414 #[error("fetching `{url}` failed: {source}")]
415 Http {
416 /// The URL fetched.
417 url: Url,
418 /// Why there was no response.
419 #[source]
420 source: HttpError,
421 },
422 /// The server answered with a status other than `2xx`.
423 #[error("fetching `{url}` returned HTTP {status}")]
424 HttpStatus {
425 /// The URL fetched.
426 url: Url,
427 /// The status code.
428 status: u16,
429 },
430 /// The body is a JSON object: a presentation in the JSON-LD form, which this crate does
431 /// not process.
432 #[error("`{0}` serves a JSON-LD presentation, which is not supported")]
433 UnsupportedFormat(Url),
434 /// The body is not a compact JWT. The source is the UTF-8 or [`JwsError`].
435 #[error("`{url}` does not serve a compact JWT: {reason}{}", cause(.source.as_ref()))]
436 InvalidBody {
437 /// The URL fetched.
438 url: Url,
439 /// What is wrong with the body.
440 reason: &'static str,
441 /// The underlying error.
442 source: Option<Box<dyn Error + Send + Sync>>,
443 },
444 /// The presentation's holder is not the DID whose document links it.
445 #[error("the holder `{holder}` is not `{did}`, the DID linking the presentation")]
446 HolderMismatch {
447 /// The DID linking the presentation.
448 did: Did,
449 /// The holder the presentation names.
450 holder: Did,
451 },
452 /// The presentation or some of its credentials did not validate.
453 #[error(transparent)]
454 Presentation(#[from] PresentationValidationError),
455 /// The presentation did not decode, or did not sign.
456 #[error(transparent)]
457 Validation(#[from] ValidationError),
458 /// The DID did not resolve.
459 #[error("resolving the DID failed: {0}")]
460 Resolution(#[from] ResolutionError),
461 /// The URL was not fetched: the DID document lists more URLs than the client's limit,
462 /// given here.
463 #[error("the DID document lists more than {0} presentation URLs")]
464 TooManyUrls(usize),
465}
466
467/// Options of [`LinkedVpValidator`]. The audience and nonce are fixed: a linked presentation
468/// has neither.
469#[derive(Debug, Clone, Default, PartialEq, Eq)]
470#[non_exhaustive]
471pub struct LinkedVpValidationOptions {
472 /// The validation time and leeway of the presentation JWT; `exp` is honoured when present
473 /// and not required.
474 pub time: TimeOptions,
475 /// The options every credential is validated with. [`CREDENTIAL_TYP`] is accepted on top
476 /// of their `additional_typ`.
477 pub credentials: CredentialValidationOptions,
478 /// How credential subjects must relate to the holder;
479 /// [`SubjectHolderRelationship::AlwaysSubject`] by default, as the specification
480 /// recommends.
481 pub subject_holder: SubjectHolderRelationship,
482 /// Whether to stop at the first failing credential.
483 pub fail_fast: FailFast,
484}
485
486impl LinkedVpValidationOptions {
487 /// Default options: validate now without leeway, default credential options,
488 /// [`SubjectHolderRelationship::AlwaysSubject`], [`FailFast::FirstError`].
489 pub fn new() -> Self {
490 Self::default()
491 }
492
493 /// These options with `time`, for the presentation JWT only.
494 #[must_use]
495 pub fn with_time(mut self, time: TimeOptions) -> Self {
496 self.time = time;
497 self
498 }
499
500 /// These options validating credentials with `credentials`.
501 #[must_use]
502 pub fn with_credentials(mut self, credentials: CredentialValidationOptions) -> Self {
503 self.credentials = credentials;
504 self
505 }
506
507 /// These options with `relationship`.
508 #[must_use]
509 pub fn with_subject_holder(mut self, relationship: SubjectHolderRelationship) -> Self {
510 self.subject_holder = relationship;
511 self
512 }
513
514 /// These options with `fail_fast`.
515 #[must_use]
516 pub fn with_fail_fast(mut self, fail_fast: FailFast) -> Self {
517 self.fail_fast = fail_fast;
518 self
519 }
520
521 /// The options of the underlying [`JwtPresentationValidator`]: no audience, no nonce, and
522 /// [`PRESENTATION_TYP`] and [`CREDENTIAL_TYP`] accepted.
523 pub fn presentation_options(&self) -> PresentationValidationOptions {
524 let mut credentials = self.credentials.clone();
525 credentials
526 .additional_typ
527 .extend(CREDENTIAL_TYP.map(str::to_owned));
528 let mut options = PresentationValidationOptions::new()
529 .with_time(self.time)
530 .with_subject_holder(self.subject_holder)
531 .with_credentials(credentials)
532 .with_fail_fast(self.fail_fast);
533 options
534 .additional_typ
535 .extend(PRESENTATION_TYP.map(str::to_owned));
536 options
537 }
538}
539
540/// A linked presentation decoded without verification: the presentation, and each entry of
541/// its `verifiableCredential` decoded on its own.
542#[derive(Debug)]
543#[non_exhaustive]
544pub struct DecodedLinkedPresentation {
545 /// The JWS header.
546 pub header: JwsHeader,
547 /// The claims set, `vp` included.
548 pub claims: JwtClaims,
549 /// The presentation, with `iss` and `jti` mapped back into it. Its
550 /// `verifiable_credential` holds the entries that are compact JWTs.
551 pub presentation: Presentation,
552 /// One result per entry of `verifiableCredential`, in order: the credential decoded, or why
553 /// that entry is not one.
554 pub credentials: Vec<Result<DecodedCredential, ValidationError>>,
555}
556
557impl DecodedLinkedPresentation {
558 /// The holder: `holder` of the presentation, which decoding set from `iss`.
559 pub fn holder(&self) -> Option<&Uri> {
560 self.presentation.holder.as_ref().map(Party::id)
561 }
562}
563
564/// Decodes a linked presentation and its credentials without verifying or validating
565/// anything, accepting [`PRESENTATION_TYP`] and [`CREDENTIAL_TYP`]. Each entry of
566/// `verifiableCredential` decodes on its own: one that is not a credential JWT is an error in
567/// [`DecodedLinkedPresentation::credentials`], next to the others.
568///
569/// # Errors
570///
571/// As [`decode_presentation`](crate::vc::validation::decode_presentation), for the
572/// presentation alone.
573pub fn decode(jwt: &Jwt) -> Result<DecodedLinkedPresentation, ValidationError> {
574 let presentation_typ: BTreeSet<String> = PRESENTATION_TYP.map(str::to_owned).into();
575 let credential_typ: BTreeSet<String> = CREDENTIAL_TYP.map(str::to_owned).into();
576 let (decoded, credentials) =
577 decode_presentation_entries(jwt, &presentation_typ, &credential_typ)?;
578 Ok(DecodedLinkedPresentation {
579 header: decoded.header,
580 claims: decoded.claims,
581 presentation: decoded.presentation,
582 credentials,
583 })
584}
585
586/// Validates linked presentations: [`JwtPresentationValidator`] with the options fixed to the
587/// specification, plus the holder and the signer being the DID that links the presentation.
588///
589/// # Examples
590///
591/// ```
592/// # #[cfg(feature = "did-key")]
593/// # {
594/// use identity_kit::jose::DefaultVerifier;
595/// use identity_kit::linked_vp::LinkedVpValidator;
596/// use identity_kit::methods::DidKey;
597/// use identity_kit::resolver::Resolver;
598///
599/// let resolver = Resolver::builder().with(DidKey::default()).build();
600/// let validator = LinkedVpValidator::new(resolver, DefaultVerifier);
601/// assert!(!validator.presentation_validator().credential_validator().has_status_check());
602/// # }
603/// ```
604#[derive(Debug)]
605pub struct LinkedVpValidator<R, V = DefaultVerifier> {
606 presentations: JwtPresentationValidator<R, V>,
607}
608
609impl<R: KeyResolver, V: JwsVerifier> LinkedVpValidator<R, V> {
610 /// A validator resolving keys with `resolver` and verifying signatures with `verifier`.
611 pub fn new(resolver: R, verifier: V) -> Self {
612 Self {
613 presentations: JwtPresentationValidator::new(resolver, verifier),
614 }
615 }
616
617 /// A validator over `presentations`, with its status check.
618 pub fn from_presentation_validator(presentations: JwtPresentationValidator<R, V>) -> Self {
619 Self { presentations }
620 }
621
622 /// The presentation validator.
623 pub fn presentation_validator(&self) -> &JwtPresentationValidator<R, V> {
624 &self.presentations
625 }
626
627 /// Validates `jwt` as a presentation linked from the document of `did`.
628 ///
629 /// The holder, and the party the token's [`KeyReference`] names, are checked against
630 /// `did` before any key is resolved, so a presentation naming another DID never makes the
631 /// resolver fetch that DID's document: a DID URL must be of `did`, a key by value must be
632 /// the `did:jwk` of `did`, and a key set of an HTTPS issuer never belongs to a DID.
633 ///
634 /// # Errors
635 ///
636 /// [`LinkedVpError::HolderMismatch`] when the holder is not `did`, otherwise
637 /// [`LinkedVpError::Presentation`] with what [`JwtPresentationValidator::validate`]
638 /// reports; a key of another DID is a [`ValidationError::HolderMismatch`] there.
639 pub async fn validate(
640 &self,
641 jwt: &Jwt,
642 did: &Did,
643 options: &LinkedVpValidationOptions,
644 ) -> Result<DecodedPresentation, LinkedVpError> {
645 let holder = extract_holder(jwt).map_err(PresentationValidationError::presentation)?;
646 if holder != *did {
647 return Err(LinkedVpError::HolderMismatch {
648 did: did.clone(),
649 holder,
650 });
651 }
652 let jws = jwt
653 .decode()
654 .map_err(|e| PresentationValidationError::presentation(e.into()))?;
655 if let Ok(reference) = KeyReference::from_jws(&jws, Some(did.as_str())) {
656 let of_did = match &reference {
657 KeyReference::DidUrl(url) => url.did() == did,
658 KeyReference::Jwk(jwk) => reference.binds_to(Some(did.as_str()), jwk),
659 _ => false,
660 };
661 if !of_did {
662 return Err(PresentationValidationError::presentation(
663 ValidationError::HolderMismatch {
664 holder: did.clone().into(),
665 key: Box::new(reference),
666 },
667 )
668 .into());
669 }
670 }
671 let decoded = self
672 .presentations
673 .validate(jwt, &options.presentation_options())
674 .await?;
675 Ok(decoded)
676 }
677}
678
679/// What became of one URL of a `LinkedVerifiablePresentation` service.
680#[derive(Debug)]
681#[non_exhaustive]
682pub struct LinkedPresentationReport {
683 /// The id of the service.
684 pub service: DidUrl,
685 /// The URL; `None` when the service entry itself is invalid.
686 pub url: Option<Url>,
687 /// The presentation, validated, or why it was not.
688 pub result: Result<DecodedPresentation, LinkedVpError>,
689}
690
691/// Fetches the presentations a DID document links with an [`HttpClient`] and validates them
692/// with a [`LinkedVpValidator`].
693///
694/// The URLs come from the document, so the client fetches whatever its controller names:
695/// `http` must enforce the protections `ReqwestClient` (feature `reqwest`) does (HTTPS only,
696/// no redirects, no non-public addresses after name resolution, a body limit and a timeout),
697/// or fetching becomes a request forgery primitive. A DID document can also list any number of
698/// URLs, so [`validate_document`](Self::validate_document) fetches at most
699/// [`max_urls`](Self::max_urls) of them.
700#[derive(Debug)]
701pub struct LinkedVpClient<C, R, V = DefaultVerifier> {
702 http: C,
703 validator: LinkedVpValidator<R, V>,
704 max_urls: usize,
705}
706
707impl<C, R, V> LinkedVpClient<C, R, V> {
708 /// The most URLs [`new`](Self::new) fetches for one DID document: 32.
709 pub const DEFAULT_MAX_URLS: usize = 32;
710}
711
712impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> LinkedVpClient<C, R, V> {
713 /// A client fetching with `http` and validating with `validator`, fetching at most
714 /// [`DEFAULT_MAX_URLS`](Self::DEFAULT_MAX_URLS) URLs of a DID document.
715 pub fn new(http: C, validator: LinkedVpValidator<R, V>) -> Self {
716 Self {
717 http,
718 validator,
719 max_urls: Self::DEFAULT_MAX_URLS,
720 }
721 }
722
723 /// This client fetching at most `max_urls` URLs of a DID document.
724 #[must_use]
725 pub fn with_max_urls(mut self, max_urls: usize) -> Self {
726 self.max_urls = max_urls;
727 self
728 }
729
730 /// The most URLs [`validate_document`](Self::validate_document) fetches for one document.
731 pub fn max_urls(&self) -> usize {
732 self.max_urls
733 }
734
735 /// The HTTP client.
736 pub fn http(&self) -> &C {
737 &self.http
738 }
739
740 /// The validator.
741 pub fn validator(&self) -> &LinkedVpValidator<R, V> {
742 &self.validator
743 }
744
745 /// The presentation JWT at `url`, unverified: the body, trimmed, must be one compact JWT.
746 ///
747 /// # Errors
748 ///
749 /// [`LinkedVpError::UnsupportedEndpoint`] for a URL that is not `https`, without fetching,
750 /// unless the client [allows plain `http`](HttpClient::allows_plain_http) for it;
751 /// [`LinkedVpError::Http`] or [`LinkedVpError::HttpStatus`] when there is no `2xx`
752 /// response; [`LinkedVpError::UnsupportedFormat`] for a JSON-LD presentation;
753 /// [`LinkedVpError::InvalidBody`] for anything else that is not a compact JWT.
754 pub async fn fetch(&self, url: &Url) -> Result<Jwt, LinkedVpError> {
755 if !fetchable(&self.http, url) {
756 return Err(LinkedVpError::UnsupportedEndpoint(url.clone()));
757 }
758 let response = self
759 .http
760 .get(url)
761 .await
762 .map_err(|source| LinkedVpError::Http {
763 url: url.clone(),
764 source,
765 })?;
766 if !(200..300).contains(&response.status) {
767 return Err(LinkedVpError::HttpStatus {
768 url: url.clone(),
769 status: response.status,
770 });
771 }
772 let invalid = |reason: &'static str, source: Box<dyn Error + Send + Sync>| {
773 LinkedVpError::InvalidBody {
774 url: url.clone(),
775 reason,
776 source: Some(source),
777 }
778 };
779 let body = core::str::from_utf8(&response.body)
780 .map_err(|e| invalid("the body is not UTF-8", Box::new(e)))?
781 .trim();
782 if body.starts_with('{') {
783 return Err(LinkedVpError::UnsupportedFormat(url.clone()));
784 }
785 Jwt::new(body).map_err(|e: JwsError| invalid("not a compact JWS", Box::new(e)))
786 }
787
788 /// Fetches and validates `url` as a presentation linked from the document of `did`.
789 ///
790 /// # Errors
791 ///
792 /// As [`fetch`](Self::fetch) and [`LinkedVpValidator::validate`].
793 pub async fn validate_url(
794 &self,
795 url: &Url,
796 did: &Did,
797 options: &LinkedVpValidationOptions,
798 ) -> Result<DecodedPresentation, LinkedVpError> {
799 let jwt = self.fetch(url).await?;
800 self.validator.validate(&jwt, did, options).await
801 }
802
803 /// Fetches and validates every presentation `document` links, one report per URL in
804 /// document order, one for each endpoint URI that is not a URL, and one for each invalid
805 /// service entry. URLs past the first [`max_urls`](Self::max_urls) are not fetched and
806 /// report [`LinkedVpError::TooManyUrls`].
807 pub async fn validate_document(
808 &self,
809 document: &DidDocument,
810 options: &LinkedVpValidationOptions,
811 ) -> Vec<LinkedPresentationReport> {
812 let mut reports = Vec::new();
813 let mut fetched = 0;
814 for service in document
815 .service
816 .iter()
817 .filter(|service| service.has_type(SERVICE_TYPE))
818 {
819 if let Err(error) = linked_vp_service(service) {
820 reports.push(LinkedPresentationReport {
821 service: service.id.clone(),
822 url: None,
823 result: Err(error),
824 });
825 continue;
826 }
827 for uri in service.service_endpoint.uris() {
828 let url = match Url::parse(uri.as_str()) {
829 Ok(url) => url,
830 Err(error) => {
831 reports.push(invalid_url(service, uri, error));
832 continue;
833 }
834 };
835 let result = if fetched < self.max_urls {
836 fetched += 1;
837 self.validate_url(&url, &document.id, options).await
838 } else {
839 Err(LinkedVpError::TooManyUrls(self.max_urls))
840 };
841 reports.push(LinkedPresentationReport {
842 service: service.id.clone(),
843 url: Some(url),
844 result,
845 });
846 }
847 }
848 reports
849 }
850}
851
852impl<C: HttpClient, V: JwsVerifier> LinkedVpClient<C, Resolver, V> {
853 /// Resolves `did` with the validator's resolver, then validates every presentation its
854 /// document links, as [`validate_document`](Self::validate_document).
855 ///
856 /// # Errors
857 ///
858 /// [`LinkedVpError::Resolution`] when `did` does not resolve to a document.
859 pub async fn validate_did(
860 &self,
861 did: &Did,
862 options: &LinkedVpValidationOptions,
863 ) -> Result<Vec<LinkedPresentationReport>, LinkedVpError> {
864 let document = self
865 .validator
866 .presentation_validator()
867 .credential_validator()
868 .resolver()
869 .resolve_document(did)
870 .await?;
871 Ok(self.validate_document(&document, options).await)
872 }
873}