1#[allow(unused_imports)]
10use crate::prelude::*;
11
12use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
13use serde_json::{Map, Value};
14
15use crate::error::{CoreError, Result};
16use crate::multikey;
17
18pub const ED25519: &str = "Ed25519";
20pub const MLDSA44: &str = "ML-DSA-44";
22pub const SLHDSA128: &str = multikey::SLHDSA128;
24
25fn refuse(text: &str) -> CoreError {
26 CoreError::InvalidDid(text.to_string())
27}
28
29fn list<'a>(document: &'a Value, name: &str) -> &'a [Value] {
30 document
31 .get(name)
32 .and_then(Value::as_array)
33 .map(Vec::as_slice)
34 .unwrap_or(&[])
35}
36
37fn absolute(reference: Option<&Value>, did: &str) -> Option<String> {
39 let text = reference?.as_str()?;
40 if text.is_empty() {
41 return None;
42 }
43 Some(if text.starts_with('#') {
44 format!("{did}{text}")
45 } else {
46 text.to_string()
47 })
48}
49
50fn all_methods(document: &Value) -> Vec<&Map<String, Value>> {
53 list(document, "verificationMethod")
54 .iter()
55 .chain(list(document, "assertionMethod"))
56 .filter_map(Value::as_object)
57 .collect()
58}
59
60fn assertion_ids(document: &Value, did: &str) -> Vec<String> {
62 list(document, "assertionMethod")
63 .iter()
64 .filter_map(|r| {
65 let target = if r.is_object() { r.get("id") } else { Some(r) };
66 absolute(target, did)
67 })
68 .collect()
69}
70
71fn document_id(document: &Value) -> &str {
72 document.get("id").and_then(Value::as_str).unwrap_or("")
73}
74
75pub fn assertion_key(
93 document: &Value,
94 did: &str,
95 verification_method: &str,
96 algorithm: &str,
97) -> Result<Vec<u8>> {
98 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
99 if document_id(document) != did {
100 return Err(refuse("the DID document's id is not the DID"));
101 }
102 let vm_id = absolute(Some(&Value::String(verification_method.to_string())), did)
103 .filter(|id| id.split('#').next() == Some(did) && id.contains('#'))
104 .ok_or_else(|| refuse("the verificationMethod is not a key of this DID"))?;
105 let matches: Vec<&Map<String, Value>> = all_methods(document)
106 .into_iter()
107 .filter(|vm| absolute(vm.get("id"), did).as_deref() == Some(vm_id.as_str()))
108 .collect();
109 let vm = match matches.as_slice() {
110 [] => return Err(refuse("the verificationMethod is not in the DID document")),
111 [one] => *one,
112 _ => {
113 return Err(refuse(
114 "the DID document lists the verificationMethod more than once",
115 ))
116 }
117 };
118 if vm.get("controller").and_then(Value::as_str) != Some(did) {
119 return Err(refuse(
120 "the verificationMethod is not controlled by the DID",
121 ));
122 }
123 if !assertion_ids(document, did).contains(&vm_id) {
124 return Err(refuse(
125 "the verificationMethod is not listed in assertionMethod",
126 ));
127 }
128 key_material(vm, algorithm)
129}
130
131#[derive(Debug, Clone, Default, PartialEq, Eq)]
133pub struct ProofKeys {
134 pub ed25519: Option<Vec<u8>>,
137 pub mldsa44: Option<Vec<u8>>,
140 pub slhdsa128: Option<Vec<u8>>,
143 pub requires_post_quantum: bool,
146 pub requires_slhdsa128: bool,
149}
150
151impl ProofKeys {
152 pub fn required(&self) -> crate::hybrid::Required {
154 crate::hybrid::Required {
155 post_quantum: false,
156 mldsa44: self.requires_post_quantum,
157 slhdsa128: self.requires_slhdsa128,
158 }
159 }
160}
161
162#[derive(Debug, Clone, Copy, Default)]
164pub struct ProofMethodRefs<'a> {
165 pub ed25519: Option<&'a str>,
166 pub mldsa44: Option<&'a str>,
167 pub slhdsa128: Option<&'a str>,
168}
169
170pub fn proof_keys_for(document: &Value, did: &str, methods: ProofMethodRefs<'_>) -> ProofKeys {
177 crate::nesting::deep_guard!(ProofKeys::default(); document);
178 let key = |vm: Option<&str>, algorithm: &str| {
179 vm.and_then(|vm| assertion_key(document, did, vm, algorithm).ok())
180 };
181 ProofKeys {
182 ed25519: key(methods.ed25519, ED25519),
183 mldsa44: key(methods.mldsa44, MLDSA44),
184 slhdsa128: key(methods.slhdsa128, SLHDSA128),
185 requires_post_quantum: publishes_mldsa44_assertion_key(document, did),
186 requires_slhdsa128: publishes_slhdsa128_assertion_key(document, did),
187 }
188}
189
190pub fn proof_keys(
193 document: &Value,
194 did: &str,
195 ed25519_method: Option<&str>,
196 mldsa44_method: Option<&str>,
197) -> ProofKeys {
198 crate::nesting::deep_guard!(ProofKeys::default(); document);
199 proof_keys_for(
200 document,
201 did,
202 ProofMethodRefs {
203 ed25519: ed25519_method,
204 mldsa44: mldsa44_method,
205 slhdsa128: None,
206 },
207 )
208}
209
210fn assertion_methods<'a>(document: &'a Value, did: &str) -> Vec<&'a Map<String, Value>> {
213 if document_id(document) != did {
214 return Vec::new();
215 }
216 let assertion = assertion_ids(document, did);
217 all_methods(document)
218 .into_iter()
219 .filter(|vm| {
220 absolute(vm.get("id"), did).is_some_and(|id| assertion.contains(&id))
221 && vm.get("controller").and_then(Value::as_str) == Some(did)
222 })
223 .collect()
224}
225
226pub fn publishes_mldsa44_assertion_key(document: &Value, did: &str) -> bool {
230 crate::nesting::deep_guard!(true; document);
231 assertion_methods(document, did).into_iter().any(|vm| {
232 let Some(body) = vm
233 .get("publicKeyMultibase")
234 .and_then(Value::as_str)
235 .and_then(|v| v.strip_prefix('z'))
236 else {
237 return false;
238 };
239 multikey::decode_base58_bounded(body)
240 .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::MLDSA44_PUB_PREFIX)
241 })
242}
243
244pub fn publishes_slhdsa128_assertion_key(document: &Value, did: &str) -> bool {
249 crate::nesting::deep_guard!(true; document);
250 assertion_methods(document, did).into_iter().any(|vm| {
251 let Some(body) = vm
252 .get("publicKeyMultibase")
253 .and_then(Value::as_str)
254 .and_then(|v| v.strip_prefix('u'))
255 else {
256 return false;
257 };
258 body.len() <= 64
261 && URL_SAFE_NO_PAD
262 .decode(body)
263 .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::SLHDSA128_PUB_PREFIX)
264 })
265}
266
267pub fn method_key(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
272 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); vm);
273 key_material(vm, algorithm)
274}
275
276fn key_material(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
278 let has_multibase = vm.contains_key("publicKeyMultibase");
279 let has_jwk = vm.contains_key("publicKeyJwk");
280 if has_multibase && has_jwk {
281 return Err(refuse("the verificationMethod carries more than one key"));
282 }
283 let vm_type = vm.get("type").and_then(Value::as_str);
284 let cannot_carry = || {
287 let named = vm_type.map_or_else(|| "None".to_string(), crate::grant_chain::py_repr_str);
288 refuse(&format!(
289 "a {named} verificationMethod cannot carry this key"
290 ))
291 };
292 if has_multibase {
293 let allowed: &[&str] = match vm_type {
294 Some("Multikey") => &[ED25519, MLDSA44, SLHDSA128],
295 Some("Ed25519VerificationKey2020") => &[ED25519],
296 _ => &[],
297 };
298 if !allowed.contains(&algorithm) {
299 return Err(cannot_carry());
300 }
301 let value = match vm.get("publicKeyMultibase") {
303 Some(Value::String(v)) => v.as_str(),
304 _ => "",
305 };
306 let (alg, raw) = crate::proof_json::multikey_decode(value).map_err(|e| match e {
308 CoreError::Json(m) => refuse(&m),
309 other => other,
310 })?;
311 if alg != algorithm {
312 return Err(refuse(&format!(
313 "the verificationMethod holds an {alg} key, not {algorithm}"
314 )));
315 }
316 return Ok(raw);
317 }
318 if has_jwk {
319 let jwk_type = matches!(
320 vm_type,
321 Some("JsonWebKey2020" | "JsonWebKey" | "Ed25519VerificationKey2020")
322 );
323 if !jwk_type || algorithm != ED25519 {
324 return Err(cannot_carry());
325 }
326 let jwk = vm
327 .get("publicKeyJwk")
328 .and_then(Value::as_object)
329 .ok_or_else(|| refuse("the publicKeyJwk is not an Ed25519 key"))?;
330 let text = |name: &str| jwk.get(name).and_then(Value::as_str);
331 if text("kty") != Some("OKP") || text("crv") != Some("Ed25519") {
332 return Err(refuse("the publicKeyJwk is not an Ed25519 key"));
333 }
334 if jwk.contains_key("d") {
335 return Err(refuse("the publicKeyJwk carries a private key"));
336 }
337 if jwk.contains_key("use") && text("use") != Some("sig") {
338 return Err(refuse("the publicKeyJwk is not meant for signatures"));
339 }
340 if let Some(ops) = jwk.get("key_ops") {
341 let verifies = ops
342 .as_array()
343 .is_some_and(|ops| ops.iter().any(|o| o.as_str() == Some("verify")));
344 if !verifies {
345 return Err(refuse(
346 "the publicKeyJwk is not meant for verifying signatures",
347 ));
348 }
349 }
350 if jwk.contains_key("alg") && !matches!(text("alg"), Some("EdDSA" | "Ed25519")) {
351 return Err(refuse("the publicKeyJwk names another algorithm"));
352 }
353 let x = text("x")
354 .filter(|x| {
355 x.len() == 43
356 && x.bytes()
357 .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
358 })
359 .ok_or_else(|| refuse("the publicKeyJwk x is not a 32-byte base64url value"))?;
360 let raw = URL_SAFE_NO_PAD
361 .decode(x)
362 .ok()
363 .filter(|raw| URL_SAFE_NO_PAD.encode(raw) == x)
364 .ok_or_else(|| refuse("the publicKeyJwk x is not canonical base64url"))?;
365 if let Some(problem) = crate::proof_json::ed25519_public_key_problem(&raw) {
366 return Err(CoreError::Crypto(problem));
367 }
368 return Ok(raw);
369 }
370 Err(refuse("the verificationMethod carries no public key"))
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use serde_json::json;
377
378 const DID: &str = "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com";
379
380 fn ed_multikey() -> String {
381 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_multikey()
382 }
383
384 fn doc(vm: Value, assertion: Value) -> Value {
385 json!({"id": DID, "verificationMethod": [vm], "assertionMethod": assertion})
386 }
387
388 fn method(id: &str) -> Value {
389 json!({"id": id, "type": "Multikey", "controller": DID, "publicKeyMultibase": ed_multikey()})
390 }
391
392 #[test]
393 fn every_rule_of_the_assertion_key() {
394 let key = format!("{DID}#key-1");
395 let good = doc(method(&key), json!([key]));
396 assert!(assertion_key(&good, DID, &key, ED25519).is_ok());
397 assert!(assertion_key(&good, DID, "#key-1", ED25519).is_ok());
398 assert!(assertion_key(
400 &doc(method("#key-1"), json!(["#key-1"])),
401 DID,
402 &key,
403 ED25519
404 )
405 .is_ok());
406 let embedded = json!({"id": DID, "assertionMethod": [method(&key)]});
408 assert!(assertion_key(&embedded, DID, &key, ED25519).is_ok());
409 assert!(assertion_key(&good, "did:webvh:other", &key, ED25519).is_err());
413 assert!(assertion_key(&good, DID, "did:webvh:other#key-1", ED25519).is_err());
414 assert!(assertion_key(&good, DID, DID, ED25519).is_err());
415 assert!(assertion_key(&doc(method(&key), json!([])), DID, &key, ED25519).is_err());
416 let twice = json!({"id": DID, "verificationMethod": [method(&key), method("#key-1")], "assertionMethod": [key]});
417 assert!(assertion_key(&twice, DID, &key, ED25519).is_err());
418 let mut other = method(&key);
419 other["controller"] = json!("did:webvh:other");
420 assert!(assertion_key(&doc(other, json!([key])), DID, &key, ED25519).is_err());
421 assert!(assertion_key(&good, DID, &key, MLDSA44).is_err());
422 assert!(!publishes_mldsa44_assertion_key(&good, DID));
423 }
424
425 #[test]
426 fn jwk_keys_follow_the_reference_rules() {
427 let key = format!("{DID}#key-1");
428 let raw = crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key();
429 let x = URL_SAFE_NO_PAD.encode(raw);
430 let with_jwk = |jwk: Value| {
431 doc(
432 json!({"id": key, "type": "JsonWebKey2020", "controller": DID, "publicKeyJwk": jwk}),
433 json!([key]),
434 )
435 };
436 let ok = with_jwk(json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
437 assert_eq!(
438 assertion_key(&ok, DID, &key, ED25519).unwrap(),
439 raw.to_vec()
440 );
441 for bad in [
442 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "d": x}),
443 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "use": "enc"}),
444 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "key_ops": ["sign"]}),
445 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "alg": "ES256"}),
446 json!({"kty": "OKP", "crv": "X25519", "x": x}),
447 json!({"kty": "OKP", "crv": "Ed25519", "x": format!("{x}=")}),
448 ] {
449 assert!(
450 assertion_key(&with_jwk(bad.clone()), DID, &key, ED25519).is_err(),
451 "{bad}"
452 );
453 }
454 }
455}