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::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
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    build_credential(opts, None)
55}
56
57/// Construct an unsigned sub-grant: a Vouch Credential that names the grant it
58/// is made under by digest, in `credentialSubject.parentGrantDigest`
59/// ([`crate::grant_chain::grant_digest`] of the direct parent grant). A
60/// sub-grant carries no `delegationChain`; its delegatee is handed the whole
61/// grant chain instead ([`crate::grant_chain::grant_chain`]). Matches the
62/// reference builder's `parent_grant_digest` (vc.build_vouch_credential).
63///
64/// Errors: the intent is missing a required field, the digest is empty, or
65/// `opts.delegation_chain` is a non-empty list (a grant names its parent one
66/// way, never both).
67pub fn build_sub_grant(opts: &BuildCredentialOptions, parent_grant_digest: &str) -> Result<Value> {
68    build_credential(opts, Some(parent_grant_digest))
69}
70
71/// Build and sign a sub-grant in one step (eddsa-jcs-2022); see
72/// [`build_sub_grant`].
73pub fn sign_sub_grant(
74    opts: &BuildCredentialOptions,
75    parent_grant_digest: &str,
76    raw_private_seed: &[u8],
77    proof_opts: &BuildProofOptions,
78) -> Result<Value> {
79    let cred = build_sub_grant(opts, parent_grant_digest)?;
80    data_integrity::sign(&cred, raw_private_seed, proof_opts)
81}
82
83fn build_credential(opts: &BuildCredentialOptions, parent_digest: Option<&str>) -> Result<Value> {
84    validate_intent(&opts.intent)?;
85    let has_chain = opts
86        .delegation_chain
87        .as_ref()
88        .and_then(|c| c.as_array())
89        .is_some_and(|a| !a.is_empty());
90    if let Some(digest) = parent_digest {
91        if digest.is_empty() {
92            return Err(CoreError::Json(
93                "parent_grant_digest must be a grant digest string".into(),
94            ));
95        }
96        if has_chain {
97            return Err(CoreError::Json(
98                "a credential carries parentGrantDigest or a delegationChain, never both".into(),
99            ));
100        }
101    }
102
103    let mut subject = Map::new();
104    subject.insert("id".into(), json!(opts.issuer_did));
105    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
106    subject.insert("intent".into(), opts.intent.clone());
107    if let Some(r) = opts.reputation_score {
108        subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
109    }
110    if let Some(digest) = parent_digest {
111        subject.insert(
112            crate::grant_chain::PARENT_GRANT_DIGEST.into(),
113            json!(digest),
114        );
115    }
116    if let Some(chain) = &opts.delegation_chain {
117        if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
118            subject.insert("delegationChain".into(), chain.clone());
119        }
120    }
121
122    let mut vc = Map::new();
123    vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
124    vc.insert("id".into(), json!(opts.credential_id));
125    vc.insert("type".into(), json!([VC_TYPE, VOUCH_CREDENTIAL_TYPE]));
126    vc.insert("issuer".into(), json!(opts.issuer_did));
127    vc.insert("validFrom".into(), json!(opts.valid_from));
128    vc.insert("validUntil".into(), json!(opts.valid_until));
129    vc.insert("credentialSubject".into(), Value::Object(subject));
130    if let Some(status) = &opts.credential_status {
131        vc.insert("credentialStatus".into(), status.clone());
132    }
133    Ok(Value::Object(vc))
134}
135
136/// Build and sign a Vouch Credential in one step (eddsa-jcs-2022).
137pub fn sign_vouch_credential(
138    opts: &BuildCredentialOptions,
139    raw_private_seed: &[u8],
140    proof_opts: &BuildProofOptions,
141) -> Result<Value> {
142    let cred = build_vouch_credential(opts)?;
143    data_integrity::sign(&cred, raw_private_seed, proof_opts)
144}
145
146/// Every `vouchVersion` this codebase has ever issued. A credential with a
147/// missing or different version is refused.
148pub const SUPPORTED_VOUCH_VERSIONS: &[&str] = &[PROTOCOL_VERSION];
149
150/// The outcome of verifying a credential: the proof, the temporal window, and
151/// the embedded delegation chain are reported separately so a caller can
152/// distinguish "bad signature" from "expired" from "chain refused".
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct VerifyResult {
155    /// The signature verifies with the key given, the key is the issuer's (for
156    /// a `did:key` issuer, the key the DID encodes), and the proof is bound to
157    /// the issuer: proofPurpose "assertionMethod" and a verificationMethod of
158    /// the issuer's DID.
159    pub proof_valid: bool,
160    /// `now` is inside [validFrom, validUntil] (with the skew), the window is
161    /// not inverted, and no proof has passed its `expires`.
162    pub time_valid: bool,
163    /// True when the credential has no delegation chain, or its chain verifies
164    /// from one of the caller's trusted roots
165    /// (`delegation::verify_delegation_chain_with`).
166    pub chain_valid: bool,
167}
168
169impl VerifyResult {
170    pub fn is_valid(&self) -> bool {
171        self.proof_valid && self.time_valid && self.chain_valid
172    }
173}
174
175/// The issuer DID of a credential: the `issuer` string, or the `id` of an
176/// issuer object.
177pub fn issuer_did(credential: &Value) -> Option<&str> {
178    match credential.get("issuer") {
179        Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()),
180        Some(Value::Object(o)) => o
181            .get("id")
182            .and_then(|v| v.as_str())
183            .filter(|s| !s.is_empty()),
184        _ => None,
185    }
186}
187
188/// True when one proof is bound to `issuer`: its proofPurpose is
189/// "assertionMethod" and its verificationMethod names a key of the issuer's
190/// DID (the part before '#' equals the issuer DID). Applies to every member of
191/// a proof set.
192pub fn proof_bound_to_issuer(proof: &Value, issuer: &str) -> bool {
193    let Some(p) = proof.as_object() else {
194        return false;
195    };
196    if p.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
197        return false;
198    }
199    match p.get("verificationMethod").and_then(|v| v.as_str()) {
200        Some(vm) if !vm.is_empty() => vm.split('#').next() == Some(issuer),
201        _ => false,
202    }
203}
204
205/// Refuse a credential whose `credentialSubject.vouchVersion` is missing or
206/// not one of [`SUPPORTED_VOUCH_VERSIONS`].
207pub fn check_vouch_version(credential: &Value) -> Result<()> {
208    let version = credential
209        .get("credentialSubject")
210        .and_then(|s| s.get("vouchVersion"));
211    match version.and_then(|v| v.as_str()) {
212        Some(v) if SUPPORTED_VOUCH_VERSIONS.contains(&v) => Ok(()),
213        Some(v) => Err(CoreError::Json(format!(
214            "unsupported vouchVersion {:?}",
215            v.chars().take(32).collect::<String>()
216        ))),
217        None => Err(CoreError::Json(
218            "credentialSubject.vouchVersion is required".into(),
219        )),
220    }
221}
222
223/// Refuse a credential whose `credentialSubject.intent.resource` is missing,
224/// not a string, or empty. The resource is a non-empty string naming what the
225/// credential is for (Specification 5.4.1); relative names such as
226/// "reports/q3.txt" are valid, so no URI syntax is required.
227pub fn check_intent_resource(credential: &Value) -> Result<()> {
228    let resource = credential
229        .get("credentialSubject")
230        .and_then(|s| s.get("intent"))
231        .and_then(|i| i.get("resource"));
232    match resource.and_then(|r| r.as_str()) {
233        Some(r) if !r.is_empty() => Ok(()),
234        _ => Err(CoreError::Json(
235            "intent.resource is REQUIRED and must be a non-empty string".into(),
236        )),
237    }
238}
239
240/// Refuse a credential whose envelope is not a Vouch Credential: `@context` is
241/// an array starting with the VC 2.0 context, `type` is an array holding
242/// "VerifiableCredential" and "VouchCredential", and `credentialSubject` and
243/// its `intent` are objects.
244pub fn check_envelope(credential: &Value) -> Result<()> {
245    let ctx_ok = credential
246        .get("@context")
247        .and_then(|c| c.as_array())
248        .and_then(|c| c.first())
249        .and_then(|c| c.as_str())
250        == Some(VC_CONTEXT_V2);
251    if !ctx_ok {
252        return Err(CoreError::Json(
253            "the credential's @context must start with the VC 2.0 context".into(),
254        ));
255    }
256    let types_ok = credential
257        .get("type")
258        .and_then(|t| t.as_array())
259        .map(|t| {
260            [VC_TYPE, VOUCH_CREDENTIAL_TYPE]
261                .iter()
262                .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
263        })
264        .unwrap_or(false);
265    if !types_ok {
266        return Err(CoreError::Json(
267            "the credential's type must include VerifiableCredential and VouchCredential".into(),
268        ));
269    }
270    let subject_ok = credential
271        .get("credentialSubject")
272        .map(|s| s.is_object() && s.get("intent").map(|i| i.is_object()).unwrap_or(false))
273        .unwrap_or(false);
274    if !subject_ok {
275        return Err(CoreError::Json(
276            "credentialSubject and its intent must be objects".into(),
277        ));
278    }
279    Ok(())
280}
281
282/// A proof's own fields, checked before any signature: type
283/// "DataIntegrityProof", a known cryptosuite, proofPurpose "assertionMethod",
284/// a verificationMethod of the issuer's DID, a non-empty proofValue, and a
285/// `created` (when present) in the time grammar. `Ok(false)` refuses the proof;
286/// `Err` is a malformed time.
287fn proof_fields_ok(proof: &Value, issuer: &str) -> Result<bool> {
288    let Some(p) = proof.as_object() else {
289        return Ok(false);
290    };
291    if p.get("type").and_then(|v| v.as_str()) != Some(data_integrity::PROOF_TYPE) {
292        return Ok(false);
293    }
294    let known = matches!(
295        p.get("cryptosuite").and_then(|v| v.as_str()),
296        Some(
297            crate::hybrid::EDDSA_CRYPTOSUITE_ID
298                | crate::hybrid::MLDSA44_CRYPTOSUITE_ID
299                | crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
300                | crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
301        )
302    );
303    if !known || !proof_bound_to_issuer(proof, issuer) {
304        return Ok(false);
305    }
306    let has_value = p
307        .get("proofValue")
308        .and_then(|v| v.as_str())
309        .is_some_and(|v| !v.is_empty());
310    if !has_value {
311        return Ok(false);
312    }
313    if let Some(created) = p.get("created") {
314        match created.as_str() {
315            Some(c) => {
316                parse_protocol_time_ns(c)?;
317            }
318            None => {
319                return Err(CoreError::Json(
320                    "proof.created must be a time string".into(),
321                ))
322            }
323        }
324    }
325    Ok(true)
326}
327
328/// The replay key for a credential, the same in every language:
329/// lowercase hex of `SHA-256(issuer UTF-8 || 0x00 || SHA-256(proofValue
330/// UTF-8))`, where `proof_value` is the `proofValue` of the proof the verifier
331/// checked (for a proof set, the Ed25519 proof). A DID never contains a NUL, so
332/// the two parts cannot run together. The core is stateless: the caller keeps
333/// the replay store and marks this key after a credential verifies.
334pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
335    use sha2::{Digest, Sha256};
336    if issuer.is_empty() || proof_value.is_empty() {
337        return Err(CoreError::Json(
338            "issuer and proofValue must be non-empty strings".into(),
339        ));
340    }
341    let inner = Sha256::digest(proof_value.as_bytes());
342    let mut h = Sha256::new();
343    h.update(issuer.as_bytes());
344    h.update([0u8]);
345    h.update(inner);
346    Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
347}
348
349/// One proof member under the top-level rules ([`proof_fields_ok`]) plus its
350/// `expires`, which must be a time string (null is not "absent") that has not
351/// passed at `now` (with the skew). Used for grants and status lists.
352pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
353    if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
354        return false;
355    }
356    match proof.get("expires") {
357        None => true,
358        Some(Value::String(e)) => match parse_protocol_time_ns(e) {
359            Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
360            Err(_) => false,
361        },
362        Some(_) => false,
363    }
364}
365
366/// True when the key the caller supplied is the issuer's own key as far as
367/// the core can tell offline: for a `did:key` issuer it must be exactly the key
368/// the DID encodes. For other DID methods the caller resolved the key and the
369/// proof's verificationMethod binding is checked instead.
370fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
371    if issuer.starts_with("did:key:") {
372        return match crate::keys::did_key_to_ed25519(issuer) {
373            Ok(k) => k.as_slice() == raw_public_key,
374            Err(_) => false,
375        };
376    }
377    true
378}
379
380/// Verify the Data Integrity proof, the validity window against `now_iso`, and
381/// the embedded delegation chain (Specification 9.3).
382///
383/// A credential that carries a delegation chain is refused here
384/// (`chain_valid` false) because no trusted starting point is named: use
385/// [`verify_with_roots`] for those. A credential without a chain needs no
386/// roots. Refused with an `Err`: a skew outside 0..120 seconds, a malformed
387/// time, a missing or unsupported `vouchVersion`, or an `intent.resource` that
388/// is missing or not a non-empty string.
389///
390/// `credentialStatus` is not checked here: call
391/// [`crate::status_list::check_credential_status`] for that. The core keeps no
392/// state, so replay protection is the caller's: keep a replay store keyed by
393/// [`replay_key`].
394pub fn verify(
395    credential: &Value,
396    raw_public_key: &[u8],
397    now_iso: &str,
398    clock_skew_seconds: i64,
399) -> Result<VerifyResult> {
400    let opts = crate::delegation::ChainOptions::default();
401    Ok(verify_explained(
402        credential,
403        raw_public_key,
404        now_iso,
405        clock_skew_seconds,
406        &opts,
407    )?
408    .0)
409}
410
411/// [`verify`] with the trusted starting points for a delegation chain: the
412/// chain's first grant must be issued by one of `trusted_roots`. With an empty
413/// list a credential carrying a chain is refused.
414pub fn verify_with_roots(
415    credential: &Value,
416    raw_public_key: &[u8],
417    now_iso: &str,
418    clock_skew_seconds: i64,
419    trusted_roots: &[String],
420) -> Result<VerifyResult> {
421    let opts = crate::delegation::ChainOptions {
422        trusted_roots: Some(trusted_roots),
423        ..Default::default()
424    };
425    Ok(verify_explained(
426        credential,
427        raw_public_key,
428        now_iso,
429        clock_skew_seconds,
430        &opts,
431    )?
432    .0)
433}
434
435/// The full verifier: returns the [`VerifyResult`] and, when the chain is
436/// refused, its reason. `opts` carries the trusted roots, grant keys for
437/// non-`did:key` issuers, the post-quantum requirement and any explicit budget
438/// (see [`crate::delegation::ChainOptions`]). The credential's own proof must
439/// be a single `eddsa-jcs-2022` proof here; [`verify_with_keys`] also takes an
440/// ML-DSA-44 key for a proof set or the earlier composite proof.
441pub fn verify_explained(
442    credential: &Value,
443    raw_public_key: &[u8],
444    now_iso: &str,
445    clock_skew_seconds: i64,
446    opts: &crate::delegation::ChainOptions,
447) -> Result<(VerifyResult, Option<String>)> {
448    verify_with_keys(
449        credential,
450        raw_public_key,
451        None,
452        now_iso,
453        clock_skew_seconds,
454        opts,
455    )
456}
457
458/// The top-level verifier for every proof shape a Vouch Credential carries:
459///
460/// * one `eddsa-jcs-2022` proof, verified with `ed25519_key` (refused when
461///   post-quantum is required: a single classical proof does not meet it);
462/// * a proof set of exactly one `eddsa-jcs-2022` and one ML-DSA-44 proof,
463///   both verified ([`crate::hybrid::verify_dual`]; needs `mldsa44_key`);
464/// * the earlier composite `hybrid-eddsa-mldsa44-jcs-2026` proof
465///   ([`crate::hybrid::verify_composite`]; needs `mldsa44_key`).
466///
467/// Before any signature: the envelope ([`check_envelope`]), the version
468/// ([`check_vouch_version`]), the resource ([`check_intent_resource`]), an
469/// issuer that is a DID, and every proof's own fields (type, a known
470/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
471/// issuer's DID). For a `did:key` issuer the Ed25519 key must be the one the DID
472/// encodes. Then the window ([`verify_temporal`]) and the delegation chain
473/// (which needs trusted roots, see [`verify_with_roots`]). The chain step
474/// starts with the credential's own binding fields
475/// ([`crate::grant_chain::binding_fields_problem`]): a `parentGrantDigest`
476/// that is not a string, a `delegationChain` that is not a list, or a digest
477/// together with a non-empty `delegationChain` gives `chain_valid` false with
478/// the reason "malformed_delegation", whatever roots are named. A sub-grant (a
479/// string digest and no chain) verifies on its own; whether it was made under
480/// a trusted chain is checked with its grant chain.
481///
482/// Supplying `mldsa44_key` means post-quantum is required for this
483/// credential: it must be 1312 bytes (else an `Err`), and a single classical
484/// proof is refused. The key applies to this credential only; grants follow
485/// `opts` (their own ML-DSA-44 keys, and `opts.require_pq`). Every trusted root
486/// must be a DID or a domain name (else an `Err`). `credentialStatus` and replay
487/// are the caller's to check, as for [`verify`].
488pub fn verify_with_keys(
489    credential: &Value,
490    ed25519_key: &[u8],
491    mldsa44_key: Option<&[u8]>,
492    now_iso: &str,
493    clock_skew_seconds: i64,
494    opts: &crate::delegation::ChainOptions,
495) -> Result<(VerifyResult, Option<String>)> {
496    check_clock_skew(clock_skew_seconds)?;
497    if let Some(ml) = mldsa44_key {
498        if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
499            return Err(CoreError::InvalidKeyLength {
500                expected: crate::pq::MLDSA44_PUBLIC_LEN,
501                got: ml.len(),
502            });
503        }
504    }
505    if let Some(roots) = opts.trusted_roots {
506        for r in roots {
507            crate::did_web::normalize_root(r)?;
508        }
509    }
510    if !credential.is_object() {
511        return Err(CoreError::Json("credential must be an object".into()));
512    }
513    check_envelope(credential)?;
514    check_vouch_version(credential)?;
515    check_intent_resource(credential)?;
516
517    let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
518    let proof_valid = match (issuer, credential.get("proof")) {
519        (Some(issuer), Some(proof)) => {
520            let members: Vec<&Value> = match proof {
521                Value::Array(items) => items.iter().collect(),
522                other => vec![other],
523            };
524            let mut fields_ok = !members.is_empty();
525            for m in &members {
526                fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
527            }
528            fields_ok
529                && key_matches_issuer(issuer, ed25519_key)
530                && proof_shape_verifies(credential, proof, ed25519_key, mldsa44_key, opts)?
531        }
532        // No issuer DID to bind the proof to, or no proof.
533        _ => false,
534    };
535    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
536    let chain_reason = crate::delegation::verify_delegation_chain_with(
537        credential,
538        now_iso,
539        clock_skew_seconds,
540        opts,
541    );
542    Ok((
543        VerifyResult {
544            proof_valid,
545            time_valid,
546            chain_valid: chain_reason.is_none(),
547        },
548        chain_reason,
549    ))
550}
551
552/// Verify the credential's proof by its shape (see [`verify_with_keys`]).
553fn proof_shape_verifies(
554    credential: &Value,
555    proof: &Value,
556    ed25519_key: &[u8],
557    mldsa44_key: Option<&[u8]>,
558    opts: &crate::delegation::ChainOptions,
559) -> Result<bool> {
560    let suite = |p: &Value| {
561        p.get("cryptosuite")
562            .and_then(|v| v.as_str())
563            .unwrap_or_default()
564            .to_string()
565    };
566    match proof {
567        Value::Object(_) => match suite(proof).as_str() {
568            crate::hybrid::EDDSA_CRYPTOSUITE_ID => {
569                // A supplied ML-DSA-44 key means post-quantum is required.
570                if opts.require_pq || mldsa44_key.is_some() {
571                    return Ok(false);
572                }
573                data_integrity::verify_proof(credential, ed25519_key)
574            }
575            crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa44_key {
576                Some(ml) => crate::hybrid::verify_composite(credential, ed25519_key, ml),
577                None => Ok(false),
578            },
579            // An ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a set.
580            _ => Ok(false),
581        },
582        Value::Array(items) => {
583            let mut suites: Vec<String> = items
584                .iter()
585                .map(|p| {
586                    let s = suite(p);
587                    if s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
588                        crate::hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
589                    } else {
590                        s
591                    }
592                })
593                .collect();
594            suites.sort();
595            if suites
596                != [
597                    crate::hybrid::EDDSA_CRYPTOSUITE_ID,
598                    crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
599                ]
600            {
601                return Ok(false); // exactly one Ed25519 and one ML-DSA-44 proof
602            }
603            match mldsa44_key {
604                Some(ml) => crate::hybrid::verify_dual(credential, ed25519_key, ml),
605                None => Ok(false),
606            }
607        }
608        _ => Ok(false),
609    }
610}
611
612/// Check that `now_iso` falls within [validFrom, validUntil] allowing
613/// `clock_skew_seconds` of drift at each edge, at full fraction precision
614/// ([`crate::time`]). An inverted window (validFrom after validUntil) is never
615/// valid, and neither is a proof past its own `expires`. Errors on a missing
616/// or malformed time and on a skew outside 0..120 seconds.
617pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
618    let skew = check_clock_skew(clock_skew_seconds)?;
619    let obj = credential
620        .as_object()
621        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
622    let vf = obj
623        .get("validFrom")
624        .and_then(|v| v.as_str())
625        .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
626    let vu = obj
627        .get("validUntil")
628        .and_then(|v| v.as_str())
629        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
630    let now = parse_protocol_time_ns(now_iso)?;
631    let from = parse_protocol_time_ns(vf)?;
632    let until = parse_protocol_time_ns(vu)?;
633    if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
634        return Ok(false);
635    }
636    // A proof may carry its own `expires`: past it, the proof no longer
637    // speaks for the credential.
638    let proofs: Vec<&Value> = match obj.get("proof") {
639        Some(Value::Array(items)) => items.iter().collect(),
640        Some(p) => vec![p],
641        None => Vec::new(),
642    };
643    for p in proofs {
644        match p.get("expires") {
645            None => {}
646            Some(Value::String(e)) => {
647                let expires = parse_protocol_time_ns(e)?;
648                if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
649                    return Ok(false);
650                }
651            }
652            Some(_) => {
653                return Err(CoreError::Json(
654                    "proof.expires must be a time string".into(),
655                ))
656            }
657        }
658    }
659    Ok(true)
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665
666    fn opts() -> BuildCredentialOptions {
667        BuildCredentialOptions {
668            issuer_did: "did:web:agent.example.com".into(),
669            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
670            intent: json!({
671                "action": "read_database",
672                "target": "users_table",
673                "resource": "https://api.example.com/v1/users"
674            }),
675            valid_from: "2026-04-26T10:00:00Z".into(),
676            valid_until: "2026-04-26T10:05:00Z".into(),
677            reputation_score: Some(150),
678            delegation_chain: None,
679            credential_status: None,
680        }
681    }
682
683    #[test]
684    fn builds_expected_shape() {
685        let vc = build_vouch_credential(&opts()).unwrap();
686        assert_eq!(
687            vc["type"],
688            json!(["VerifiableCredential", "VouchCredential"])
689        );
690        assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
691        // reputationScore clamps to 100.
692        assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
693    }
694
695    #[test]
696    fn rejects_missing_intent_fields() {
697        let mut o = opts();
698        o.intent = json!({ "action": "read", "target": "t" }); // no resource
699        assert!(build_vouch_credential(&o).is_err());
700    }
701
702    #[test]
703    fn sub_grant_names_its_parent_one_way_only() {
704        let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
705        let sub = build_sub_grant(&opts(), digest).unwrap();
706        assert_eq!(sub["credentialSubject"]["parentGrantDigest"], json!(digest));
707        assert!(sub["credentialSubject"].get("delegationChain").is_none());
708        // Written after reputationScore, as the reference builder does.
709        let keys: Vec<&str> = sub["credentialSubject"]
710            .as_object()
711            .unwrap()
712            .keys()
713            .map(|k| k.as_str())
714            .collect();
715        assert_eq!(
716            keys,
717            [
718                "id",
719                "vouchVersion",
720                "intent",
721                "reputationScore",
722                "parentGrantDigest"
723            ]
724        );
725        assert!(build_vouch_credential(&opts())
726            .unwrap()
727            .pointer("/credentialSubject/parentGrantDigest")
728            .is_none());
729        assert_eq!(
730            build_sub_grant(&opts(), "").unwrap_err().to_string(),
731            "json error: parent_grant_digest must be a grant digest string"
732        );
733        let mut both = opts();
734        both.delegation_chain = Some(json!([{"issuer": "did:web:a"}]));
735        assert_eq!(
736            build_sub_grant(&both, digest).unwrap_err().to_string(),
737            "json error: a credential carries parentGrantDigest or a delegationChain, never both"
738        );
739        // An empty chain is no chain.
740        both.delegation_chain = Some(json!([]));
741        assert!(build_sub_grant(&both, digest).is_ok());
742        // The intent is still checked first.
743        let mut bad = opts();
744        bad.intent = json!({ "action": "read" });
745        assert!(build_sub_grant(&bad, "")
746            .unwrap_err()
747            .to_string()
748            .contains("intent."));
749        let seed = [5u8; 32];
750        let signed = sign_sub_grant(
751            &opts(),
752            digest,
753            &seed,
754            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
755        )
756        .unwrap();
757        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
758        assert!(verify(&signed, &pk, "2026-04-26T10:02:00Z", 30)
759            .unwrap()
760            .is_valid());
761    }
762
763    #[test]
764    fn own_binding_fields_are_checked_on_every_verify_path() {
765        let seed = [5u8; 32];
766        let po = BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
767        let with = |fields: Value| {
768            let mut c = build_vouch_credential(&opts()).unwrap();
769            for (k, v) in fields.as_object().unwrap() {
770                c["credentialSubject"][k] = v.clone();
771            }
772            data_integrity::sign(&c, &seed, &po).unwrap()
773        };
774        let roots = ["did:web:root.example".to_string()];
775        let with_roots = crate::delegation::ChainOptions {
776            trusted_roots: Some(&roots),
777            ..Default::default()
778        };
779        let none = crate::delegation::ChainOptions::default();
780        // (chain_valid, reason) from each verify path.
781        let every_path = |c: &Value| {
782            let mut out = Vec::new();
783            for r in [
784                verify(c, &pk(), NOW, 30).unwrap(),
785                verify_with_roots(c, &pk(), NOW, 30, &roots).unwrap(),
786            ] {
787                assert!(r.proof_valid && r.time_valid);
788                out.push((r.chain_valid, None));
789            }
790            for o in [&none, &with_roots] {
791                let (r, reason) = verify_explained(c, &pk(), NOW, 30, o).unwrap();
792                assert!(r.proof_valid && r.time_valid);
793                out.push((r.chain_valid, reason.clone()));
794                let (r, reason2) = verify_with_keys(c, &pk(), None, NOW, 30, o).unwrap();
795                assert_eq!(reason2, reason);
796                out.push((r.chain_valid, reason2));
797                out.push((
798                    reason.is_none(),
799                    crate::delegation::verify_delegation_chain_with(c, NOW, 30, o),
800                ));
801            }
802            out
803        };
804        let malformed = Some("malformed_delegation".to_string());
805        let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
806        for fields in [
807            json!({"parentGrantDigest": null}),
808            json!({"parentGrantDigest": 5}),
809            json!({"parentGrantDigest": ["u"]}),
810            json!({"parentGrantDigest": {}}),
811            json!({"delegationChain": null}),
812            json!({"delegationChain": {}}),
813            json!({"parentGrantDigest": digest, "delegationChain": [{"issuer": "did:web:a"}]}),
814            json!({"parentGrantDigest": null, "delegationChain": [{"issuer": "did:web:a"}]}),
815        ] {
816            for (i, (chain_valid, reason)) in
817                every_path(&with(fields.clone())).into_iter().enumerate()
818            {
819                assert!(!chain_valid, "{fields} path {i}");
820                if i >= 2 {
821                    assert_eq!(reason, malformed, "{fields} path {i}");
822                }
823            }
824        }
825        // A sub-grant on its own (a string digest, no chain) verifies, with or
826        // without roots; so does one with an empty chain.
827        for fields in [
828            json!({ "parentGrantDigest": digest }),
829            json!({"parentGrantDigest": digest, "delegationChain": []}),
830        ] {
831            for (i, (chain_valid, reason)) in
832                every_path(&with(fields.clone())).into_iter().enumerate()
833            {
834                assert!(chain_valid, "{fields} path {i}");
835                assert_eq!(reason, None, "{fields} path {i}");
836            }
837        }
838    }
839
840    #[test]
841    fn sign_and_verify_within_window() {
842        let seed = [5u8; 32];
843        let proof_opts =
844            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
845        let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
846        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
847        let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
848        assert!(r.is_valid());
849        // Expired.
850        let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
851        assert!(r2.proof_valid && !r2.time_valid);
852    }
853
854    fn signed_with(purpose: &str, vm: &str) -> Value {
855        let seed = [5u8; 32];
856        let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
857        proof_opts.proof_purpose = purpose.into();
858        sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
859    }
860
861    fn pk() -> [u8; 32] {
862        crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
863    }
864
865    const NOW: &str = "2026-04-26T10:02:00Z";
866
867    #[test]
868    fn proof_must_be_an_assertion_by_the_issuer() {
869        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
870        assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
871        let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
872        assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
873        let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
874        assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
875        let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
876        assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
877    }
878
879    #[test]
880    fn did_key_issuer_must_be_the_signing_key() {
881        let seed = [6u8; 32];
882        let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
883        let did = kp.did_key();
884        let mut o = opts();
885        o.issuer_did = did.clone();
886        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
887        let signed = sign_vouch_credential(
888            &o,
889            &seed,
890            &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
891        )
892        .unwrap();
893        assert!(verify(&signed, &kp.public_key(), NOW, 30)
894            .unwrap()
895            .is_valid());
896        // The same credential re-signed by another key that claims the DID.
897        let other = [7u8; 32];
898        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
899        let impostor = sign_vouch_credential(
900            &o,
901            &other,
902            &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
903        )
904        .unwrap();
905        let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
906        assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
907    }
908
909    #[test]
910    fn vouch_version_and_resource_are_required() {
911        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
912        for (path, value) in [
913            ("vouchVersion", Value::Null),
914            ("vouchVersion", json!("2.0")),
915            ("vouchVersion", json!(1.0)),
916        ] {
917            let mut c = ok.clone();
918            if value.is_null() {
919                c["credentialSubject"].as_object_mut().unwrap().remove(path);
920            } else {
921                c["credentialSubject"][path] = value;
922            }
923            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
924        }
925        for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
926            let mut c = ok.clone();
927            c["credentialSubject"]["intent"]["resource"] = bad.clone();
928            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
929        }
930        // A relative name is a valid resource (it is signed, so re-sign it).
931        let mut o = opts();
932        o.intent["resource"] = json!("reports/q3.txt");
933        let signed = sign_vouch_credential(
934            &o,
935            &[5u8; 32],
936            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
937        )
938        .unwrap();
939        assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
940    }
941
942    #[test]
943    fn window_rules() {
944        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
945        // A skew outside 0..120 seconds is refused, never wrapped.
946        for skew in [-1, 121, i64::MAX, i64::MIN] {
947            assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
948            assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
949        }
950        // A naive or loose `now` is refused.
951        for now in [
952            "2026-04-26T10:02:00",
953            "2026-04-26 10:02:00Z",
954            "2026-04-26t10:02:00z",
955        ] {
956            assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
957        }
958        // Fractions count: one nanosecond past validUntil is expired at skew 0.
959        assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
960        assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
961        // An inverted window is never valid.
962        let inverted =
963            json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
964        assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
965        // A proof past its own `expires` no longer speaks for the credential.
966        let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
967                           "proof": {"expires": "2026-04-26T10:01:00Z"}});
968        assert!(!verify_temporal(&c, NOW, 30).unwrap());
969        c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
970        assert!(verify_temporal(&c, NOW, 30).unwrap());
971        c["proof"]["expires"] = json!(5);
972        assert!(verify_temporal(&c, NOW, 30).is_err());
973    }
974
975    #[test]
976    fn proof_context_must_match_the_document() {
977        let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
978        c["proof"]["@context"] = json!(["https://example.com/other"]);
979        assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
980    }
981
982    #[test]
983    fn issuer_object_is_bound_by_its_id() {
984        let mut o = opts();
985        o.issuer_did = "did:web:agent.example.com".into();
986        let mut cred = build_vouch_credential(&o).unwrap();
987        cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
988        let signed = data_integrity::sign(
989            &cred,
990            &[5u8; 32],
991            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
992        )
993        .unwrap();
994        assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
995        let mut bad = cred.clone();
996        bad["issuer"] = json!(["did:web:agent.example.com"]);
997        let signed = data_integrity::sign(
998            &bad,
999            &[5u8; 32],
1000            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1001        )
1002        .unwrap();
1003        assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1004    }
1005
1006    #[test]
1007    fn envelope_must_be_a_vouch_credential() {
1008        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1009        for (key, value) in [
1010            ("@context", Value::Null),
1011            ("@context", json!("https://www.w3.org/ns/credentials/v2")),
1012            ("@context", json!(["https://example.com/other"])),
1013            ("type", json!(["VerifiableCredential"])),
1014            ("type", json!("VouchCredential")),
1015        ] {
1016            let mut c = ok.clone();
1017            if value.is_null() {
1018                c.as_object_mut().unwrap().remove(key);
1019            } else {
1020                c[key] = value.clone();
1021            }
1022            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
1023        }
1024        // An issuer that is not a DID is never bound.
1025        let mut o = opts();
1026        o.issuer_did = "agent.example.com".into();
1027        let signed = sign_vouch_credential(
1028            &o,
1029            &[5u8; 32],
1030            &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1031        )
1032        .unwrap();
1033        assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1034        // A malformed proof.created is refused.
1035        let mut c = ok.clone();
1036        c["proof"]["created"] = json!("yesterday");
1037        assert!(verify(&c, &pk(), NOW, 30).is_err());
1038    }
1039
1040    #[test]
1041    fn every_proof_shape_through_one_verifier() {
1042        use crate::delegation::ChainOptions;
1043        let seed = [5u8; 32];
1044        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1045        let unsigned = build_vouch_credential(&opts()).unwrap();
1046        let dual = crate::hybrid::sign_dual(
1047            &unsigned,
1048            &seed,
1049            &ml,
1050            "did:web:agent.example.com#key-1",
1051            "did:web:agent.example.com#key-2",
1052            "2026-04-26T10:00:00Z",
1053        )
1054        .unwrap();
1055        let none = ChainOptions::default();
1056        let pq = ChainOptions {
1057            require_pq: true,
1058            ..Default::default()
1059        };
1060        let mlk = ml.public_key();
1061        let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
1062            verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
1063        };
1064        assert!(run(&dual, Some(&mlk), &none).is_valid());
1065        assert!(run(&dual, Some(&mlk), &pq).is_valid());
1066        // A proof set without the ML-DSA key, or through the Ed25519-only form.
1067        assert!(!run(&dual, None, &none).proof_valid);
1068        assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
1069        // A single classical proof does not meet the post-quantum profile, and
1070        // supplying an ML-DSA-44 key means post-quantum is required.
1071        let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1072        assert!(run(&single, None, &none).is_valid());
1073        assert!(!run(&single, None, &pq).proof_valid);
1074        assert!(!run(&single, Some(&mlk), &none).proof_valid);
1075        // The ML-DSA-44 key must be 1312 bytes.
1076        assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
1077        // Every trusted root must be a DID or a domain name.
1078        let bad_roots = vec!["127.0.0.1".to_string()];
1079        let with_bad = ChainOptions {
1080            trusted_roots: Some(&bad_roots),
1081            ..Default::default()
1082        };
1083        assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
1084        // The ML-DSA member alone, or the set with an extra member.
1085        let mut lone = dual.clone();
1086        lone["proof"] = dual["proof"][1].clone();
1087        assert!(!run(&lone, Some(&mlk), &none).proof_valid);
1088        let mut extra = dual.clone();
1089        extra["proof"]
1090            .as_array_mut()
1091            .unwrap()
1092            .push(dual["proof"][0].clone());
1093        assert!(!run(&extra, Some(&mlk), &none).proof_valid);
1094        // An unknown cryptosuite in the set is refused at the top level.
1095        let mut unknown = dual.clone();
1096        let mut odd = dual["proof"][0].clone();
1097        odd["cryptosuite"] = json!("some-unregistered-suite-2030");
1098        unknown["proof"].as_array_mut().unwrap().push(odd);
1099        assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
1100    }
1101
1102    #[test]
1103    fn replay_key_is_issuer_nul_and_proof_digest() {
1104        use sha2::{Digest, Sha256};
1105        let k = replay_key("did:web:a.example", "z3abc").unwrap();
1106        let mut h = Sha256::new();
1107        h.update(b"did:web:a.example\x00");
1108        h.update(Sha256::digest(b"z3abc"));
1109        let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
1110        assert_eq!(k, want);
1111        assert_eq!(k.len(), 64);
1112        assert!(replay_key("", "z3abc").is_err());
1113        assert!(replay_key("did:web:a.example", "").is_err());
1114        // The NUL keeps the two parts apart.
1115        assert_ne!(
1116            replay_key("did:web:a", "bc").unwrap(),
1117            replay_key("did:web:ab", "c").unwrap()
1118        );
1119    }
1120}