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