vouch_core/
data_integrity.rs1use serde_json::{Map, Value};
14use sha2::{Digest, Sha256};
15
16use crate::error::{CoreError, Result};
17use crate::jcs;
18use crate::keys::{self, Ed25519KeyPair};
19
20pub const CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
21pub const PROOF_TYPE: &str = "DataIntegrityProof";
22
23#[derive(Debug, Clone)]
27pub struct BuildProofOptions {
28 pub verification_method: String,
29 pub proof_purpose: String,
30 pub created: String,
31}
32
33impl BuildProofOptions {
34 pub fn new(verification_method: impl Into<String>, created: impl Into<String>) -> Self {
35 Self {
36 verification_method: verification_method.into(),
37 proof_purpose: "assertionMethod".to_string(),
38 created: created.into(),
39 }
40 }
41}
42
43fn unsigned_proof(opts: &BuildProofOptions) -> Map<String, Value> {
44 let mut proof = Map::new();
48 proof.insert("type".into(), Value::String(PROOF_TYPE.into()));
49 proof.insert("cryptosuite".into(), Value::String(CRYPTOSUITE_ID.into()));
50 proof.insert("created".into(), Value::String(opts.created.clone()));
51 proof.insert(
52 "verificationMethod".into(),
53 Value::String(opts.verification_method.clone()),
54 );
55 proof.insert(
56 "proofPurpose".into(),
57 Value::String(opts.proof_purpose.clone()),
58 );
59 proof
60}
61
62pub fn proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
65 let mut with_proof = credential.clone();
66 with_proof
67 .as_object_mut()
68 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
69 .insert("proof".into(), Value::Object(unsigned.clone()));
70 let canonical = jcs::canonicalize(&with_proof);
71 let digest = Sha256::digest(&canonical);
72 Ok(digest.into())
73}
74
75pub fn build_proof(
78 credential: &Value,
79 raw_private_seed: &[u8],
80 opts: &BuildProofOptions,
81) -> Result<Value> {
82 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
83 let mut proof = unsigned_proof(opts);
84 let digest = proof_digest(credential, &proof)?;
85 let signature = kp.sign(&digest);
86 let proof_value = format!("z{}", bs58::encode(signature).into_string());
87 proof.insert("proofValue".into(), Value::String(proof_value));
88 Ok(Value::Object(proof))
89}
90
91pub fn sign(
94 credential: &Value,
95 raw_private_seed: &[u8],
96 opts: &BuildProofOptions,
97) -> Result<Value> {
98 let proof = build_proof(credential, raw_private_seed, opts)?;
99 let mut signed = credential.clone();
100 signed
101 .as_object_mut()
102 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
103 .insert("proof".into(), proof);
104 Ok(signed)
105}
106
107pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
117 let obj = credential
118 .as_object()
119 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
120 let proof = obj
121 .get("proof")
122 .and_then(|p| p.as_object())
123 .ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;
124
125 match proof.get("type").and_then(|v| v.as_str()) {
126 Some(PROOF_TYPE) => {}
127 other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
128 }
129 match proof.get("cryptosuite").and_then(|v| v.as_str()) {
130 Some(CRYPTOSUITE_ID) => {}
131 other => {
132 return Err(CoreError::Json(format!(
133 "unexpected cryptosuite: {other:?}"
134 )))
135 }
136 }
137 let proof_value = proof
138 .get("proofValue")
139 .and_then(|v| v.as_str())
140 .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
141 let body = proof_value
142 .strip_prefix('z')
143 .ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
144 let signature = crate::multikey::decode_base58_bounded(body)?;
145
146 let mut unsigned = proof.clone();
147 unsigned.remove("proofValue");
148 let digest = proof_digest(credential, &unsigned)?;
149 keys::verify(raw_public_key, &digest, &signature)
150}
151
152pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
154 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
155 verify_proof(credential, &kp.public_key())
156}
157
158pub fn proof_verification_method(credential: &Value) -> Result<String> {
163 credential
164 .as_object()
165 .and_then(|o| o.get("proof"))
166 .and_then(|p| p.as_object())
167 .and_then(|p| p.get("verificationMethod"))
168 .and_then(|v| v.as_str())
169 .map(|s| s.to_string())
170 .ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use serde_json::json;
177
178 fn sample_credential() -> Value {
179 json!({
180 "@context": ["https://www.w3.org/ns/credentials/v2"],
181 "type": ["VerifiableCredential", "VouchCredential"],
182 "issuer": "did:web:agent.example.com",
183 "validFrom": "2026-04-26T10:00:00Z",
184 "validUntil": "2026-04-26T10:05:00Z",
185 "credentialSubject": {
186 "id": "did:web:agent.example.com",
187 "vouchVersion": "1.0",
188 "intent": {
189 "action": "read_database",
190 "target": "users_table",
191 "resource": "https://api.example.com/v1/users"
192 }
193 }
194 })
195 }
196
197 #[test]
198 fn sign_then_verify_roundtrip() {
199 let seed = [9u8; 32];
200 let cred = sample_credential();
201 let opts =
202 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
203 let signed = sign(&cred, &seed, &opts).unwrap();
204 assert!(verify_with_seed(&signed, &seed).unwrap());
205 }
206
207 #[test]
208 fn tamper_fails_verification() {
209 let seed = [9u8; 32];
210 let cred = sample_credential();
211 let opts =
212 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
213 let mut signed = sign(&cred, &seed, &opts).unwrap();
214 signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
215 assert!(!verify_with_seed(&signed, &seed).unwrap());
216 }
217
218 #[test]
219 fn exposes_proof_verification_method() {
220 let seed = [9u8; 32];
221 let opts =
222 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
223 let signed = sign(&sample_credential(), &seed, &opts).unwrap();
224 assert_eq!(
225 proof_verification_method(&signed).unwrap(),
226 "did:web:agent.example.com#key-1"
227 );
228 assert!(proof_verification_method(&sample_credential()).is_err());
229 }
230
231 #[test]
232 fn deterministic_proof_value() {
233 let seed = [9u8; 32];
234 let cred = sample_credential();
235 let opts =
236 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
237 let a = build_proof(&cred, &seed, &opts).unwrap();
238 let b = build_proof(&cred, &seed, &opts).unwrap();
239 assert_eq!(a["proofValue"], b["proofValue"]);
240 }
241}