#[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;
pub const ED25519: &str = "Ed25519";
pub const MLDSA44: &str = "ML-DSA-44";
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(&[])
}
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()
})
}
fn all_methods(document: &Value) -> Vec<&Map<String, Value>> {
list(document, "verificationMethod")
.iter()
.chain(list(document, "assertionMethod"))
.filter_map(Value::as_object)
.collect()
}
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("")
}
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)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProofKeys {
pub ed25519: Option<Vec<u8>>,
pub mldsa44: Option<Vec<u8>>,
pub slhdsa128: Option<Vec<u8>>,
pub requires_post_quantum: bool,
pub requires_slhdsa128: bool,
}
impl ProofKeys {
pub fn required(&self) -> crate::hybrid::Required {
crate::hybrid::Required {
post_quantum: false,
mldsa44: self.requires_post_quantum,
slhdsa128: self.requires_slhdsa128,
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ProofMethodRefs<'a> {
pub ed25519: Option<&'a str>,
pub mldsa44: Option<&'a str>,
pub slhdsa128: Option<&'a str>,
}
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),
}
}
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,
},
)
}
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()
}
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)
})
}
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;
};
body.len() <= 64
&& URL_SAFE_NO_PAD
.decode(body)
.is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::SLHDSA128_PUB_PREFIX)
})
}
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)
}
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);
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());
}
let value = match vm.get("publicKeyMultibase") {
Some(Value::String(v)) => v.as_str(),
_ => "",
};
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());
assert!(assertion_key(
&doc(method("#key-1"), json!(["#key-1"])),
DID,
&key,
ED25519
)
.is_ok());
let embedded = json!({"id": DID, "assertionMethod": [method(&key)]});
assert!(assertion_key(&embedded, DID, &key, ED25519).is_ok());
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}"
);
}
}
}