vouch-core 4.0.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
//! 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`]).

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";

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`] or [`MLDSA44`]),
///   decoded strictly.
pub fn assertion_key(
    document: &Value,
    did: &str,
    verification_method: &str,
    algorithm: &str,
) -> Result<Vec<u8>> {
    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 document publishes an ML-DSA-44 assertion key, so the
    /// post-quantum proof is required.
    pub requires_post_quantum: bool,
}

/// The keys `document` gives `did` for a proof whose Ed25519 member names
/// `ed25519_method` and whose ML-DSA-44 member names `mldsa44_method` (None
/// for a single classical proof), each chosen with the rules of
/// [`assertion_key`], and whether the document publishes an ML-DSA-44
/// assertion key ([`publishes_mldsa44_assertion_key`]). A key the document
/// does not allow is None.
pub fn proof_keys(
    document: &Value,
    did: &str,
    ed25519_method: Option<&str>,
    mldsa44_method: Option<&str>,
) -> ProofKeys {
    ProofKeys {
        ed25519: ed25519_method.and_then(|vm| assertion_key(document, did, vm, ED25519).ok()),
        mldsa44: mldsa44_method.and_then(|vm| assertion_key(document, did, vm, MLDSA44).ok()),
        requires_post_quantum: publishes_mldsa44_assertion_key(document, did),
    }
}

/// 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 {
    if document_id(document) != did {
        return false;
    }
    let assertion = assertion_ids(document, did);
    all_methods(document).into_iter().any(|vm| {
        let listed = absolute(vm.get("id"), did).is_some_and(|id| assertion.contains(&id));
        if !listed || vm.get("controller").and_then(Value::as_str) != Some(did) {
            return false;
        }
        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)
    })
}

/// 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);
    if has_multibase {
        let allowed: &[&str] = match vm_type {
            Some("Multikey") => &[ED25519, MLDSA44],
            Some("Ed25519VerificationKey2020") => &[ED25519],
            _ => &[],
        };
        if !allowed.contains(&algorithm) {
            return Err(refuse("this verificationMethod type cannot carry this key"));
        }
        let value = vm
            .get("publicKeyMultibase")
            .and_then(Value::as_str)
            .ok_or_else(|| refuse("the publicKeyMultibase is not a string"))?;
        let decoded = multikey::decode(value)?;
        if decoded.algorithm != algorithm {
            return Err(refuse(
                "the verificationMethod holds a key of another algorithm",
            ));
        }
        return Ok(decoded.raw_key);
    }
    if has_jwk {
        let jwk_type = matches!(
            vm_type,
            Some("JsonWebKey2020" | "JsonWebKey" | "Ed25519VerificationKey2020")
        );
        if !jwk_type || algorithm != ED25519 {
            return Err(refuse("this verificationMethod type cannot carry this key"));
        }
        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"))?;
        crate::keys::strict_verifying_key(&raw)?;
        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}"
            );
        }
    }
}