Skip to main content

identity_kit/did/
document.rs

1//! The DID document data model (DID Core §5) and operations on it.
2
3use core::fmt;
4use core::mem;
5use core::str::FromStr;
6use std::borrow::Cow;
7use std::collections::{HashMap, HashSet};
8
9use indexmap::{IndexMap, IndexSet};
10use serde::de::{self, MapAccess, SeqAccess, Visitor};
11use serde::ser::SerializeMap as _;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13use serde_json::Value;
14
15use super::{Did, DidUrl, DidUrlReference, Uri};
16use crate::jose::{Jwk, OneOrMany};
17
18/// Why a [`DidDocument`] operation was refused.
19#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20#[non_exhaustive]
21pub enum DocumentError {
22    /// `@context` is not a string, a map or a non-empty array.
23    #[error("`@context` must be a string, a map or a non-empty array")]
24    InvalidContext,
25    /// A verification method with this id is already in the document, or the document defines
26    /// the id twice with different material.
27    #[error("verification method `{0}` already exists")]
28    DuplicateVerificationMethod(DidUrl),
29    /// A service with this id is already in the document.
30    #[error("service `{0}` already exists")]
31    DuplicateService(DidUrl),
32    /// No verification method with this id is in the document.
33    #[error("verification method `{0}` not found")]
34    VerificationMethodNotFound(DidUrl),
35    /// The DID URL belongs to another DID than the document.
36    #[error("`{url}` does not belong to document `{document}`")]
37    ForeignDid {
38        /// The DID URL that was looked up.
39        url: DidUrl,
40        /// The `id` of the document.
41        document: Did,
42    },
43    /// The verification method exists but is not listed under the relationship.
44    #[error("verification method `{id}` is not listed under `{relationship}`")]
45    NotInRelationship {
46        /// The id of the verification method.
47        id: DidUrl,
48        /// The relationship that was required.
49        relationship: VerificationRelationship,
50    },
51    /// Not the name of a verification relationship.
52    #[error("unknown verification relationship `{0}`")]
53    UnknownRelationship(String),
54    /// An extension property with the name of a core property.
55    #[error("`{0}` is a core property, not an extension property")]
56    ReservedProperty(String),
57}
58
59// ---------------------------------------------------------------------------------------------
60// Building blocks
61// ---------------------------------------------------------------------------------------------
62
63/// `skip_serializing_if` for optional lists: `None` and empty lists are omitted alike.
64fn is_none_or_empty<T>(value: &Option<OneOrMany<T>>) -> bool {
65    value.as_ref().is_none_or(OneOrMany::is_empty)
66}
67
68/// The `@context` of a DID document, carried verbatim: a string, a map or a non-empty array of
69/// them.
70///
71/// This crate does no JSON-LD processing; the context is data that round-trips.
72///
73/// # Examples
74///
75/// ```
76/// use identity_kit::did::Context;
77///
78/// let context = Context::uris([Context::DID_V1, "https://w3id.org/security/suites/jws-2020/v1"]);
79/// assert!(context.contains(Context::DID_V1));
80/// assert_eq!(
81///     serde_json::to_string(&context)?,
82///     r#"["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"]"#
83/// );
84/// # Ok::<(), serde_json::Error>(())
85/// ```
86#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87#[serde(transparent)]
88pub struct Context(Value);
89
90impl Context {
91    /// The DID Core 1.0 context URI.
92    pub const DID_V1: &'static str = "https://www.w3.org/ns/did/v1";
93
94    /// The context `"https://www.w3.org/ns/did/v1"`.
95    pub fn did_v1() -> Self {
96        Self::uri(Self::DID_V1)
97    }
98
99    /// A single context URI.
100    pub fn uri(uri: impl Into<String>) -> Self {
101        Self(Value::String(uri.into()))
102    }
103
104    /// An array of context URIs.
105    pub fn uris<I, S>(uris: I) -> Self
106    where
107        I: IntoIterator<Item = S>,
108        S: Into<String>,
109    {
110        Self(Value::Array(
111            uris.into_iter().map(|s| Value::String(s.into())).collect(),
112        ))
113    }
114
115    /// Any JSON value allowed as a context.
116    ///
117    /// # Errors
118    ///
119    /// [`DocumentError::InvalidContext`] unless `value` is a string, a map or a non-empty array.
120    pub fn new(value: Value) -> Result<Self, DocumentError> {
121        match &value {
122            Value::String(_) | Value::Object(_) => Ok(Self(value)),
123            Value::Array(items) if !items.is_empty() => Ok(Self(value)),
124            _ => Err(DocumentError::InvalidContext),
125        }
126    }
127
128    /// The context as JSON.
129    pub fn as_value(&self) -> &Value {
130        &self.0
131    }
132
133    /// The context as JSON.
134    pub fn into_value(self) -> Value {
135        self.0
136    }
137
138    /// Whether `uri` is the context or one of the strings in the context array.
139    pub fn contains(&self, uri: &str) -> bool {
140        match &self.0 {
141            Value::String(s) => s == uri,
142            Value::Array(items) => items.iter().any(|item| item.as_str() == Some(uri)),
143            _ => false,
144        }
145    }
146}
147
148impl<'de> Deserialize<'de> for Context {
149    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
150        Self::new(Value::deserialize(deserializer)?).map_err(de::Error::custom)
151    }
152}
153
154/// A verification relationship (DID Core §5.3): the purpose a verification method may be used
155/// for. The `Display` and `FromStr` forms are the DID document property names.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
157#[serde(rename_all = "camelCase")]
158pub enum VerificationRelationship {
159    /// `authentication`
160    Authentication,
161    /// `assertionMethod`
162    AssertionMethod,
163    /// `keyAgreement`
164    KeyAgreement,
165    /// `capabilityInvocation`
166    CapabilityInvocation,
167    /// `capabilityDelegation`
168    CapabilityDelegation,
169}
170
171impl VerificationRelationship {
172    /// Every relationship, in the order DID Core lists them.
173    pub const ALL: &'static [VerificationRelationship] = &[
174        Self::Authentication,
175        Self::AssertionMethod,
176        Self::KeyAgreement,
177        Self::CapabilityInvocation,
178        Self::CapabilityDelegation,
179    ];
180
181    /// The DID document property name, for example `assertionMethod`.
182    pub const fn as_str(self) -> &'static str {
183        match self {
184            Self::Authentication => "authentication",
185            Self::AssertionMethod => "assertionMethod",
186            Self::KeyAgreement => "keyAgreement",
187            Self::CapabilityInvocation => "capabilityInvocation",
188            Self::CapabilityDelegation => "capabilityDelegation",
189        }
190    }
191}
192
193impl fmt::Display for VerificationRelationship {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        f.write_str(self.as_str())
196    }
197}
198
199impl FromStr for VerificationRelationship {
200    type Err = DocumentError;
201
202    fn from_str(s: &str) -> Result<Self, Self::Err> {
203        Self::ALL
204            .iter()
205            .copied()
206            .find(|rel| rel.as_str() == s)
207            .ok_or_else(|| DocumentError::UnknownRelationship(s.to_owned()))
208    }
209}
210
211/// The `type` of a verification method: an open string with constants for the types this crate
212/// produces.
213///
214/// # Examples
215///
216/// ```
217/// use identity_kit::did::MethodType;
218///
219/// assert_eq!(MethodType::JSON_WEB_KEY_2020.as_str(), "JsonWebKey2020");
220/// assert_eq!(MethodType::new("JsonWebKey2020"), MethodType::JSON_WEB_KEY_2020);
221/// assert_eq!(serde_json::to_string(&MethodType::MULTIKEY)?, "\"Multikey\"");
222/// # Ok::<(), serde_json::Error>(())
223/// ```
224#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
225pub struct MethodType(Cow<'static, str>);
226
227impl MethodType {
228    /// `JsonWebKey2020`: `publicKeyJwk` material (JSON Web Signature 2020 suite).
229    pub const JSON_WEB_KEY_2020: MethodType = MethodType(Cow::Borrowed("JsonWebKey2020"));
230    /// `JsonWebKey`: `publicKeyJwk` material (Controlled Identifiers 1.0).
231    pub const JSON_WEB_KEY: MethodType = MethodType(Cow::Borrowed("JsonWebKey"));
232    /// `Multikey`: `publicKeyMultibase` material (Controlled Identifiers 1.0).
233    pub const MULTIKEY: MethodType = MethodType(Cow::Borrowed("Multikey"));
234    /// `Ed25519VerificationKey2020`: `publicKeyMultibase` material (Ed25519 Signature 2020 suite).
235    pub const ED25519_VERIFICATION_KEY_2020: MethodType =
236        MethodType(Cow::Borrowed("Ed25519VerificationKey2020"));
237
238    /// Any type name.
239    pub fn new(name: impl Into<String>) -> Self {
240        Self(Cow::Owned(name.into()))
241    }
242
243    /// The type name.
244    pub fn as_str(&self) -> &str {
245        &self.0
246    }
247}
248
249impl fmt::Debug for MethodType {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        fmt::Debug::fmt(self.as_str(), f)
252    }
253}
254
255impl fmt::Display for MethodType {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        f.write_str(self.as_str())
258    }
259}
260
261impl From<&str> for MethodType {
262    fn from(name: &str) -> Self {
263        Self::new(name)
264    }
265}
266
267impl From<String> for MethodType {
268    fn from(name: String) -> Self {
269        Self::new(name)
270    }
271}
272
273impl PartialEq<str> for MethodType {
274    fn eq(&self, other: &str) -> bool {
275        self.as_str() == other
276    }
277}
278
279impl PartialEq<&str> for MethodType {
280    fn eq(&self, other: &&str) -> bool {
281        self.as_str() == *other
282    }
283}
284
285impl Serialize for MethodType {
286    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
287        serializer.serialize_str(self.as_str())
288    }
289}
290
291impl<'de> Deserialize<'de> for MethodType {
292    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
293        String::deserialize(deserializer).map(Self::new)
294    }
295}
296
297// ---------------------------------------------------------------------------------------------
298// Verification methods
299// ---------------------------------------------------------------------------------------------
300
301/// The verification material of a verification method (DID Core §5.2.1): exactly one of
302/// `publicKeyJwk` and `publicKeyMultibase`.
303///
304/// A `publicKeyJwk` must not carry private parameters; such a key is rejected when read and
305/// refused when written.
306#[derive(Debug, Clone, PartialEq, Eq)]
307#[non_exhaustive]
308pub enum VerificationMaterial {
309    /// `publicKeyJwk`: a public JSON Web Key.
310    PublicKeyJwk(Box<Jwk>),
311    /// `publicKeyMultibase`: a multibase-encoded public key.
312    PublicKeyMultibase(String),
313}
314
315impl VerificationMaterial {
316    /// `publicKeyJwk` with the public part of `jwk`.
317    pub fn jwk(jwk: &Jwk) -> Self {
318        Self::PublicKeyJwk(Box::new(jwk.public()))
319    }
320
321    /// `publicKeyMultibase`.
322    pub fn multibase(value: impl Into<String>) -> Self {
323        Self::PublicKeyMultibase(value.into())
324    }
325
326    /// The JWK, when the material is `publicKeyJwk`.
327    pub fn as_jwk(&self) -> Option<&Jwk> {
328        match self {
329            Self::PublicKeyJwk(jwk) => Some(jwk),
330            Self::PublicKeyMultibase(_) => None,
331        }
332    }
333
334    /// The multibase string, when the material is `publicKeyMultibase`.
335    pub fn as_multibase(&self) -> Option<&str> {
336        match self {
337            Self::PublicKeyMultibase(value) => Some(value),
338            Self::PublicKeyJwk(_) => None,
339        }
340    }
341}
342
343impl Serialize for VerificationMaterial {
344    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
345        let mut map = serializer.serialize_map(Some(1))?;
346        match self {
347            Self::PublicKeyJwk(jwk) => {
348                if jwk.is_private() {
349                    return Err(serde::ser::Error::custom(
350                        "`publicKeyJwk` must not contain private parameters",
351                    ));
352                }
353                map.serialize_entry("publicKeyJwk", jwk)?;
354            }
355            Self::PublicKeyMultibase(value) => map.serialize_entry("publicKeyMultibase", value)?,
356        }
357        map.end()
358    }
359}
360
361/// The two material members as optional fields, so they can be flattened out of a method.
362#[derive(Deserialize)]
363struct MaterialMembers {
364    #[serde(rename = "publicKeyJwk", default)]
365    public_key_jwk: Option<Jwk>,
366    #[serde(rename = "publicKeyMultibase", default)]
367    public_key_multibase: Option<String>,
368}
369
370impl<'de> Deserialize<'de> for VerificationMaterial {
371    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
372        let members = MaterialMembers::deserialize(deserializer)?;
373        match (members.public_key_jwk, members.public_key_multibase) {
374            (Some(jwk), None) if jwk.is_private() => Err(de::Error::custom(
375                "`publicKeyJwk` must not contain private parameters",
376            )),
377            (Some(jwk), None) => Ok(Self::PublicKeyJwk(Box::new(jwk))),
378            (None, Some(value)) => Ok(Self::PublicKeyMultibase(value)),
379            (None, None) => Err(de::Error::custom(
380                "verification method has neither `publicKeyJwk` nor `publicKeyMultibase`",
381            )),
382            (Some(_), Some(_)) => Err(de::Error::custom(
383                "verification method has both `publicKeyJwk` and `publicKeyMultibase`",
384            )),
385        }
386    }
387}
388
389/// A verification method (DID Core §5.2): a public key with an id, a type and a controller.
390///
391/// Members other than the four core ones live in `properties`, in insertion order.
392///
393/// # Examples
394///
395/// ```
396/// use identity_kit::did::{MethodType, VerificationMaterial, VerificationMethod};
397///
398/// let json = r#"{
399///   "id": "did:example:123#key-1",
400///   "type": "Multikey",
401///   "controller": "did:example:123",
402///   "publicKeyMultibase": "z6MkmM42vxfqZQsv4ehtTjFFxQ4sQKS2w6WR7emozFAn5cxu"
403/// }"#;
404/// let method: VerificationMethod = serde_json::from_str(json)?;
405/// assert_eq!(method.method_type, MethodType::MULTIKEY);
406/// assert_eq!(method.controller.as_str(), "did:example:123");
407/// assert_eq!(
408///     method.material.as_multibase(),
409///     Some("z6MkmM42vxfqZQsv4ehtTjFFxQ4sQKS2w6WR7emozFAn5cxu")
410/// );
411/// # Ok::<(), serde_json::Error>(())
412/// ```
413#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414#[non_exhaustive]
415pub struct VerificationMethod {
416    /// The DID URL identifying the method, usually the document DID with a fragment.
417    pub id: DidUrl,
418    /// The `type`, which tells which cryptographic suite reads the material.
419    #[serde(rename = "type")]
420    pub method_type: MethodType,
421    /// The DID of the controller of the key.
422    pub controller: Did,
423    /// `publicKeyJwk` or `publicKeyMultibase`.
424    #[serde(flatten)]
425    pub material: VerificationMaterial,
426    /// Every other member, in insertion order.
427    #[serde(flatten)]
428    pub properties: IndexMap<String, Value>,
429}
430
431impl VerificationMethod {
432    /// A verification method with the four core members.
433    pub fn new(
434        id: DidUrl,
435        method_type: MethodType,
436        controller: Did,
437        material: VerificationMaterial,
438    ) -> Self {
439        Self {
440            id,
441            method_type,
442            controller,
443            material,
444            properties: IndexMap::new(),
445        }
446    }
447
448    /// The `publicKeyJwk`, if that is the material.
449    pub fn public_key_jwk(&self) -> Option<&Jwk> {
450        self.material.as_jwk()
451    }
452
453    /// The `publicKeyMultibase`, if that is the material.
454    pub fn public_key_multibase(&self) -> Option<&str> {
455        self.material.as_multibase()
456    }
457}
458
459/// An entry of a verification relationship: a reference to a method in `verificationMethod`,
460/// or a method embedded in the relationship and usable for that purpose only (DID Core §5.3).
461#[derive(Debug, Clone, PartialEq, Eq)]
462pub enum MethodRef {
463    /// A DID URL (possibly relative) of a method listed under `verificationMethod`.
464    Reference(DidUrlReference),
465    /// A method defined in place.
466    Embedded(Box<VerificationMethod>),
467}
468
469impl MethodRef {
470    /// A reference to `id`.
471    pub fn reference(id: impl Into<DidUrlReference>) -> Self {
472        Self::Reference(id.into())
473    }
474
475    /// An embedded method.
476    pub fn embedded(method: VerificationMethod) -> Self {
477        Self::Embedded(Box::new(method))
478    }
479
480    /// The embedded method, if this entry embeds one.
481    pub fn as_embedded(&self) -> Option<&VerificationMethod> {
482        match self {
483            Self::Embedded(method) => Some(method),
484            Self::Reference(_) => None,
485        }
486    }
487
488    /// The reference, if this entry is one.
489    pub fn as_reference(&self) -> Option<&DidUrlReference> {
490        match self {
491            Self::Reference(reference) => Some(reference),
492            Self::Embedded(_) => None,
493        }
494    }
495
496    /// Whether this entry denotes the method `id` in a document whose `id` is `base`.
497    pub fn refers_to(&self, id: &DidUrl, base: &Did) -> bool {
498        match self {
499            Self::Reference(reference) => reference.refers_to(id, base),
500            Self::Embedded(method) => method.id == *id,
501        }
502    }
503}
504
505impl From<DidUrl> for MethodRef {
506    fn from(id: DidUrl) -> Self {
507        Self::Reference(id.into())
508    }
509}
510
511impl From<DidUrlReference> for MethodRef {
512    fn from(reference: DidUrlReference) -> Self {
513        Self::Reference(reference)
514    }
515}
516
517impl From<VerificationMethod> for MethodRef {
518    fn from(method: VerificationMethod) -> Self {
519        Self::embedded(method)
520    }
521}
522
523impl Serialize for MethodRef {
524    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
525        match self {
526            Self::Reference(reference) => reference.serialize(serializer),
527            Self::Embedded(method) => method.serialize(serializer),
528        }
529    }
530}
531
532impl<'de> Deserialize<'de> for MethodRef {
533    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
534        struct MethodRefVisitor;
535
536        impl<'de> Visitor<'de> for MethodRefVisitor {
537            type Value = MethodRef;
538
539            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540                f.write_str("a DID URL string or a verification method object")
541            }
542
543            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
544                DidUrlReference::parse(value)
545                    .map(MethodRef::Reference)
546                    .map_err(E::custom)
547            }
548
549            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
550                VerificationMethod::deserialize(de::value::MapAccessDeserializer::new(map))
551                    .map(MethodRef::embedded)
552            }
553        }
554
555        deserializer.deserialize_any(MethodRefVisitor)
556    }
557}
558
559// ---------------------------------------------------------------------------------------------
560// Services
561// ---------------------------------------------------------------------------------------------
562
563/// The `serviceEndpoint` of a service (DID Core §5.4): a URI, a set of URIs, or a map.
564#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
565#[serde(untagged)]
566pub enum ServiceEndpoint {
567    /// A single URI.
568    Uri(Uri),
569    /// A non-empty set of URIs, in document order.
570    Set(IndexSet<Uri>),
571    /// A map, carried verbatim.
572    Map(IndexMap<String, Value>),
573}
574
575impl ServiceEndpoint {
576    /// A single URI.
577    pub fn uri(uri: Uri) -> Self {
578        Self::Uri(uri)
579    }
580
581    /// The URIs, when the endpoint is a URI or a set of them.
582    pub fn uris(&self) -> impl Iterator<Item = &Uri> {
583        let slice: Box<dyn Iterator<Item = &Uri>> = match self {
584            Self::Uri(uri) => Box::new(core::iter::once(uri)),
585            Self::Set(set) => Box::new(set.iter()),
586            Self::Map(_) => Box::new(core::iter::empty()),
587        };
588        slice
589    }
590}
591
592impl From<Uri> for ServiceEndpoint {
593    fn from(uri: Uri) -> Self {
594        Self::Uri(uri)
595    }
596}
597
598impl<'de> Deserialize<'de> for ServiceEndpoint {
599    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
600        struct EndpointVisitor;
601
602        impl<'de> Visitor<'de> for EndpointVisitor {
603            type Value = ServiceEndpoint;
604
605            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606                f.write_str("a URI string, a non-empty array of URI strings, or an object")
607            }
608
609            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
610                Uri::parse(value)
611                    .map(ServiceEndpoint::Uri)
612                    .map_err(E::custom)
613            }
614
615            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
616                let mut set = IndexSet::new();
617                while let Some(uri) = seq.next_element::<Uri>()? {
618                    set.insert(uri);
619                }
620                if set.is_empty() {
621                    return Err(de::Error::custom(
622                        "`serviceEndpoint` set must contain at least one URI",
623                    ));
624                }
625                Ok(ServiceEndpoint::Set(set))
626            }
627
628            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
629                let mut entries = IndexMap::new();
630                while let Some((key, value)) = map.next_entry::<String, Value>()? {
631                    entries.insert(key, value);
632                }
633                Ok(ServiceEndpoint::Map(entries))
634            }
635        }
636
637        deserializer.deserialize_any(EndpointVisitor)
638    }
639}
640
641/// A service (DID Core §5.4): a way of interacting with the DID subject.
642///
643/// `type` serializes as a string when single. Members other than the three core ones live in
644/// `properties`, in insertion order.
645#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
646#[non_exhaustive]
647pub struct Service {
648    /// The DID URL identifying the service, usually the document DID with a fragment.
649    pub id: DidUrl,
650    /// The service type or types.
651    #[serde(rename = "type")]
652    pub service_type: OneOrMany<String>,
653    /// Where the service is.
654    #[serde(rename = "serviceEndpoint")]
655    pub service_endpoint: ServiceEndpoint,
656    /// Every other member, in insertion order.
657    #[serde(flatten)]
658    pub properties: IndexMap<String, Value>,
659}
660
661impl Service {
662    /// A service with the three core members.
663    pub fn new(
664        id: DidUrl,
665        service_type: impl Into<OneOrMany<String>>,
666        service_endpoint: impl Into<ServiceEndpoint>,
667    ) -> Self {
668        Self {
669            id,
670            service_type: service_type.into(),
671            service_endpoint: service_endpoint.into(),
672            properties: IndexMap::new(),
673        }
674    }
675
676    /// Whether `service_type` is among the service's types.
677    pub fn has_type(&self, service_type: &str) -> bool {
678        self.service_type.iter().any(|t| t == service_type)
679    }
680}
681
682// ---------------------------------------------------------------------------------------------
683// The document
684// ---------------------------------------------------------------------------------------------
685
686/// A DID document (DID Core §5): the core properties as fields, everything else in `properties`.
687///
688/// The JSON representation is deterministic: `@context` comes first, then `id`, the core
689/// properties in the order DID Core lists them, and extension properties in insertion order.
690/// `None` and empty lists are omitted. A document parsed from JSON and written again holds the
691/// same members with the same values; the bytes are identical when the input already used that
692/// order. Extension properties must not use a core property name (see
693/// [`CORE_PROPERTIES`](Self::CORE_PROPERTIES)); the builder refuses one, and a document whose
694/// `properties` field holds one serializes a duplicate member.
695///
696/// The fields are public for reading and plain mutation; the methods keep the invariants that
697/// DID Core requires (unique method and service ids, references that point at listed methods).
698/// Deserialization enforces them too: a document that defines one verification method id twice
699/// with different content (listed or embedded) is rejected, so no lookup can pick different
700/// material for one id, and so is one with two services sharing an id, as DID Core §5.4 requires
701/// of a consumer. Embedding the same method under several relationships, as DID Core's own
702/// examples do, is one definition and allowed.
703///
704/// # Examples
705///
706/// ```
707/// use identity_kit::did::{DidDocument, VerificationRelationship};
708///
709/// // DID Core §4.1, Example 1 (with its editorial typo fixed).
710/// let json = r#"{
711///   "@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2020/v1"],
712///   "id": "did:example:123456789abcdefghi",
713///   "authentication": [{
714///     "id": "did:example:123456789abcdefghi#keys-1",
715///     "type": "Ed25519VerificationKey2020",
716///     "controller": "did:example:123456789abcdefghi",
717///     "publicKeyMultibase": "zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"
718///   }]
719/// }"#;
720/// let document: DidDocument = serde_json::from_str(json)?;
721/// assert_eq!(document.id.as_str(), "did:example:123456789abcdefghi");
722///
723/// let key = document.id.join("#keys-1")?;
724/// let method = document.resolve_verification_method(&key, Some(VerificationRelationship::Authentication))?;
725/// assert_eq!(method.public_key_multibase(), Some("zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"));
726///
727/// // The method is embedded under `authentication` and usable for nothing else.
728/// assert!(document.resolve_verification_method(&key, Some(VerificationRelationship::AssertionMethod)).is_err());
729/// # Ok::<(), Box<dyn std::error::Error>>(())
730/// ```
731#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
732#[non_exhaustive]
733#[serde(remote = "Self")]
734pub struct DidDocument {
735    /// `@context`, carried verbatim.
736    #[serde(rename = "@context", default, skip_serializing_if = "Option::is_none")]
737    pub context: Option<Context>,
738    /// The DID of the subject.
739    pub id: Did,
740    /// Other identifiers of the subject.
741    #[serde(rename = "alsoKnownAs", default, skip_serializing_if = "Vec::is_empty")]
742    pub also_known_as: Vec<Uri>,
743    /// The DIDs whose controllers may change this document; omitted when `None` or empty, and
744    /// `None` when read as an empty set.
745    #[serde(default, skip_serializing_if = "is_none_or_empty")]
746    pub controller: Option<OneOrMany<Did>>,
747    /// Verification methods that relationships may reference.
748    #[serde(
749        rename = "verificationMethod",
750        default,
751        skip_serializing_if = "Vec::is_empty"
752    )]
753    pub verification_method: Vec<VerificationMethod>,
754    /// `authentication`
755    #[serde(default, skip_serializing_if = "Vec::is_empty")]
756    pub authentication: Vec<MethodRef>,
757    /// `assertionMethod`
758    #[serde(
759        rename = "assertionMethod",
760        default,
761        skip_serializing_if = "Vec::is_empty"
762    )]
763    pub assertion_method: Vec<MethodRef>,
764    /// `keyAgreement`
765    #[serde(
766        rename = "keyAgreement",
767        default,
768        skip_serializing_if = "Vec::is_empty"
769    )]
770    pub key_agreement: Vec<MethodRef>,
771    /// `capabilityInvocation`
772    #[serde(
773        rename = "capabilityInvocation",
774        default,
775        skip_serializing_if = "Vec::is_empty"
776    )]
777    pub capability_invocation: Vec<MethodRef>,
778    /// `capabilityDelegation`
779    #[serde(
780        rename = "capabilityDelegation",
781        default,
782        skip_serializing_if = "Vec::is_empty"
783    )]
784    pub capability_delegation: Vec<MethodRef>,
785    /// Services.
786    #[serde(default, skip_serializing_if = "Vec::is_empty")]
787    pub service: Vec<Service>,
788    /// Every other property, in insertion order.
789    #[serde(flatten)]
790    pub properties: IndexMap<String, Value>,
791}
792
793impl Serialize for DidDocument {
794    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
795        Self::serialize(self, serializer)
796    }
797}
798
799impl<'de> Deserialize<'de> for DidDocument {
800    /// Reads the document and rejects duplicate verification method or service ids. An empty
801    /// `controller` set reads as no controller, which is how it is written.
802    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
803        let mut document = Self::deserialize(deserializer)?;
804        document.check_unique_ids().map_err(de::Error::custom)?;
805        if is_none_or_empty(&document.controller) {
806            document.controller = None;
807        }
808        Ok(document)
809    }
810}
811
812impl DidDocument {
813    /// The property names DID Core §5 defines, which `properties` must not contain.
814    pub const CORE_PROPERTIES: &'static [&'static str] = &[
815        "@context",
816        "id",
817        "alsoKnownAs",
818        "controller",
819        "verificationMethod",
820        "authentication",
821        "assertionMethod",
822        "keyAgreement",
823        "capabilityInvocation",
824        "capabilityDelegation",
825        "service",
826    ];
827
828    /// An empty document for `id`.
829    pub fn new(id: Did) -> Self {
830        Self {
831            context: None,
832            id,
833            also_known_as: Vec::new(),
834            controller: None,
835            verification_method: Vec::new(),
836            authentication: Vec::new(),
837            assertion_method: Vec::new(),
838            key_agreement: Vec::new(),
839            capability_invocation: Vec::new(),
840            capability_delegation: Vec::new(),
841            service: Vec::new(),
842            properties: IndexMap::new(),
843        }
844    }
845
846    /// A builder for a document for `id`.
847    pub fn builder(id: Did) -> DidDocumentBuilder {
848        DidDocumentBuilder {
849            document: Self::new(id),
850            error: None,
851        }
852    }
853
854    /// The entries of `relationship`.
855    pub fn relationship(&self, relationship: VerificationRelationship) -> &[MethodRef] {
856        match relationship {
857            VerificationRelationship::Authentication => &self.authentication,
858            VerificationRelationship::AssertionMethod => &self.assertion_method,
859            VerificationRelationship::KeyAgreement => &self.key_agreement,
860            VerificationRelationship::CapabilityInvocation => &self.capability_invocation,
861            VerificationRelationship::CapabilityDelegation => &self.capability_delegation,
862        }
863    }
864
865    /// The entries of `relationship`, mutably.
866    pub fn relationship_mut(
867        &mut self,
868        relationship: VerificationRelationship,
869    ) -> &mut Vec<MethodRef> {
870        match relationship {
871            VerificationRelationship::Authentication => &mut self.authentication,
872            VerificationRelationship::AssertionMethod => &mut self.assertion_method,
873            VerificationRelationship::KeyAgreement => &mut self.key_agreement,
874            VerificationRelationship::CapabilityInvocation => &mut self.capability_invocation,
875            VerificationRelationship::CapabilityDelegation => &mut self.capability_delegation,
876        }
877    }
878
879    /// The methods embedded in any relationship.
880    fn embedded_methods(&self) -> impl Iterator<Item = &VerificationMethod> {
881        VerificationRelationship::ALL
882            .iter()
883            .flat_map(|rel| self.relationship(*rel))
884            .filter_map(MethodRef::as_embedded)
885    }
886
887    /// The verification method with `id`, listed under `verificationMethod` or embedded in a
888    /// relationship.
889    pub fn verification_method(&self, id: &DidUrl) -> Option<&VerificationMethod> {
890        self.verification_method
891            .iter()
892            .chain(self.embedded_methods())
893            .find(|method| method.id == *id)
894    }
895
896    /// The verification methods usable for `relationship`, or every method in the document
897    /// when `relationship` is `None`.
898    ///
899    /// References are followed; a reference to a method that is not listed under
900    /// `verificationMethod` yields nothing.
901    pub fn methods(
902        &self,
903        relationship: Option<VerificationRelationship>,
904    ) -> impl Iterator<Item = &VerificationMethod> {
905        let entries: Box<dyn Iterator<Item = &VerificationMethod>> =
906            match relationship {
907                None => Box::new(
908                    self.verification_method
909                        .iter()
910                        .chain(self.embedded_methods()),
911                ),
912                Some(rel) => Box::new(self.relationship(rel).iter().filter_map(
913                    |entry| match entry {
914                        MethodRef::Embedded(method) => Some(&**method),
915                        MethodRef::Reference(reference) => {
916                            let id = reference.resolve(&self.id).ok()?;
917                            self.verification_method.iter().find(|m| m.id == id)
918                        }
919                    },
920                )),
921            };
922        entries
923    }
924
925    /// The verification method `id`, optionally restricted to those usable for `relationship`.
926    ///
927    /// `id` must belong to this document's DID. The method may be listed under
928    /// `verificationMethod` or embedded in a relationship; with a `relationship`, it must be
929    /// referenced (absolutely or relatively) or embedded under that relationship.
930    ///
931    /// # Errors
932    ///
933    /// - [`DocumentError::ForeignDid`] when `id` is a DID URL of another DID.
934    /// - [`DocumentError::VerificationMethodNotFound`] when no method has that id.
935    /// - [`DocumentError::NotInRelationship`] when it exists but not under `relationship`.
936    pub fn resolve_verification_method(
937        &self,
938        id: &DidUrl,
939        relationship: Option<VerificationRelationship>,
940    ) -> Result<&VerificationMethod, DocumentError> {
941        if id.did() != &self.id {
942            return Err(DocumentError::ForeignDid {
943                url: id.clone(),
944                document: self.id.clone(),
945            });
946        }
947        let Some(relationship) = relationship else {
948            return self
949                .verification_method(id)
950                .ok_or_else(|| DocumentError::VerificationMethodNotFound(id.clone()));
951        };
952        for entry in self.relationship(relationship) {
953            match entry {
954                MethodRef::Embedded(method) if method.id == *id => return Ok(method),
955                MethodRef::Reference(reference) if reference.refers_to(id, &self.id) => {
956                    return self
957                        .verification_method
958                        .iter()
959                        .find(|method| method.id == *id)
960                        .ok_or_else(|| DocumentError::VerificationMethodNotFound(id.clone()));
961                }
962                _ => {}
963            }
964        }
965        if self.verification_method(id).is_some() {
966            Err(DocumentError::NotInRelationship {
967                id: id.clone(),
968                relationship,
969            })
970        } else {
971            Err(DocumentError::VerificationMethodNotFound(id.clone()))
972        }
973    }
974
975    /// [`resolve_verification_method`](Self::resolve_verification_method) for a reference that
976    /// may be relative (`#key-1`), resolved against this document's `id`.
977    ///
978    /// # Errors
979    ///
980    /// As [`resolve_verification_method`](Self::resolve_verification_method).
981    pub fn resolve_method_reference(
982        &self,
983        reference: &DidUrlReference,
984        relationship: Option<VerificationRelationship>,
985    ) -> Result<&VerificationMethod, DocumentError> {
986        // A relative reference this type accepted always joins to a DID.
987        let id = reference.resolve(&self.id).map_err(|_| match reference {
988            DidUrlReference::Absolute(url) => DocumentError::ForeignDid {
989                url: url.clone(),
990                document: self.id.clone(),
991            },
992            DidUrlReference::Relative(_) => {
993                DocumentError::VerificationMethodNotFound(self.id.to_url())
994            }
995        })?;
996        self.resolve_verification_method(&id, relationship)
997    }
998
999    /// Adds `method` under `verificationMethod` and references it from each of `relationships`.
1000    ///
1001    /// # Errors
1002    ///
1003    /// [`DocumentError::DuplicateVerificationMethod`] when a method with that id exists, listed
1004    /// or embedded; the document is unchanged.
1005    pub fn insert_verification_method(
1006        &mut self,
1007        method: VerificationMethod,
1008        relationships: impl IntoIterator<Item = VerificationRelationship>,
1009    ) -> Result<(), DocumentError> {
1010        if self.verification_method(&method.id).is_some() {
1011            return Err(DocumentError::DuplicateVerificationMethod(method.id));
1012        }
1013        let id = method.id.clone();
1014        self.verification_method.push(method);
1015        for relationship in relationships {
1016            self.attach_relationship(&id, relationship)?;
1017        }
1018        Ok(())
1019    }
1020
1021    /// Checks that every verification method id (listed or embedded) has one definition and that
1022    /// no two services share an id: the invariant the mutating methods keep and deserialization
1023    /// enforces. The same method embedded under several relationships is one definition.
1024    ///
1025    /// # Errors
1026    ///
1027    /// [`DocumentError::DuplicateVerificationMethod`] naming the first id defined twice with
1028    /// different content, or [`DocumentError::DuplicateService`] naming the first repeated
1029    /// service id.
1030    pub fn check_unique_ids(&self) -> Result<(), DocumentError> {
1031        let mut seen = HashMap::new();
1032        for method in self
1033            .verification_method
1034            .iter()
1035            .chain(self.embedded_methods())
1036        {
1037            if *seen.entry(&method.id).or_insert(method) != method {
1038                return Err(DocumentError::DuplicateVerificationMethod(
1039                    method.id.clone(),
1040                ));
1041            }
1042        }
1043        let mut seen = HashSet::new();
1044        for service in &self.service {
1045            if !seen.insert(&service.id) {
1046                return Err(DocumentError::DuplicateService(service.id.clone()));
1047            }
1048        }
1049        Ok(())
1050    }
1051
1052    /// Removes the method `id`, listed or embedded, and every relationship entry for it.
1053    pub fn remove_verification_method(&mut self, id: &DidUrl) -> Option<VerificationMethod> {
1054        // Every listed entry with the id goes, should plain mutation have duplicated it.
1055        let (matching, rest): (Vec<_>, Vec<_>) = mem::take(&mut self.verification_method)
1056            .into_iter()
1057            .partition(|method| method.id == *id);
1058        self.verification_method = rest;
1059        let listed = matching.into_iter().next();
1060        let mut embedded = None;
1061        let base = self.id.clone();
1062        for relationship in VerificationRelationship::ALL {
1063            let entries = self.relationship_mut(*relationship);
1064            let mut index = 0;
1065            while index < entries.len() {
1066                if entries[index].refers_to(id, &base) {
1067                    if let MethodRef::Embedded(method) = entries.remove(index) {
1068                        embedded.get_or_insert(*method);
1069                    }
1070                } else {
1071                    index += 1;
1072                }
1073            }
1074        }
1075        listed.or(embedded)
1076    }
1077
1078    /// References the listed method `id` from `relationship`.
1079    ///
1080    /// Returns whether an entry was added: `Ok(false)` when the relationship already references
1081    /// or embeds the method.
1082    ///
1083    /// # Errors
1084    ///
1085    /// [`DocumentError::VerificationMethodNotFound`] when `id` is not listed under
1086    /// `verificationMethod` (a reference to an embedded method would dangle).
1087    pub fn attach_relationship(
1088        &mut self,
1089        id: &DidUrl,
1090        relationship: VerificationRelationship,
1091    ) -> Result<bool, DocumentError> {
1092        if !self.verification_method.iter().any(|m| m.id == *id) {
1093            return Err(DocumentError::VerificationMethodNotFound(id.clone()));
1094        }
1095        let base = self.id.clone();
1096        let entries = self.relationship_mut(relationship);
1097        if entries.iter().any(|entry| entry.refers_to(id, &base)) {
1098            return Ok(false);
1099        }
1100        entries.push(MethodRef::Reference(id.clone().into()));
1101        Ok(true)
1102    }
1103
1104    /// Removes every entry for the method `id` from `relationship`, returning whether there
1105    /// was one.
1106    pub fn detach_relationship(
1107        &mut self,
1108        id: &DidUrl,
1109        relationship: VerificationRelationship,
1110    ) -> bool {
1111        let base = self.id.clone();
1112        let entries = self.relationship_mut(relationship);
1113        let before = entries.len();
1114        entries.retain(|entry| !entry.refers_to(id, &base));
1115        entries.len() != before
1116    }
1117
1118    /// The service `id`.
1119    pub fn service(&self, id: &DidUrl) -> Option<&Service> {
1120        self.service.iter().find(|service| service.id == *id)
1121    }
1122
1123    /// Adds `service`.
1124    ///
1125    /// # Errors
1126    ///
1127    /// [`DocumentError::DuplicateService`] when a service with that id exists.
1128    pub fn insert_service(&mut self, service: Service) -> Result<(), DocumentError> {
1129        if self.service(&service.id).is_some() {
1130            return Err(DocumentError::DuplicateService(service.id));
1131        }
1132        self.service.push(service);
1133        Ok(())
1134    }
1135
1136    /// Removes the service `id`.
1137    pub fn remove_service(&mut self, id: &DidUrl) -> Option<Service> {
1138        self.service
1139            .iter()
1140            .position(|service| service.id == *id)
1141            .map(|index| self.service.remove(index))
1142    }
1143
1144    /// Rewrites every DID in the document through `f`: the `id`, the controllers, the ids and
1145    /// controllers of verification methods (listed and embedded), absolute relationship
1146    /// references and service ids. Relative references, `alsoKnownAs` and extension properties
1147    /// are left as they are.
1148    ///
1149    /// This is how a method whose DID depends on the document (a `did:web` moving domains, a
1150    /// placeholder DID replaced by the registered one) produces its final document.
1151    ///
1152    /// `f` is expected to map distinct DIDs to distinct DIDs. Merging two DIDs into one can give
1153    /// two methods or services the same id; that is not checked here, and
1154    /// [`check_unique_ids`](Self::check_unique_ids) reports it.
1155    ///
1156    /// # Examples
1157    ///
1158    /// ```
1159    /// use identity_kit::did::{Did, DidDocument, MethodType, VerificationMaterial, VerificationMethod, VerificationRelationship};
1160    ///
1161    /// let placeholder = Did::parse("did:example:placeholder")?;
1162    /// let mut document = DidDocument::new(placeholder.clone());
1163    /// document.insert_verification_method(
1164    ///     VerificationMethod::new(
1165    ///         placeholder.join("#key-1")?,
1166    ///         MethodType::MULTIKEY,
1167    ///         placeholder.clone(),
1168    ///         VerificationMaterial::multibase("z6MkmM42vxfqZQsv4ehtTjFFxQ4sQKS2w6WR7emozFAn5cxu"),
1169    ///     ),
1170    ///     [VerificationRelationship::Authentication],
1171    /// )?;
1172    ///
1173    /// let registered = Did::parse("did:web:example.com")?;
1174    /// document.map_dids(|did| if did == placeholder { registered.clone() } else { did });
1175    ///
1176    /// assert_eq!(document.id, registered);
1177    /// assert_eq!(document.verification_method[0].id.as_str(), "did:web:example.com#key-1");
1178    /// assert_eq!(document.verification_method[0].controller, registered);
1179    /// let key = registered.join("#key-1")?;
1180    /// assert!(document.resolve_verification_method(&key, Some(VerificationRelationship::Authentication)).is_ok());
1181    /// # Ok::<(), Box<dyn std::error::Error>>(())
1182    /// ```
1183    pub fn map_dids(&mut self, mut f: impl FnMut(Did) -> Did) {
1184        fn map_url(url: &mut DidUrl, f: &mut impl FnMut(Did) -> Did) {
1185            let did = f(url.did().clone());
1186            if &did != url.did() {
1187                *url = url.with_did(did);
1188            }
1189        }
1190        fn map_method(method: &mut VerificationMethod, f: &mut impl FnMut(Did) -> Did) {
1191            map_url(&mut method.id, f);
1192            method.controller = f(method.controller.clone());
1193        }
1194
1195        self.id = f(self.id.clone());
1196        if let Some(controller) = &mut self.controller {
1197            for did in controller.iter_mut() {
1198                *did = f(did.clone());
1199            }
1200        }
1201        for method in &mut self.verification_method {
1202            map_method(method, &mut f);
1203        }
1204        for relationship in VerificationRelationship::ALL {
1205            for entry in self.relationship_mut(*relationship) {
1206                match entry {
1207                    MethodRef::Reference(DidUrlReference::Absolute(url)) => map_url(url, &mut f),
1208                    MethodRef::Reference(DidUrlReference::Relative(_)) => {}
1209                    MethodRef::Embedded(method) => map_method(method, &mut f),
1210                }
1211            }
1212        }
1213        for service in &mut self.service {
1214            map_url(&mut service.id, &mut f);
1215        }
1216    }
1217}
1218
1219/// Builds a [`DidDocument`], reporting the first invariant violation at [`build`](Self::build).
1220#[derive(Debug, Clone)]
1221pub struct DidDocumentBuilder {
1222    document: DidDocument,
1223    error: Option<DocumentError>,
1224}
1225
1226impl DidDocumentBuilder {
1227    /// Sets `@context`.
1228    #[must_use]
1229    pub fn context(mut self, context: Context) -> Self {
1230        self.document.context = Some(context);
1231        self
1232    }
1233
1234    /// Adds an `alsoKnownAs` URI.
1235    #[must_use]
1236    pub fn also_known_as(mut self, uri: Uri) -> Self {
1237        self.document.also_known_as.push(uri);
1238        self
1239    }
1240
1241    /// Adds a controller; one controller serializes as a string, more as an array.
1242    #[must_use]
1243    pub fn controller(mut self, did: Did) -> Self {
1244        self.document.controller = Some(match self.document.controller.take() {
1245            None => OneOrMany::One(did),
1246            Some(existing) => {
1247                let mut dids = existing.into_vec();
1248                dids.push(did);
1249                OneOrMany::Many(dids)
1250            }
1251        });
1252        self
1253    }
1254
1255    /// Adds a verification method under `verificationMethod`, referenced from `relationships`.
1256    #[must_use]
1257    pub fn verification_method(
1258        mut self,
1259        method: VerificationMethod,
1260        relationships: impl IntoIterator<Item = VerificationRelationship>,
1261    ) -> Self {
1262        if self.error.is_none() {
1263            self.error = self
1264                .document
1265                .insert_verification_method(method, relationships)
1266                .err();
1267        }
1268        self
1269    }
1270
1271    /// Embeds a verification method in `relationship`, usable for that purpose only.
1272    #[must_use]
1273    pub fn embedded_method(
1274        mut self,
1275        relationship: VerificationRelationship,
1276        method: VerificationMethod,
1277    ) -> Self {
1278        if self.error.is_none() {
1279            if self.document.verification_method(&method.id).is_some() {
1280                self.error = Some(DocumentError::DuplicateVerificationMethod(method.id));
1281            } else {
1282                self.document
1283                    .relationship_mut(relationship)
1284                    .push(MethodRef::embedded(method));
1285            }
1286        }
1287        self
1288    }
1289
1290    /// Adds a service.
1291    #[must_use]
1292    pub fn service(mut self, service: Service) -> Self {
1293        if self.error.is_none() {
1294            self.error = self.document.insert_service(service).err();
1295        }
1296        self
1297    }
1298
1299    /// Adds an extension property; a core property name is refused at
1300    /// [`build`](Self::build) with [`DocumentError::ReservedProperty`].
1301    #[must_use]
1302    pub fn property(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
1303        let name = name.into();
1304        if DidDocument::CORE_PROPERTIES.contains(&name.as_str()) {
1305            if self.error.is_none() {
1306                self.error = Some(DocumentError::ReservedProperty(name));
1307            }
1308        } else {
1309            self.document.properties.insert(name, value.into());
1310        }
1311        self
1312    }
1313
1314    /// The document.
1315    ///
1316    /// # Errors
1317    ///
1318    /// The first [`DocumentError`] an addition raised: a duplicate method or service id.
1319    pub fn build(self) -> Result<DidDocument, DocumentError> {
1320        match self.error {
1321            Some(error) => Err(error),
1322            None => Ok(self.document),
1323        }
1324    }
1325}