Skip to main content

vouch_core/
credentials.rs

1//! Vouch Credential build and verify.
2//!
3//! Byte-exact port of the TypeScript `buildVouchCredential` (vc.ts): same JSON
4//! shape and field ordering. The core is deterministic and clock-free, so the
5//! caller supplies the credential id and the validity window (the SDK/wrapper
6//! computes them); verification takes the current instant as a parameter.
7
8use serde_json::{json, Map, Value};
9
10use crate::data_integrity::{self, BuildProofOptions};
11use crate::error::{CoreError, Result};
12use crate::time::iso_to_epoch_seconds;
13
14pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
15pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
16pub const VC_TYPE: &str = "VerifiableCredential";
17pub const VOUCH_CREDENTIAL_TYPE: &str = "VouchCredential";
18pub const PROTOCOL_VERSION: &str = "1.0";
19
20/// Inputs to build an unsigned Vouch Credential.
21#[derive(Debug, Clone)]
22pub struct BuildCredentialOptions {
23    pub issuer_did: String,
24    pub credential_id: String,
25    pub intent: Value,
26    pub valid_from: String,
27    pub valid_until: String,
28    pub reputation_score: Option<i64>,
29    pub delegation_chain: Option<Value>,
30    pub credential_status: Option<Value>,
31}
32
33/// Validate that `intent` carries the REQUIRED non-empty action/target/resource
34/// (Specification 5.4.1).
35pub fn validate_intent(intent: &Value) -> Result<()> {
36    let obj = intent
37        .as_object()
38        .ok_or_else(|| CoreError::Json("intent must be an object".into()))?;
39    for req in ["action", "target", "resource"] {
40        match obj.get(req).and_then(|v| v.as_str()) {
41            Some(s) if !s.is_empty() => {}
42            _ => {
43                return Err(CoreError::Json(format!(
44                    "intent.{req} is REQUIRED and must be a non-empty string"
45                )))
46            }
47        }
48    }
49    Ok(())
50}
51
52/// Construct an unsigned Vouch Credential matching `buildVouchCredential`.
53pub fn build_vouch_credential(opts: &BuildCredentialOptions) -> Result<Value> {
54    validate_intent(&opts.intent)?;
55
56    let mut subject = Map::new();
57    subject.insert("id".into(), json!(opts.issuer_did));
58    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
59    subject.insert("intent".into(), opts.intent.clone());
60    if let Some(r) = opts.reputation_score {
61        subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
62    }
63    if let Some(chain) = &opts.delegation_chain {
64        if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
65            subject.insert("delegationChain".into(), chain.clone());
66        }
67    }
68
69    let mut vc = Map::new();
70    vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
71    vc.insert("id".into(), json!(opts.credential_id));
72    vc.insert("type".into(), json!([VC_TYPE, VOUCH_CREDENTIAL_TYPE]));
73    vc.insert("issuer".into(), json!(opts.issuer_did));
74    vc.insert("validFrom".into(), json!(opts.valid_from));
75    vc.insert("validUntil".into(), json!(opts.valid_until));
76    vc.insert("credentialSubject".into(), Value::Object(subject));
77    if let Some(status) = &opts.credential_status {
78        vc.insert("credentialStatus".into(), status.clone());
79    }
80    Ok(Value::Object(vc))
81}
82
83/// Build and sign a Vouch Credential in one step (eddsa-jcs-2022).
84pub fn sign_vouch_credential(
85    opts: &BuildCredentialOptions,
86    raw_private_seed: &[u8],
87    proof_opts: &BuildProofOptions,
88) -> Result<Value> {
89    let cred = build_vouch_credential(opts)?;
90    data_integrity::sign(&cred, raw_private_seed, proof_opts)
91}
92
93/// The outcome of verifying a credential: the proof, the temporal window, and
94/// the embedded delegation chain are reported separately so a caller can
95/// distinguish "bad signature" from "expired" from "chain refused".
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct VerifyResult {
98    pub proof_valid: bool,
99    pub time_valid: bool,
100    /// True when the credential has no delegation chain, or its chain verifies
101    /// (`delegation::verify_delegation_chain`).
102    pub chain_valid: bool,
103}
104
105impl VerifyResult {
106    pub fn is_valid(&self) -> bool {
107        self.proof_valid && self.time_valid && self.chain_valid
108    }
109}
110
111/// Verify the Data Integrity proof, the validity window against `now_iso`, and
112/// the embedded delegation chain (Specification 9.3). Chain grant issuers must
113/// be `did:key` here; use `delegation::verify_delegation_chain` directly to
114/// supply keys for other issuers or to pin trusted roots.
115pub fn verify(
116    credential: &Value,
117    raw_public_key: &[u8],
118    now_iso: &str,
119    clock_skew_seconds: i64,
120) -> Result<VerifyResult> {
121    let proof_valid = data_integrity::verify_proof(credential, raw_public_key)?;
122    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
123    let chain_valid = crate::delegation::verify_delegation_chain(
124        credential,
125        now_iso,
126        clock_skew_seconds,
127        &std::collections::BTreeMap::new(),
128        None,
129    )
130    .is_none();
131    Ok(VerifyResult {
132        proof_valid,
133        time_valid,
134        chain_valid,
135    })
136}
137
138/// Check that `now_iso` falls within [validFrom, validUntil] allowing
139/// `clock_skew_seconds` of drift at each edge (matches the Python verifier).
140pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
141    let obj = credential
142        .as_object()
143        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
144    let vf = obj
145        .get("validFrom")
146        .and_then(|v| v.as_str())
147        .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
148    let vu = obj
149        .get("validUntil")
150        .and_then(|v| v.as_str())
151        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
152    let now = iso_to_epoch_seconds(now_iso)?;
153    let from = iso_to_epoch_seconds(vf)?;
154    let until = iso_to_epoch_seconds(vu)?;
155    Ok(now >= from - clock_skew_seconds && now <= until + clock_skew_seconds)
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    fn opts() -> BuildCredentialOptions {
163        BuildCredentialOptions {
164            issuer_did: "did:web:agent.example.com".into(),
165            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
166            intent: json!({
167                "action": "read_database",
168                "target": "users_table",
169                "resource": "https://api.example.com/v1/users"
170            }),
171            valid_from: "2026-04-26T10:00:00Z".into(),
172            valid_until: "2026-04-26T10:05:00Z".into(),
173            reputation_score: Some(150),
174            delegation_chain: None,
175            credential_status: None,
176        }
177    }
178
179    #[test]
180    fn builds_expected_shape() {
181        let vc = build_vouch_credential(&opts()).unwrap();
182        assert_eq!(
183            vc["type"],
184            json!(["VerifiableCredential", "VouchCredential"])
185        );
186        assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
187        // reputationScore clamps to 100.
188        assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
189    }
190
191    #[test]
192    fn rejects_missing_intent_fields() {
193        let mut o = opts();
194        o.intent = json!({ "action": "read", "target": "t" }); // no resource
195        assert!(build_vouch_credential(&o).is_err());
196    }
197
198    #[test]
199    fn sign_and_verify_within_window() {
200        let seed = [5u8; 32];
201        let proof_opts =
202            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
203        let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
204        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
205        let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
206        assert!(r.is_valid());
207        // Expired.
208        let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
209        assert!(r2.proof_valid && !r2.time_valid);
210    }
211}