1use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
10use serde_json::{Map, Value};
11
12use crate::error::{CoreError, Result};
13use crate::multikey;
14
15pub const ED25519: &str = "Ed25519";
17pub const MLDSA44: &str = "ML-DSA-44";
19pub const SLHDSA128: &str = multikey::SLHDSA128;
21
22fn refuse(text: &str) -> CoreError {
23 CoreError::InvalidDid(text.to_string())
24}
25
26fn list<'a>(document: &'a Value, name: &str) -> &'a [Value] {
27 document
28 .get(name)
29 .and_then(Value::as_array)
30 .map(Vec::as_slice)
31 .unwrap_or(&[])
32}
33
34fn absolute(reference: Option<&Value>, did: &str) -> Option<String> {
36 let text = reference?.as_str()?;
37 if text.is_empty() {
38 return None;
39 }
40 Some(if text.starts_with('#') {
41 format!("{did}{text}")
42 } else {
43 text.to_string()
44 })
45}
46
47fn all_methods(document: &Value) -> Vec<&Map<String, Value>> {
50 list(document, "verificationMethod")
51 .iter()
52 .chain(list(document, "assertionMethod"))
53 .filter_map(Value::as_object)
54 .collect()
55}
56
57fn assertion_ids(document: &Value, did: &str) -> Vec<String> {
59 list(document, "assertionMethod")
60 .iter()
61 .filter_map(|r| {
62 let target = if r.is_object() { r.get("id") } else { Some(r) };
63 absolute(target, did)
64 })
65 .collect()
66}
67
68fn document_id(document: &Value) -> &str {
69 document.get("id").and_then(Value::as_str).unwrap_or("")
70}
71
72pub fn assertion_key(
90 document: &Value,
91 did: &str,
92 verification_method: &str,
93 algorithm: &str,
94) -> Result<Vec<u8>> {
95 if document_id(document) != did {
96 return Err(refuse("the DID document's id is not the DID"));
97 }
98 let vm_id = absolute(Some(&Value::String(verification_method.to_string())), did)
99 .filter(|id| id.split('#').next() == Some(did) && id.contains('#'))
100 .ok_or_else(|| refuse("the verificationMethod is not a key of this DID"))?;
101 let matches: Vec<&Map<String, Value>> = all_methods(document)
102 .into_iter()
103 .filter(|vm| absolute(vm.get("id"), did).as_deref() == Some(vm_id.as_str()))
104 .collect();
105 let vm = match matches.as_slice() {
106 [] => return Err(refuse("the verificationMethod is not in the DID document")),
107 [one] => *one,
108 _ => {
109 return Err(refuse(
110 "the DID document lists the verificationMethod more than once",
111 ))
112 }
113 };
114 if vm.get("controller").and_then(Value::as_str) != Some(did) {
115 return Err(refuse(
116 "the verificationMethod is not controlled by the DID",
117 ));
118 }
119 if !assertion_ids(document, did).contains(&vm_id) {
120 return Err(refuse(
121 "the verificationMethod is not listed in assertionMethod",
122 ));
123 }
124 key_material(vm, algorithm)
125}
126
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
129pub struct ProofKeys {
130 pub ed25519: Option<Vec<u8>>,
133 pub mldsa44: Option<Vec<u8>>,
136 pub slhdsa128: Option<Vec<u8>>,
139 pub requires_post_quantum: bool,
142 pub requires_slhdsa128: bool,
145}
146
147impl ProofKeys {
148 pub fn required(&self) -> crate::hybrid::Required {
150 crate::hybrid::Required {
151 post_quantum: false,
152 mldsa44: self.requires_post_quantum,
153 slhdsa128: self.requires_slhdsa128,
154 }
155 }
156}
157
158#[derive(Debug, Clone, Copy, Default)]
160pub struct ProofMethodRefs<'a> {
161 pub ed25519: Option<&'a str>,
162 pub mldsa44: Option<&'a str>,
163 pub slhdsa128: Option<&'a str>,
164}
165
166pub fn proof_keys_for(document: &Value, did: &str, methods: ProofMethodRefs<'_>) -> ProofKeys {
173 let key = |vm: Option<&str>, algorithm: &str| {
174 vm.and_then(|vm| assertion_key(document, did, vm, algorithm).ok())
175 };
176 ProofKeys {
177 ed25519: key(methods.ed25519, ED25519),
178 mldsa44: key(methods.mldsa44, MLDSA44),
179 slhdsa128: key(methods.slhdsa128, SLHDSA128),
180 requires_post_quantum: publishes_mldsa44_assertion_key(document, did),
181 requires_slhdsa128: publishes_slhdsa128_assertion_key(document, did),
182 }
183}
184
185pub fn proof_keys(
188 document: &Value,
189 did: &str,
190 ed25519_method: Option<&str>,
191 mldsa44_method: Option<&str>,
192) -> ProofKeys {
193 proof_keys_for(
194 document,
195 did,
196 ProofMethodRefs {
197 ed25519: ed25519_method,
198 mldsa44: mldsa44_method,
199 slhdsa128: None,
200 },
201 )
202}
203
204fn assertion_methods<'a>(document: &'a Value, did: &str) -> Vec<&'a Map<String, Value>> {
207 if document_id(document) != did {
208 return Vec::new();
209 }
210 let assertion = assertion_ids(document, did);
211 all_methods(document)
212 .into_iter()
213 .filter(|vm| {
214 absolute(vm.get("id"), did).is_some_and(|id| assertion.contains(&id))
215 && vm.get("controller").and_then(Value::as_str) == Some(did)
216 })
217 .collect()
218}
219
220pub fn publishes_mldsa44_assertion_key(document: &Value, did: &str) -> bool {
224 assertion_methods(document, did).into_iter().any(|vm| {
225 let Some(body) = vm
226 .get("publicKeyMultibase")
227 .and_then(Value::as_str)
228 .and_then(|v| v.strip_prefix('z'))
229 else {
230 return false;
231 };
232 multikey::decode_base58_bounded(body)
233 .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::MLDSA44_PUB_PREFIX)
234 })
235}
236
237pub fn publishes_slhdsa128_assertion_key(document: &Value, did: &str) -> bool {
242 assertion_methods(document, did).into_iter().any(|vm| {
243 let Some(body) = vm
244 .get("publicKeyMultibase")
245 .and_then(Value::as_str)
246 .and_then(|v| v.strip_prefix('u'))
247 else {
248 return false;
249 };
250 body.len() <= 64
253 && URL_SAFE_NO_PAD
254 .decode(body)
255 .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::SLHDSA128_PUB_PREFIX)
256 })
257}
258
259fn key_material(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
261 let has_multibase = vm.contains_key("publicKeyMultibase");
262 let has_jwk = vm.contains_key("publicKeyJwk");
263 if has_multibase && has_jwk {
264 return Err(refuse("the verificationMethod carries more than one key"));
265 }
266 let vm_type = vm.get("type").and_then(Value::as_str);
267 if has_multibase {
268 let allowed: &[&str] = match vm_type {
269 Some("Multikey") => &[ED25519, MLDSA44, SLHDSA128],
270 Some("Ed25519VerificationKey2020") => &[ED25519],
271 _ => &[],
272 };
273 if !allowed.contains(&algorithm) {
274 return Err(refuse("this verificationMethod type cannot carry this key"));
275 }
276 let value = vm
277 .get("publicKeyMultibase")
278 .and_then(Value::as_str)
279 .ok_or_else(|| refuse("the publicKeyMultibase is not a string"))?;
280 let decoded = multikey::decode(value)?;
281 if decoded.algorithm != algorithm {
282 return Err(refuse(
283 "the verificationMethod holds a key of another algorithm",
284 ));
285 }
286 return Ok(decoded.raw_key);
287 }
288 if has_jwk {
289 let jwk_type = matches!(
290 vm_type,
291 Some("JsonWebKey2020" | "JsonWebKey" | "Ed25519VerificationKey2020")
292 );
293 if !jwk_type || algorithm != ED25519 {
294 return Err(refuse("this verificationMethod type cannot carry this key"));
295 }
296 let jwk = vm
297 .get("publicKeyJwk")
298 .and_then(Value::as_object)
299 .ok_or_else(|| refuse("the publicKeyJwk is not an Ed25519 key"))?;
300 let text = |name: &str| jwk.get(name).and_then(Value::as_str);
301 if text("kty") != Some("OKP") || text("crv") != Some("Ed25519") {
302 return Err(refuse("the publicKeyJwk is not an Ed25519 key"));
303 }
304 if jwk.contains_key("d") {
305 return Err(refuse("the publicKeyJwk carries a private key"));
306 }
307 if jwk.contains_key("use") && text("use") != Some("sig") {
308 return Err(refuse("the publicKeyJwk is not meant for signatures"));
309 }
310 if let Some(ops) = jwk.get("key_ops") {
311 let verifies = ops
312 .as_array()
313 .is_some_and(|ops| ops.iter().any(|o| o.as_str() == Some("verify")));
314 if !verifies {
315 return Err(refuse(
316 "the publicKeyJwk is not meant for verifying signatures",
317 ));
318 }
319 }
320 if jwk.contains_key("alg") && !matches!(text("alg"), Some("EdDSA" | "Ed25519")) {
321 return Err(refuse("the publicKeyJwk names another algorithm"));
322 }
323 let x = text("x")
324 .filter(|x| {
325 x.len() == 43
326 && x.bytes()
327 .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
328 })
329 .ok_or_else(|| refuse("the publicKeyJwk x is not a 32-byte base64url value"))?;
330 let raw = URL_SAFE_NO_PAD
331 .decode(x)
332 .ok()
333 .filter(|raw| URL_SAFE_NO_PAD.encode(raw) == x)
334 .ok_or_else(|| refuse("the publicKeyJwk x is not canonical base64url"))?;
335 crate::keys::strict_verifying_key(&raw)?;
336 return Ok(raw);
337 }
338 Err(refuse("the verificationMethod carries no public key"))
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344 use serde_json::json;
345
346 const DID: &str = "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com";
347
348 fn ed_multikey() -> String {
349 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_multikey()
350 }
351
352 fn doc(vm: Value, assertion: Value) -> Value {
353 json!({"id": DID, "verificationMethod": [vm], "assertionMethod": assertion})
354 }
355
356 fn method(id: &str) -> Value {
357 json!({"id": id, "type": "Multikey", "controller": DID, "publicKeyMultibase": ed_multikey()})
358 }
359
360 #[test]
361 fn every_rule_of_the_assertion_key() {
362 let key = format!("{DID}#key-1");
363 let good = doc(method(&key), json!([key]));
364 assert!(assertion_key(&good, DID, &key, ED25519).is_ok());
365 assert!(assertion_key(&good, DID, "#key-1", ED25519).is_ok());
366 assert!(assertion_key(
368 &doc(method("#key-1"), json!(["#key-1"])),
369 DID,
370 &key,
371 ED25519
372 )
373 .is_ok());
374 let embedded = json!({"id": DID, "assertionMethod": [method(&key)]});
376 assert!(assertion_key(&embedded, DID, &key, ED25519).is_ok());
377 assert!(assertion_key(&good, "did:webvh:other", &key, ED25519).is_err());
381 assert!(assertion_key(&good, DID, "did:webvh:other#key-1", ED25519).is_err());
382 assert!(assertion_key(&good, DID, DID, ED25519).is_err());
383 assert!(assertion_key(&doc(method(&key), json!([])), DID, &key, ED25519).is_err());
384 let twice = json!({"id": DID, "verificationMethod": [method(&key), method("#key-1")], "assertionMethod": [key]});
385 assert!(assertion_key(&twice, DID, &key, ED25519).is_err());
386 let mut other = method(&key);
387 other["controller"] = json!("did:webvh:other");
388 assert!(assertion_key(&doc(other, json!([key])), DID, &key, ED25519).is_err());
389 assert!(assertion_key(&good, DID, &key, MLDSA44).is_err());
390 assert!(!publishes_mldsa44_assertion_key(&good, DID));
391 }
392
393 #[test]
394 fn jwk_keys_follow_the_reference_rules() {
395 let key = format!("{DID}#key-1");
396 let raw = crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key();
397 let x = URL_SAFE_NO_PAD.encode(raw);
398 let with_jwk = |jwk: Value| {
399 doc(
400 json!({"id": key, "type": "JsonWebKey2020", "controller": DID, "publicKeyJwk": jwk}),
401 json!([key]),
402 )
403 };
404 let ok = with_jwk(json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
405 assert_eq!(
406 assertion_key(&ok, DID, &key, ED25519).unwrap(),
407 raw.to_vec()
408 );
409 for bad in [
410 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "d": x}),
411 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "use": "enc"}),
412 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "key_ops": ["sign"]}),
413 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "alg": "ES256"}),
414 json!({"kty": "OKP", "crv": "X25519", "x": x}),
415 json!({"kty": "OKP", "crv": "Ed25519", "x": format!("{x}=")}),
416 ] {
417 assert!(
418 assertion_key(&with_jwk(bad.clone()), DID, &key, ED25519).is_err(),
419 "{bad}"
420 );
421 }
422 }
423}