Skip to main content

did_bio_core/
document.rs

1//! W3C DID document data model for `did:bio` (spec Section 5) and the DID
2//! Resolution result envelope (spec Section 6.2).
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::Error;
7use crate::multikey::{self, KeyCodec};
8
9/// The JSON-LD context of W3C DID v1.0 core.
10pub const CONTEXT_DID_V1: &str = "https://www.w3.org/ns/did/v1";
11/// The JSON-LD context of Controlled Identifiers v1.0, which defines
12/// `Multikey` and `JsonWebKey`.
13pub const CONTEXT_CID_V1: &str = "https://www.w3.org/ns/cid/v1";
14
15/// Media type of the JSON-LD representation (DID 1.0).
16pub const MEDIA_TYPE_DID_LD_JSON: &str = "application/did+ld+json";
17/// Media type of the plain JSON representation (DID 1.0).
18pub const MEDIA_TYPE_DID_JSON: &str = "application/did+json";
19/// Media type registered by DID 1.1, replacing both of the above. It
20/// carries the same JSON-LD serialization (spec Section 2).
21pub const MEDIA_TYPE_DID: &str = "application/did";
22
23/// Verification method `type` for Multikey encoded keys.
24pub const VM_TYPE_MULTIKEY: &str = "Multikey";
25/// Verification method `type` for JWK encoded keys (ML-DSA-87).
26pub const VM_TYPE_JSON_WEB_KEY: &str = "JsonWebKey";
27
28/// JWK `kty` for ML-DSA keys per draft-ietf-cose-dilithium. It is
29/// provisional (spec Section 5.2).
30pub const JWK_KTY_AKP: &str = "AKP";
31/// JWK `alg` for ML-DSA-87 (FIPS 204).
32pub const JWK_ALG_ML_DSA_87: &str = "ML-DSA-87";
33
34/// Byte length of an ML-DSA-87 public key (FIPS 204).
35pub const ML_DSA_87_PUBLIC_KEY_LEN: usize = 2592;
36/// Byte length of an ML-DSA-87 signature (FIPS 204).
37pub const ML_DSA_87_SIGNATURE_LEN: usize = 4627;
38
39/// The default `@context` array of every `did:bio` document (spec Section 5.1).
40pub fn default_context() -> Vec<String> {
41    vec![CONTEXT_DID_V1.to_string(), CONTEXT_CID_V1.to_string()]
42}
43
44fn base64url(bytes: &[u8]) -> String {
45    use base64::Engine as _;
46    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
47}
48
49/// An `AKP` public JWK carrying an ML-DSA public key, per
50/// draft-ietf-cose-dilithium. It is provisional until IETF registration is
51/// final (spec Section 5.2).
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct AkpPublicJwk {
54    /// Key type, always `"AKP"`.
55    pub kty: String,
56    /// Algorithm, `"ML-DSA-87"` for this method.
57    pub alg: String,
58    /// Public key bytes, base64url without padding.
59    #[serde(rename = "pub")]
60    pub public_key: String,
61}
62
63impl AkpPublicJwk {
64    /// Build the JWK for an ML-DSA-87 public key.
65    pub fn ml_dsa_87(public_key: &[u8]) -> Result<Self, Error> {
66        if public_key.len() != ML_DSA_87_PUBLIC_KEY_LEN {
67            return Err(Error::InvalidKeyLength {
68                expected: ML_DSA_87_PUBLIC_KEY_LEN,
69                actual: public_key.len(),
70            });
71        }
72        Ok(AkpPublicJwk {
73            kty: JWK_KTY_AKP.to_string(),
74            alg: JWK_ALG_ML_DSA_87.to_string(),
75            public_key: base64url(public_key),
76        })
77    }
78
79    /// Decode the `pub` member to raw key bytes.
80    pub fn decode_public_key(&self) -> Result<Vec<u8>, Error> {
81        use base64::Engine as _;
82        base64::engine::general_purpose::URL_SAFE_NO_PAD
83            .decode(&self.public_key)
84            .map_err(|_| Error::InvalidMultikey("JWK `pub` is not valid base64url"))
85    }
86}
87
88/// The single verification material property of a verification method.
89/// Each method has exactly one (spec Section 5.2).
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[non_exhaustive]
92pub enum VerificationMaterial {
93    /// `publicKeyMultibase`, Multikey encoded key material.
94    #[serde(rename = "publicKeyMultibase")]
95    PublicKeyMultibase(String),
96    /// `publicKeyJwk`, JWK key material for ML-DSA-87.
97    #[serde(rename = "publicKeyJwk")]
98    PublicKeyJwk(AkpPublicJwk),
99}
100
101/// A verification method map (spec Section 5.2).
102///
103/// Deserializing refuses a method with no verification material property
104/// or with more than one, so two readers of the same document never pick
105/// different keys.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[serde(try_from = "VerificationMethodFields")]
108pub struct VerificationMethodMap {
109    /// DID URL of this method, `<did>#<fragment>`.
110    pub id: String,
111    /// `Multikey` or `JsonWebKey`.
112    #[serde(rename = "type")]
113    pub method_type: String,
114    /// The DID that controls this method.
115    pub controller: String,
116    /// The verification material property.
117    #[serde(flatten)]
118    pub material: VerificationMaterial,
119}
120
121/// A verification method map as it arrives, before the check that it has
122/// exactly one material property.
123#[derive(Deserialize)]
124struct VerificationMethodFields {
125    id: String,
126    #[serde(rename = "type")]
127    method_type: String,
128    controller: String,
129    #[serde(rename = "publicKeyMultibase")]
130    public_key_multibase: Option<String>,
131    #[serde(rename = "publicKeyJwk")]
132    public_key_jwk: Option<AkpPublicJwk>,
133}
134
135impl TryFrom<VerificationMethodFields> for VerificationMethodMap {
136    type Error = &'static str;
137
138    fn try_from(fields: VerificationMethodFields) -> Result<Self, Self::Error> {
139        let material = match (fields.public_key_multibase, fields.public_key_jwk) {
140            (Some(multibase), None) => VerificationMaterial::PublicKeyMultibase(multibase),
141            (None, Some(jwk)) => VerificationMaterial::PublicKeyJwk(jwk),
142            (None, None) => return Err("verification method has no verification material"),
143            (Some(_), Some(_)) => {
144                return Err("verification method has more than one verification material")
145            }
146        };
147        Ok(VerificationMethodMap {
148            id: fields.id,
149            method_type: fields.method_type,
150            controller: fields.controller,
151            material,
152        })
153    }
154}
155
156impl VerificationMethodMap {
157    /// Build a `Multikey` verification method from raw key bytes.
158    pub fn multikey(
159        id: String,
160        controller: String,
161        codec: KeyCodec,
162        key: &[u8],
163    ) -> Result<Self, Error> {
164        Ok(VerificationMethodMap {
165            id,
166            method_type: VM_TYPE_MULTIKEY.to_string(),
167            controller,
168            material: VerificationMaterial::PublicKeyMultibase(multikey::encode(codec, key)?),
169        })
170    }
171
172    /// Build the `JsonWebKey` verification method for an ML-DSA-87 key.
173    pub fn ml_dsa_87(id: String, controller: String, key: &[u8]) -> Result<Self, Error> {
174        Ok(VerificationMethodMap {
175            id,
176            method_type: VM_TYPE_JSON_WEB_KEY.to_string(),
177            controller,
178            material: VerificationMaterial::PublicKeyJwk(AkpPublicJwk::ml_dsa_87(key)?),
179        })
180    }
181
182    /// The fragment of this method's `id`, the text after `#`, if any.
183    pub fn fragment(&self) -> Option<&str> {
184        self.id.split_once('#').map(|(_, fragment)| fragment)
185    }
186
187    /// Decode this method's public key to raw bytes, regardless of
188    /// encoding.
189    pub fn decode_key(&self) -> Result<Vec<u8>, Error> {
190        match &self.material {
191            VerificationMaterial::PublicKeyMultibase(mb) => Ok(multikey::decode(mb)?.1),
192            VerificationMaterial::PublicKeyJwk(jwk) => jwk.decode_public_key(),
193        }
194    }
195}
196
197/// A service map (spec Section 5.4).
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199pub struct ServiceMap {
200    /// DID URL of this service, `<did>#<fragment>`.
201    pub id: String,
202    /// Service type, such as `BioMetadata`.
203    #[serde(rename = "type")]
204    pub service_type: String,
205    /// Service endpoint URI.
206    #[serde(rename = "serviceEndpoint")]
207    pub service_endpoint: String,
208}
209
210/// A `did:bio` DID document (spec Section 5).
211///
212/// Field order matches the serialization shown in the spec. Empty arrays
213/// are omitted from serialization, so a deactivated document (spec
214/// Section 5.7) serializes as `{"@context": [...], "id": "<did>"}`.
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
216pub struct DidDocument {
217    /// JSON-LD contexts (spec Section 5.1).
218    #[serde(rename = "@context")]
219    pub context: Vec<String>,
220    /// The DID this document describes.
221    pub id: String,
222    /// Controller DIDs (spec Section 5.5).
223    #[serde(skip_serializing_if = "Vec::is_empty", default)]
224    pub controller: Vec<String>,
225    /// Verification methods (spec Section 5.2).
226    #[serde(
227        rename = "verificationMethod",
228        skip_serializing_if = "Vec::is_empty",
229        default
230    )]
231    pub verification_method: Vec<VerificationMethodMap>,
232    /// `authentication` relationship, by reference.
233    #[serde(skip_serializing_if = "Vec::is_empty", default)]
234    pub authentication: Vec<String>,
235    /// `assertionMethod` relationship, by reference.
236    #[serde(
237        rename = "assertionMethod",
238        skip_serializing_if = "Vec::is_empty",
239        default
240    )]
241    pub assertion_method: Vec<String>,
242    /// `keyAgreement` relationship, by reference.
243    #[serde(
244        rename = "keyAgreement",
245        skip_serializing_if = "Vec::is_empty",
246        default
247    )]
248    pub key_agreement: Vec<String>,
249    /// `capabilityInvocation` relationship, by reference.
250    #[serde(
251        rename = "capabilityInvocation",
252        skip_serializing_if = "Vec::is_empty",
253        default
254    )]
255    pub capability_invocation: Vec<String>,
256    /// `capabilityDelegation` relationship, by reference.
257    #[serde(
258        rename = "capabilityDelegation",
259        skip_serializing_if = "Vec::is_empty",
260        default
261    )]
262    pub capability_delegation: Vec<String>,
263    /// Services (spec Section 5.4).
264    #[serde(skip_serializing_if = "Vec::is_empty", default)]
265    pub service: Vec<ServiceMap>,
266}
267
268/// The five W3C DID verification relationships (spec Section 5.3).
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
270pub enum VerificationRelationship {
271    /// `authentication`.
272    Authentication,
273    /// `assertionMethod`.
274    AssertionMethod,
275    /// `keyAgreement`.
276    KeyAgreement,
277    /// `capabilityInvocation`.
278    CapabilityInvocation,
279    /// `capabilityDelegation`.
280    CapabilityDelegation,
281}
282
283impl DidDocument {
284    /// The references listed under a verification relationship.
285    pub fn relationship(&self, relationship: VerificationRelationship) -> &[String] {
286        match relationship {
287            VerificationRelationship::Authentication => &self.authentication,
288            VerificationRelationship::AssertionMethod => &self.assertion_method,
289            VerificationRelationship::KeyAgreement => &self.key_agreement,
290            VerificationRelationship::CapabilityInvocation => &self.capability_invocation,
291            VerificationRelationship::CapabilityDelegation => &self.capability_delegation,
292        }
293    }
294
295    /// Find a verification method by its full DID URL `id`.
296    pub fn verification_method_by_id(&self, id: &str) -> Option<&VerificationMethodMap> {
297        self.verification_method.iter().find(|vm| vm.id == id)
298    }
299
300    /// Find a verification method by bare fragment, without `#`.
301    pub fn verification_method_by_fragment(
302        &self,
303        fragment: &str,
304    ) -> Option<&VerificationMethodMap> {
305        self.verification_method
306            .iter()
307            .find(|vm| vm.fragment() == Some(fragment))
308    }
309
310    /// Find a service by bare fragment, without `#`.
311    pub fn service_by_fragment(&self, fragment: &str) -> Option<&ServiceMap> {
312        self.service
313            .iter()
314            .find(|s| s.id.split_once('#').map(|(_, f)| f) == Some(fragment))
315    }
316
317    /// What a DID URL with this `fragment` names in the document, or the
318    /// document itself without a fragment. Fragments are unique across
319    /// methods and services (spec Section 5.4), so at most one matches.
320    pub fn dereference(&self, fragment: Option<&str>) -> Option<Dereferenced<'_>> {
321        match fragment {
322            None => Some(Dereferenced::Document(self)),
323            Some(fragment) => self
324                .verification_method_by_fragment(fragment)
325                .map(Dereferenced::VerificationMethod)
326                .or_else(|| {
327                    self.service_by_fragment(fragment)
328                        .map(Dereferenced::Service)
329                }),
330        }
331    }
332}
333
334/// What a DID URL names. It serializes as the resource itself.
335#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
336#[serde(untagged)]
337pub enum Dereferenced<'a> {
338    /// The whole document, for a DID URL without a fragment.
339    Document(&'a DidDocument),
340    /// A verification method.
341    VerificationMethod(&'a VerificationMethodMap),
342    /// A service.
343    Service(&'a ServiceMap),
344}
345
346/// `didDocumentMetadata` (spec Section 6.2).
347///
348/// All members are optional so that the unsuccessful resolution case
349/// serializes as the empty structure required by DID Resolution.
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
351pub struct DidDocumentMetadata {
352    /// Whether the DID is permanently deactivated (spec Section 5.7).
353    #[serde(skip_serializing_if = "Option::is_none", default)]
354    pub deactivated: Option<bool>,
355    /// The registry `version` counter as a decimal string, `"0"` for a
356    /// generative document.
357    #[serde(rename = "versionId", skip_serializing_if = "Option::is_none", default)]
358    pub version_id: Option<String>,
359    /// XML datetime of the last registry update, absent for generative
360    /// documents.
361    #[serde(skip_serializing_if = "Option::is_none", default)]
362    pub updated: Option<String>,
363}
364
365impl DidDocumentMetadata {
366    /// Metadata of a generative document, with `versionId "0"` and not
367    /// deactivated (spec Section 6.2 step 6).
368    pub fn generative() -> Self {
369        DidDocumentMetadata {
370            deactivated: Some(false),
371            version_id: Some("0".to_string()),
372            updated: None,
373        }
374    }
375
376    /// Metadata of a materialized registry backed document (spec Section 6.2
377    /// steps 8-9).
378    pub fn registered(deactivated: bool, version: u64, updated_at: i64) -> Self {
379        DidDocumentMetadata {
380            deactivated: Some(deactivated),
381            version_id: Some(version.to_string()),
382            updated: Some(crate::datetime::xml_datetime(updated_at)),
383        }
384    }
385}
386
387/// `didResolutionMetadata` (spec Section 6.2).
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
389pub struct DidResolutionMetadata {
390    /// Media type of the returned representation.
391    #[serde(
392        rename = "contentType",
393        skip_serializing_if = "Option::is_none",
394        default
395    )]
396    pub content_type: Option<String>,
397    /// DID Resolution error code, present only on failure.
398    #[serde(skip_serializing_if = "Option::is_none", default)]
399    pub error: Option<String>,
400}
401
402/// A complete DID Resolution result, made of the resolution metadata, the
403/// document and the document metadata.
404#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
405pub struct DidResolution {
406    /// Metadata about the resolution process.
407    #[serde(rename = "didResolutionMetadata")]
408    pub resolution_metadata: DidResolutionMetadata,
409    /// The resolved document, `null` on failure.
410    #[serde(rename = "didDocument")]
411    pub document: Option<DidDocument>,
412    /// Metadata about the document, the empty structure on failure.
413    #[serde(rename = "didDocumentMetadata")]
414    pub document_metadata: DidDocumentMetadata,
415}
416
417impl DidResolution {
418    /// A successful resolution carrying the JSON-LD content type.
419    pub fn success(document: DidDocument, document_metadata: DidDocumentMetadata) -> Self {
420        DidResolution {
421            resolution_metadata: DidResolutionMetadata {
422                content_type: Some(MEDIA_TYPE_DID_LD_JSON.to_string()),
423                error: None,
424            },
425            document: Some(document),
426            document_metadata,
427        }
428    }
429
430    /// A failed resolution carrying a DID Resolution error code, such as
431    /// [`crate::resolution_error::INVALID_DID`].
432    pub fn error(code: &str) -> Self {
433        DidResolution {
434            resolution_metadata: DidResolutionMetadata {
435                content_type: None,
436                error: Some(code.to_string()),
437            },
438            document: None,
439            document_metadata: DidDocumentMetadata::default(),
440        }
441    }
442}