Skip to main content

vouch_core/
did_document.rs

1//! Choosing a DID's assertion key from its DID document, with the rules of
2//! the Python reference (`vouch.did_web.DIDDocument.assertion_key` and
3//! `publishes_mldsa44_assertion_key`).
4//!
5//! The core never fetches a DID document. These rules run on a document the
6//! caller already holds, such as the verified state of a did:webvh log
7//! ([`crate::did_webvh::verify_log`]).
8
9#[allow(unused_imports)]
10use crate::prelude::*;
11
12use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
13use serde_json::{Map, Value};
14
15use crate::error::{CoreError, Result};
16use crate::multikey;
17
18/// The Ed25519 algorithm name, as [`multikey::decode`] reports it.
19pub const ED25519: &str = "Ed25519";
20/// The ML-DSA-44 algorithm name, as [`multikey::decode`] reports it.
21pub const MLDSA44: &str = "ML-DSA-44";
22/// The SLH-DSA-SHA2-128s algorithm name, as [`multikey::decode`] reports it.
23pub const SLHDSA128: &str = multikey::SLHDSA128;
24
25fn refuse(text: &str) -> CoreError {
26    CoreError::InvalidDid(text.to_string())
27}
28
29fn list<'a>(document: &'a Value, name: &str) -> &'a [Value] {
30    document
31        .get(name)
32        .and_then(Value::as_array)
33        .map(Vec::as_slice)
34        .unwrap_or(&[])
35}
36
37/// An id written relative to the document ("#key-1") made absolute.
38fn absolute(reference: Option<&Value>, did: &str) -> Option<String> {
39    let text = reference?.as_str()?;
40    if text.is_empty() {
41        return None;
42    }
43    Some(if text.starts_with('#') {
44        format!("{did}{text}")
45    } else {
46        text.to_string()
47    })
48}
49
50/// Every method object: the verificationMethod list, then the methods
51/// embedded in assertionMethod.
52fn all_methods(document: &Value) -> Vec<&Map<String, Value>> {
53    list(document, "verificationMethod")
54        .iter()
55        .chain(list(document, "assertionMethod"))
56        .filter_map(Value::as_object)
57        .collect()
58}
59
60/// The ids the document lists in assertionMethod, by reference or embedded.
61fn assertion_ids(document: &Value, did: &str) -> Vec<String> {
62    list(document, "assertionMethod")
63        .iter()
64        .filter_map(|r| {
65            let target = if r.is_object() { r.get("id") } else { Some(r) };
66            absolute(target, did)
67        })
68        .collect()
69}
70
71fn document_id(document: &Value) -> &str {
72    document.get("id").and_then(Value::as_str).unwrap_or("")
73}
74
75/// The raw public key a proof names, when `document` lets `did` use it for
76/// assertions. Every rule must hold, or the key is refused:
77///
78/// - the document's `id` is exactly `did`;
79/// - `verification_method` is `did` plus a fragment (or just the fragment),
80///   and exactly one method in the document has that id (ids written
81///   relative to the document, "#key-1", count);
82/// - the method's `controller` is `did`;
83/// - the method is listed in `assertionMethod`, by reference (absolute or
84///   relative) or embedded there;
85/// - the method carries one kind of key material, of the right kind:
86///   `Multikey` or `Ed25519VerificationKey2020` with `publicKeyMultibase`, or
87///   `JsonWebKey2020` / `JsonWebKey` (or the earlier
88///   `Ed25519VerificationKey2020`) with a public Ed25519 `publicKeyJwk` meant
89///   for signatures;
90/// - the key is a well-formed `algorithm` key ([`ED25519`], [`MLDSA44`] or
91///   [`SLHDSA128`]), decoded strictly.
92pub fn assertion_key(
93    document: &Value,
94    did: &str,
95    verification_method: &str,
96    algorithm: &str,
97) -> Result<Vec<u8>> {
98    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
99    if document_id(document) != did {
100        return Err(refuse("the DID document's id is not the DID"));
101    }
102    let vm_id = absolute(Some(&Value::String(verification_method.to_string())), did)
103        .filter(|id| id.split('#').next() == Some(did) && id.contains('#'))
104        .ok_or_else(|| refuse("the verificationMethod is not a key of this DID"))?;
105    let matches: Vec<&Map<String, Value>> = all_methods(document)
106        .into_iter()
107        .filter(|vm| absolute(vm.get("id"), did).as_deref() == Some(vm_id.as_str()))
108        .collect();
109    let vm = match matches.as_slice() {
110        [] => return Err(refuse("the verificationMethod is not in the DID document")),
111        [one] => *one,
112        _ => {
113            return Err(refuse(
114                "the DID document lists the verificationMethod more than once",
115            ))
116        }
117    };
118    if vm.get("controller").and_then(Value::as_str) != Some(did) {
119        return Err(refuse(
120            "the verificationMethod is not controlled by the DID",
121        ));
122    }
123    if !assertion_ids(document, did).contains(&vm_id) {
124        return Err(refuse(
125            "the verificationMethod is not listed in assertionMethod",
126        ));
127    }
128    key_material(vm, algorithm)
129}
130
131/// The keys a DID document gives a DID for one proof (see [`proof_keys`]).
132#[derive(Debug, Clone, Default, PartialEq, Eq)]
133pub struct ProofKeys {
134    /// The Ed25519 key the proof's Ed25519 verificationMethod names, when the
135    /// document lets the DID use it for assertions.
136    pub ed25519: Option<Vec<u8>>,
137    /// The ML-DSA-44 key the proof's ML-DSA-44 verificationMethod names, the
138    /// same way.
139    pub mldsa44: Option<Vec<u8>>,
140    /// The SLH-DSA-SHA2-128s key the proof's SLH-DSA verificationMethod
141    /// names, the same way.
142    pub slhdsa128: Option<Vec<u8>>,
143    /// The document publishes an ML-DSA-44 assertion key, so the ML-DSA-44
144    /// proof is required.
145    pub requires_post_quantum: bool,
146    /// The document publishes an SLH-DSA-SHA2-128s assertion key, so the
147    /// SLH-DSA proof is required.
148    pub requires_slhdsa128: bool,
149}
150
151impl ProofKeys {
152    /// The proofs the document's published keys require.
153    pub fn required(&self) -> crate::hybrid::Required {
154        crate::hybrid::Required {
155            post_quantum: false,
156            mldsa44: self.requires_post_quantum,
157            slhdsa128: self.requires_slhdsa128,
158        }
159    }
160}
161
162/// The verificationMethods a proof names, by suite.
163#[derive(Debug, Clone, Copy, Default)]
164pub struct ProofMethodRefs<'a> {
165    pub ed25519: Option<&'a str>,
166    pub mldsa44: Option<&'a str>,
167    pub slhdsa128: Option<&'a str>,
168}
169
170/// The keys `document` gives `did` for a proof whose members name `methods`
171/// (only the Ed25519 one for a single classical proof), each chosen with the
172/// rules of [`assertion_key`], and whether the document publishes a
173/// post-quantum assertion key ([`publishes_mldsa44_assertion_key`],
174/// [`publishes_slhdsa128_assertion_key`]). A key the document does not allow
175/// is None.
176pub fn proof_keys_for(document: &Value, did: &str, methods: ProofMethodRefs<'_>) -> ProofKeys {
177    crate::nesting::deep_guard!(ProofKeys::default(); document);
178    let key = |vm: Option<&str>, algorithm: &str| {
179        vm.and_then(|vm| assertion_key(document, did, vm, algorithm).ok())
180    };
181    ProofKeys {
182        ed25519: key(methods.ed25519, ED25519),
183        mldsa44: key(methods.mldsa44, MLDSA44),
184        slhdsa128: key(methods.slhdsa128, SLHDSA128),
185        requires_post_quantum: publishes_mldsa44_assertion_key(document, did),
186        requires_slhdsa128: publishes_slhdsa128_assertion_key(document, did),
187    }
188}
189
190/// [`proof_keys_for`] for a proof with an Ed25519 member and, in a set, an
191/// ML-DSA-44 member.
192pub fn proof_keys(
193    document: &Value,
194    did: &str,
195    ed25519_method: Option<&str>,
196    mldsa44_method: Option<&str>,
197) -> ProofKeys {
198    crate::nesting::deep_guard!(ProofKeys::default(); document);
199    proof_keys_for(
200        document,
201        did,
202        ProofMethodRefs {
203            ed25519: ed25519_method,
204            mldsa44: mldsa44_method,
205            slhdsa128: None,
206        },
207    )
208}
209
210/// The methods the document lists for `did`'s assertions and that `did`
211/// controls.
212fn assertion_methods<'a>(document: &'a Value, did: &str) -> Vec<&'a Map<String, Value>> {
213    if document_id(document) != did {
214        return Vec::new();
215    }
216    let assertion = assertion_ids(document, did);
217    all_methods(document)
218        .into_iter()
219        .filter(|vm| {
220            absolute(vm.get("id"), did).is_some_and(|id| assertion.contains(&id))
221                && vm.get("controller").and_then(Value::as_str) == Some(did)
222        })
223        .collect()
224}
225
226/// True when the document lists, for `did`'s assertions, a method whose
227/// Multikey names the ML-DSA-44 codec. A verifier then requires the
228/// post-quantum proof, so it cannot be dropped from a credential.
229pub fn publishes_mldsa44_assertion_key(document: &Value, did: &str) -> bool {
230    crate::nesting::deep_guard!(true; document);
231    assertion_methods(document, did).into_iter().any(|vm| {
232        let Some(body) = vm
233            .get("publicKeyMultibase")
234            .and_then(Value::as_str)
235            .and_then(|v| v.strip_prefix('z'))
236        else {
237            return false;
238        };
239        multikey::decode_base58_bounded(body)
240            .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::MLDSA44_PUB_PREFIX)
241    })
242}
243
244/// True when the document lists, for `did`'s assertions, a method whose
245/// Multikey names the SLH-DSA-SHA2-128s codec (base64url, as that key is
246/// written). A verifier then requires the SLH-DSA proof, so it cannot be
247/// dropped from a credential.
248pub fn publishes_slhdsa128_assertion_key(document: &Value, did: &str) -> bool {
249    crate::nesting::deep_guard!(true; document);
250    assertion_methods(document, did).into_iter().any(|vm| {
251        let Some(body) = vm
252            .get("publicKeyMultibase")
253            .and_then(Value::as_str)
254            .and_then(|v| v.strip_prefix('u'))
255        else {
256            return false;
257        };
258        // Only the prefix is read: the first three characters hold the first
259        // two bytes, whatever follows.
260        body.len() <= 64
261            && URL_SAFE_NO_PAD
262                .decode(body)
263                .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::SLHDSA128_PUB_PREFIX)
264    })
265}
266
267/// The raw key of one verification method, checked strictly (the method's
268/// type, one kind of key material, the algorithm, the strict decoding), with
269/// no rule about the document it sits in: for display and tooling that lists
270/// a document's keys. A proof's key comes from [`assertion_key`].
271pub fn method_key(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
272    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); vm);
273    key_material(vm, algorithm)
274}
275
276/// The raw key of a verification method, checked strictly.
277fn key_material(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
278    let has_multibase = vm.contains_key("publicKeyMultibase");
279    let has_jwk = vm.contains_key("publicKeyJwk");
280    if has_multibase && has_jwk {
281        return Err(refuse("the verificationMethod carries more than one key"));
282    }
283    let vm_type = vm.get("type").and_then(Value::as_str);
284    // The reference names the type as Python's repr does ('Multikey', or None
285    // for a type that is not text).
286    let cannot_carry = || {
287        let named = vm_type.map_or_else(|| "None".to_string(), crate::grant_chain::py_repr_str);
288        refuse(&format!(
289            "a {named} verificationMethod cannot carry this key"
290        ))
291    };
292    if has_multibase {
293        let allowed: &[&str] = match vm_type {
294            Some("Multikey") => &[ED25519, MLDSA44, SLHDSA128],
295            Some("Ed25519VerificationKey2020") => &[ED25519],
296            _ => &[],
297        };
298        if !allowed.contains(&algorithm) {
299            return Err(cannot_carry());
300        }
301        // The reference's Multikey reader and its refusals.
302        let value = match vm.get("publicKeyMultibase") {
303            Some(Value::String(v)) => v.as_str(),
304            _ => "",
305        };
306        // A key the strict Ed25519 rules refuse stays a weak-key refusal.
307        let (alg, raw) = crate::proof_json::multikey_decode(value).map_err(|e| match e {
308            CoreError::Json(m) => refuse(&m),
309            other => other,
310        })?;
311        if alg != algorithm {
312            return Err(refuse(&format!(
313                "the verificationMethod holds an {alg} key, not {algorithm}"
314            )));
315        }
316        return Ok(raw);
317    }
318    if has_jwk {
319        let jwk_type = matches!(
320            vm_type,
321            Some("JsonWebKey2020" | "JsonWebKey" | "Ed25519VerificationKey2020")
322        );
323        if !jwk_type || algorithm != ED25519 {
324            return Err(cannot_carry());
325        }
326        let jwk = vm
327            .get("publicKeyJwk")
328            .and_then(Value::as_object)
329            .ok_or_else(|| refuse("the publicKeyJwk is not an Ed25519 key"))?;
330        let text = |name: &str| jwk.get(name).and_then(Value::as_str);
331        if text("kty") != Some("OKP") || text("crv") != Some("Ed25519") {
332            return Err(refuse("the publicKeyJwk is not an Ed25519 key"));
333        }
334        if jwk.contains_key("d") {
335            return Err(refuse("the publicKeyJwk carries a private key"));
336        }
337        if jwk.contains_key("use") && text("use") != Some("sig") {
338            return Err(refuse("the publicKeyJwk is not meant for signatures"));
339        }
340        if let Some(ops) = jwk.get("key_ops") {
341            let verifies = ops
342                .as_array()
343                .is_some_and(|ops| ops.iter().any(|o| o.as_str() == Some("verify")));
344            if !verifies {
345                return Err(refuse(
346                    "the publicKeyJwk is not meant for verifying signatures",
347                ));
348            }
349        }
350        if jwk.contains_key("alg") && !matches!(text("alg"), Some("EdDSA" | "Ed25519")) {
351            return Err(refuse("the publicKeyJwk names another algorithm"));
352        }
353        let x = text("x")
354            .filter(|x| {
355                x.len() == 43
356                    && x.bytes()
357                        .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
358            })
359            .ok_or_else(|| refuse("the publicKeyJwk x is not a 32-byte base64url value"))?;
360        let raw = URL_SAFE_NO_PAD
361            .decode(x)
362            .ok()
363            .filter(|raw| URL_SAFE_NO_PAD.encode(raw) == x)
364            .ok_or_else(|| refuse("the publicKeyJwk x is not canonical base64url"))?;
365        if let Some(problem) = crate::proof_json::ed25519_public_key_problem(&raw) {
366            return Err(CoreError::Crypto(problem));
367        }
368        return Ok(raw);
369    }
370    Err(refuse("the verificationMethod carries no public key"))
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use serde_json::json;
377
378    const DID: &str = "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com";
379
380    fn ed_multikey() -> String {
381        crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_multikey()
382    }
383
384    fn doc(vm: Value, assertion: Value) -> Value {
385        json!({"id": DID, "verificationMethod": [vm], "assertionMethod": assertion})
386    }
387
388    fn method(id: &str) -> Value {
389        json!({"id": id, "type": "Multikey", "controller": DID, "publicKeyMultibase": ed_multikey()})
390    }
391
392    #[test]
393    fn every_rule_of_the_assertion_key() {
394        let key = format!("{DID}#key-1");
395        let good = doc(method(&key), json!([key]));
396        assert!(assertion_key(&good, DID, &key, ED25519).is_ok());
397        assert!(assertion_key(&good, DID, "#key-1", ED25519).is_ok());
398        // Relative ids in the document count too.
399        assert!(assertion_key(
400            &doc(method("#key-1"), json!(["#key-1"])),
401            DID,
402            &key,
403            ED25519
404        )
405        .is_ok());
406        // Embedded in assertionMethod.
407        let embedded = json!({"id": DID, "assertionMethod": [method(&key)]});
408        assert!(assertion_key(&embedded, DID, &key, ED25519).is_ok());
409        // The document is another DID's; the method is another DID's; the
410        // method is not listed for assertions; listed twice; another
411        // controller; the wrong algorithm.
412        assert!(assertion_key(&good, "did:webvh:other", &key, ED25519).is_err());
413        assert!(assertion_key(&good, DID, "did:webvh:other#key-1", ED25519).is_err());
414        assert!(assertion_key(&good, DID, DID, ED25519).is_err());
415        assert!(assertion_key(&doc(method(&key), json!([])), DID, &key, ED25519).is_err());
416        let twice = json!({"id": DID, "verificationMethod": [method(&key), method("#key-1")], "assertionMethod": [key]});
417        assert!(assertion_key(&twice, DID, &key, ED25519).is_err());
418        let mut other = method(&key);
419        other["controller"] = json!("did:webvh:other");
420        assert!(assertion_key(&doc(other, json!([key])), DID, &key, ED25519).is_err());
421        assert!(assertion_key(&good, DID, &key, MLDSA44).is_err());
422        assert!(!publishes_mldsa44_assertion_key(&good, DID));
423    }
424
425    #[test]
426    fn jwk_keys_follow_the_reference_rules() {
427        let key = format!("{DID}#key-1");
428        let raw = crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key();
429        let x = URL_SAFE_NO_PAD.encode(raw);
430        let with_jwk = |jwk: Value| {
431            doc(
432                json!({"id": key, "type": "JsonWebKey2020", "controller": DID, "publicKeyJwk": jwk}),
433                json!([key]),
434            )
435        };
436        let ok = with_jwk(json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
437        assert_eq!(
438            assertion_key(&ok, DID, &key, ED25519).unwrap(),
439            raw.to_vec()
440        );
441        for bad in [
442            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "d": x}),
443            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "use": "enc"}),
444            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "key_ops": ["sign"]}),
445            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "alg": "ES256"}),
446            json!({"kty": "OKP", "crv": "X25519", "x": x}),
447            json!({"kty": "OKP", "crv": "Ed25519", "x": format!("{x}=")}),
448        ] {
449            assert!(
450                assertion_key(&with_jwk(bad.clone()), DID, &key, ED25519).is_err(),
451                "{bad}"
452            );
453        }
454    }
455}