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