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
18use 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/// Options for building a proof. `created` is supplied by the caller (an
29/// ISO-8601 instant such as "2026-04-26T10:00:00Z") so proofs are deterministic
30/// and reproducible across implementations.
31#[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    // Field insertion order matches the reference SDK so the emitted proof is
50    // byte-identical. JCS sorts keys for signing, so order is irrelevant to the
51    // signature, but it keeps the stored document stable across SDKs.
52    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
67/// Strip any `proof` member, yielding the unsecured document.
68fn 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
76/// Build the proof configuration: the unsigned proof carrying the document's
77/// `@context`, per the Data Integrity proof configuration algorithm.
78fn 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
90/// Compute the 64-byte W3C Data Integrity signing input for a JCS cryptosuite:
91/// SHA-256 of the canonical proof configuration, joined with SHA-256 of the
92/// canonical unsecured document. This is the value that gets signed.
93pub 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
106/// The pre-alignment signing input: a single SHA-256 over the JCS canonical form
107/// of the credential with the unsigned proof attached. Retained so credentials
108/// issued before the Data Integrity alignment continue to verify. Never used for
109/// new proofs.
110pub 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
121/// Build an `eddsa-jcs-2022` proof for `credential` using a raw 32-byte Ed25519
122/// seed. Returns the proof object (the caller attaches it, or use `sign`).
123pub 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
137/// Sign a credential: build the proof and return the credential with `proof`
138/// attached.
139pub 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
153/// Verify an `eddsa-jcs-2022` proof attached to `credential` against a raw
154/// 32-byte Ed25519 public key. Returns Ok(true) on a valid signature, Ok(false)
155/// on a signature mismatch, Err on a malformed proof.
156///
157/// SECURITY: this checks the signature against the key you pass, NOT that the
158/// key belongs to the `verificationMethod` the proof claims. Resolve the key
159/// from [`proof_verification_method`] (or otherwise confirm the key-to-method
160/// binding) so a credential cannot claim one method while being signed by
161/// another key you happen to trust.
162pub 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    // Fall back to the pre-alignment signing input so credentials issued before
200    // the Data Integrity alignment still verify.
201    let legacy = legacy_proof_digest(credential, &unsigned)?;
202    keys::verify(raw_public_key, &legacy, &signature)
203}
204
205/// Decode an `eddsa-jcs-2022` proofValue strictly: multibase base58btc ('z')
206/// that decodes to exactly 64 bytes.
207pub 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
221/// A proof may carry its own `@context`, but the signing input always uses the
222/// document's, so a proof `@context` that differs from the document's would be
223/// an unsigned field. Such a proof is refused.
224pub 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
231/// Convenience: derive the public key from a seed and verify (for self-checks).
232pub 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
237/// Return the `verificationMethod` declared by the credential's proof. Callers
238/// should resolve the verification key from THIS identifier before verifying, so
239/// the key is bound to the method the proof claims (see the SECURITY note on
240/// [`verify_proof`]).
241pub 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    /// A credential issued before the Data Integrity alignment, whose signature
258    /// covers the pre-alignment signing input, MUST still verify.
259    #[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}