vouch-core 4.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Choosing a DID's assertion key from its DID document, with the rules of
//! the Python reference (`vouch.did_web.DIDDocument.assertion_key` and
//! `publishes_mldsa44_assertion_key`).
//!
//! The core never fetches a DID document. These rules run on a document the
//! caller already holds, such as the verified state of a did:webvh log
//! ([`crate::did_webvh::verify_log`]).

#[allow(unused_imports)]
use crate::prelude::*;

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use serde_json::{Map, Value};

use crate::error::{CoreError, Result};
use crate::multikey;

/// The Ed25519 algorithm name, as [`multikey::decode`] reports it.
pub const ED25519: &str = "Ed25519";
/// The ML-DSA-44 algorithm name, as [`multikey::decode`] reports it.
pub const MLDSA44: &str = "ML-DSA-44";
/// The SLH-DSA-SHA2-128s algorithm name, as [`multikey::decode`] reports it.
pub const SLHDSA128: &str = multikey::SLHDSA128;

fn refuse(text: &str) -> CoreError {
    CoreError::InvalidDid(text.to_string())
}

fn list<'a>(document: &'a Value, name: &str) -> &'a [Value] {
    document
        .get(name)
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or(&[])
}

/// An id written relative to the document ("#key-1") made absolute.
fn absolute(reference: Option<&Value>, did: &str) -> Option<String> {
    let text = reference?.as_str()?;
    if text.is_empty() {
        return None;
    }
    Some(if text.starts_with('#') {
        format!("{did}{text}")
    } else {
        text.to_string()
    })
}

/// Every method object: the verificationMethod list, then the methods
/// embedded in assertionMethod.
fn all_methods(document: &Value) -> Vec<&Map<String, Value>> {
    list(document, "verificationMethod")
        .iter()
        .chain(list(document, "assertionMethod"))
        .filter_map(Value::as_object)
        .collect()
}

/// The ids the document lists in assertionMethod, by reference or embedded.
fn assertion_ids(document: &Value, did: &str) -> Vec<String> {
    list(document, "assertionMethod")
        .iter()
        .filter_map(|r| {
            let target = if r.is_object() { r.get("id") } else { Some(r) };
            absolute(target, did)
        })
        .collect()
}

fn document_id(document: &Value) -> &str {
    document.get("id").and_then(Value::as_str).unwrap_or("")
}

/// The raw public key a proof names, when `document` lets `did` use it for
/// assertions. Every rule must hold, or the key is refused:
///
/// - the document's `id` is exactly `did`;
/// - `verification_method` is `did` plus a fragment (or just the fragment),
///   and exactly one method in the document has that id (ids written
///   relative to the document, "#key-1", count);
/// - the method's `controller` is `did`;
/// - the method is listed in `assertionMethod`, by reference (absolute or
///   relative) or embedded there;
/// - the method carries one kind of key material, of the right kind:
///   `Multikey` or `Ed25519VerificationKey2020` with `publicKeyMultibase`, or
///   `JsonWebKey2020` / `JsonWebKey` (or the earlier
///   `Ed25519VerificationKey2020`) with a public Ed25519 `publicKeyJwk` meant
///   for signatures;
/// - the key is a well-formed `algorithm` key ([`ED25519`], [`MLDSA44`] or
///   [`SLHDSA128`]), decoded strictly.
pub fn assertion_key(
    document: &Value,
    did: &str,
    verification_method: &str,
    algorithm: &str,
) -> Result<Vec<u8>> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
    if document_id(document) != did {
        return Err(refuse("the DID document's id is not the DID"));
    }
    let vm_id = absolute(Some(&Value::String(verification_method.to_string())), did)
        .filter(|id| id.split('#').next() == Some(did) && id.contains('#'))
        .ok_or_else(|| refuse("the verificationMethod is not a key of this DID"))?;
    let matches: Vec<&Map<String, Value>> = all_methods(document)
        .into_iter()
        .filter(|vm| absolute(vm.get("id"), did).as_deref() == Some(vm_id.as_str()))
        .collect();
    let vm = match matches.as_slice() {
        [] => return Err(refuse("the verificationMethod is not in the DID document")),
        [one] => *one,
        _ => {
            return Err(refuse(
                "the DID document lists the verificationMethod more than once",
            ))
        }
    };
    if vm.get("controller").and_then(Value::as_str) != Some(did) {
        return Err(refuse(
            "the verificationMethod is not controlled by the DID",
        ));
    }
    if !assertion_ids(document, did).contains(&vm_id) {
        return Err(refuse(
            "the verificationMethod is not listed in assertionMethod",
        ));
    }
    key_material(vm, algorithm)
}

/// The keys a DID document gives a DID for one proof (see [`proof_keys`]).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProofKeys {
    /// The Ed25519 key the proof's Ed25519 verificationMethod names, when the
    /// document lets the DID use it for assertions.
    pub ed25519: Option<Vec<u8>>,
    /// The ML-DSA-44 key the proof's ML-DSA-44 verificationMethod names, the
    /// same way.
    pub mldsa44: Option<Vec<u8>>,
    /// The SLH-DSA-SHA2-128s key the proof's SLH-DSA verificationMethod
    /// names, the same way.
    pub slhdsa128: Option<Vec<u8>>,
    /// The document publishes an ML-DSA-44 assertion key, so the ML-DSA-44
    /// proof is required.
    pub requires_post_quantum: bool,
    /// The document publishes an SLH-DSA-SHA2-128s assertion key, so the
    /// SLH-DSA proof is required.
    pub requires_slhdsa128: bool,
}

impl ProofKeys {
    /// The proofs the document's published keys require.
    pub fn required(&self) -> crate::hybrid::Required {
        crate::hybrid::Required {
            post_quantum: false,
            mldsa44: self.requires_post_quantum,
            slhdsa128: self.requires_slhdsa128,
        }
    }
}

/// The verificationMethods a proof names, by suite.
#[derive(Debug, Clone, Copy, Default)]
pub struct ProofMethodRefs<'a> {
    pub ed25519: Option<&'a str>,
    pub mldsa44: Option<&'a str>,
    pub slhdsa128: Option<&'a str>,
}

/// The keys `document` gives `did` for a proof whose members name `methods`
/// (only the Ed25519 one for a single classical proof), each chosen with the
/// rules of [`assertion_key`], and whether the document publishes a
/// post-quantum assertion key ([`publishes_mldsa44_assertion_key`],
/// [`publishes_slhdsa128_assertion_key`]). A key the document does not allow
/// is None.
pub fn proof_keys_for(document: &Value, did: &str, methods: ProofMethodRefs<'_>) -> ProofKeys {
    crate::nesting::deep_guard!(ProofKeys::default(); document);
    let key = |vm: Option<&str>, algorithm: &str| {
        vm.and_then(|vm| assertion_key(document, did, vm, algorithm).ok())
    };
    ProofKeys {
        ed25519: key(methods.ed25519, ED25519),
        mldsa44: key(methods.mldsa44, MLDSA44),
        slhdsa128: key(methods.slhdsa128, SLHDSA128),
        requires_post_quantum: publishes_mldsa44_assertion_key(document, did),
        requires_slhdsa128: publishes_slhdsa128_assertion_key(document, did),
    }
}

/// [`proof_keys_for`] for a proof with an Ed25519 member and, in a set, an
/// ML-DSA-44 member.
pub fn proof_keys(
    document: &Value,
    did: &str,
    ed25519_method: Option<&str>,
    mldsa44_method: Option<&str>,
) -> ProofKeys {
    crate::nesting::deep_guard!(ProofKeys::default(); document);
    proof_keys_for(
        document,
        did,
        ProofMethodRefs {
            ed25519: ed25519_method,
            mldsa44: mldsa44_method,
            slhdsa128: None,
        },
    )
}

/// The methods the document lists for `did`'s assertions and that `did`
/// controls.
fn assertion_methods<'a>(document: &'a Value, did: &str) -> Vec<&'a Map<String, Value>> {
    if document_id(document) != did {
        return Vec::new();
    }
    let assertion = assertion_ids(document, did);
    all_methods(document)
        .into_iter()
        .filter(|vm| {
            absolute(vm.get("id"), did).is_some_and(|id| assertion.contains(&id))
                && vm.get("controller").and_then(Value::as_str) == Some(did)
        })
        .collect()
}

/// True when the document lists, for `did`'s assertions, a method whose
/// Multikey names the ML-DSA-44 codec. A verifier then requires the
/// post-quantum proof, so it cannot be dropped from a credential.
pub fn publishes_mldsa44_assertion_key(document: &Value, did: &str) -> bool {
    crate::nesting::deep_guard!(true; document);
    assertion_methods(document, did).into_iter().any(|vm| {
        let Some(body) = vm
            .get("publicKeyMultibase")
            .and_then(Value::as_str)
            .and_then(|v| v.strip_prefix('z'))
        else {
            return false;
        };
        multikey::decode_base58_bounded(body)
            .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::MLDSA44_PUB_PREFIX)
    })
}

/// True when the document lists, for `did`'s assertions, a method whose
/// Multikey names the SLH-DSA-SHA2-128s codec (base64url, as that key is
/// written). A verifier then requires the SLH-DSA proof, so it cannot be
/// dropped from a credential.
pub fn publishes_slhdsa128_assertion_key(document: &Value, did: &str) -> bool {
    crate::nesting::deep_guard!(true; document);
    assertion_methods(document, did).into_iter().any(|vm| {
        let Some(body) = vm
            .get("publicKeyMultibase")
            .and_then(Value::as_str)
            .and_then(|v| v.strip_prefix('u'))
        else {
            return false;
        };
        // Only the prefix is read: the first three characters hold the first
        // two bytes, whatever follows.
        body.len() <= 64
            && URL_SAFE_NO_PAD
                .decode(body)
                .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::SLHDSA128_PUB_PREFIX)
    })
}

/// The raw key of one verification method, checked strictly (the method's
/// type, one kind of key material, the algorithm, the strict decoding), with
/// no rule about the document it sits in: for display and tooling that lists
/// a document's keys. A proof's key comes from [`assertion_key`].
pub fn method_key(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); vm);
    key_material(vm, algorithm)
}

/// The raw key of a verification method, checked strictly.
fn key_material(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
    let has_multibase = vm.contains_key("publicKeyMultibase");
    let has_jwk = vm.contains_key("publicKeyJwk");
    if has_multibase && has_jwk {
        return Err(refuse("the verificationMethod carries more than one key"));
    }
    let vm_type = vm.get("type").and_then(Value::as_str);
    // The reference names the type as Python's repr does ('Multikey', or None
    // for a type that is not text).
    let cannot_carry = || {
        let named = vm_type.map_or_else(|| "None".to_string(), crate::grant_chain::py_repr_str);
        refuse(&format!(
            "a {named} verificationMethod cannot carry this key"
        ))
    };
    if has_multibase {
        let allowed: &[&str] = match vm_type {
            Some("Multikey") => &[ED25519, MLDSA44, SLHDSA128],
            Some("Ed25519VerificationKey2020") => &[ED25519],
            _ => &[],
        };
        if !allowed.contains(&algorithm) {
            return Err(cannot_carry());
        }
        // The reference's Multikey reader and its refusals.
        let value = match vm.get("publicKeyMultibase") {
            Some(Value::String(v)) => v.as_str(),
            _ => "",
        };
        // A key the strict Ed25519 rules refuse stays a weak-key refusal.
        let (alg, raw) = crate::proof_json::multikey_decode(value).map_err(|e| match e {
            CoreError::Json(m) => refuse(&m),
            other => other,
        })?;
        if alg != algorithm {
            return Err(refuse(&format!(
                "the verificationMethod holds an {alg} key, not {algorithm}"
            )));
        }
        return Ok(raw);
    }
    if has_jwk {
        let jwk_type = matches!(
            vm_type,
            Some("JsonWebKey2020" | "JsonWebKey" | "Ed25519VerificationKey2020")
        );
        if !jwk_type || algorithm != ED25519 {
            return Err(cannot_carry());
        }
        let jwk = vm
            .get("publicKeyJwk")
            .and_then(Value::as_object)
            .ok_or_else(|| refuse("the publicKeyJwk is not an Ed25519 key"))?;
        let text = |name: &str| jwk.get(name).and_then(Value::as_str);
        if text("kty") != Some("OKP") || text("crv") != Some("Ed25519") {
            return Err(refuse("the publicKeyJwk is not an Ed25519 key"));
        }
        if jwk.contains_key("d") {
            return Err(refuse("the publicKeyJwk carries a private key"));
        }
        if jwk.contains_key("use") && text("use") != Some("sig") {
            return Err(refuse("the publicKeyJwk is not meant for signatures"));
        }
        if let Some(ops) = jwk.get("key_ops") {
            let verifies = ops
                .as_array()
                .is_some_and(|ops| ops.iter().any(|o| o.as_str() == Some("verify")));
            if !verifies {
                return Err(refuse(
                    "the publicKeyJwk is not meant for verifying signatures",
                ));
            }
        }
        if jwk.contains_key("alg") && !matches!(text("alg"), Some("EdDSA" | "Ed25519")) {
            return Err(refuse("the publicKeyJwk names another algorithm"));
        }
        let x = text("x")
            .filter(|x| {
                x.len() == 43
                    && x.bytes()
                        .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
            })
            .ok_or_else(|| refuse("the publicKeyJwk x is not a 32-byte base64url value"))?;
        let raw = URL_SAFE_NO_PAD
            .decode(x)
            .ok()
            .filter(|raw| URL_SAFE_NO_PAD.encode(raw) == x)
            .ok_or_else(|| refuse("the publicKeyJwk x is not canonical base64url"))?;
        if let Some(problem) = crate::proof_json::ed25519_public_key_problem(&raw) {
            return Err(CoreError::Crypto(problem));
        }
        return Ok(raw);
    }
    Err(refuse("the verificationMethod carries no public key"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    const DID: &str = "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com";

    fn ed_multikey() -> String {
        crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_multikey()
    }

    fn doc(vm: Value, assertion: Value) -> Value {
        json!({"id": DID, "verificationMethod": [vm], "assertionMethod": assertion})
    }

    fn method(id: &str) -> Value {
        json!({"id": id, "type": "Multikey", "controller": DID, "publicKeyMultibase": ed_multikey()})
    }

    #[test]
    fn every_rule_of_the_assertion_key() {
        let key = format!("{DID}#key-1");
        let good = doc(method(&key), json!([key]));
        assert!(assertion_key(&good, DID, &key, ED25519).is_ok());
        assert!(assertion_key(&good, DID, "#key-1", ED25519).is_ok());
        // Relative ids in the document count too.
        assert!(assertion_key(
            &doc(method("#key-1"), json!(["#key-1"])),
            DID,
            &key,
            ED25519
        )
        .is_ok());
        // Embedded in assertionMethod.
        let embedded = json!({"id": DID, "assertionMethod": [method(&key)]});
        assert!(assertion_key(&embedded, DID, &key, ED25519).is_ok());
        // The document is another DID's; the method is another DID's; the
        // method is not listed for assertions; listed twice; another
        // controller; the wrong algorithm.
        assert!(assertion_key(&good, "did:webvh:other", &key, ED25519).is_err());
        assert!(assertion_key(&good, DID, "did:webvh:other#key-1", ED25519).is_err());
        assert!(assertion_key(&good, DID, DID, ED25519).is_err());
        assert!(assertion_key(&doc(method(&key), json!([])), DID, &key, ED25519).is_err());
        let twice = json!({"id": DID, "verificationMethod": [method(&key), method("#key-1")], "assertionMethod": [key]});
        assert!(assertion_key(&twice, DID, &key, ED25519).is_err());
        let mut other = method(&key);
        other["controller"] = json!("did:webvh:other");
        assert!(assertion_key(&doc(other, json!([key])), DID, &key, ED25519).is_err());
        assert!(assertion_key(&good, DID, &key, MLDSA44).is_err());
        assert!(!publishes_mldsa44_assertion_key(&good, DID));
    }

    #[test]
    fn jwk_keys_follow_the_reference_rules() {
        let key = format!("{DID}#key-1");
        let raw = crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key();
        let x = URL_SAFE_NO_PAD.encode(raw);
        let with_jwk = |jwk: Value| {
            doc(
                json!({"id": key, "type": "JsonWebKey2020", "controller": DID, "publicKeyJwk": jwk}),
                json!([key]),
            )
        };
        let ok = with_jwk(json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
        assert_eq!(
            assertion_key(&ok, DID, &key, ED25519).unwrap(),
            raw.to_vec()
        );
        for bad in [
            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "d": x}),
            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "use": "enc"}),
            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "key_ops": ["sign"]}),
            json!({"kty": "OKP", "crv": "Ed25519", "x": x, "alg": "ES256"}),
            json!({"kty": "OKP", "crv": "X25519", "x": x}),
            json!({"kty": "OKP", "crv": "Ed25519", "x": format!("{x}=")}),
        ] {
            assert!(
                assertion_key(&with_jwk(bad.clone()), DID, &key, ED25519).is_err(),
                "{bad}"
            );
        }
    }
}