1#[allow(unused_imports)]
19use crate::prelude::*;
20
21use serde_json::{Map, Value};
22use sha2::{Digest, Sha256};
23
24use crate::error::{CoreError, Result};
25use crate::jcs;
26use crate::keys::{self, Ed25519KeyPair};
27
28pub const CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
29pub const PROOF_TYPE: &str = "DataIntegrityProof";
30
31#[derive(Debug, Clone)]
35pub struct BuildProofOptions {
36 pub verification_method: String,
37 pub proof_purpose: String,
38 pub created: String,
39}
40
41impl BuildProofOptions {
42 pub fn new(verification_method: impl Into<String>, created: impl Into<String>) -> Self {
43 Self {
44 verification_method: verification_method.into(),
45 proof_purpose: "assertionMethod".to_string(),
46 created: created.into(),
47 }
48 }
49}
50
51fn unsigned_proof(opts: &BuildProofOptions) -> Map<String, Value> {
52 let mut proof = Map::new();
56 proof.insert("type".into(), Value::String(PROOF_TYPE.into()));
57 proof.insert("cryptosuite".into(), Value::String(CRYPTOSUITE_ID.into()));
58 proof.insert("created".into(), Value::String(opts.created.clone()));
59 proof.insert(
60 "verificationMethod".into(),
61 Value::String(opts.verification_method.clone()),
62 );
63 proof.insert(
64 "proofPurpose".into(),
65 Value::String(opts.proof_purpose.clone()),
66 );
67 proof
68}
69
70fn unsecured_document(credential: &Value) -> Result<Value> {
72 let mut doc = credential.clone();
73 doc.as_object_mut()
74 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
75 .remove("proof");
76 Ok(doc)
77}
78
79fn proof_configuration(
83 document: &Value,
84 unsigned: &Map<String, Value>,
85) -> Result<Map<String, Value>> {
86 let mut config = unsigned.clone();
87 config.remove("proofValue");
88 if !config.contains_key("@context") {
89 if let Some(ctx) = document.get("@context") {
90 config.insert("@context".into(), ctx.clone());
91 }
92 }
93 Ok(config)
94}
95
96pub fn add_document_context(document: &Value, proof: &mut Map<String, Value>) {
102 crate::nesting::deep_guard!((); document, proof);
103 let Some(ctx) = document.get("@context") else {
104 return;
105 };
106 let mut out = Map::new();
107 out.insert("@context".into(), ctx.clone());
108 for (k, v) in core::mem::take(proof) {
109 if k != "@context" {
110 out.insert(k, v);
111 }
112 }
113 *proof = out;
114}
115
116pub fn hash_data(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 64]> {
120 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
121 let document = unsecured_document(credential)?;
122 let config = proof_configuration(&document, unsigned)?;
123
124 let config_hash = Sha256::digest(jcs::canonicalize(&Value::Object(config)));
125 let document_hash = Sha256::digest(jcs::canonicalize(&document));
126
127 let mut out = [0u8; 64];
128 out[..32].copy_from_slice(&config_hash);
129 out[32..].copy_from_slice(&document_hash);
130 Ok(out)
131}
132
133pub fn legacy_proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
138 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
139 let mut with_proof = credential.clone();
140 with_proof
141 .as_object_mut()
142 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
143 .insert("proof".into(), Value::Object(unsigned.clone()));
144 let canonical = jcs::canonicalize(&with_proof);
145 let digest = Sha256::digest(&canonical);
146 Ok(digest.into())
147}
148
149pub fn build_proof(
152 credential: &Value,
153 raw_private_seed: &[u8],
154 opts: &BuildProofOptions,
155) -> Result<Value> {
156 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
157 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
158 let mut proof = unsigned_proof(opts);
159 add_document_context(&unsecured_document(credential)?, &mut proof);
160 let signing_input = hash_data(credential, &proof)?;
161 let signature = kp.sign(&signing_input);
162 let proof_value = format!("z{}", bs58::encode(signature).into_string());
163 proof.insert("proofValue".into(), Value::String(proof_value));
164 Ok(Value::Object(proof))
165}
166
167pub fn sign(
170 credential: &Value,
171 raw_private_seed: &[u8],
172 opts: &BuildProofOptions,
173) -> Result<Value> {
174 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
175 let proof = build_proof(credential, raw_private_seed, opts)?;
176 let mut signed = credential.clone();
177 signed
178 .as_object_mut()
179 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
180 .insert("proof".into(), proof);
181 Ok(signed)
182}
183
184pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
194 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
195 let obj = credential
196 .as_object()
197 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
198 let proof = obj
199 .get("proof")
200 .and_then(|p| p.as_object())
201 .ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;
202
203 match proof.get("type").and_then(|v| v.as_str()) {
204 Some(PROOF_TYPE) => {}
205 other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
206 }
207 match proof.get("cryptosuite").and_then(|v| v.as_str()) {
208 Some(CRYPTOSUITE_ID) => {}
209 other => {
210 return Err(CoreError::Json(format!(
211 "unexpected cryptosuite: {other:?}"
212 )))
213 }
214 }
215 let proof_value = proof
216 .get("proofValue")
217 .and_then(|v| v.as_str())
218 .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
219 let signature = decode_ed25519_proof_value(proof_value)?;
220 if !proof_context_matches(credential, proof) {
221 return Ok(false);
222 }
223
224 let mut unsigned = proof.clone();
225 unsigned.remove("proofValue");
226
227 let signing_input = hash_data(credential, &unsigned)?;
228 if keys::verify(raw_public_key, &signing_input, &signature)? {
229 return Ok(true);
230 }
231 let legacy = legacy_proof_digest(credential, &unsigned)?;
234 keys::verify(raw_public_key, &legacy, &signature)
235}
236
237pub fn decode_ed25519_proof_value(proof_value: &str) -> Result<Vec<u8>> {
240 let body = proof_value
241 .strip_prefix('z')
242 .ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
243 let signature = crate::multikey::decode_base58_bounded(body)?;
244 if signature.len() != keys::ED25519_SIGNATURE_LEN {
245 return Err(CoreError::InvalidSignatureLength {
246 expected: keys::ED25519_SIGNATURE_LEN,
247 got: signature.len(),
248 });
249 }
250 Ok(signature)
251}
252
253fn context_values(ctx: &Value) -> Option<&[Value]> {
256 match ctx {
257 Value::Null => None,
258 Value::Array(items) if items.is_empty() => None,
259 Value::Array(items) => Some(items.as_slice()),
260 one => Some(core::slice::from_ref(one)),
261 }
262}
263
264pub fn proof_context_matches(document: &Value, proof: &Map<String, Value>) -> bool {
270 crate::nesting::deep_guard!(false; document, proof);
271 let Some(ctx) = proof.get("@context") else {
272 return true;
273 };
274 let (Some(want), Some(have)) = (
275 context_values(ctx),
276 document.get("@context").and_then(context_values),
277 ) else {
278 return false;
279 };
280 have.len() >= want.len() && have[..want.len()] == *want
281}
282
283pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
285 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
286 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
287 verify_proof(credential, &kp.public_key())
288}
289
290pub fn proof_verification_method(credential: &Value) -> Result<String> {
295 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
296 credential
297 .as_object()
298 .and_then(|o| o.get("proof"))
299 .and_then(|p| p.as_object())
300 .and_then(|p| p.get("verificationMethod"))
301 .and_then(|v| v.as_str())
302 .map(|s| s.to_string())
303 .ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309 use serde_json::json;
310
311 #[test]
314 fn verifies_pre_alignment_credential() {
315 let public_key = [
316 0x4c, 0xb5, 0xab, 0xf6, 0xad, 0x79, 0xfb, 0xf5, 0xab, 0xbc, 0xca, 0xfc, 0xc2, 0x69,
317 0xd8, 0x5c, 0xd2, 0x65, 0x1e, 0xd4, 0xb8, 0x85, 0xb5, 0x86, 0x9f, 0x24, 0x1a, 0xed,
318 0xf0, 0xa5, 0xba, 0x29,
319 ];
320 let credential = json!({
321 "@context": [
322 "https://www.w3.org/ns/credentials/v2",
323 "https://vouch-protocol.com/contexts/v1"
324 ],
325 "type": ["VerifiableCredential", "VouchCredential"],
326 "issuer": "did:web:test.example.com",
327 "validFrom": "2026-04-26T10:00:00Z",
328 "validUntil": "2026-04-26T10:05:00Z",
329 "credentialSubject": {
330 "id": "did:web:test.example.com",
331 "vouchVersion": "1.0",
332 "intent": {
333 "action": "read_database",
334 "target": "users_table",
335 "resource": "https://api.example.com/v1/users"
336 }
337 },
338 "proof": {
339 "type": "DataIntegrityProof",
340 "cryptosuite": "eddsa-jcs-2022",
341 "created": "2026-04-26T10:00:00Z",
342 "verificationMethod": "did:web:test.example.com#key-1",
343 "proofPurpose": "assertionMethod",
344 "proofValue": "z24FsZHuADF9uwHAfsjW3okmynrNCCN4QkQirEPfEy5MtcXzg4uhFqz4o3RVH57cFvVXg9oarC4m51YEmNu5UQRLQ"
345 }
346 });
347 assert!(verify_proof(&credential, &public_key).expect("verification error"));
348 }
349
350 fn sample_credential() -> Value {
351 json!({
352 "@context": ["https://www.w3.org/ns/credentials/v2"],
353 "type": ["VerifiableCredential", "VouchCredential"],
354 "issuer": "did:web:agent.example.com",
355 "validFrom": "2026-04-26T10:00:00Z",
356 "validUntil": "2026-04-26T10:05:00Z",
357 "credentialSubject": {
358 "id": "did:web:agent.example.com",
359 "vouchVersion": "1.0",
360 "intent": {
361 "action": "read_database",
362 "target": "users_table",
363 "resource": "https://api.example.com/v1/users"
364 }
365 }
366 })
367 }
368
369 #[test]
370 fn sign_then_verify_roundtrip() {
371 let seed = [9u8; 32];
372 let cred = sample_credential();
373 let opts =
374 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
375 let signed = sign(&cred, &seed, &opts).unwrap();
376 assert!(verify_with_seed(&signed, &seed).unwrap());
377 }
378
379 #[test]
380 fn tamper_fails_verification() {
381 let seed = [9u8; 32];
382 let cred = sample_credential();
383 let opts =
384 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
385 let mut signed = sign(&cred, &seed, &opts).unwrap();
386 signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
387 assert!(!verify_with_seed(&signed, &seed).unwrap());
388 }
389
390 #[test]
391 fn exposes_proof_verification_method() {
392 let seed = [9u8; 32];
393 let opts =
394 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
395 let signed = sign(&sample_credential(), &seed, &opts).unwrap();
396 assert_eq!(
397 proof_verification_method(&signed).unwrap(),
398 "did:web:agent.example.com#key-1"
399 );
400 assert!(proof_verification_method(&sample_credential()).is_err());
401 }
402
403 #[test]
404 fn deterministic_proof_value() {
405 let seed = [9u8; 32];
406 let cred = sample_credential();
407 let opts =
408 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
409 let a = build_proof(&cred, &seed, &opts).unwrap();
410 let b = build_proof(&cred, &seed, &opts).unwrap();
411 assert_eq!(a["proofValue"], b["proofValue"]);
412 }
413
414 fn did_key_signed(seed: &[u8; 32]) -> Value {
415 let kp = Ed25519KeyPair::from_seed(seed);
416 let did = kp.did_key();
417 let mut cred = sample_credential();
418 cred["issuer"] = json!(did);
419 cred["@context"] = json!([
420 "https://www.w3.org/ns/credentials/v2",
421 "https://vouch-protocol.com/contexts/v1"
422 ]);
423 let opts = BuildProofOptions::new(
424 crate::verification_method::ed25519_method(&did),
425 "2026-04-26T10:00:00Z",
426 );
427 sign(&cred, seed, &opts).unwrap()
428 }
429
430 #[test]
431 fn a_proof_carries_a_copy_of_the_document_context_first() {
432 let signed = did_key_signed(&[9u8; 32]);
433 let proof = signed["proof"].as_object().unwrap();
434 assert_eq!(proof.keys().next().map(String::as_str), Some("@context"));
435 assert_eq!(proof["@context"], signed["@context"]);
436 assert!(verify_with_seed(&signed, &[9u8; 32]).unwrap());
437 }
438
439 #[test]
440 fn a_document_without_context_gives_a_proof_without_one() {
441 let mut cred = sample_credential();
442 cred.as_object_mut().unwrap().remove("@context");
443 let opts =
444 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
445 let proof = build_proof(&cred, &[9u8; 32], &opts).unwrap();
446 assert!(proof.get("@context").is_none());
447 }
448
449 #[test]
453 fn a_proof_without_context_still_verifies() {
454 let seed = [9u8; 32];
455 let signed = did_key_signed(&seed);
456 let mut older = signed.clone();
457 older["proof"].as_object_mut().unwrap().remove("@context");
458 assert!(verify_with_seed(&older, &seed).unwrap());
459 assert_eq!(older["proof"]["proofValue"], signed["proof"]["proofValue"]);
460 }
461
462 #[test]
463 fn a_tampered_proof_context_fails() {
464 let seed = [9u8; 32];
465 let signed = did_key_signed(&seed);
466 for ctx in [
467 json!(["https://other.example"]),
468 json!([
469 "https://vouch-protocol.com/contexts/v1",
470 "https://www.w3.org/ns/credentials/v2"
471 ]),
472 json!([
473 "https://www.w3.org/ns/credentials/v2",
474 "https://vouch-protocol.com/contexts/v1",
475 "https://x"
476 ]),
477 json!([]),
478 Value::Null,
479 json!({}),
480 ] {
481 let mut bad = signed.clone();
482 bad["proof"]["@context"] = ctx.clone();
483 assert!(!verify_with_seed(&bad, &seed).unwrap(), "{ctx}");
484 }
485 let mut prefix = signed.clone();
488 prefix["proof"]["@context"] = json!(["https://www.w3.org/ns/credentials/v2"]);
489 assert!(!verify_with_seed(&prefix, &seed).unwrap());
490 }
491
492 #[test]
493 fn a_prefix_proof_context_signed_over_it_verifies() {
494 let seed = [9u8; 32];
495 let cred = sample_credential();
496 let mut unsigned = unsigned_proof(&BuildProofOptions::new(
497 "did:web:agent.example.com#key-1",
498 "2026-04-26T10:00:00Z",
499 ));
500 unsigned.insert(
501 "@context".into(),
502 json!(["https://www.w3.org/ns/credentials/v2"]),
503 );
504 let mut doc = cred.clone();
505 doc["@context"] = json!(["https://www.w3.org/ns/credentials/v2", "https://x.example"]);
506 let input = hash_data(&doc, &unsigned).unwrap();
507 let sig = Ed25519KeyPair::from_seed(&seed).sign(&input);
508 unsigned.insert(
509 "proofValue".into(),
510 json!(format!("z{}", bs58::encode(sig).into_string())),
511 );
512 doc["proof"] = Value::Object(unsigned);
513 assert!(verify_with_seed(&doc, &seed).unwrap());
514 doc["@context"] = json!(["https://x.example", "https://www.w3.org/ns/credentials/v2"]);
516 assert!(!verify_with_seed(&doc, &seed).unwrap());
517 }
518
519 #[test]
520 fn context_prefix_rule() {
521 let doc = json!({"@context": ["a", "b"]});
522 let ok = |ctx: Value| {
523 let mut p = Map::new();
524 p.insert("@context".into(), ctx);
525 proof_context_matches(&doc, &p)
526 };
527 assert!(proof_context_matches(&doc, &Map::new()));
528 assert!(ok(json!(["a", "b"])));
529 assert!(ok(json!(["a"])));
530 assert!(ok(json!("a")));
531 assert!(!ok(json!("b")));
532 assert!(!ok(json!(["b", "a"])));
533 assert!(!ok(json!(["a", "b", "c"])));
534 assert!(!ok(json!([])));
535 assert!(!ok(Value::Null));
536 assert!(!proof_context_matches(&json!({}), &{
537 let mut p = Map::new();
538 p.insert("@context".into(), json!(["a"]));
539 p
540 }));
541 }
542}