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    // The earlier composite proof (hybrid-eddsa-mldsa44-jcs-2026) is no
295    // longer accepted: the post-quantum profile is the proof set of two
296    // separate proofs only.
297    let known = matches!(
298        p.get("cryptosuite").and_then(|v| v.as_str()),
299        Some(
300            crate::hybrid::EDDSA_CRYPTOSUITE_ID
301                | crate::hybrid::MLDSA44_CRYPTOSUITE_ID
302                | crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
303        )
304    );
305    if !known || !proof_bound_to_issuer(proof, issuer) {
306        return Ok(false);
307    }
308    let has_value = p
309        .get("proofValue")
310        .and_then(|v| v.as_str())
311        .is_some_and(|v| !v.is_empty());
312    if !has_value {
313        return Ok(false);
314    }
315    if let Some(created) = p.get("created") {
316        match created.as_str() {
317            Some(c) => {
318                parse_protocol_time_ns(c)?;
319            }
320            None => {
321                return Err(CoreError::Json(
322                    "proof.created must be a time string".into(),
323                ))
324            }
325        }
326    }
327    Ok(true)
328}
329
330/// The replay key for a credential, the same in every language:
331/// lowercase hex of `SHA-256(issuer UTF-8 || 0x00 || SHA-256(proofValue
332/// UTF-8))`, where `proof_value` is the `proofValue` of the proof the verifier
333/// checked (for a proof set, the Ed25519 proof). A DID never contains a NUL, so
334/// the two parts cannot run together. The core is stateless: the caller keeps
335/// the replay store and marks this key after a credential verifies.
336pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
337    use sha2::{Digest, Sha256};
338    if issuer.is_empty() || proof_value.is_empty() {
339        return Err(CoreError::Json(
340            "issuer and proofValue must be non-empty strings".into(),
341        ));
342    }
343    let inner = Sha256::digest(proof_value.as_bytes());
344    let mut h = Sha256::new();
345    h.update(issuer.as_bytes());
346    h.update([0u8]);
347    h.update(inner);
348    Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
349}
350
351/// One proof member under the top-level rules ([`proof_fields_ok`]) plus its
352/// `expires`, which must be a time string (null is not "absent") that has not
353/// passed at `now` (with the skew). Used for grants and status lists.
354pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
355    if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
356        return false;
357    }
358    match proof.get("expires") {
359        None => true,
360        Some(Value::String(e)) => match parse_protocol_time_ns(e) {
361            Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
362            Err(_) => false,
363        },
364        Some(_) => false,
365    }
366}
367
368/// True when the key the caller supplied is the issuer's own key as far as
369/// the core can tell offline: for a `did:key` issuer it must be exactly the key
370/// the DID encodes. For other DID methods the caller resolved the key and the
371/// proof's verificationMethod binding is checked instead.
372fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
373    if issuer.starts_with("did:key:") {
374        return match crate::keys::did_key_to_ed25519(issuer) {
375            Ok(k) => k.as_slice() == raw_public_key,
376            Err(_) => false,
377        };
378    }
379    true
380}
381
382/// Verify the Data Integrity proof, the validity window against `now_iso`, and
383/// the embedded delegation chain (Specification 9.3).
384///
385/// A credential that carries a delegation chain is refused here
386/// (`chain_valid` false) because no trusted starting point is named: use
387/// [`verify_with_roots`] for those. A credential without a chain needs no
388/// roots. Refused with an `Err`: a skew outside 0..120 seconds, a malformed
389/// time, a missing or unsupported `vouchVersion`, or an `intent.resource` that
390/// is missing or not a non-empty string.
391///
392/// `credentialStatus` is not checked here: call
393/// [`crate::status_list::check_credential_status`] for that. The core keeps no
394/// state, so replay protection is the caller's: keep a replay store keyed by
395/// [`replay_key`].
396pub fn verify(
397    credential: &Value,
398    raw_public_key: &[u8],
399    now_iso: &str,
400    clock_skew_seconds: i64,
401) -> Result<VerifyResult> {
402    let opts = crate::delegation::ChainOptions::default();
403    Ok(verify_explained(
404        credential,
405        raw_public_key,
406        now_iso,
407        clock_skew_seconds,
408        &opts,
409    )?
410    .0)
411}
412
413/// [`verify`] with the trusted starting points for a delegation chain: the
414/// chain's first grant must be issued by one of `trusted_roots`. With an empty
415/// list a credential carrying a chain is refused.
416pub fn verify_with_roots(
417    credential: &Value,
418    raw_public_key: &[u8],
419    now_iso: &str,
420    clock_skew_seconds: i64,
421    trusted_roots: &[String],
422) -> Result<VerifyResult> {
423    let opts = crate::delegation::ChainOptions {
424        trusted_roots: Some(trusted_roots),
425        ..Default::default()
426    };
427    Ok(verify_explained(
428        credential,
429        raw_public_key,
430        now_iso,
431        clock_skew_seconds,
432        &opts,
433    )?
434    .0)
435}
436
437/// The full verifier: returns the [`VerifyResult`] and, when the chain is
438/// refused, its reason. `opts` carries the trusted roots, grant keys for
439/// non-`did:key` issuers, the post-quantum requirement and any explicit budget
440/// (see [`crate::delegation::ChainOptions`]). The credential's own proof must
441/// be a single `eddsa-jcs-2022` proof here; [`verify_with_keys`] also takes an
442/// ML-DSA-44 key for a proof set.
443pub fn verify_explained(
444    credential: &Value,
445    raw_public_key: &[u8],
446    now_iso: &str,
447    clock_skew_seconds: i64,
448    opts: &crate::delegation::ChainOptions,
449) -> Result<(VerifyResult, Option<String>)> {
450    verify_with_keys(
451        credential,
452        raw_public_key,
453        None,
454        now_iso,
455        clock_skew_seconds,
456        opts,
457    )
458}
459
460/// The top-level verifier for every proof shape a Vouch Credential carries:
461///
462/// * one `eddsa-jcs-2022` proof, verified with `ed25519_key` (refused when
463///   post-quantum is required: a single classical proof does not meet it);
464/// * a proof set of exactly one `eddsa-jcs-2022` and one ML-DSA-44 proof,
465///   both verified ([`crate::hybrid::verify_dual`]; needs `mldsa44_key`);
466///
467/// The earlier composite `hybrid-eddsa-mldsa44-jcs-2026` proof is refused
468/// (proofValid false); [`crate::hybrid::verify_composite`] still checks one on
469/// its own for migration tooling.
470///
471/// Before any signature: the envelope ([`check_envelope`]), the version
472/// ([`check_vouch_version`]), the resource ([`check_intent_resource`]), an
473/// issuer that is a DID, and every proof's own fields (type, a known
474/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
475/// issuer's DID). For a `did:key` issuer the Ed25519 key must be the one the DID
476/// encodes. Then the window ([`verify_temporal`]) and the delegation chain
477/// (which needs trusted roots, see [`verify_with_roots`]). The chain step
478/// starts with the credential's own binding fields
479/// ([`crate::grant_chain::binding_fields_problem`]): a `parentGrantDigest`
480/// that is not a string, a `delegationChain` that is not a list, or a digest
481/// together with a non-empty `delegationChain` gives `chain_valid` false with
482/// the reason "malformed_delegation", whatever roots are named. A sub-grant (a
483/// string digest and no chain) verifies on its own; whether it was made under
484/// a trusted chain is checked with its grant chain.
485///
486/// Supplying `mldsa44_key` means post-quantum is required for this
487/// credential: it must be 1312 bytes (else an `Err`), and a single classical
488/// proof is refused. The key applies to this credential only; grants follow
489/// `opts` (their own ML-DSA-44 keys, and `opts.require_pq`). Every trusted root
490/// must be a DID or a domain name (else an `Err`). `credentialStatus` and replay
491/// are the caller's to check, as for [`verify`].
492pub fn verify_with_keys(
493    credential: &Value,
494    ed25519_key: &[u8],
495    mldsa44_key: Option<&[u8]>,
496    now_iso: &str,
497    clock_skew_seconds: i64,
498    opts: &crate::delegation::ChainOptions,
499) -> Result<(VerifyResult, Option<String>)> {
500    check_clock_skew(clock_skew_seconds)?;
501    if let Some(ml) = mldsa44_key {
502        if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
503            return Err(CoreError::InvalidKeyLength {
504                expected: crate::pq::MLDSA44_PUBLIC_LEN,
505                got: ml.len(),
506            });
507        }
508    }
509    // A supplied ML-DSA-44 key means post-quantum is required.
510    verify_with_selected_keys(
511        credential,
512        Some(ed25519_key),
513        mldsa44_key,
514        mldsa44_key.is_some(),
515        now_iso,
516        clock_skew_seconds,
517        opts,
518    )
519}
520
521/// The verifier behind [`verify_with_keys`] and
522/// [`verify_with_did_webvh_log`], once the issuer's keys are chosen: with no
523/// Ed25519 key the proof is not valid, and `issuer_requires_pq` refuses a
524/// single classical proof.
525fn verify_with_selected_keys(
526    credential: &Value,
527    ed25519_key: Option<&[u8]>,
528    mldsa44_key: Option<&[u8]>,
529    issuer_requires_pq: bool,
530    now_iso: &str,
531    clock_skew_seconds: i64,
532    opts: &crate::delegation::ChainOptions,
533) -> Result<(VerifyResult, Option<String>)> {
534    check_clock_skew(clock_skew_seconds)?;
535    if let Some(roots) = opts.trusted_roots {
536        for r in roots {
537            crate::did_web::normalize_root(r)?;
538        }
539    }
540    if !credential.is_object() {
541        return Err(CoreError::Json("credential must be an object".into()));
542    }
543    check_envelope(credential)?;
544    check_vouch_version(credential)?;
545    check_intent_resource(credential)?;
546
547    let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
548    let proof_valid = match (issuer, credential.get("proof")) {
549        (Some(issuer), Some(proof)) => {
550            let members: Vec<&Value> = match proof {
551                Value::Array(items) => items.iter().collect(),
552                other => vec![other],
553            };
554            let mut fields_ok = !members.is_empty();
555            for m in &members {
556                fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
557            }
558            match ed25519_key {
559                Some(ed) => {
560                    fields_ok
561                        && key_matches_issuer(issuer, ed)
562                        && proof_shape_verifies(
563                            credential,
564                            proof,
565                            ed,
566                            mldsa44_key,
567                            issuer_requires_pq,
568                            opts,
569                        )?
570                }
571                // No key for the issuer: nothing to check the signature with.
572                None => false,
573            }
574        }
575        // No issuer DID to bind the proof to, or no proof.
576        _ => false,
577    };
578    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
579    let chain_reason = crate::delegation::verify_delegation_chain_with(
580        credential,
581        now_iso,
582        clock_skew_seconds,
583        opts,
584    );
585    Ok((
586        VerifyResult {
587            proof_valid,
588            time_valid,
589            chain_valid: chain_reason.is_none(),
590        },
591        chain_reason,
592    ))
593}
594
595/// The outcome of [`verify_with_did_webvh_log`].
596#[derive(Debug, Clone, PartialEq, Eq)]
597pub struct DidWebvhVerifyOutcome {
598    /// The verdict, as [`verify_with_keys`] gives it.
599    pub result: VerifyResult,
600    /// Why the delegation chain was refused, when it was.
601    pub chain_reason: Option<String>,
602    /// The issuer's log: its latest versionId (remember it as the version
603    /// seen for this DID), or why it was refused (then the proof is not
604    /// valid).
605    pub log: std::result::Result<String, crate::did_webvh::DidWebvhError>,
606    /// The logs of the grant issuers the delegation chain needed, by DID, as
607    /// [`crate::did_webvh::LogSet::outcomes`] reports them (the issuer's own
608    /// log is in `log`).
609    pub grant_logs: std::collections::BTreeMap<
610        String,
611        std::result::Result<String, crate::did_webvh::DidWebvhError>,
612    >,
613}
614
615/// The verificationMethods a credential's (or a grant's) proof names for its
616/// Ed25519 key and its ML-DSA-44 key (none for a single classical proof).
617pub(crate) fn proof_methods(credential: &Value) -> (Option<String>, Option<String>) {
618    let suite = |p: &Value| {
619        p.get("cryptosuite")
620            .and_then(Value::as_str)
621            .map(str::to_string)
622    };
623    let vm = |p: &Value| {
624        p.get("verificationMethod")
625            .and_then(Value::as_str)
626            .map(str::to_string)
627    };
628    let is_mldsa = |s: &str| {
629        s == crate::hybrid::MLDSA44_CRYPTOSUITE_ID
630            || s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
631    };
632    match credential.get("proof") {
633        Some(p @ Value::Object(_)) => match suite(p).as_deref() {
634            Some(crate::hybrid::EDDSA_CRYPTOSUITE_ID) => (vm(p), None),
635            Some(crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID) => {
636                // The composite convention: the ML-DSA-44 key sits at #key-2
637                // of the same DID.
638                let ed = vm(p);
639                let ml = ed.as_deref().map(|v| match v.strip_suffix("#key-1") {
640                    Some(base) => format!("{base}#key-2"),
641                    None => match v.split_once('#') {
642                        Some((base, _)) => format!("{base}#key-2"),
643                        None => format!("{v}#key-2"),
644                    },
645                });
646                (ed, ml)
647            }
648            _ => (None, None),
649        },
650        Some(Value::Array(items)) => {
651            let ed = items
652                .iter()
653                .find(|p| suite(p).as_deref() == Some(crate::hybrid::EDDSA_CRYPTOSUITE_ID))
654                .and_then(vm);
655            let ml = items
656                .iter()
657                .find(|p| suite(p).as_deref().is_some_and(is_mldsa))
658                .and_then(vm);
659            (ed, ml)
660        }
661        _ => (None, None),
662    }
663}
664
665/// Verify a credential whose issuer is a did:webvh DID, with the did:webvh
666/// logs the caller fetched: the core keeps no state and never fetches, so the
667/// caller fetches each log from [`crate::did_webvh::log_url`], puts it in
668/// `logs` with the latest versionId it saw before for that DID, and
669/// remembers the versions the outcome reports.
670///
671/// The issuer's log must be in `logs` (else an `Err`). It is verified in full
672/// ([`crate::did_webvh::verify_log`], always the latest entry) against the
673/// set's clock, which is the system clock unless the caller fixed it
674/// ([`crate::did_webvh::LogClock`]): the credential's `now_iso` decides its
675/// own validity window, never whether a log entry is dated in the future.
676/// The issuer's keys come from the latest state with the rules of
677/// [`crate::did_document::assertion_key`]: the state's id is exactly the
678/// issuer, and the key the proof names is the issuer's own, listed in
679/// assertionMethod. When the state lists an ML-DSA-44 key for assertions,
680/// the post-quantum proof is required, so it cannot be dropped from a
681/// credential. A refused or deactivated log gives no key, so the proof is not
682/// valid.
683///
684/// The delegation chain's did:webvh grant issuers resolve the same way from
685/// `logs` (see [`crate::delegation::ChainOptions::grant_logs`]; the set given
686/// here is used in place of `opts.grant_logs`). Everything else is as
687/// [`verify_with_keys`].
688///
689/// Errors (as for [`verify_with_keys`]) on a malformed request, when the
690/// credential's issuer is not a did:webvh DID, and when `logs` holds no log
691/// for it.
692pub fn verify_with_did_webvh_log(
693    credential: &Value,
694    logs: &crate::did_webvh::LogSet,
695    now_iso: &str,
696    clock_skew_seconds: i64,
697    opts: &crate::delegation::ChainOptions,
698) -> Result<DidWebvhVerifyOutcome> {
699    check_clock_skew(clock_skew_seconds)?;
700    parse_protocol_time_ns(now_iso)?;
701    let issuer = issuer_did(credential)
702        .filter(|i| crate::did_webvh::is_did_webvh(i))
703        .ok_or_else(|| {
704            CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
705        })?
706        .to_string();
707    let resolved = logs
708        .resolve(&issuer)
709        .ok_or_else(|| CoreError::Json("there is no log for the credential's issuer".into()))?;
710    let keys = match &resolved {
711        Ok(resolution) => {
712            let (ed_vm, ml_vm) = proof_methods(credential);
713            crate::did_document::proof_keys(
714                &resolution.document,
715                &issuer,
716                ed_vm.as_deref(),
717                ml_vm.as_deref(),
718            )
719        }
720        Err(_) => crate::did_document::ProofKeys::default(),
721    };
722    let chain = crate::delegation::ChainOptions {
723        grant_logs: Some(logs),
724        ..*opts
725    };
726    let (result, chain_reason) = verify_with_selected_keys(
727        credential,
728        keys.ed25519.as_deref(),
729        keys.mldsa44.as_deref(),
730        keys.requires_post_quantum,
731        now_iso,
732        clock_skew_seconds,
733        &chain,
734    )?;
735    let mut grant_logs = logs.outcomes();
736    grant_logs.remove(&issuer);
737    Ok(DidWebvhVerifyOutcome {
738        result,
739        chain_reason,
740        log: resolved.map(|r| r.latest_version_id),
741        grant_logs,
742    })
743}
744
745/// [`verify_request_json_with_clock`], with did:webvh logs checked against
746/// the system clock.
747pub fn verify_request_json(request: &Value) -> Result<Value> {
748    verify_request_json_with_clock(request, crate::did_webvh::LogClock::System)
749}
750
751/// [`verify_with_keys`] as one JSON request, for a credential whose issuer's
752/// keys the caller already holds, with the delegation chain's grant keys kept
753/// apart from its trusted roots and the did:webvh logs of grant issuers.
754///
755/// The request is `{"credential", "publicKey", "mldsa44PublicKey"}` plus the
756/// chain and log members every verify request shares (`now`,
757/// `clockSkewSeconds`, `trustedRoots`, `requirePostQuantum`, `grantKeys`,
758/// `grantMldsa44Keys`, `grantLogs`, `grantLogsB64`, `grantSeenVersionIds`,
759/// `limits`, `logNow`; see [`crate::did_webvh::verify_credential_json`]):
760///
761/// - `credential`: the credential, a JSON object;
762/// - `publicKey`: the issuer's Ed25519 key (base64, 32 bytes);
763/// - `mldsa44PublicKey` (optional): the issuer's ML-DSA-44 key (base64,
764///   1312 bytes). Giving it requires the post-quantum proof on this
765///   credential, as for [`verify_with_keys`].
766///
767/// A key in `grantKeys` resolves a grant's signature only: unlike the root
768/// keys of the fleet entry points, it never makes its DID a trusted root. A
769/// did:webvh grant issuer with no key there takes its keys from its log in
770/// `grantLogs` (see [`crate::delegation::ChainOptions::grant_logs`]), checked
771/// against `logNow` when the request gives one, else against `clock`.
772///
773/// Returns `{"proofValid", "timeValid", "chainValid", "valid",
774/// "chainReason", "grantVersionIds", "grantLogErrors"}`: the last two give,
775/// by DID, the latest versionId of each grant issuer's log the chain needed
776/// (remember it as the version seen) or why it was refused. Errors on a
777/// malformed request.
778pub fn verify_request_json_with_clock(
779    request: &Value,
780    clock: crate::did_webvh::LogClock,
781) -> Result<Value> {
782    use crate::did_webvh::{base64_decode, grant_log_json, read_chain_request, request_object};
783
784    let mut allowed = vec!["credential", "publicKey", "mldsa44PublicKey"];
785    allowed.extend(crate::did_webvh::CHAIN_REQUEST_MEMBERS);
786    let obj = request_object(request, &allowed)?;
787    let credential = obj
788        .get("credential")
789        .filter(|c| c.is_object())
790        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
791    let public_key = obj
792        .get("publicKey")
793        .and_then(Value::as_str)
794        .ok_or_else(|| CoreError::Json("publicKey must be a base64 Ed25519 key".into()))?;
795    let public_key = base64_decode(public_key, "publicKey")?;
796    let mldsa44_key = match obj.get("mldsa44PublicKey") {
797        None | Some(Value::Null) => None,
798        Some(Value::String(b64)) => Some(base64_decode(b64, "mldsa44PublicKey")?),
799        Some(_) => {
800            return Err(CoreError::Json(
801                "mldsa44PublicKey must be a base64 ML-DSA-44 key".into(),
802            ))
803        }
804    };
805    let request = read_chain_request(obj, clock)?;
806    let chain = crate::delegation::ChainOptions {
807        trusted_roots: request.roots.as_deref(),
808        grant_keys: request.grant_keys.as_ref(),
809        mldsa_keys: request.grant_mldsa_keys.as_ref(),
810        require_pq: request.require_pq,
811        grant_logs: Some(&request.logs),
812        ..Default::default()
813    };
814    let (r, chain_reason) = verify_with_keys(
815        credential,
816        &public_key,
817        mldsa44_key.as_deref(),
818        &request.now,
819        request.skew,
820        &chain,
821    )?;
822    let (grant_versions, grant_errors) = grant_log_json(&request.logs.outcomes());
823    Ok(serde_json::json!({
824        "proofValid": r.proof_valid,
825        "timeValid": r.time_valid,
826        "chainValid": r.chain_valid,
827        "valid": r.is_valid(),
828        "chainReason": chain_reason,
829        "grantVersionIds": grant_versions,
830        "grantLogErrors": grant_errors,
831    }))
832}
833
834/// Verify the credential's proof by its shape (see [`verify_with_keys`]).
835fn proof_shape_verifies(
836    credential: &Value,
837    proof: &Value,
838    ed25519_key: &[u8],
839    mldsa44_key: Option<&[u8]>,
840    issuer_requires_pq: bool,
841    opts: &crate::delegation::ChainOptions,
842) -> Result<bool> {
843    let suite = |p: &Value| {
844        p.get("cryptosuite")
845            .and_then(|v| v.as_str())
846            .unwrap_or_default()
847            .to_string()
848    };
849    match proof {
850        Value::Object(_) => match suite(proof).as_str() {
851            crate::hybrid::EDDSA_CRYPTOSUITE_ID => {
852                if opts.require_pq || issuer_requires_pq {
853                    return Ok(false);
854                }
855                data_integrity::verify_proof(credential, ed25519_key)
856            }
857            crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa44_key {
858                Some(ml) => crate::hybrid::verify_composite(credential, ed25519_key, ml),
859                None => Ok(false),
860            },
861            // An ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a set.
862            _ => Ok(false),
863        },
864        Value::Array(items) => {
865            let mut suites: Vec<String> = items
866                .iter()
867                .map(|p| {
868                    let s = suite(p);
869                    if s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
870                        crate::hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
871                    } else {
872                        s
873                    }
874                })
875                .collect();
876            suites.sort();
877            if suites
878                != [
879                    crate::hybrid::EDDSA_CRYPTOSUITE_ID,
880                    crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
881                ]
882            {
883                return Ok(false); // exactly one Ed25519 and one ML-DSA-44 proof
884            }
885            match mldsa44_key {
886                Some(ml) => crate::hybrid::verify_dual(credential, ed25519_key, ml),
887                None => Ok(false),
888            }
889        }
890        _ => Ok(false),
891    }
892}
893
894/// Check that `now_iso` falls within [validFrom, validUntil] allowing
895/// `clock_skew_seconds` of drift at each edge, at full fraction precision
896/// ([`crate::time`]). An inverted window (validFrom after validUntil) is never
897/// valid, and neither is a proof past its own `expires`. Errors on a missing
898/// or malformed time and on a skew outside 0..120 seconds.
899pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
900    let skew = check_clock_skew(clock_skew_seconds)?;
901    let obj = credential
902        .as_object()
903        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
904    let vf = obj
905        .get("validFrom")
906        .and_then(|v| v.as_str())
907        .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
908    let vu = obj
909        .get("validUntil")
910        .and_then(|v| v.as_str())
911        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
912    let now = parse_protocol_time_ns(now_iso)?;
913    let from = parse_protocol_time_ns(vf)?;
914    let until = parse_protocol_time_ns(vu)?;
915    if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
916        return Ok(false);
917    }
918    // A proof may carry its own `expires`: past it, the proof no longer
919    // speaks for the credential.
920    let proofs: Vec<&Value> = match obj.get("proof") {
921        Some(Value::Array(items)) => items.iter().collect(),
922        Some(p) => vec![p],
923        None => Vec::new(),
924    };
925    for p in proofs {
926        match p.get("expires") {
927            None => {}
928            Some(Value::String(e)) => {
929                let expires = parse_protocol_time_ns(e)?;
930                if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
931                    return Ok(false);
932                }
933            }
934            Some(_) => {
935                return Err(CoreError::Json(
936                    "proof.expires must be a time string".into(),
937                ))
938            }
939        }
940    }
941    Ok(true)
942}
943
944#[cfg(test)]
945mod tests {
946    use super::*;
947
948    fn opts() -> BuildCredentialOptions {
949        BuildCredentialOptions {
950            issuer_did: "did:web:agent.example.com".into(),
951            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
952            intent: json!({
953                "action": "read_database",
954                "target": "users_table",
955                "resource": "https://api.example.com/v1/users"
956            }),
957            valid_from: "2026-04-26T10:00:00Z".into(),
958            valid_until: "2026-04-26T10:05:00Z".into(),
959            reputation_score: Some(150),
960            delegation_chain: None,
961            credential_status: None,
962        }
963    }
964
965    #[test]
966    fn builds_expected_shape() {
967        let vc = build_vouch_credential(&opts()).unwrap();
968        assert_eq!(
969            vc["type"],
970            json!(["VerifiableCredential", "VouchCredential"])
971        );
972        assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
973        // reputationScore clamps to 100.
974        assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
975    }
976
977    #[test]
978    fn rejects_missing_intent_fields() {
979        let mut o = opts();
980        o.intent = json!({ "action": "read", "target": "t" }); // no resource
981        assert!(build_vouch_credential(&o).is_err());
982    }
983
984    #[test]
985    fn sub_grant_names_its_parent_one_way_only() {
986        let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
987        let sub = build_sub_grant(&opts(), digest).unwrap();
988        assert_eq!(sub["credentialSubject"]["parentGrantDigest"], json!(digest));
989        assert!(sub["credentialSubject"].get("delegationChain").is_none());
990        // Written after reputationScore, as the reference builder does.
991        let keys: Vec<&str> = sub["credentialSubject"]
992            .as_object()
993            .unwrap()
994            .keys()
995            .map(|k| k.as_str())
996            .collect();
997        assert_eq!(
998            keys,
999            [
1000                "id",
1001                "vouchVersion",
1002                "intent",
1003                "reputationScore",
1004                "parentGrantDigest"
1005            ]
1006        );
1007        assert!(build_vouch_credential(&opts())
1008            .unwrap()
1009            .pointer("/credentialSubject/parentGrantDigest")
1010            .is_none());
1011        assert_eq!(
1012            build_sub_grant(&opts(), "").unwrap_err().to_string(),
1013            "json error: parent_grant_digest must be a grant digest string"
1014        );
1015        let mut both = opts();
1016        both.delegation_chain = Some(json!([{"issuer": "did:web:a"}]));
1017        assert_eq!(
1018            build_sub_grant(&both, digest).unwrap_err().to_string(),
1019            "json error: a credential carries parentGrantDigest or a delegationChain, never both"
1020        );
1021        // An empty chain is no chain.
1022        both.delegation_chain = Some(json!([]));
1023        assert!(build_sub_grant(&both, digest).is_ok());
1024        // The intent is still checked first.
1025        let mut bad = opts();
1026        bad.intent = json!({ "action": "read" });
1027        assert!(build_sub_grant(&bad, "")
1028            .unwrap_err()
1029            .to_string()
1030            .contains("intent."));
1031        let seed = [5u8; 32];
1032        let signed = sign_sub_grant(
1033            &opts(),
1034            digest,
1035            &seed,
1036            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1037        )
1038        .unwrap();
1039        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1040        assert!(verify(&signed, &pk, "2026-04-26T10:02:00Z", 30)
1041            .unwrap()
1042            .is_valid());
1043    }
1044
1045    #[test]
1046    fn own_binding_fields_are_checked_on_every_verify_path() {
1047        let seed = [5u8; 32];
1048        let po = BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
1049        let with = |fields: Value| {
1050            let mut c = build_vouch_credential(&opts()).unwrap();
1051            for (k, v) in fields.as_object().unwrap() {
1052                c["credentialSubject"][k] = v.clone();
1053            }
1054            data_integrity::sign(&c, &seed, &po).unwrap()
1055        };
1056        let roots = ["did:web:root.example".to_string()];
1057        let with_roots = crate::delegation::ChainOptions {
1058            trusted_roots: Some(&roots),
1059            ..Default::default()
1060        };
1061        let none = crate::delegation::ChainOptions::default();
1062        // (chain_valid, reason) from each verify path.
1063        let every_path = |c: &Value| {
1064            let mut out = Vec::new();
1065            for r in [
1066                verify(c, &pk(), NOW, 30).unwrap(),
1067                verify_with_roots(c, &pk(), NOW, 30, &roots).unwrap(),
1068            ] {
1069                assert!(r.proof_valid && r.time_valid);
1070                out.push((r.chain_valid, None));
1071            }
1072            for o in [&none, &with_roots] {
1073                let (r, reason) = verify_explained(c, &pk(), NOW, 30, o).unwrap();
1074                assert!(r.proof_valid && r.time_valid);
1075                out.push((r.chain_valid, reason.clone()));
1076                let (r, reason2) = verify_with_keys(c, &pk(), None, NOW, 30, o).unwrap();
1077                assert_eq!(reason2, reason);
1078                out.push((r.chain_valid, reason2));
1079                out.push((
1080                    reason.is_none(),
1081                    crate::delegation::verify_delegation_chain_with(c, NOW, 30, o),
1082                ));
1083            }
1084            out
1085        };
1086        let malformed = Some("malformed_delegation".to_string());
1087        let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
1088        for fields in [
1089            json!({"parentGrantDigest": null}),
1090            json!({"parentGrantDigest": 5}),
1091            json!({"parentGrantDigest": ["u"]}),
1092            json!({"parentGrantDigest": {}}),
1093            json!({"delegationChain": null}),
1094            json!({"delegationChain": {}}),
1095            json!({"parentGrantDigest": digest, "delegationChain": [{"issuer": "did:web:a"}]}),
1096            json!({"parentGrantDigest": null, "delegationChain": [{"issuer": "did:web:a"}]}),
1097        ] {
1098            for (i, (chain_valid, reason)) in
1099                every_path(&with(fields.clone())).into_iter().enumerate()
1100            {
1101                assert!(!chain_valid, "{fields} path {i}");
1102                if i >= 2 {
1103                    assert_eq!(reason, malformed, "{fields} path {i}");
1104                }
1105            }
1106        }
1107        // A sub-grant on its own (a string digest, no chain) verifies, with or
1108        // without roots; so does one with an empty chain.
1109        for fields in [
1110            json!({ "parentGrantDigest": digest }),
1111            json!({"parentGrantDigest": digest, "delegationChain": []}),
1112        ] {
1113            for (i, (chain_valid, reason)) in
1114                every_path(&with(fields.clone())).into_iter().enumerate()
1115            {
1116                assert!(chain_valid, "{fields} path {i}");
1117                assert_eq!(reason, None, "{fields} path {i}");
1118            }
1119        }
1120    }
1121
1122    #[test]
1123    fn sign_and_verify_within_window() {
1124        let seed = [5u8; 32];
1125        let proof_opts =
1126            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
1127        let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
1128        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1129        let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
1130        assert!(r.is_valid());
1131        // Expired.
1132        let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
1133        assert!(r2.proof_valid && !r2.time_valid);
1134    }
1135
1136    fn signed_with(purpose: &str, vm: &str) -> Value {
1137        let seed = [5u8; 32];
1138        let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
1139        proof_opts.proof_purpose = purpose.into();
1140        sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
1141    }
1142
1143    fn pk() -> [u8; 32] {
1144        crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
1145    }
1146
1147    const NOW: &str = "2026-04-26T10:02:00Z";
1148
1149    #[test]
1150    fn proof_must_be_an_assertion_by_the_issuer() {
1151        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1152        assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
1153        let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
1154        assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
1155        let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
1156        assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
1157        let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
1158        assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
1159    }
1160
1161    #[test]
1162    fn did_key_issuer_must_be_the_signing_key() {
1163        let seed = [6u8; 32];
1164        let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
1165        let did = kp.did_key();
1166        let mut o = opts();
1167        o.issuer_did = did.clone();
1168        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1169        let signed = sign_vouch_credential(
1170            &o,
1171            &seed,
1172            &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
1173        )
1174        .unwrap();
1175        assert!(verify(&signed, &kp.public_key(), NOW, 30)
1176            .unwrap()
1177            .is_valid());
1178        // The same credential re-signed by another key that claims the DID.
1179        let other = [7u8; 32];
1180        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1181        let impostor = sign_vouch_credential(
1182            &o,
1183            &other,
1184            &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
1185        )
1186        .unwrap();
1187        let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
1188        assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
1189    }
1190
1191    #[test]
1192    fn vouch_version_and_resource_are_required() {
1193        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1194        for (path, value) in [
1195            ("vouchVersion", Value::Null),
1196            ("vouchVersion", json!("2.0")),
1197            ("vouchVersion", json!(1.0)),
1198        ] {
1199            let mut c = ok.clone();
1200            if value.is_null() {
1201                c["credentialSubject"].as_object_mut().unwrap().remove(path);
1202            } else {
1203                c["credentialSubject"][path] = value;
1204            }
1205            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
1206        }
1207        for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
1208            let mut c = ok.clone();
1209            c["credentialSubject"]["intent"]["resource"] = bad.clone();
1210            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
1211        }
1212        // A relative name is a valid resource (it is signed, so re-sign it).
1213        let mut o = opts();
1214        o.intent["resource"] = json!("reports/q3.txt");
1215        let signed = sign_vouch_credential(
1216            &o,
1217            &[5u8; 32],
1218            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1219        )
1220        .unwrap();
1221        assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
1222    }
1223
1224    #[test]
1225    fn window_rules() {
1226        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1227        // A skew outside 0..120 seconds is refused, never wrapped.
1228        for skew in [-1, 121, i64::MAX, i64::MIN] {
1229            assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
1230            assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
1231        }
1232        // A naive or loose `now` is refused.
1233        for now in [
1234            "2026-04-26T10:02:00",
1235            "2026-04-26 10:02:00Z",
1236            "2026-04-26t10:02:00z",
1237        ] {
1238            assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
1239        }
1240        // Fractions count: one nanosecond past validUntil is expired at skew 0.
1241        assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
1242        assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
1243        // An inverted window is never valid.
1244        let inverted =
1245            json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
1246        assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
1247        // A proof past its own `expires` no longer speaks for the credential.
1248        let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
1249                           "proof": {"expires": "2026-04-26T10:01:00Z"}});
1250        assert!(!verify_temporal(&c, NOW, 30).unwrap());
1251        c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
1252        assert!(verify_temporal(&c, NOW, 30).unwrap());
1253        c["proof"]["expires"] = json!(5);
1254        assert!(verify_temporal(&c, NOW, 30).is_err());
1255    }
1256
1257    #[test]
1258    fn proof_context_must_match_the_document() {
1259        let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1260        c["proof"]["@context"] = json!(["https://example.com/other"]);
1261        assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
1262    }
1263
1264    #[test]
1265    fn issuer_object_is_bound_by_its_id() {
1266        let mut o = opts();
1267        o.issuer_did = "did:web:agent.example.com".into();
1268        let mut cred = build_vouch_credential(&o).unwrap();
1269        cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
1270        let signed = data_integrity::sign(
1271            &cred,
1272            &[5u8; 32],
1273            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1274        )
1275        .unwrap();
1276        assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
1277        let mut bad = cred.clone();
1278        bad["issuer"] = json!(["did:web:agent.example.com"]);
1279        let signed = data_integrity::sign(
1280            &bad,
1281            &[5u8; 32],
1282            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1283        )
1284        .unwrap();
1285        assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1286    }
1287
1288    #[test]
1289    fn envelope_must_be_a_vouch_credential() {
1290        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1291        for (key, value) in [
1292            ("@context", Value::Null),
1293            ("@context", json!("https://www.w3.org/ns/credentials/v2")),
1294            ("@context", json!(["https://example.com/other"])),
1295            ("type", json!(["VerifiableCredential"])),
1296            ("type", json!("VouchCredential")),
1297        ] {
1298            let mut c = ok.clone();
1299            if value.is_null() {
1300                c.as_object_mut().unwrap().remove(key);
1301            } else {
1302                c[key] = value.clone();
1303            }
1304            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
1305        }
1306        // An issuer that is not a DID is never bound.
1307        let mut o = opts();
1308        o.issuer_did = "agent.example.com".into();
1309        let signed = sign_vouch_credential(
1310            &o,
1311            &[5u8; 32],
1312            &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1313        )
1314        .unwrap();
1315        assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1316        // A malformed proof.created is refused.
1317        let mut c = ok.clone();
1318        c["proof"]["created"] = json!("yesterday");
1319        assert!(verify(&c, &pk(), NOW, 30).is_err());
1320    }
1321
1322    #[test]
1323    fn every_proof_shape_through_one_verifier() {
1324        use crate::delegation::ChainOptions;
1325        let seed = [5u8; 32];
1326        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1327        let unsigned = build_vouch_credential(&opts()).unwrap();
1328        let dual = crate::hybrid::sign_dual(
1329            &unsigned,
1330            &seed,
1331            &ml,
1332            "did:web:agent.example.com#key-1",
1333            "did:web:agent.example.com#key-2",
1334            "2026-04-26T10:00:00Z",
1335        )
1336        .unwrap();
1337        let none = ChainOptions::default();
1338        let pq = ChainOptions {
1339            require_pq: true,
1340            ..Default::default()
1341        };
1342        let mlk = ml.public_key();
1343        let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
1344            verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
1345        };
1346        assert!(run(&dual, Some(&mlk), &none).is_valid());
1347        assert!(run(&dual, Some(&mlk), &pq).is_valid());
1348        // A proof set without the ML-DSA key, or through the Ed25519-only form.
1349        assert!(!run(&dual, None, &none).proof_valid);
1350        assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
1351        // A single classical proof does not meet the post-quantum profile, and
1352        // supplying an ML-DSA-44 key means post-quantum is required.
1353        let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1354        assert!(run(&single, None, &none).is_valid());
1355        assert!(!run(&single, None, &pq).proof_valid);
1356        assert!(!run(&single, Some(&mlk), &none).proof_valid);
1357        // The ML-DSA-44 key must be 1312 bytes.
1358        assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
1359        // Every trusted root must be a DID or a domain name.
1360        let bad_roots = vec!["127.0.0.1".to_string()];
1361        let with_bad = ChainOptions {
1362            trusted_roots: Some(&bad_roots),
1363            ..Default::default()
1364        };
1365        assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
1366        // The ML-DSA member alone, or the set with an extra member.
1367        let mut lone = dual.clone();
1368        lone["proof"] = dual["proof"][1].clone();
1369        assert!(!run(&lone, Some(&mlk), &none).proof_valid);
1370        let mut extra = dual.clone();
1371        extra["proof"]
1372            .as_array_mut()
1373            .unwrap()
1374            .push(dual["proof"][0].clone());
1375        assert!(!run(&extra, Some(&mlk), &none).proof_valid);
1376        // An unknown cryptosuite in the set is refused at the top level.
1377        let mut unknown = dual.clone();
1378        let mut odd = dual["proof"][0].clone();
1379        odd["cryptosuite"] = json!("some-unregistered-suite-2030");
1380        unknown["proof"].as_array_mut().unwrap().push(odd);
1381        assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
1382    }
1383
1384    #[test]
1385    fn replay_key_is_issuer_nul_and_proof_digest() {
1386        use sha2::{Digest, Sha256};
1387        let k = replay_key("did:web:a.example", "z3abc").unwrap();
1388        let mut h = Sha256::new();
1389        h.update(b"did:web:a.example\x00");
1390        h.update(Sha256::digest(b"z3abc"));
1391        let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
1392        assert_eq!(k, want);
1393        assert_eq!(k.len(), 64);
1394        assert!(replay_key("", "z3abc").is_err());
1395        assert!(replay_key("did:web:a.example", "").is_err());
1396        // The NUL keeps the two parts apart.
1397        assert_ne!(
1398            replay_key("did:web:a", "bc").unwrap(),
1399            replay_key("did:web:ab", "c").unwrap()
1400        );
1401    }
1402}