Skip to main content

vouch_core/
data_integrity.rs

1//! Data Integrity proofs, cryptosuite `eddsa-jcs-2022`.
2//!
3//! Signing input follows the W3C Data Integrity hashing algorithm, so proofs
4//! issued here verify under any conformant `eddsa-jcs-2022` implementation:
5//!   1. Build the proof configuration (the unsigned proof plus the document's
6//!      `@context`) and JCS-canonicalize it (RFC 8785).
7//!   2. JCS-canonicalize the unsecured document (the credential with no proof).
8//!   3. hashData = SHA-256(canonical proof configuration)
9//!      || SHA-256(canonical document)   (64 bytes, config first).
10//!   4. Ed25519-sign hashData.
11//!   5. proofValue = "z" + base58btc(signature).
12//!
13//! Verification also accepts the pre-alignment signing input (a single SHA-256
14//! over the JCS form of the credential with the unsigned proof attached) so
15//! credentials issued before this alignment keep verifying. See
16//! [`legacy_proof_digest`].
17
18#[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/// Options for building a proof. `created` is supplied by the caller (an
32/// ISO-8601 instant such as "2026-04-26T10:00:00Z") so proofs are deterministic
33/// and reproducible across implementations.
34#[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    // Field insertion order matches the reference SDK so the emitted proof is
53    // byte-identical. JCS sorts keys for signing, so order is irrelevant to the
54    // signature, but it keeps the stored document stable across SDKs.
55    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
70/// Strip any `proof` member, yielding the unsecured document.
71fn 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
79/// Build the proof configuration: the unsigned proof carrying the document's
80/// `@context`, per the Data Integrity proof configuration algorithm.
81fn proof_configuration(
82    document: &Value,
83    unsigned: &Map<String, Value>,
84) -> Result<Map<String, Value>> {
85    let mut config = unsigned.clone();
86    config.remove("proofValue");
87    if let Some(ctx) = document.get("@context") {
88        config.insert("@context".into(), ctx.clone());
89    }
90    Ok(config)
91}
92
93/// Compute the 64-byte W3C Data Integrity signing input for a JCS cryptosuite:
94/// SHA-256 of the canonical proof configuration, joined with SHA-256 of the
95/// canonical unsecured document. This is the value that gets signed.
96pub fn hash_data(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 64]> {
97    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
98    let document = unsecured_document(credential)?;
99    let config = proof_configuration(&document, unsigned)?;
100
101    let config_hash = Sha256::digest(jcs::canonicalize(&Value::Object(config)));
102    let document_hash = Sha256::digest(jcs::canonicalize(&document));
103
104    let mut out = [0u8; 64];
105    out[..32].copy_from_slice(&config_hash);
106    out[32..].copy_from_slice(&document_hash);
107    Ok(out)
108}
109
110/// The pre-alignment signing input: a single SHA-256 over the JCS canonical form
111/// of the credential with the unsigned proof attached. Retained so credentials
112/// issued before the Data Integrity alignment continue to verify. Never used for
113/// new proofs.
114pub fn legacy_proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
115    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
116    let mut with_proof = credential.clone();
117    with_proof
118        .as_object_mut()
119        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
120        .insert("proof".into(), Value::Object(unsigned.clone()));
121    let canonical = jcs::canonicalize(&with_proof);
122    let digest = Sha256::digest(&canonical);
123    Ok(digest.into())
124}
125
126/// Build an `eddsa-jcs-2022` proof for `credential` using a raw 32-byte Ed25519
127/// seed. Returns the proof object (the caller attaches it, or use `sign`).
128pub fn build_proof(
129    credential: &Value,
130    raw_private_seed: &[u8],
131    opts: &BuildProofOptions,
132) -> Result<Value> {
133    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
134    let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
135    let mut proof = unsigned_proof(opts);
136    let signing_input = hash_data(credential, &proof)?;
137    let signature = kp.sign(&signing_input);
138    let proof_value = format!("z{}", bs58::encode(signature).into_string());
139    proof.insert("proofValue".into(), Value::String(proof_value));
140    Ok(Value::Object(proof))
141}
142
143/// Sign a credential: build the proof and return the credential with `proof`
144/// attached.
145pub fn sign(
146    credential: &Value,
147    raw_private_seed: &[u8],
148    opts: &BuildProofOptions,
149) -> Result<Value> {
150    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
151    let proof = build_proof(credential, raw_private_seed, opts)?;
152    let mut signed = credential.clone();
153    signed
154        .as_object_mut()
155        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
156        .insert("proof".into(), proof);
157    Ok(signed)
158}
159
160/// Verify an `eddsa-jcs-2022` proof attached to `credential` against a raw
161/// 32-byte Ed25519 public key. Returns Ok(true) on a valid signature, Ok(false)
162/// on a signature mismatch, Err on a malformed proof.
163///
164/// SECURITY: this checks the signature against the key you pass, NOT that the
165/// key belongs to the `verificationMethod` the proof claims. Resolve the key
166/// from [`proof_verification_method`] (or otherwise confirm the key-to-method
167/// binding) so a credential cannot claim one method while being signed by
168/// another key you happen to trust.
169pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
170    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
171    let obj = credential
172        .as_object()
173        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
174    let proof = obj
175        .get("proof")
176        .and_then(|p| p.as_object())
177        .ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;
178
179    match proof.get("type").and_then(|v| v.as_str()) {
180        Some(PROOF_TYPE) => {}
181        other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
182    }
183    match proof.get("cryptosuite").and_then(|v| v.as_str()) {
184        Some(CRYPTOSUITE_ID) => {}
185        other => {
186            return Err(CoreError::Json(format!(
187                "unexpected cryptosuite: {other:?}"
188            )))
189        }
190    }
191    let proof_value = proof
192        .get("proofValue")
193        .and_then(|v| v.as_str())
194        .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
195    let signature = decode_ed25519_proof_value(proof_value)?;
196    if !proof_context_matches(credential, proof) {
197        return Ok(false);
198    }
199
200    let mut unsigned = proof.clone();
201    unsigned.remove("proofValue");
202
203    let signing_input = hash_data(credential, &unsigned)?;
204    if keys::verify(raw_public_key, &signing_input, &signature)? {
205        return Ok(true);
206    }
207    // Fall back to the pre-alignment signing input so credentials issued before
208    // the Data Integrity alignment still verify.
209    let legacy = legacy_proof_digest(credential, &unsigned)?;
210    keys::verify(raw_public_key, &legacy, &signature)
211}
212
213/// Decode an `eddsa-jcs-2022` proofValue strictly: multibase base58btc ('z')
214/// that decodes to exactly 64 bytes.
215pub fn decode_ed25519_proof_value(proof_value: &str) -> Result<Vec<u8>> {
216    let body = proof_value
217        .strip_prefix('z')
218        .ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
219    let signature = crate::multikey::decode_base58_bounded(body)?;
220    if signature.len() != keys::ED25519_SIGNATURE_LEN {
221        return Err(CoreError::InvalidSignatureLength {
222            expected: keys::ED25519_SIGNATURE_LEN,
223            got: signature.len(),
224        });
225    }
226    Ok(signature)
227}
228
229/// A proof may carry its own `@context`, but the signing input always uses the
230/// document's, so a proof `@context` that differs from the document's would be
231/// an unsigned field. Such a proof is refused.
232pub fn proof_context_matches(document: &Value, proof: &Map<String, Value>) -> bool {
233    crate::nesting::deep_guard!(false; document, proof);
234    // A document with no @context reads as null, as in the reference.
235    match proof.get("@context") {
236        None => true,
237        Some(ctx) => document.get("@context").unwrap_or(&Value::Null) == ctx,
238    }
239}
240
241/// Convenience: derive the public key from a seed and verify (for self-checks).
242pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
243    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
244    let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
245    verify_proof(credential, &kp.public_key())
246}
247
248/// Return the `verificationMethod` declared by the credential's proof. Callers
249/// should resolve the verification key from THIS identifier before verifying, so
250/// the key is bound to the method the proof claims (see the SECURITY note on
251/// [`verify_proof`]).
252pub fn proof_verification_method(credential: &Value) -> Result<String> {
253    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
254    credential
255        .as_object()
256        .and_then(|o| o.get("proof"))
257        .and_then(|p| p.as_object())
258        .and_then(|p| p.get("verificationMethod"))
259        .and_then(|v| v.as_str())
260        .map(|s| s.to_string())
261        .ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use serde_json::json;
268
269    /// A credential issued before the Data Integrity alignment, whose signature
270    /// covers the pre-alignment signing input, MUST still verify.
271    #[test]
272    fn verifies_pre_alignment_credential() {
273        let public_key = [
274            0x4c, 0xb5, 0xab, 0xf6, 0xad, 0x79, 0xfb, 0xf5, 0xab, 0xbc, 0xca, 0xfc, 0xc2, 0x69,
275            0xd8, 0x5c, 0xd2, 0x65, 0x1e, 0xd4, 0xb8, 0x85, 0xb5, 0x86, 0x9f, 0x24, 0x1a, 0xed,
276            0xf0, 0xa5, 0xba, 0x29,
277        ];
278        let credential = json!({
279            "@context": [
280                "https://www.w3.org/ns/credentials/v2",
281                "https://vouch-protocol.com/contexts/v1"
282            ],
283            "type": ["VerifiableCredential", "VouchCredential"],
284            "issuer": "did:web:test.example.com",
285            "validFrom": "2026-04-26T10:00:00Z",
286            "validUntil": "2026-04-26T10:05:00Z",
287            "credentialSubject": {
288                "id": "did:web:test.example.com",
289                "vouchVersion": "1.0",
290                "intent": {
291                    "action": "read_database",
292                    "target": "users_table",
293                    "resource": "https://api.example.com/v1/users"
294                }
295            },
296            "proof": {
297                "type": "DataIntegrityProof",
298                "cryptosuite": "eddsa-jcs-2022",
299                "created": "2026-04-26T10:00:00Z",
300                "verificationMethod": "did:web:test.example.com#key-1",
301                "proofPurpose": "assertionMethod",
302                "proofValue": "z24FsZHuADF9uwHAfsjW3okmynrNCCN4QkQirEPfEy5MtcXzg4uhFqz4o3RVH57cFvVXg9oarC4m51YEmNu5UQRLQ"
303            }
304        });
305        assert!(verify_proof(&credential, &public_key).expect("verification error"));
306    }
307
308    fn sample_credential() -> Value {
309        json!({
310            "@context": ["https://www.w3.org/ns/credentials/v2"],
311            "type": ["VerifiableCredential", "VouchCredential"],
312            "issuer": "did:web:agent.example.com",
313            "validFrom": "2026-04-26T10:00:00Z",
314            "validUntil": "2026-04-26T10:05:00Z",
315            "credentialSubject": {
316                "id": "did:web:agent.example.com",
317                "vouchVersion": "1.0",
318                "intent": {
319                    "action": "read_database",
320                    "target": "users_table",
321                    "resource": "https://api.example.com/v1/users"
322                }
323            }
324        })
325    }
326
327    #[test]
328    fn sign_then_verify_roundtrip() {
329        let seed = [9u8; 32];
330        let cred = sample_credential();
331        let opts =
332            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
333        let signed = sign(&cred, &seed, &opts).unwrap();
334        assert!(verify_with_seed(&signed, &seed).unwrap());
335    }
336
337    #[test]
338    fn tamper_fails_verification() {
339        let seed = [9u8; 32];
340        let cred = sample_credential();
341        let opts =
342            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
343        let mut signed = sign(&cred, &seed, &opts).unwrap();
344        signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
345        assert!(!verify_with_seed(&signed, &seed).unwrap());
346    }
347
348    #[test]
349    fn exposes_proof_verification_method() {
350        let seed = [9u8; 32];
351        let opts =
352            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
353        let signed = sign(&sample_credential(), &seed, &opts).unwrap();
354        assert_eq!(
355            proof_verification_method(&signed).unwrap(),
356            "did:web:agent.example.com#key-1"
357        );
358        assert!(proof_verification_method(&sample_credential()).is_err());
359    }
360
361    #[test]
362    fn deterministic_proof_value() {
363        let seed = [9u8; 32];
364        let cred = sample_credential();
365        let opts =
366            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
367        let a = build_proof(&cred, &seed, &opts).unwrap();
368        let b = build_proof(&cred, &seed, &opts).unwrap();
369        assert_eq!(a["proofValue"], b["proofValue"]);
370    }
371}