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 and the temporal window are
94/// reported separately so a caller can distinguish "bad signature" from
95/// "expired".
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct VerifyResult {
98    pub proof_valid: bool,
99    pub time_valid: bool,
100}
101
102impl VerifyResult {
103    pub fn is_valid(&self) -> bool {
104        self.proof_valid && self.time_valid
105    }
106}
107
108/// Verify the Data Integrity proof and the validity window against `now_iso`.
109pub fn verify(
110    credential: &Value,
111    raw_public_key: &[u8],
112    now_iso: &str,
113    clock_skew_seconds: i64,
114) -> Result<VerifyResult> {
115    let proof_valid = data_integrity::verify_proof(credential, raw_public_key)?;
116    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
117    Ok(VerifyResult {
118        proof_valid,
119        time_valid,
120    })
121}
122
123/// Check that `now_iso` falls within [validFrom, validUntil] allowing
124/// `clock_skew_seconds` of drift at each edge (matches the Python verifier).
125pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
126    let obj = credential
127        .as_object()
128        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
129    let vf = obj
130        .get("validFrom")
131        .and_then(|v| v.as_str())
132        .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
133    let vu = obj
134        .get("validUntil")
135        .and_then(|v| v.as_str())
136        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
137    let now = iso_to_epoch_seconds(now_iso)?;
138    let from = iso_to_epoch_seconds(vf)?;
139    let until = iso_to_epoch_seconds(vu)?;
140    Ok(now >= from - clock_skew_seconds && now <= until + clock_skew_seconds)
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn opts() -> BuildCredentialOptions {
148        BuildCredentialOptions {
149            issuer_did: "did:web:agent.example.com".into(),
150            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
151            intent: json!({
152                "action": "read_database",
153                "target": "users_table",
154                "resource": "https://api.example.com/v1/users"
155            }),
156            valid_from: "2026-04-26T10:00:00Z".into(),
157            valid_until: "2026-04-26T10:05:00Z".into(),
158            reputation_score: Some(150),
159            delegation_chain: None,
160            credential_status: None,
161        }
162    }
163
164    #[test]
165    fn builds_expected_shape() {
166        let vc = build_vouch_credential(&opts()).unwrap();
167        assert_eq!(
168            vc["type"],
169            json!(["VerifiableCredential", "VouchCredential"])
170        );
171        assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
172        // reputationScore clamps to 100.
173        assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
174    }
175
176    #[test]
177    fn rejects_missing_intent_fields() {
178        let mut o = opts();
179        o.intent = json!({ "action": "read", "target": "t" }); // no resource
180        assert!(build_vouch_credential(&o).is_err());
181    }
182
183    #[test]
184    fn sign_and_verify_within_window() {
185        let seed = [5u8; 32];
186        let proof_opts =
187            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
188        let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
189        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
190        let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
191        assert!(r.is_valid());
192        // Expired.
193        let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
194        assert!(r2.proof_valid && !r2.time_valid);
195    }
196}