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