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