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";
19
20fn refuse(text: &str) -> CoreError {
21 CoreError::InvalidDid(text.to_string())
22}
23
24fn list<'a>(document: &'a Value, name: &str) -> &'a [Value] {
25 document
26 .get(name)
27 .and_then(Value::as_array)
28 .map(Vec::as_slice)
29 .unwrap_or(&[])
30}
31
32fn absolute(reference: Option<&Value>, did: &str) -> Option<String> {
34 let text = reference?.as_str()?;
35 if text.is_empty() {
36 return None;
37 }
38 Some(if text.starts_with('#') {
39 format!("{did}{text}")
40 } else {
41 text.to_string()
42 })
43}
44
45fn all_methods(document: &Value) -> Vec<&Map<String, Value>> {
48 list(document, "verificationMethod")
49 .iter()
50 .chain(list(document, "assertionMethod"))
51 .filter_map(Value::as_object)
52 .collect()
53}
54
55fn assertion_ids(document: &Value, did: &str) -> Vec<String> {
57 list(document, "assertionMethod")
58 .iter()
59 .filter_map(|r| {
60 let target = if r.is_object() { r.get("id") } else { Some(r) };
61 absolute(target, did)
62 })
63 .collect()
64}
65
66fn document_id(document: &Value) -> &str {
67 document.get("id").and_then(Value::as_str).unwrap_or("")
68}
69
70pub fn assertion_key(
88 document: &Value,
89 did: &str,
90 verification_method: &str,
91 algorithm: &str,
92) -> Result<Vec<u8>> {
93 if document_id(document) != did {
94 return Err(refuse("the DID document's id is not the DID"));
95 }
96 let vm_id = absolute(Some(&Value::String(verification_method.to_string())), did)
97 .filter(|id| id.split('#').next() == Some(did) && id.contains('#'))
98 .ok_or_else(|| refuse("the verificationMethod is not a key of this DID"))?;
99 let matches: Vec<&Map<String, Value>> = all_methods(document)
100 .into_iter()
101 .filter(|vm| absolute(vm.get("id"), did).as_deref() == Some(vm_id.as_str()))
102 .collect();
103 let vm = match matches.as_slice() {
104 [] => return Err(refuse("the verificationMethod is not in the DID document")),
105 [one] => *one,
106 _ => {
107 return Err(refuse(
108 "the DID document lists the verificationMethod more than once",
109 ))
110 }
111 };
112 if vm.get("controller").and_then(Value::as_str) != Some(did) {
113 return Err(refuse(
114 "the verificationMethod is not controlled by the DID",
115 ));
116 }
117 if !assertion_ids(document, did).contains(&vm_id) {
118 return Err(refuse(
119 "the verificationMethod is not listed in assertionMethod",
120 ));
121 }
122 key_material(vm, algorithm)
123}
124
125#[derive(Debug, Clone, Default, PartialEq, Eq)]
127pub struct ProofKeys {
128 pub ed25519: Option<Vec<u8>>,
131 pub mldsa44: Option<Vec<u8>>,
134 pub requires_post_quantum: bool,
137}
138
139pub fn proof_keys(
146 document: &Value,
147 did: &str,
148 ed25519_method: Option<&str>,
149 mldsa44_method: Option<&str>,
150) -> ProofKeys {
151 ProofKeys {
152 ed25519: ed25519_method.and_then(|vm| assertion_key(document, did, vm, ED25519).ok()),
153 mldsa44: mldsa44_method.and_then(|vm| assertion_key(document, did, vm, MLDSA44).ok()),
154 requires_post_quantum: publishes_mldsa44_assertion_key(document, did),
155 }
156}
157
158pub fn publishes_mldsa44_assertion_key(document: &Value, did: &str) -> bool {
162 if document_id(document) != did {
163 return false;
164 }
165 let assertion = assertion_ids(document, did);
166 all_methods(document).into_iter().any(|vm| {
167 let listed = absolute(vm.get("id"), did).is_some_and(|id| assertion.contains(&id));
168 if !listed || vm.get("controller").and_then(Value::as_str) != Some(did) {
169 return false;
170 }
171 let Some(body) = vm
172 .get("publicKeyMultibase")
173 .and_then(Value::as_str)
174 .and_then(|v| v.strip_prefix('z'))
175 else {
176 return false;
177 };
178 multikey::decode_base58_bounded(body)
179 .is_ok_and(|raw| raw.len() >= 2 && raw[..2] == multikey::MLDSA44_PUB_PREFIX)
180 })
181}
182
183fn key_material(vm: &Map<String, Value>, algorithm: &str) -> Result<Vec<u8>> {
185 let has_multibase = vm.contains_key("publicKeyMultibase");
186 let has_jwk = vm.contains_key("publicKeyJwk");
187 if has_multibase && has_jwk {
188 return Err(refuse("the verificationMethod carries more than one key"));
189 }
190 let vm_type = vm.get("type").and_then(Value::as_str);
191 if has_multibase {
192 let allowed: &[&str] = match vm_type {
193 Some("Multikey") => &[ED25519, MLDSA44],
194 Some("Ed25519VerificationKey2020") => &[ED25519],
195 _ => &[],
196 };
197 if !allowed.contains(&algorithm) {
198 return Err(refuse("this verificationMethod type cannot carry this key"));
199 }
200 let value = vm
201 .get("publicKeyMultibase")
202 .and_then(Value::as_str)
203 .ok_or_else(|| refuse("the publicKeyMultibase is not a string"))?;
204 let decoded = multikey::decode(value)?;
205 if decoded.algorithm != algorithm {
206 return Err(refuse(
207 "the verificationMethod holds a key of another algorithm",
208 ));
209 }
210 return Ok(decoded.raw_key);
211 }
212 if has_jwk {
213 let jwk_type = matches!(
214 vm_type,
215 Some("JsonWebKey2020" | "JsonWebKey" | "Ed25519VerificationKey2020")
216 );
217 if !jwk_type || algorithm != ED25519 {
218 return Err(refuse("this verificationMethod type cannot carry this key"));
219 }
220 let jwk = vm
221 .get("publicKeyJwk")
222 .and_then(Value::as_object)
223 .ok_or_else(|| refuse("the publicKeyJwk is not an Ed25519 key"))?;
224 let text = |name: &str| jwk.get(name).and_then(Value::as_str);
225 if text("kty") != Some("OKP") || text("crv") != Some("Ed25519") {
226 return Err(refuse("the publicKeyJwk is not an Ed25519 key"));
227 }
228 if jwk.contains_key("d") {
229 return Err(refuse("the publicKeyJwk carries a private key"));
230 }
231 if jwk.contains_key("use") && text("use") != Some("sig") {
232 return Err(refuse("the publicKeyJwk is not meant for signatures"));
233 }
234 if let Some(ops) = jwk.get("key_ops") {
235 let verifies = ops
236 .as_array()
237 .is_some_and(|ops| ops.iter().any(|o| o.as_str() == Some("verify")));
238 if !verifies {
239 return Err(refuse(
240 "the publicKeyJwk is not meant for verifying signatures",
241 ));
242 }
243 }
244 if jwk.contains_key("alg") && !matches!(text("alg"), Some("EdDSA" | "Ed25519")) {
245 return Err(refuse("the publicKeyJwk names another algorithm"));
246 }
247 let x = text("x")
248 .filter(|x| {
249 x.len() == 43
250 && x.bytes()
251 .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
252 })
253 .ok_or_else(|| refuse("the publicKeyJwk x is not a 32-byte base64url value"))?;
254 let raw = URL_SAFE_NO_PAD
255 .decode(x)
256 .ok()
257 .filter(|raw| URL_SAFE_NO_PAD.encode(raw) == x)
258 .ok_or_else(|| refuse("the publicKeyJwk x is not canonical base64url"))?;
259 crate::keys::strict_verifying_key(&raw)?;
260 return Ok(raw);
261 }
262 Err(refuse("the verificationMethod carries no public key"))
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268 use serde_json::json;
269
270 const DID: &str = "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com";
271
272 fn ed_multikey() -> String {
273 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_multikey()
274 }
275
276 fn doc(vm: Value, assertion: Value) -> Value {
277 json!({"id": DID, "verificationMethod": [vm], "assertionMethod": assertion})
278 }
279
280 fn method(id: &str) -> Value {
281 json!({"id": id, "type": "Multikey", "controller": DID, "publicKeyMultibase": ed_multikey()})
282 }
283
284 #[test]
285 fn every_rule_of_the_assertion_key() {
286 let key = format!("{DID}#key-1");
287 let good = doc(method(&key), json!([key]));
288 assert!(assertion_key(&good, DID, &key, ED25519).is_ok());
289 assert!(assertion_key(&good, DID, "#key-1", ED25519).is_ok());
290 assert!(assertion_key(
292 &doc(method("#key-1"), json!(["#key-1"])),
293 DID,
294 &key,
295 ED25519
296 )
297 .is_ok());
298 let embedded = json!({"id": DID, "assertionMethod": [method(&key)]});
300 assert!(assertion_key(&embedded, DID, &key, ED25519).is_ok());
301 assert!(assertion_key(&good, "did:webvh:other", &key, ED25519).is_err());
305 assert!(assertion_key(&good, DID, "did:webvh:other#key-1", ED25519).is_err());
306 assert!(assertion_key(&good, DID, DID, ED25519).is_err());
307 assert!(assertion_key(&doc(method(&key), json!([])), DID, &key, ED25519).is_err());
308 let twice = json!({"id": DID, "verificationMethod": [method(&key), method("#key-1")], "assertionMethod": [key]});
309 assert!(assertion_key(&twice, DID, &key, ED25519).is_err());
310 let mut other = method(&key);
311 other["controller"] = json!("did:webvh:other");
312 assert!(assertion_key(&doc(other, json!([key])), DID, &key, ED25519).is_err());
313 assert!(assertion_key(&good, DID, &key, MLDSA44).is_err());
314 assert!(!publishes_mldsa44_assertion_key(&good, DID));
315 }
316
317 #[test]
318 fn jwk_keys_follow_the_reference_rules() {
319 let key = format!("{DID}#key-1");
320 let raw = crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key();
321 let x = URL_SAFE_NO_PAD.encode(raw);
322 let with_jwk = |jwk: Value| {
323 doc(
324 json!({"id": key, "type": "JsonWebKey2020", "controller": DID, "publicKeyJwk": jwk}),
325 json!([key]),
326 )
327 };
328 let ok = with_jwk(json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
329 assert_eq!(
330 assertion_key(&ok, DID, &key, ED25519).unwrap(),
331 raw.to_vec()
332 );
333 for bad in [
334 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "d": x}),
335 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "use": "enc"}),
336 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "key_ops": ["sign"]}),
337 json!({"kty": "OKP", "crv": "Ed25519", "x": x, "alg": "ES256"}),
338 json!({"kty": "OKP", "crv": "X25519", "x": x}),
339 json!({"kty": "OKP", "crv": "Ed25519", "x": format!("{x}=")}),
340 ] {
341 assert!(
342 assertion_key(&with_jwk(bad.clone()), DID, &key, ED25519).is_err(),
343 "{bad}"
344 );
345 }
346 }
347}