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