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