1use serde_json::{Map, Value};
19use sha2::{Digest, Sha256};
20
21use crate::error::{CoreError, Result};
22use crate::jcs;
23use crate::keys::{self, Ed25519KeyPair};
24
25pub const CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
26pub const PROOF_TYPE: &str = "DataIntegrityProof";
27
28#[derive(Debug, Clone)]
32pub struct BuildProofOptions {
33 pub verification_method: String,
34 pub proof_purpose: String,
35 pub created: String,
36}
37
38impl BuildProofOptions {
39 pub fn new(verification_method: impl Into<String>, created: impl Into<String>) -> Self {
40 Self {
41 verification_method: verification_method.into(),
42 proof_purpose: "assertionMethod".to_string(),
43 created: created.into(),
44 }
45 }
46}
47
48fn unsigned_proof(opts: &BuildProofOptions) -> Map<String, Value> {
49 let mut proof = Map::new();
53 proof.insert("type".into(), Value::String(PROOF_TYPE.into()));
54 proof.insert("cryptosuite".into(), Value::String(CRYPTOSUITE_ID.into()));
55 proof.insert("created".into(), Value::String(opts.created.clone()));
56 proof.insert(
57 "verificationMethod".into(),
58 Value::String(opts.verification_method.clone()),
59 );
60 proof.insert(
61 "proofPurpose".into(),
62 Value::String(opts.proof_purpose.clone()),
63 );
64 proof
65}
66
67fn unsecured_document(credential: &Value) -> Result<Value> {
69 let mut doc = credential.clone();
70 doc.as_object_mut()
71 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
72 .remove("proof");
73 Ok(doc)
74}
75
76fn proof_configuration(
79 document: &Value,
80 unsigned: &Map<String, Value>,
81) -> Result<Map<String, Value>> {
82 let mut config = unsigned.clone();
83 config.remove("proofValue");
84 if let Some(ctx) = document.get("@context") {
85 config.insert("@context".into(), ctx.clone());
86 }
87 Ok(config)
88}
89
90pub fn hash_data(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 64]> {
94 let document = unsecured_document(credential)?;
95 let config = proof_configuration(&document, unsigned)?;
96
97 let config_hash = Sha256::digest(jcs::canonicalize(&Value::Object(config)));
98 let document_hash = Sha256::digest(jcs::canonicalize(&document));
99
100 let mut out = [0u8; 64];
101 out[..32].copy_from_slice(&config_hash);
102 out[32..].copy_from_slice(&document_hash);
103 Ok(out)
104}
105
106pub fn legacy_proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
111 let mut with_proof = credential.clone();
112 with_proof
113 .as_object_mut()
114 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
115 .insert("proof".into(), Value::Object(unsigned.clone()));
116 let canonical = jcs::canonicalize(&with_proof);
117 let digest = Sha256::digest(&canonical);
118 Ok(digest.into())
119}
120
121pub fn build_proof(
124 credential: &Value,
125 raw_private_seed: &[u8],
126 opts: &BuildProofOptions,
127) -> Result<Value> {
128 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
129 let mut proof = unsigned_proof(opts);
130 let signing_input = hash_data(credential, &proof)?;
131 let signature = kp.sign(&signing_input);
132 let proof_value = format!("z{}", bs58::encode(signature).into_string());
133 proof.insert("proofValue".into(), Value::String(proof_value));
134 Ok(Value::Object(proof))
135}
136
137pub fn sign(
140 credential: &Value,
141 raw_private_seed: &[u8],
142 opts: &BuildProofOptions,
143) -> Result<Value> {
144 let proof = build_proof(credential, raw_private_seed, opts)?;
145 let mut signed = credential.clone();
146 signed
147 .as_object_mut()
148 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
149 .insert("proof".into(), proof);
150 Ok(signed)
151}
152
153pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
163 let obj = credential
164 .as_object()
165 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
166 let proof = obj
167 .get("proof")
168 .and_then(|p| p.as_object())
169 .ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;
170
171 match proof.get("type").and_then(|v| v.as_str()) {
172 Some(PROOF_TYPE) => {}
173 other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
174 }
175 match proof.get("cryptosuite").and_then(|v| v.as_str()) {
176 Some(CRYPTOSUITE_ID) => {}
177 other => {
178 return Err(CoreError::Json(format!(
179 "unexpected cryptosuite: {other:?}"
180 )))
181 }
182 }
183 let proof_value = proof
184 .get("proofValue")
185 .and_then(|v| v.as_str())
186 .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
187 let signature = decode_ed25519_proof_value(proof_value)?;
188 if !proof_context_matches(credential, proof) {
189 return Ok(false);
190 }
191
192 let mut unsigned = proof.clone();
193 unsigned.remove("proofValue");
194
195 let signing_input = hash_data(credential, &unsigned)?;
196 if keys::verify(raw_public_key, &signing_input, &signature)? {
197 return Ok(true);
198 }
199 let legacy = legacy_proof_digest(credential, &unsigned)?;
202 keys::verify(raw_public_key, &legacy, &signature)
203}
204
205pub fn decode_ed25519_proof_value(proof_value: &str) -> Result<Vec<u8>> {
208 let body = proof_value
209 .strip_prefix('z')
210 .ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
211 let signature = crate::multikey::decode_base58_bounded(body)?;
212 if signature.len() != keys::ED25519_SIGNATURE_LEN {
213 return Err(CoreError::InvalidSignatureLength {
214 expected: keys::ED25519_SIGNATURE_LEN,
215 got: signature.len(),
216 });
217 }
218 Ok(signature)
219}
220
221pub fn proof_context_matches(document: &Value, proof: &Map<String, Value>) -> bool {
225 match proof.get("@context") {
226 None => true,
227 Some(ctx) => document.get("@context") == Some(ctx),
228 }
229}
230
231pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
233 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
234 verify_proof(credential, &kp.public_key())
235}
236
237pub fn proof_verification_method(credential: &Value) -> Result<String> {
242 credential
243 .as_object()
244 .and_then(|o| o.get("proof"))
245 .and_then(|p| p.as_object())
246 .and_then(|p| p.get("verificationMethod"))
247 .and_then(|v| v.as_str())
248 .map(|s| s.to_string())
249 .ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use serde_json::json;
256
257 #[test]
260 fn verifies_pre_alignment_credential() {
261 let public_key = [
262 0x4c, 0xb5, 0xab, 0xf6, 0xad, 0x79, 0xfb, 0xf5, 0xab, 0xbc, 0xca, 0xfc, 0xc2, 0x69,
263 0xd8, 0x5c, 0xd2, 0x65, 0x1e, 0xd4, 0xb8, 0x85, 0xb5, 0x86, 0x9f, 0x24, 0x1a, 0xed,
264 0xf0, 0xa5, 0xba, 0x29,
265 ];
266 let credential = json!({
267 "@context": [
268 "https://www.w3.org/ns/credentials/v2",
269 "https://vouch-protocol.com/contexts/v1"
270 ],
271 "type": ["VerifiableCredential", "VouchCredential"],
272 "issuer": "did:web:test.example.com",
273 "validFrom": "2026-04-26T10:00:00Z",
274 "validUntil": "2026-04-26T10:05:00Z",
275 "credentialSubject": {
276 "id": "did:web:test.example.com",
277 "vouchVersion": "1.0",
278 "intent": {
279 "action": "read_database",
280 "target": "users_table",
281 "resource": "https://api.example.com/v1/users"
282 }
283 },
284 "proof": {
285 "type": "DataIntegrityProof",
286 "cryptosuite": "eddsa-jcs-2022",
287 "created": "2026-04-26T10:00:00Z",
288 "verificationMethod": "did:web:test.example.com#key-1",
289 "proofPurpose": "assertionMethod",
290 "proofValue": "z24FsZHuADF9uwHAfsjW3okmynrNCCN4QkQirEPfEy5MtcXzg4uhFqz4o3RVH57cFvVXg9oarC4m51YEmNu5UQRLQ"
291 }
292 });
293 assert!(verify_proof(&credential, &public_key).expect("verification error"));
294 }
295
296 fn sample_credential() -> Value {
297 json!({
298 "@context": ["https://www.w3.org/ns/credentials/v2"],
299 "type": ["VerifiableCredential", "VouchCredential"],
300 "issuer": "did:web:agent.example.com",
301 "validFrom": "2026-04-26T10:00:00Z",
302 "validUntil": "2026-04-26T10:05:00Z",
303 "credentialSubject": {
304 "id": "did:web:agent.example.com",
305 "vouchVersion": "1.0",
306 "intent": {
307 "action": "read_database",
308 "target": "users_table",
309 "resource": "https://api.example.com/v1/users"
310 }
311 }
312 })
313 }
314
315 #[test]
316 fn sign_then_verify_roundtrip() {
317 let seed = [9u8; 32];
318 let cred = sample_credential();
319 let opts =
320 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
321 let signed = sign(&cred, &seed, &opts).unwrap();
322 assert!(verify_with_seed(&signed, &seed).unwrap());
323 }
324
325 #[test]
326 fn tamper_fails_verification() {
327 let seed = [9u8; 32];
328 let cred = sample_credential();
329 let opts =
330 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
331 let mut signed = sign(&cred, &seed, &opts).unwrap();
332 signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
333 assert!(!verify_with_seed(&signed, &seed).unwrap());
334 }
335
336 #[test]
337 fn exposes_proof_verification_method() {
338 let seed = [9u8; 32];
339 let opts =
340 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
341 let signed = sign(&sample_credential(), &seed, &opts).unwrap();
342 assert_eq!(
343 proof_verification_method(&signed).unwrap(),
344 "did:web:agent.example.com#key-1"
345 );
346 assert!(proof_verification_method(&sample_credential()).is_err());
347 }
348
349 #[test]
350 fn deterministic_proof_value() {
351 let seed = [9u8; 32];
352 let cred = sample_credential();
353 let opts =
354 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
355 let a = build_proof(&cred, &seed, &opts).unwrap();
356 let b = build_proof(&cred, &seed, &opts).unwrap();
357 assert_eq!(a["proofValue"], b["proofValue"]);
358 }
359}