Skip to main content

vouch_core/
delegation.rs

1//! Delegation links and time-bound chain validation.
2//!
3//! A delegation link carries an issuer, subject, intent, and an optional
4//! validity window (Specification 9.2). Time-bound validation enforces that each
5//! link's window is within its parent's (time attenuation, 9.3 step 6) and that
6//! the current instant is within the narrowest link's window. The full v1.7
7//! capability-attenuation rule across the other dimensions lives with the SDKs;
8//! this core provides the link structure plus the deterministic temporal checks.
9
10#[allow(unused_imports)]
11use crate::prelude::*;
12
13use alloc::collections::BTreeMap;
14
15use serde_json::{json, Map, Value};
16
17use crate::attenuation;
18use crate::data_integrity;
19use crate::error::{CoreError, Result};
20use crate::grant_chain;
21use crate::hybrid;
22use crate::multikey;
23use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
24
25/// Inputs for one delegation link.
26#[derive(Debug, Clone)]
27pub struct DelegationLinkInput {
28    pub issuer: String,
29    pub subject: String,
30    pub intent: Value,
31    pub valid_from: Option<String>,
32    pub valid_until: Option<String>,
33    pub parent_proof_value: Option<String>,
34}
35
36/// Build a delegation link object (field order matches the SDK).
37pub fn build_delegation_link(input: &DelegationLinkInput) -> Value {
38    crate::nesting::deep_guard!(Value::Null; input);
39    let mut link = Map::new();
40    link.insert("issuer".into(), json!(input.issuer));
41    link.insert("subject".into(), json!(input.subject));
42    link.insert("intent".into(), input.intent.clone());
43    if let Some(vf) = &input.valid_from {
44        link.insert("validFrom".into(), json!(vf));
45    }
46    if let Some(vu) = &input.valid_until {
47        link.insert("validUntil".into(), json!(vu));
48    }
49    if let Some(pp) = &input.parent_proof_value {
50        link.insert("parentProofValue".into(), json!(pp));
51    }
52    Value::Object(link)
53}
54
55/// A link's window bound: absent is open, a protocol-time string is parsed,
56/// and anything else (null, a number, an object) is an error.
57fn link_bound(obj: &Map<String, Value>, key: &str) -> Result<Option<i128>> {
58    match obj.get(key) {
59        None => Ok(None),
60        Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
61        Some(_) => Err(CoreError::Json(format!(
62            "delegation link {key} must be a time string"
63        ))),
64    }
65}
66
67fn link_window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
68    let obj = link
69        .as_object()
70        .ok_or_else(|| CoreError::Json("delegation link must be an object".into()))?;
71    Ok((
72        link_bound(obj, "validFrom")?,
73        link_bound(obj, "validUntil")?,
74    ))
75}
76
77/// Validate the time-bound rule over a chain ordered root -> leaf. Every
78/// link's window must sit inside the window of EVERY link above it (the
79/// running intersection, so a middle link with no window does not detach the
80/// leaf from the root's window), no window may be inverted, and `now_iso` must
81/// fall inside the intersection of all the windows (allowing the skew).
82/// Returns Ok(true) if the chain is time-valid. Errors on a bound that is not a
83/// time string, a malformed time, or a skew outside 0..120 seconds.
84pub fn verify_chain_time_bound(
85    chain: &[Value],
86    now_iso: &str,
87    clock_skew_seconds: i64,
88) -> Result<bool> {
89    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); chain);
90    let skew = check_clock_skew(clock_skew_seconds)?;
91    let now = parse_protocol_time_ns(now_iso)?;
92    let mut eff_from: Option<i128> = None;
93    let mut eff_until: Option<i128> = None;
94
95    for link in chain {
96        let (vf, vu) = link_window(link)?;
97        if let (Some(f), Some(u)) = (vf, vu) {
98            if f > u {
99                return Ok(false); // inverted window
100            }
101        }
102        if let (Some(f), Some(ef)) = (vf, eff_from) {
103            if f < ef {
104                return Ok(false); // starts before an ancestor
105            }
106        }
107        if let (Some(u), Some(eu)) = (vu, eff_until) {
108            if u > eu {
109                return Ok(false); // ends after an ancestor
110            }
111        }
112        if let Some(f) = vf {
113            eff_from = Some(eff_from.map_or(f, |cur| cur.max(f)));
114        }
115        if let Some(u) = vu {
116            eff_until = Some(eff_until.map_or(u, |cur| cur.min(u)));
117        }
118    }
119    Ok(window_state_ns(now, eff_from, eff_until, skew) == WindowState::Ok)
120}
121
122// ---------------------------------------------------------------------------
123// Delegation chain verification (Specification 9.3)
124// ---------------------------------------------------------------------------
125//
126// A faithful port of `vouch.verifier.verify_delegation_chain` (Python is the
127// reference). Every step and reason code matches it exactly; the shared vectors
128// in `test-vectors/delegation-chain/vector.json` are the contract.
129
130/// Map a signed Vouch credential onto the six-dimension link shape that
131/// `attenuation::non_expansion` compares: action / target / resource from
132/// `credentialSubject.intent`, time from `validFrom` / `validUntil`, rate and
133/// policy from `intent.rate` / `intent.policy`, subject from `intent.delegatee`.
134pub fn capability_view(credential: &Value, include_time: bool) -> Value {
135    crate::nesting::deep_guard!(Value::Null; credential);
136    let intent = credential
137        .get("credentialSubject")
138        .and_then(|s| s.get("intent"))
139        .and_then(|i| i.as_object())
140        .cloned()
141        .unwrap_or_default();
142    let mut view = Map::new();
143    view.insert(
144        "issuer".into(),
145        issuer_did(credential)
146            .map(Value::String)
147            .unwrap_or(Value::Null),
148    );
149    view.insert(
150        "subject".into(),
151        intent.get("delegatee").cloned().unwrap_or(Value::Null),
152    );
153    let mut dims = Map::new();
154    for k in ["action", "target", "resource", "amount"] {
155        if let Some(v) = intent.get(k) {
156            dims.insert(k.into(), v.clone());
157        }
158    }
159    view.insert("intent".into(), Value::Object(dims));
160    if include_time {
161        for k in ["validFrom", "validUntil"] {
162            if let Some(v) = credential.get(k) {
163                view.insert(k.into(), v.clone());
164            }
165        }
166    }
167    for k in ["rate", "policy"] {
168        if let Some(v) = intent.get(k) {
169            view.insert(k.into(), v.clone());
170        }
171    }
172    Value::Object(view)
173}
174
175/// The issuer DID of a grant or credential: the `issuer` string, or the `id` of
176/// an issuer object. An array or any other shape has no issuer.
177fn issuer_did(credential: &Value) -> Option<String> {
178    crate::credentials::issuer_did(credential).map(String::from)
179}
180
181/// The Ed25519 key of a grant issuer: from the caller's map, else (for a
182/// `did:key`) the key the DID encodes. For a `did:key` issuer a key in the
183/// caller's map must equal the DID's own key, and a `did:key` that does not
184/// decode resolves to nothing.
185fn resolve_chain_key(did: &str, root_keys: &BTreeMap<String, Vec<u8>>) -> Option<Vec<u8>> {
186    let from_did = match did.strip_prefix("did:key:") {
187        Some(mk) => {
188            let decoded = multikey::decode(mk).ok()?;
189            if decoded.algorithm != "Ed25519" {
190                return None;
191            }
192            Some(decoded.raw_key)
193        }
194        None => None,
195    };
196    // A key the caller named that the strict Ed25519 rules refuse is no key
197    // (it stays the only key named for that DID).
198    let given = root_keys.get(did);
199    if given.is_some_and(|k| crate::keys::strict_verifying_key(k).is_err()) {
200        return None;
201    }
202    match (given, from_did) {
203        (Some(k), Some(d)) => (k == &d).then_some(d),
204        (Some(k), None) => Some(k.clone()),
205        (None, d) => d,
206    }
207}
208
209/// The keys a grant's signature is checked with.
210struct GrantIssuerKeys {
211    ed25519: Vec<u8>,
212    mldsa44: Option<Vec<u8>>,
213    slhdsa128: Option<Vec<u8>>,
214    /// The proofs the issuer's document requires on its grant: one for each
215    /// post-quantum assertion key it publishes.
216    requires: hybrid::Required,
217}
218
219/// A grant issuer's keys, in the reference's order: the caller's key for the
220/// DID (`grant_keys`) or its did:key first; else, for a did:webvh issuer
221/// whose log the caller gave (`opts.grant_logs`), the keys the latest
222/// verified state lists for the verificationMethods the grant's proof names.
223/// A post-quantum key the caller gave (`opts.mldsa_keys`,
224/// `opts.slhdsa_keys`, a pinned key or a key resolver's answer) comes before
225/// the state's, and makes that suite's proof required on the grant, exactly
226/// as a key the issuer's document publishes does. None when no Ed25519 key
227/// is found.
228fn grant_issuer_keys(
229    issuer: &str,
230    grant: &Value,
231    grant_keys: &BTreeMap<String, Vec<u8>>,
232    opts: &ChainOptions,
233) -> Option<GrantIssuerKeys> {
234    // A post-quantum key known for the grant issuer is a key whose proof the
235    // grant must carry: otherwise it could be stripped, and the grant would
236    // stand on its Ed25519 proof alone. An unusable answer (an empty key)
237    // keeps the requirement and checks nothing, so the grant is refused.
238    let given_requires = hybrid::Required {
239        post_quantum: false,
240        mldsa44: opts.mldsa_keys.is_some_and(|m| m.contains_key(issuer)),
241        slhdsa128: opts.slhdsa_keys.is_some_and(|m| m.contains_key(issuer)),
242    };
243    let given_mldsa = opts
244        .mldsa_keys
245        .and_then(|m| m.get(issuer))
246        .filter(|k| !k.is_empty())
247        .cloned();
248    let given_slhdsa = opts
249        .slhdsa_keys
250        .and_then(|m| m.get(issuer))
251        .filter(|k| !k.is_empty())
252        .cloned();
253    if let Some(ed25519) = resolve_chain_key(issuer, grant_keys) {
254        return Some(GrantIssuerKeys {
255            ed25519,
256            mldsa44: given_mldsa,
257            slhdsa128: given_slhdsa,
258            requires: given_requires,
259        });
260    }
261    if grant_keys.contains_key(issuer) {
262        return None;
263    }
264    let fetched = opts
265        .grant_documents
266        .filter(|_| issuer.starts_with("did:web:") || crate::did_webvh::is_did_webvh(issuer))
267        .and_then(|docs| docs.get(issuer));
268    let state = match fetched {
269        Some(document) => document.clone(),
270        None if crate::did_webvh::is_did_webvh(issuer) => {
271            opts.grant_logs?.resolve(issuer)?.ok()?.document
272        }
273        None => return None,
274    };
275    let methods = crate::credentials::proof_methods(grant);
276    let keys = crate::did_document::proof_keys_for(
277        &state,
278        issuer,
279        crate::did_document::ProofMethodRefs {
280            ed25519: methods.ed25519.as_deref(),
281            mldsa44: methods.mldsa44.as_deref(),
282            slhdsa128: methods.slhdsa128.as_deref(),
283        },
284    );
285    let published = keys.required();
286    let requires = hybrid::Required {
287        post_quantum: published.post_quantum,
288        mldsa44: published.mldsa44 || given_requires.mldsa44,
289        slhdsa128: published.slhdsa128 || given_requires.slhdsa128,
290    };
291    Some(GrantIssuerKeys {
292        ed25519: keys.ed25519?,
293        mldsa44: given_mldsa.or(keys.mldsa44),
294        slhdsa128: given_slhdsa.or(keys.slhdsa128),
295        requires,
296    })
297}
298
299/// The proof value a link binds to its parent: the eddsa-jcs-2022 member of a
300/// proof set, else the first proof value, else a single proof's value.
301pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
302    match grant.get("proof") {
303        Some(Value::Array(items)) => {
304            for p in items {
305                if p.get("cryptosuite").and_then(|v| v.as_str())
306                    == Some(data_integrity::CRYPTOSUITE_ID)
307                {
308                    return p
309                        .get("proofValue")
310                        .and_then(|v| v.as_str())
311                        .unwrap_or("")
312                        .to_string();
313                }
314            }
315            for p in items {
316                if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
317                    if !v.is_empty() {
318                        return v.to_string();
319                    }
320                }
321            }
322            String::new()
323        }
324        Some(Value::Object(p)) => p
325            .get("proofValue")
326            .and_then(|v| v.as_str())
327            .unwrap_or("")
328            .to_string(),
329        _ => String::new(),
330    }
331}
332
333/// Check a grant's proof with the top-level proof rules.
334///
335/// Every member is an object with type "DataIntegrityProof", a known
336/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
337/// grant issuer's DID, a proofValue, a valid `created` and an `expires` (when
338/// present) that has not passed. The shape is one `eddsa-jcs-2022` proof, or
339/// a set of exactly one `eddsa-jcs-2022` member and one member of each
340/// post-quantum suite it carries ([`hybrid::set_members`]). The earlier
341/// composite proof is refused. The Ed25519 proof always verifies with `key`;
342/// a post-quantum member is checked whenever its key is known, and when
343/// `required` asks for anything post-quantum a single classical proof fails,
344/// every suite it names must be in the set, and every post-quantum member
345/// needs its key.
346#[allow(clippy::too_many_arguments)]
347fn verify_grant_proof(
348    grant: &Value,
349    issuer: &str,
350    key: &[u8],
351    mldsa_key: Option<&[u8]>,
352    slhdsa_key: Option<&[u8]>,
353    required: hybrid::Required,
354    now: i128,
355    skew: i128,
356) -> bool {
357    if !grant_proof_well_formed(grant, issuer, now, skew) {
358        return false;
359    }
360    match grant.get("proof") {
361        Some(Value::Object(_)) => {
362            !required.any() && matches!(data_integrity::verify_proof(grant, key), Ok(true))
363        }
364        Some(Value::Array(items)) => {
365            let Some(members) = hybrid::set_members(items) else {
366                return false;
367            };
368            if !required.met_by(&members.suites()) {
369                return false;
370            }
371            let verdict = if required.any() {
372                hybrid::verify_set(grant, key, mldsa_key, slhdsa_key)
373            } else {
374                // Only the members whose key is known can be checked: they
375                // must verify, the Ed25519 one always.
376                hybrid::verify_set_known_keys(grant, key, mldsa_key, slhdsa_key)
377            };
378            matches!(verdict, Ok(true))
379        }
380        _ => false,
381    }
382}
383
384/// The checks of [`verify_grant_proof`] that need no key: every member passes
385/// the top-level proof rules, and the shape is one `eddsa-jcs-2022` proof or
386/// a proof set ([`hybrid::set_members`]). The earlier composite proof, like
387/// every other single proof object, is refused.
388fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
389    let Some(proof) = grant.get("proof") else {
390        return false;
391    };
392    let members: Vec<&Value> = match proof {
393        Value::Array(items) => items.iter().collect(),
394        other => vec![other],
395    };
396    if members.is_empty()
397        || !members
398            .iter()
399            .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
400    {
401        return false;
402    }
403    match proof {
404        Value::Object(_) => hybrid::Suite::of_proof(proof) == Some(hybrid::Suite::Eddsa),
405        Value::Array(items) => hybrid::set_members(items).is_some(),
406        _ => false,
407    }
408}
409
410fn first_64(s: &str) -> String {
411    s.chars().take(64).collect()
412}
413
414/// The reason a chain is refused when the caller named no trusted starting
415/// point (trusted roots) for it.
416pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
417    "the chain's starting point is not trusted: pass trusted roots";
418
419/// The reason a chain is refused by the verifier's resource guard or an
420/// explicit budget the caller set.
421pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
422
423/// An encoded delegation chain (its JCS form) larger than this is refused
424/// before any signature is checked. This is a resource guard only: there is no
425/// fixed depth limit, since a chain is limited by narrowing scope, never by its
426/// number of links.
427pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
428
429/// A trusted root as the caller wrote it, as a DID, read exactly as the Python
430/// reference reads it ([`crate::did_web::normalize_root`]): a bare domain such
431/// as "yourcompany.com" means "did:web:yourcompany.com" ("host:8443" means
432/// "did:web:host%3A8443"); a full DID is used as it is. None when the root is
433/// neither (an IP literal, a URL, a trailing dot, a bad port, ...).
434pub fn root_did(root: &str) -> Option<String> {
435    crate::did_web::normalize_root(root).ok()
436}
437
438/// True when the caller's trusted root names `issuer` exactly (see
439/// [`root_did`]); a root that does not parse names nobody.
440pub fn root_matches(root: &str, issuer: &str) -> bool {
441    root_did(root).as_deref() == Some(issuer)
442}
443
444/// How a verifier checks an embedded delegation chain.
445#[derive(Debug, Clone, Copy, Default)]
446pub struct ChainOptions<'a> {
447    /// The trusted starting points: the chain's first grant must be issued by
448    /// one of them. A chain is refused when this is `None`
449    /// ([`REASON_TRUSTED_ROOTS_REQUIRED`]); an empty list trusts nobody
450    /// ("untrusted_principal"). A bare domain stands for its did:web
451    /// ([`root_did`]).
452    pub trusted_roots: Option<&'a [String]>,
453    /// Ed25519 keys for grant issuers that are not `did:key` (a `did:key`
454    /// issuer always resolves offline from the DID itself). A key here only
455    /// resolves a grant's signature: it never makes its DID a trusted root.
456    pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
457    /// ML-DSA-44 public keys by grant issuer DID. A grant whose issuer has a
458    /// key here has its ML-DSA-44 member checked.
459    pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
460    /// SLH-DSA-SHA2-128s public keys by grant issuer DID. A grant whose
461    /// issuer has a key here has its SLH-DSA member checked.
462    pub slhdsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
463    /// The SLH-DSA-SHA2-128s public key of the credential's own issuer (not
464    /// of a grant issuer), for [`crate::credentials::verify_with_keys`]:
465    /// giving it requires the SLH-DSA proof on that credential. The chain
466    /// check does not read it.
467    pub slhdsa128_key: Option<&'a [u8]>,
468    /// did:webvh logs of grant issuers, fetched by the caller. A did:webvh
469    /// grant issuer with no key in `grant_keys` takes its keys from the
470    /// latest verified state of its log here, with the rules of
471    /// [`crate::did_document::assertion_key`] for the verificationMethods the
472    /// grant's proof names; a state that publishes a post-quantum assertion
473    /// key requires that suite's proof on that grant. A log that is missing,
474    /// refused or deactivated gives no key ("delegation_issuer_key_unresolved").
475    /// The log is verified only when the chain check reaches a grant it signs.
476    pub grant_logs: Option<&'a crate::did_webvh::LogSet>,
477    /// DID documents of did:web and did:webvh grant issuers, fetched by the
478    /// caller (for did:webvh, the latest verified state of its log). A grant
479    /// issuer with no key in `grant_keys` takes its keys from its document
480    /// here, before `grant_logs`, with the same rules.
481    pub grant_documents: Option<&'a BTreeMap<String, Value>>,
482    /// Require the post-quantum profile on every grant: each must carry a
483    /// valid proof set (Ed25519 and at least one post-quantum proof), with
484    /// the key of every post-quantum member known.
485    pub require_pq: bool,
486    /// The cryptosuites every grant's proofs must include (the verifier's
487    /// `requireSuites` setting, which covers the credential and every grant
488    /// above it). A grant without one of them is refused before any key is
489    /// looked up, and a post-quantum suite named here needs its key, as
490    /// `require_pq` does.
491    pub require_suites: &'a [hybrid::Suite],
492    /// An explicit depth budget chosen by the caller. `None` means no depth
493    /// limit (there is no default one).
494    pub max_depth: Option<usize>,
495    /// Check only the links before this index (their grants, keys,
496    /// signatures, bindings and windows) and answer None when they pass. A
497    /// host that looks keys up one grant at a time asks this before it
498    /// looks up the next grant issuer's key, so a DID that no verified
499    /// grant named is never looked up.
500    pub through_link: Option<usize>,
501}
502
503/// Verify a credential's embedded `delegationChain`. Returns `None` when the
504/// chain is valid (or absent), otherwise the reason code.
505///
506/// `root_keys` supplies Ed25519 keys for non-`did:key` grant issuers (for a
507/// `did:key` issuer it must equal the DID's own key); `root_dids` is the set of
508/// trusted root DIDs the chain must start from. A credential that carries a
509/// chain is refused when `root_dids` is `None`, and an empty list trusts
510/// nobody. See [`verify_delegation_chain_with`] for every option.
511pub fn verify_delegation_chain(
512    credential: &Value,
513    now_iso: &str,
514    clock_skew_seconds: i64,
515    root_keys: &BTreeMap<String, Vec<u8>>,
516    root_dids: Option<&[String]>,
517) -> Option<String> {
518    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
519    let opts = ChainOptions {
520        trusted_roots: root_dids,
521        grant_keys: Some(root_keys),
522        ..Default::default()
523    };
524    verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
525}
526
527/// The chain checks that need no key, in the reference's order: the
528/// credential's own binding fields, the size guard and any depth budget, the
529/// trusted roots, and the link fields alone (each link continues the one
530/// before it, the last names the credential's issuer, the chain starts at a
531/// trusted root, and every grant is bound to the grant before it). The
532/// reason to refuse, or None (also for a credential with no chain). A host
533/// runs this before it asks for any key or fetches any document.
534pub fn chain_links_problem(
535    credential: &Value,
536    now_iso: &str,
537    clock_skew_seconds: i64,
538    opts: &ChainOptions,
539) -> Option<String> {
540    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
541    let malformed = || Some("malformed_delegation".to_string());
542    if !credential.is_object() {
543        return malformed();
544    }
545    // The credential's own binding fields: a present delegationChain must be
546    // a list and a present parentGrantDigest a string (null, {}, "", 0 or
547    // false is malformed, never absent, D29), never both a digest and a chain.
548    if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
549        return Some(reason.into());
550    }
551    let chain_value = match credential
552        .get("credentialSubject")
553        .and_then(|s| s.get("delegationChain"))
554    {
555        None => return None,
556        Some(Value::Array(a)) if a.is_empty() => return None,
557        Some(v @ Value::Array(_)) => v,
558        // Refused above: a delegationChain that is not a list.
559        Some(_) => return malformed(),
560    };
561    let chain = chain_value.as_array().expect("checked above");
562    match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
563        Ok(None) => {}
564        Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
565        Err(_) => return malformed(),
566    }
567    let Some(roots) = opts.trusted_roots else {
568        return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
569    };
570    if check_clock_skew(clock_skew_seconds).is_err() || parse_protocol_time_ns(now_iso).is_err() {
571        return malformed();
572    }
573
574    // Pre-filter from the link fields alone, before any key is resolved.
575    for link in chain {
576        let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
577            && link.get("subject").is_some_and(|v| v.is_string());
578        if !shape_ok {
579            return malformed();
580        }
581    }
582    for i in 1..chain.len() {
583        if chain[i - 1].get("subject") != chain[i].get("issuer") {
584            return Some("delegation_subject_issuer_mismatch".into());
585        }
586    }
587    let last_subject = chain[chain.len() - 1]
588        .get("subject")
589        .and_then(|v| v.as_str());
590    if last_subject.map(String::from) != issuer_did(credential) {
591        return Some("delegation_subject_issuer_mismatch".into());
592    }
593    let root = chain[0]
594        .get("issuer")
595        .and_then(|v| v.as_str())
596        .unwrap_or("");
597    if !roots.iter().any(|d| root_matches(d, root)) {
598        return Some("untrusted_principal".into());
599    }
600    // Every grant is bound to the grant before it (flat chains name it by
601    // digest, older nested ones embed the links above them). A link without
602    // its grant is left to the per-link checks, which report it as
603    // delegation_link_unsigned.
604    if chain
605        .iter()
606        .all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
607    {
608        if let Some(reason) = grant_chain::chain_binding_problem(chain) {
609            return Some(reason.into());
610        }
611    }
612
613    None
614}
615
616/// Verify a credential's embedded `delegationChain` under `opts`. Returns
617/// `None` when the chain is valid (or absent), otherwise the reason code.
618///
619/// Order: first the credential's own binding fields
620/// ([`grant_chain::binding_fields_problem`]: a present `delegationChain` is a
621/// list, so null, `{}`, `""`, 0 or false is malformed; a present
622/// `parentGrantDigest` is a string; and the credential does not carry a digest
623/// together with a non-empty `delegationChain`; else "malformed_delegation").
624/// Every verify path ([`crate::credentials::verify_with_keys`] and the entry
625/// points over it) runs this, so it is the credential shape check for those
626/// fields everywhere. A sub-grant with a string digest and no chain passes
627/// here; its grant chain is checked apart. Then the size guard (1 MiB of JCS)
628/// and any explicit depth
629/// budget, the trusted roots, then a pre-filter from the link fields alone
630/// (each link's issuer is the previous link's subject, and the first issuer
631/// is a trusted root), all before any key is resolved or signature checked.
632/// The pre-filter also checks that the last link's subject is the credential's
633/// issuer and, when every link carries its grant as an object, that every
634/// grant is bound to the grant before it
635/// ([`grant_chain::chain_binding_problem`]: the first grant is a root grant,
636/// and every later grant carries the digest of the grant before it in
637/// `parentGrantDigest`, or embeds a chain equal to the links before it;
638/// otherwise "delegation_parent_mismatch", or "malformed_delegation" for a
639/// binding field of the wrong type or both bindings on one grant). Then each
640/// link's signed grant: issuer, the proof's own fields and
641/// shape (before any key is looked up), the key, the signatures (post-quantum
642/// required with no ML-DSA-44 key known is "delegation_signature_invalid"),
643/// parent binding, delegatee and window; and non-expansion across every
644/// dimension.
645pub fn verify_delegation_chain_with(
646    credential: &Value,
647    now_iso: &str,
648    clock_skew_seconds: i64,
649    opts: &ChainOptions,
650) -> Option<String> {
651    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
652    let malformed = || Some("malformed_delegation".to_string());
653    if let Some(reason) = chain_links_problem(credential, now_iso, clock_skew_seconds, opts) {
654        return Some(reason);
655    }
656    let chain = credential
657        .get("credentialSubject")
658        .and_then(|s| s.get("delegationChain"))
659        .and_then(Value::as_array)
660        .filter(|c| !c.is_empty())?;
661    let (Ok(skew), Ok(now)) = (
662        check_clock_skew(clock_skew_seconds),
663        parse_protocol_time_ns(now_iso),
664    ) else {
665        return malformed();
666    };
667
668    let empty = BTreeMap::new();
669    let grant_keys = opts.grant_keys.unwrap_or(&empty);
670
671    let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
672    for (index, link) in chain.iter().enumerate() {
673        if opts.through_link == Some(index) {
674            return None;
675        }
676        let link_issuer = link["issuer"].as_str().unwrap_or_default();
677        let link_subject = link["subject"].as_str().unwrap_or_default();
678        let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
679            return Some("delegation_link_unsigned".into());
680        };
681        if !matches!(
682            grant.get("proof"),
683            Some(Value::Object(_)) | Some(Value::Array(_))
684        ) {
685            return Some("delegation_link_unsigned".into());
686        }
687        let grant_issuer = issuer_did(grant);
688        if grant_issuer.as_deref() != Some(link_issuer) {
689            return Some("delegation_link_issuer_mismatch".into());
690        }
691        // The proof's own fields and shape are checked before any key is
692        // looked up, so a malformed proof reads the same in every language.
693        if !grant_proof_well_formed(grant, link_issuer, now, skew) {
694            return Some("delegation_signature_invalid".into());
695        }
696        // The verifier's requireSuites setting holds for every grant too:
697        // the grants are where the authority comes from.
698        if !opts.require_suites.is_empty() {
699            let carried = hybrid::proof_suites(grant);
700            if opts.require_suites.iter().any(|s| !carried.contains(s)) {
701                return Some("delegation_signature_invalid".into());
702            }
703        }
704        let Some(keys) = grant_issuer_keys(link_issuer, grant, grant_keys, opts) else {
705            return Some("delegation_issuer_key_unresolved".into());
706        };
707        // With post-quantum required and a post-quantum member's key not
708        // known, the grant's proof cannot meet it: verify_grant_proof refuses
709        // it.
710        if !verify_grant_proof(
711            grant,
712            link_issuer,
713            &keys.ed25519,
714            keys.mldsa44.as_deref(),
715            keys.slhdsa128.as_deref(),
716            hybrid::Required {
717                post_quantum: opts.require_pq
718                    || keys.requires.post_quantum
719                    || opts
720                        .require_suites
721                        .iter()
722                        .any(|s| *s != hybrid::Suite::Eddsa),
723                mldsa44: keys.requires.mldsa44
724                    || opts.require_suites.contains(&hybrid::Suite::Mldsa44),
725                slhdsa128: keys.requires.slhdsa128
726                    || opts.require_suites.contains(&hybrid::Suite::Slhdsa128),
727            },
728            now,
729            skew,
730        ) {
731            return Some("delegation_signature_invalid".into());
732        }
733        if let Some(bound) = link.get("parentProofValue") {
734            // Present but null or not text is malformed, never "absent" (D29).
735            let Some(bound) = bound.as_str() else {
736                return malformed();
737            };
738            if bound != first_64(&parent_proof_binding_value(grant)) {
739                return Some("delegation_link_tampered".into());
740            }
741        }
742        let delegatee = grant
743            .get("credentialSubject")
744            .and_then(|s| s.get("intent"))
745            .and_then(|i| i.get("delegatee"))
746            .and_then(|d| d.as_str())
747            .filter(|d| !d.is_empty());
748        let Some(delegatee) = delegatee else {
749            return Some("delegation_no_delegatee".into());
750        };
751        if delegatee != link_subject {
752            return Some("delegation_subject_mismatch".into());
753        }
754        let window = (
755            grant
756                .get("validFrom")
757                .and_then(|v| v.as_str())
758                .map(parse_protocol_time_ns),
759            grant
760                .get("validUntil")
761                .and_then(|v| v.as_str())
762                .map(parse_protocol_time_ns),
763        );
764        let (Some(Ok(from)), Some(Ok(until))) = window else {
765            return malformed();
766        };
767        match window_state_ns(now, Some(from), Some(until), skew) {
768            WindowState::Ok => {}
769            WindowState::Expired => return Some("delegation_expired".into()),
770            WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
771            WindowState::Inverted => return malformed(),
772        }
773        grants.push(grant);
774    }
775
776    let last_subject = chain[chain.len() - 1]
777        .get("subject")
778        .and_then(|v| v.as_str());
779    if last_subject.map(String::from) != issuer_did(credential) {
780        return Some("delegation_subject_issuer_mismatch".into());
781    }
782
783    let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
784    views.push(capability_view(credential, true));
785    if let Err(dim) = attenuation::first_broader_step(&views) {
786        return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
787    }
788    None
789}
790
791// What the no_std depth guard checks in the JSON these types carry.
792crate::nesting::nested_fields!(DelegationLinkInput; intent);
793crate::nesting::nested_fields!(ChainOptions<'_>; grant_documents);
794
795#[cfg(test)]
796mod tests {
797    use super::*;
798
799    fn link(vf: &str, vu: &str) -> Value {
800        build_delegation_link(&DelegationLinkInput {
801            issuer: "did:web:a".into(),
802            subject: "did:web:b".into(),
803            intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
804            valid_from: Some(vf.into()),
805            valid_until: Some(vu.into()),
806            parent_proof_value: None,
807        })
808    }
809
810    #[test]
811    fn nested_windows_pass() {
812        let chain = vec![
813            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
814            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
815        ];
816        assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
817    }
818
819    #[test]
820    fn child_wider_than_parent_fails() {
821        let chain = vec![
822            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
823            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), // wider
824        ];
825        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
826    }
827
828    #[test]
829    fn now_outside_leaf_window_fails() {
830        let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
831        assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
832    }
833
834    #[test]
835    fn a_window_less_middle_link_stays_bounded_by_the_root() {
836        let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
837                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
838        let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
839        let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
840                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
841        let chain = vec![root.clone(), mid, leaf];
842        assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
843        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
844        // A bound that is not a time string is an error, not "no bound".
845        let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
846                         "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
847        assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
848        // Inverted, and skew out of range.
849        let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
850        assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
851        assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
852    }
853
854    // --- Signed chains: roots, size guard, and the post-quantum profile ---
855
856    struct Party {
857        seed: [u8; 32],
858        did: String,
859    }
860
861    fn party(n: u8) -> Party {
862        let seed = [n; 32];
863        let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
864        Party { seed, did }
865    }
866
867    fn vm(p: &Party) -> String {
868        format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
869    }
870
871    fn grant_body(from: &Party, to: &Party) -> Value {
872        json!({
873            "@context": ["https://www.w3.org/ns/credentials/v2"],
874            "type": ["VerifiableCredential", "VouchCredential"],
875            "issuer": from.did,
876            "validFrom": "2026-04-26T09:00:00Z",
877            "validUntil": "2026-04-26T12:00:00Z",
878            "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
879                "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
880        })
881    }
882
883    fn leaf_credential(leaf: &Party, link: Value) -> Value {
884        json!({
885            "@context": ["https://www.w3.org/ns/credentials/v2"],
886            "type": ["VerifiableCredential", "VouchCredential"],
887            "issuer": leaf.did,
888            "validFrom": "2026-04-26T10:00:00Z",
889            "validUntil": "2026-04-26T10:05:00Z",
890            "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
891                "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
892                "delegationChain": [link]}
893        })
894    }
895
896    const NOW: &str = "2026-04-26T10:01:00Z";
897
898    fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
899        ChainOptions {
900            trusted_roots: Some(roots),
901            ..Default::default()
902        }
903    }
904
905    #[test]
906    fn signed_chain_needs_roots_and_respects_the_size_guard() {
907        let (root, leaf) = (party(1), party(2));
908        let grant = data_integrity::sign(
909            &grant_body(&root, &leaf),
910            &root.seed,
911            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
912        )
913        .unwrap();
914        let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
915        let cred = leaf_credential(&leaf, link.clone());
916        let roots = vec![root.did.clone()];
917        assert_eq!(
918            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
919            None
920        );
921        assert_eq!(
922            verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
923            Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
924        );
925        // An empty list trusts nobody.
926        assert_eq!(
927            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
928            Some("untrusted_principal".into())
929        );
930        // A bare domain means its did:web; it never matches a did:key root.
931        let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
932        assert_eq!(
933            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
934            Some("untrusted_principal".into())
935        );
936        assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
937        assert!(!root_matches(
938            "yourcompany.com",
939            "did:web:yourcompany.com.evil"
940        ));
941        assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
942        assert_eq!(
943            root_did("yourcompany.com").as_deref(),
944            Some("did:web:yourcompany.com")
945        );
946        assert_eq!(
947            root_did("yourcompany.com:8443").as_deref(),
948            Some("did:web:yourcompany.com%3A8443")
949        );
950        assert!(root_did("127.0.0.1").is_none());
951        let other = vec!["did:web:someone-else".to_string()];
952        assert_eq!(
953            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
954            Some("untrusted_principal".into())
955        );
956        // No fixed depth limit, but an explicit budget still applies.
957        let budget = ChainOptions {
958            max_depth: Some(0),
959            ..opts_with(&roots)
960        };
961        assert_eq!(
962            verify_delegation_chain_with(&cred, NOW, 30, &budget),
963            Some(REASON_BUDGET_EXCEEDED.into())
964        );
965        // More than 1 MiB encoded is refused before any signature is checked.
966        let mut big = link;
967        big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
968        let cred = leaf_credential(&leaf, big);
969        assert_eq!(
970            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
971            Some(REASON_BUDGET_EXCEEDED.into())
972        );
973    }
974
975    #[test]
976    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
977    fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
978        let (root, leaf) = (party(3), party(4));
979        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
980        let body = grant_body(&root, &leaf);
981        let dual = hybrid::sign_dual(
982            &body,
983            &root.seed,
984            &ml,
985            &vm(&root),
986            &format!("{}#mldsa", root.did),
987            "2026-04-26T09:00:00Z",
988        )
989        .unwrap();
990        let single = data_integrity::sign(
991            &body,
992            &root.seed,
993            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
994        )
995        .unwrap();
996        let roots = vec![root.did.clone()];
997        let mut mldsa_keys = BTreeMap::new();
998        mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
999        let pq = ChainOptions {
1000            trusted_roots: Some(&roots),
1001            mldsa_keys: Some(&mldsa_keys),
1002            require_pq: true,
1003            ..Default::default()
1004        };
1005        let chain_of = |grant: &Value| {
1006            leaf_credential(
1007                &leaf,
1008                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1009            )
1010        };
1011        assert_eq!(
1012            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
1013            None
1014        );
1015        // A classical-only grant does not meet the post-quantum profile.
1016        assert_eq!(
1017            verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
1018            Some("delegation_signature_invalid".into())
1019        );
1020        // A broken ML-DSA member fails it too.
1021        let mut broken = dual.clone();
1022        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1023        assert_eq!(
1024            verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
1025            Some("delegation_signature_invalid".into())
1026        );
1027        // Post-quantum required and no ML-DSA key known: the proof cannot meet it.
1028        let none = ChainOptions {
1029            mldsa_keys: None,
1030            ..pq
1031        };
1032        assert_eq!(
1033            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
1034            Some("delegation_signature_invalid".into())
1035        );
1036        // Without the requirement the classical member is what is checked.
1037        assert_eq!(
1038            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
1039            None
1040        );
1041        // Every member must be the issuer's own: a member naming another DID fails.
1042        let mut foreign = dual.clone();
1043        foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
1044        assert_eq!(
1045            verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
1046            Some("delegation_signature_invalid".into())
1047        );
1048    }
1049
1050    /// A one-link chain whose grant carries `proof`, signed over the grant body.
1051    fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
1052        let mut grant = grant_body(root, leaf);
1053        grant["proof"] = proof;
1054        leaf_credential(
1055            leaf,
1056            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1057        )
1058    }
1059
1060    fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
1061        data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
1062    }
1063
1064    #[test]
1065    fn grant_proofs_follow_the_top_level_rules() {
1066        let (root, leaf) = (party(5), party(6));
1067        let roots = vec![root.did.clone()];
1068        let o = opts_with(&roots);
1069        let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
1070        let good = eddsa_proof(&root, &leaf, base());
1071        let check = |proof: Value| {
1072            verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
1073        };
1074        assert_eq!(check(good.clone()), None);
1075        let invalid = Some("delegation_signature_invalid".to_string());
1076        // An expires that has passed, or is null (both inside the signed proof).
1077        for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
1078            let mut p = good.clone();
1079            p["expires"] = expires.clone();
1080            let mut unsigned = p.clone();
1081            unsigned.as_object_mut().unwrap().remove("proofValue");
1082            let input =
1083                data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
1084                    .unwrap();
1085            let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
1086            p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
1087            assert_eq!(check(p), invalid, "expires {expires}");
1088        }
1089        // A created that is not a time.
1090        let mut opts = base();
1091        opts.created = "yesterday".into();
1092        assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
1093        // An unknown cryptosuite, a missing proofValue, a member that is not an object.
1094        let mut p = good.clone();
1095        p["cryptosuite"] = json!("some-unregistered-suite-2030");
1096        assert_eq!(check(p), invalid);
1097        let mut p = good.clone();
1098        p.as_object_mut().unwrap().remove("proofValue");
1099        assert_eq!(check(p), invalid);
1100        assert_eq!(check(json!([good.clone(), 7])), invalid);
1101        // A set is exactly one eddsa-jcs-2022 and one ML-DSA-44 member.
1102        assert_eq!(check(json!([good.clone()])), invalid);
1103        assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
1104    }
1105
1106    #[test]
1107    fn grant_issuer_is_a_did_string_or_id() {
1108        let (root, leaf) = (party(7), party(8));
1109        let roots = vec![root.did.clone()];
1110        let mut body = grant_body(&root, &leaf);
1111        body["issuer"] = json!([root.did.clone()]);
1112        let grant = data_integrity::sign(
1113            &body,
1114            &root.seed,
1115            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1116        )
1117        .unwrap();
1118        let cred = leaf_credential(
1119            &leaf,
1120            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1121        );
1122        assert_eq!(
1123            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
1124            Some("delegation_link_issuer_mismatch".into())
1125        );
1126    }
1127
1128    #[test]
1129    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1130    fn a_known_mldsa_key_checks_the_grant_member() {
1131        let (root, leaf) = (party(9), party(10));
1132        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1133        let body = grant_body(&root, &leaf);
1134        let dual = hybrid::sign_dual(
1135            &body,
1136            &root.seed,
1137            &ml,
1138            &vm(&root),
1139            &format!("{}#mldsa", root.did),
1140            "2026-04-26T09:00:00Z",
1141        )
1142        .unwrap();
1143        let roots = vec![root.did.clone()];
1144        let mut keys = BTreeMap::new();
1145        keys.insert(root.did.clone(), ml.public_key().to_vec());
1146        let known = ChainOptions {
1147            trusted_roots: Some(&roots),
1148            mldsa_keys: Some(&keys),
1149            ..Default::default()
1150        };
1151        let link = |g: &Value| {
1152            leaf_credential(
1153                &leaf,
1154                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1155            )
1156        };
1157        assert_eq!(
1158            verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
1159            None
1160        );
1161        // A broken ML-DSA-44 member fails once its key is known, PQ required or not.
1162        let mut broken = dual.clone();
1163        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1164        assert_eq!(
1165            verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
1166            Some("delegation_signature_invalid".into())
1167        );
1168        // The earlier composite proof on a grant is refused, even with the
1169        // ML-DSA-44 key known: the post-quantum profile is the proof set only.
1170        let composite =
1171            hybrid::composite_for_tests(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z");
1172        assert_eq!(
1173            verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1174            Some("delegation_signature_invalid".into())
1175        );
1176        assert_eq!(
1177            verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1178            Some("delegation_signature_invalid".into())
1179        );
1180    }
1181
1182    #[test]
1183    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1184    fn a_grant_may_carry_an_slhdsa_proof() {
1185        let (root, leaf) = (party(21), party(22));
1186        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1187        let slh = crate::slh::SlhDsa128KeyPair::generate().unwrap();
1188        let body = grant_body(&root, &leaf);
1189        let ed_vm = vm(&root);
1190        let sign = |with_ml: bool| {
1191            hybrid::sign_set(
1192                &body,
1193                &root.seed,
1194                &ed_vm,
1195                with_ml.then_some(hybrid::PqSigner {
1196                    key: &ml,
1197                    verification_method: &crate::issuance::mldsa44_verification_method(&ed_vm),
1198                }),
1199                Some(hybrid::PqSigner {
1200                    key: &slh,
1201                    verification_method: &crate::issuance::slhdsa128_verification_method(&ed_vm),
1202                }),
1203                "2026-04-26T09:00:00Z",
1204            )
1205            .unwrap()
1206        };
1207        let roots = vec![root.did.clone()];
1208        let ml_keys = BTreeMap::from([(root.did.clone(), ml.public_key().to_vec())]);
1209        let slh_keys = BTreeMap::from([(root.did.clone(), slh.public_key().to_vec())]);
1210        let link = |g: &Value| {
1211            leaf_credential(
1212                &leaf,
1213                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1214            )
1215        };
1216        let all = ChainOptions {
1217            trusted_roots: Some(&roots),
1218            mldsa_keys: Some(&ml_keys),
1219            slhdsa_keys: Some(&slh_keys),
1220            ..Default::default()
1221        };
1222        let slh_only = ChainOptions {
1223            mldsa_keys: None,
1224            ..all
1225        };
1226        let invalid = Some("delegation_signature_invalid".to_string());
1227        for with_ml in [true, false] {
1228            let grant = sign(with_ml);
1229            // A known ML-DSA-44 key makes that proof required: a grant
1230            // without it is refused, so the proof cannot be stripped.
1231            if !with_ml {
1232                assert_eq!(
1233                    verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
1234                    invalid
1235                );
1236            }
1237            let all = if with_ml { all } else { slh_only };
1238            assert_eq!(
1239                verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
1240                None
1241            );
1242            // Post-quantum required: every post-quantum member needs its key.
1243            let required = ChainOptions {
1244                require_pq: true,
1245                ..all
1246            };
1247            assert_eq!(
1248                verify_delegation_chain_with(&link(&grant), NOW, 30, &required),
1249                None
1250            );
1251            let no_slh = ChainOptions {
1252                slhdsa_keys: None,
1253                ..required
1254            };
1255            assert_eq!(
1256                verify_delegation_chain_with(&link(&grant), NOW, 30, &no_slh),
1257                invalid
1258            );
1259            // A broken SLH-DSA member fails once its key is known.
1260            let mut broken = grant.clone();
1261            let last = broken["proof"].as_array().unwrap().len() - 1;
1262            let value = broken["proof"][last]["proofValue"]
1263                .as_str()
1264                .unwrap()
1265                .to_string();
1266            let flipped = if value.ends_with('A') { "Q" } else { "A" };
1267            broken["proof"][last]["proofValue"] =
1268                json!(format!("{}{flipped}", &value[..value.len() - 1]));
1269            assert_eq!(
1270                verify_delegation_chain_with(&link(&broken), NOW, 30, &all),
1271                invalid
1272            );
1273        }
1274    }
1275
1276    #[test]
1277    fn a_did_key_grant_issuer_keeps_its_own_key() {
1278        let (root, leaf, other) = (party(11), party(12), party(13));
1279        let grant = data_integrity::sign(
1280            &grant_body(&root, &leaf),
1281            &root.seed,
1282            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1283        )
1284        .unwrap();
1285        let cred = leaf_credential(
1286            &leaf,
1287            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1288        );
1289        let roots = vec![root.did.clone()];
1290        let mut keys = BTreeMap::new();
1291        keys.insert(
1292            root.did.clone(),
1293            crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1294                .public_key()
1295                .to_vec(),
1296        );
1297        let pinned = ChainOptions {
1298            trusted_roots: Some(&roots),
1299            grant_keys: Some(&keys),
1300            ..Default::default()
1301        };
1302        assert_eq!(
1303            verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1304            Some("delegation_issuer_key_unresolved".into())
1305        );
1306    }
1307
1308    #[test]
1309    fn link_fields_are_checked_before_any_key() {
1310        // A chain from an untrusted start, or with a gap, is refused before the
1311        // (unresolvable) grant keys are looked at.
1312        let link = |iss: &str, sub: &str| {
1313            json!({"issuer": iss, "subject": sub,
1314                   "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1315        };
1316        let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1317        let roots = vec!["did:web:root".to_string()];
1318        assert_eq!(
1319            verify_delegation_chain_with(
1320                &cred(json!([link("did:web:other", "did:web:c")])),
1321                NOW,
1322                30,
1323                &opts_with(&roots)
1324            ),
1325            Some("untrusted_principal".into())
1326        );
1327        assert_eq!(
1328            verify_delegation_chain_with(
1329                &cred(json!([
1330                    link("did:web:root", "did:web:a"),
1331                    link("did:web:b", "did:web:c")
1332                ])),
1333                NOW,
1334                30,
1335                &opts_with(&roots)
1336            ),
1337            Some("delegation_subject_issuer_mismatch".into())
1338        );
1339        // The last link must name the credential's issuer, before any key.
1340        assert_eq!(
1341            verify_delegation_chain_with(
1342                &cred(json!([link("did:web:root", "did:web:other")])),
1343                NOW,
1344                30,
1345                &opts_with(&roots)
1346            ),
1347            Some("delegation_subject_issuer_mismatch".into())
1348        );
1349        // With a trusted, continuous chain, a bare proof is refused by its own
1350        // fields before any key is looked up.
1351        assert_eq!(
1352            verify_delegation_chain_with(
1353                &cred(json!([link("did:web:root", "did:web:c")])),
1354                NOW,
1355                30,
1356                &opts_with(&roots)
1357            ),
1358            Some("delegation_signature_invalid".into())
1359        );
1360        // null and other non-array chains are malformed, never "absent".
1361        for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1362            assert_eq!(
1363                verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1364                Some("malformed_delegation".into()),
1365                "{chain}"
1366            );
1367        }
1368        // The size guard runs before the roots check.
1369        let big =
1370            cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1371        assert_eq!(
1372            verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1373            Some(REASON_BUDGET_EXCEEDED.into())
1374        );
1375    }
1376
1377    #[test]
1378    fn grant_binding_is_checked_before_any_key() {
1379        // did:web grant issuers with no keys known: anything that reached a key
1380        // lookup would be delegation_signature_invalid or key_unresolved.
1381        let grant = |iss: &str, sub: &str, extra: Value| {
1382            let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
1383                "credentialSubject": {"intent": {"delegatee": sub}}});
1384            for (k, v) in extra.as_object().unwrap() {
1385                g["credentialSubject"][k] = v.clone();
1386            }
1387            g
1388        };
1389        let link = |g: &Value| {
1390            json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
1391                   "parentCredential": g})
1392        };
1393        let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1394        let roots = vec!["did:web:root".to_string()];
1395        let check = |chain: Vec<Value>| {
1396            verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
1397        };
1398        let g1 = grant("did:web:root", "did:web:a", json!({}));
1399        let digest = grant_chain::grant_digest(&g1).unwrap();
1400        let bound = grant(
1401            "did:web:a",
1402            "did:web:c",
1403            json!({ "parentGrantDigest": digest }),
1404        );
1405        let unbound = grant("did:web:a", "did:web:c", json!({}));
1406        // Bound: the per-link checks run and refuse the bare proof.
1407        assert_eq!(
1408            check(vec![link(&g1), link(&bound)]),
1409            Some("delegation_signature_invalid".into())
1410        );
1411        assert_eq!(
1412            check(vec![link(&g1), link(&unbound)]),
1413            Some("delegation_parent_mismatch".into())
1414        );
1415        // A root grant that names a parent (the chain above it cut off).
1416        let cut = grant(
1417            "did:web:root",
1418            "did:web:c",
1419            json!({ "parentGrantDigest": "uEiAAAA" }),
1420        );
1421        assert_eq!(
1422            check(vec![link(&cut)]),
1423            Some("delegation_parent_mismatch".into())
1424        );
1425        // A digest of the wrong type, or both bindings: malformed.
1426        for extra in [
1427            json!({ "parentGrantDigest": null }),
1428            json!({ "delegationChain": null }),
1429            json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
1430        ] {
1431            let g2 = grant("did:web:a", "did:web:c", extra.clone());
1432            assert_eq!(
1433                check(vec![link(&g1), link(&g2)]),
1434                Some("malformed_delegation".into()),
1435                "{extra}"
1436            );
1437        }
1438        // The pre-filter's earlier checks still come first.
1439        assert_eq!(
1440            verify_delegation_chain_with(
1441                &cred(vec![link(&g1), link(&unbound)]),
1442                NOW,
1443                30,
1444                &opts_with(&["did:web:other".to_string()])
1445            ),
1446            Some("untrusted_principal".into())
1447        );
1448        // A link without its grant skips the binding rule (which would call the
1449        // unbound second grant a mismatch) and is refused as unsigned.
1450        for missing in [None, Some(json!("grant")), Some(Value::Null)] {
1451            let mut first = link(&g1);
1452            match &missing {
1453                None => {
1454                    first.as_object_mut().unwrap().remove("parentCredential");
1455                }
1456                Some(v) => first["parentCredential"] = v.clone(),
1457            }
1458            assert_eq!(
1459                check(vec![first, link(&unbound)]),
1460                Some("delegation_link_unsigned".into()),
1461                "{missing:?}"
1462            );
1463        }
1464    }
1465}