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    match (root_keys.get(did), from_did) {
191        (Some(k), Some(d)) => (k == &d).then_some(d),
192        (Some(k), None) => Some(k.clone()),
193        (None, d) => d,
194    }
195}
196
197/// The proof value a link binds to its parent: the eddsa-jcs-2022 member of a
198/// proof set, else the first proof value, else a single proof's value.
199pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
200    match grant.get("proof") {
201        Some(Value::Array(items)) => {
202            for p in items {
203                if p.get("cryptosuite").and_then(|v| v.as_str())
204                    == Some(data_integrity::CRYPTOSUITE_ID)
205                {
206                    return p
207                        .get("proofValue")
208                        .and_then(|v| v.as_str())
209                        .unwrap_or("")
210                        .to_string();
211                }
212            }
213            for p in items {
214                if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
215                    if !v.is_empty() {
216                        return v.to_string();
217                    }
218                }
219            }
220            String::new()
221        }
222        Some(Value::Object(p)) => p
223            .get("proofValue")
224            .and_then(|v| v.as_str())
225            .unwrap_or("")
226            .to_string(),
227        _ => String::new(),
228    }
229}
230
231/// Check a grant's proof with the top-level proof rules.
232///
233/// Every member is an object with type "DataIntegrityProof", a known
234/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
235/// grant issuer's DID, a proofValue, a valid `created` and an `expires` (when
236/// present) that has not passed. The shape is one `eddsa-jcs-2022` proof, the
237/// earlier composite proof (accepted only when the issuer's ML-DSA-44 key is
238/// known), or a set of exactly one `eddsa-jcs-2022` and one ML-DSA-44 member.
239/// The Ed25519 proof always verifies with `key`; the ML-DSA-44 member is
240/// checked whenever `mldsa_key` is known and is required when `require_pq` is
241/// set (a single classical proof then fails).
242fn verify_grant_proof(
243    grant: &Value,
244    issuer: &str,
245    key: &[u8],
246    mldsa_key: Option<&[u8]>,
247    require_pq: bool,
248    now: i128,
249    skew: i128,
250) -> bool {
251    let Some(proof) = grant.get("proof") else {
252        return false;
253    };
254    let members: Vec<&Value> = match proof {
255        Value::Array(items) => items.iter().collect(),
256        other => vec![other],
257    };
258    if members.is_empty()
259        || !members
260            .iter()
261            .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
262    {
263        return false;
264    }
265    let suite = |p: &Value| {
266        p.get("cryptosuite")
267            .and_then(|v| v.as_str())
268            .unwrap_or_default()
269            .to_string()
270    };
271    match proof {
272        Value::Object(_) => match suite(proof).as_str() {
273            data_integrity::CRYPTOSUITE_ID => {
274                !require_pq && matches!(data_integrity::verify_proof(grant, key), Ok(true))
275            }
276            hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa_key {
277                Some(ml) => matches!(hybrid::verify_composite(grant, key, ml), Ok(true)),
278                None => false,
279            },
280            _ => false,
281        },
282        Value::Array(items) => {
283            let mut suites: Vec<String> = items
284                .iter()
285                .map(|p| {
286                    let s = suite(p);
287                    if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
288                        hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
289                    } else {
290                        s
291                    }
292                })
293                .collect();
294            suites.sort();
295            if suites != [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID] {
296                return false;
297            }
298            match mldsa_key {
299                Some(ml) => matches!(hybrid::verify_dual(grant, key, ml), Ok(true)),
300                None if require_pq => false,
301                None => {
302                    // Only the Ed25519 member can be checked: it must verify.
303                    let Some(ed) = items
304                        .iter()
305                        .find(|p| suite(p) == data_integrity::CRYPTOSUITE_ID)
306                    else {
307                        return false;
308                    };
309                    let mut single = grant.clone();
310                    single["proof"] = (*ed).clone();
311                    matches!(data_integrity::verify_proof(&single, key), Ok(true))
312                }
313            }
314        }
315        _ => false,
316    }
317}
318
319/// The checks of [`verify_grant_proof`] that need no key: every member passes
320/// the top-level proof rules, and the shape is one `eddsa-jcs-2022` proof, the
321/// earlier composite proof, or a set of exactly one `eddsa-jcs-2022` and one
322/// ML-DSA-44 member.
323fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
324    let Some(proof) = grant.get("proof") else {
325        return false;
326    };
327    let members: Vec<&Value> = match proof {
328        Value::Array(items) => items.iter().collect(),
329        other => vec![other],
330    };
331    if members.is_empty()
332        || !members
333            .iter()
334            .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
335    {
336        return false;
337    }
338    let suite = |p: &Value| {
339        let s = p
340            .get("cryptosuite")
341            .and_then(|v| v.as_str())
342            .unwrap_or_default();
343        if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
344            hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
345        } else {
346            s.to_string()
347        }
348    };
349    match proof {
350        Value::Object(_) => matches!(
351            suite(proof).as_str(),
352            data_integrity::CRYPTOSUITE_ID | hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
353        ),
354        Value::Array(items) => {
355            let mut suites: Vec<String> = items.iter().map(suite).collect();
356            suites.sort();
357            suites == [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID]
358        }
359        _ => false,
360    }
361}
362
363fn first_64(s: &str) -> String {
364    s.chars().take(64).collect()
365}
366
367/// The reason a chain is refused when the caller named no trusted starting
368/// point (trusted roots) for it.
369pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
370    "the chain's starting point is not trusted: pass trusted roots";
371
372/// The reason a chain is refused by the verifier's resource guard or an
373/// explicit budget the caller set.
374pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
375
376/// An encoded delegation chain (its JCS form) larger than this is refused
377/// before any signature is checked. This is a resource guard only: there is no
378/// fixed depth limit, since a chain is limited by narrowing scope, never by its
379/// number of links.
380pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
381
382/// A trusted root as the caller wrote it, as a DID, read exactly as the Python
383/// reference reads it ([`crate::did_web::normalize_root`]): a bare domain such
384/// as "yourcompany.com" means "did:web:yourcompany.com" ("host:8443" means
385/// "did:web:host%3A8443"); a full DID is used as it is. None when the root is
386/// neither (an IP literal, a URL, a trailing dot, a bad port, ...).
387pub fn root_did(root: &str) -> Option<String> {
388    crate::did_web::normalize_root(root).ok()
389}
390
391/// True when the caller's trusted root names `issuer` exactly (see
392/// [`root_did`]); a root that does not parse names nobody.
393pub fn root_matches(root: &str, issuer: &str) -> bool {
394    root_did(root).as_deref() == Some(issuer)
395}
396
397/// How a verifier checks an embedded delegation chain.
398#[derive(Debug, Clone, Copy, Default)]
399pub struct ChainOptions<'a> {
400    /// The trusted starting points: the chain's first grant must be issued by
401    /// one of them. A chain is refused when this is `None`
402    /// ([`REASON_TRUSTED_ROOTS_REQUIRED`]); an empty list trusts nobody
403    /// ("untrusted_principal"). A bare domain stands for its did:web
404    /// ([`root_did`]).
405    pub trusted_roots: Option<&'a [String]>,
406    /// Ed25519 keys for grant issuers that are not `did:key` (a `did:key`
407    /// issuer always resolves offline from the DID itself).
408    pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
409    /// ML-DSA-44 public keys by grant issuer DID. A grant whose issuer has a
410    /// key here has its ML-DSA-44 member checked (and the earlier composite
411    /// proof accepted).
412    pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
413    /// Require the post-quantum profile on every grant: each must carry a
414    /// valid dual proof (Ed25519 and ML-DSA-44), with its ML-DSA-44 key known.
415    pub require_pq: bool,
416    /// An explicit depth budget chosen by the caller. `None` means no depth
417    /// limit (there is no default one).
418    pub max_depth: Option<usize>,
419}
420
421/// Verify a credential's embedded `delegationChain`. Returns `None` when the
422/// chain is valid (or absent), otherwise the reason code.
423///
424/// `root_keys` supplies Ed25519 keys for non-`did:key` grant issuers (for a
425/// `did:key` issuer it must equal the DID's own key); `root_dids` is the set of
426/// trusted root DIDs the chain must start from. A credential that carries a
427/// chain is refused when `root_dids` is `None`, and an empty list trusts
428/// nobody. See [`verify_delegation_chain_with`] for every option.
429pub fn verify_delegation_chain(
430    credential: &Value,
431    now_iso: &str,
432    clock_skew_seconds: i64,
433    root_keys: &BTreeMap<String, Vec<u8>>,
434    root_dids: Option<&[String]>,
435) -> Option<String> {
436    let opts = ChainOptions {
437        trusted_roots: root_dids,
438        grant_keys: Some(root_keys),
439        ..Default::default()
440    };
441    verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
442}
443
444/// Verify a credential's embedded `delegationChain` under `opts`. Returns
445/// `None` when the chain is valid (or absent), otherwise the reason code.
446///
447/// Order: first the credential's own binding fields
448/// ([`grant_chain::binding_fields_problem`]: a present `delegationChain` is a
449/// list, so null, `{}`, `""`, 0 or false is malformed; a present
450/// `parentGrantDigest` is a string; and the credential does not carry a digest
451/// together with a non-empty `delegationChain`; else "malformed_delegation").
452/// Every verify path ([`crate::credentials::verify_with_keys`] and the entry
453/// points over it) runs this, so it is the credential shape check for those
454/// fields everywhere. A sub-grant with a string digest and no chain passes
455/// here; its grant chain is checked apart. Then the size guard (1 MiB of JCS)
456/// and any explicit depth
457/// budget, the trusted roots, then a pre-filter from the link fields alone
458/// (each link's issuer is the previous link's subject, and the first issuer
459/// is a trusted root), all before any key is resolved or signature checked.
460/// The pre-filter also checks that the last link's subject is the credential's
461/// issuer and, when every link carries its grant as an object, that every
462/// grant is bound to the grant before it
463/// ([`grant_chain::chain_binding_problem`]: the first grant is a root grant,
464/// and every later grant carries the digest of the grant before it in
465/// `parentGrantDigest`, or embeds a chain equal to the links before it;
466/// otherwise "delegation_parent_mismatch", or "malformed_delegation" for a
467/// binding field of the wrong type or both bindings on one grant). Then each
468/// link's signed grant: issuer, the proof's own fields and
469/// shape (before any key is looked up), the key, the signatures (post-quantum
470/// required with no ML-DSA-44 key known is "delegation_signature_invalid"),
471/// parent binding, delegatee and window; and non-expansion across every
472/// dimension.
473pub fn verify_delegation_chain_with(
474    credential: &Value,
475    now_iso: &str,
476    clock_skew_seconds: i64,
477    opts: &ChainOptions,
478) -> Option<String> {
479    let malformed = || Some("malformed_delegation".to_string());
480    if !credential.is_object() {
481        return malformed();
482    }
483    // The credential's own binding fields: a present delegationChain must be
484    // a list and a present parentGrantDigest a string (null, {}, "", 0 or
485    // false is malformed, never absent, D29), never both a digest and a chain.
486    if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
487        return Some(reason.into());
488    }
489    let chain_value = match credential
490        .get("credentialSubject")
491        .and_then(|s| s.get("delegationChain"))
492    {
493        None => return None,
494        Some(Value::Array(a)) if a.is_empty() => return None,
495        Some(v @ Value::Array(_)) => v,
496        // Refused above: a delegationChain that is not a list.
497        Some(_) => return malformed(),
498    };
499    let chain = chain_value.as_array().expect("checked above");
500    match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
501        Ok(None) => {}
502        Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
503        Err(_) => return malformed(),
504    }
505    let Some(roots) = opts.trusted_roots else {
506        return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
507    };
508    let Ok(skew) = check_clock_skew(clock_skew_seconds) else {
509        return malformed();
510    };
511    let Ok(now) = parse_protocol_time_ns(now_iso) else {
512        return malformed();
513    };
514
515    // Pre-filter from the link fields alone, before any key is resolved.
516    for link in chain {
517        let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
518            && link.get("subject").is_some_and(|v| v.is_string());
519        if !shape_ok {
520            return malformed();
521        }
522    }
523    for i in 1..chain.len() {
524        if chain[i - 1].get("subject") != chain[i].get("issuer") {
525            return Some("delegation_subject_issuer_mismatch".into());
526        }
527    }
528    let last_subject = chain[chain.len() - 1]
529        .get("subject")
530        .and_then(|v| v.as_str());
531    if last_subject.map(String::from) != issuer_did(credential) {
532        return Some("delegation_subject_issuer_mismatch".into());
533    }
534    let root = chain[0]
535        .get("issuer")
536        .and_then(|v| v.as_str())
537        .unwrap_or("");
538    if !roots.iter().any(|d| root_matches(d, root)) {
539        return Some("untrusted_principal".into());
540    }
541    // Every grant is bound to the grant before it (flat chains name it by
542    // digest, older nested ones embed the links above them). A link without
543    // its grant is left to the per-link checks, which report it as
544    // delegation_link_unsigned.
545    if chain
546        .iter()
547        .all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
548    {
549        if let Some(reason) = grant_chain::chain_binding_problem(chain) {
550            return Some(reason.into());
551        }
552    }
553
554    let empty = BTreeMap::new();
555    let grant_keys = opts.grant_keys.unwrap_or(&empty);
556
557    let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
558    for link in chain {
559        let link_issuer = link["issuer"].as_str().unwrap_or_default();
560        let link_subject = link["subject"].as_str().unwrap_or_default();
561        let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
562            return Some("delegation_link_unsigned".into());
563        };
564        if !matches!(
565            grant.get("proof"),
566            Some(Value::Object(_)) | Some(Value::Array(_))
567        ) {
568            return Some("delegation_link_unsigned".into());
569        }
570        let grant_issuer = issuer_did(grant);
571        if grant_issuer.as_deref() != Some(link_issuer) {
572            return Some("delegation_link_issuer_mismatch".into());
573        }
574        // The proof's own fields and shape are checked before any key is
575        // looked up, so a malformed proof reads the same in every language.
576        if !grant_proof_well_formed(grant, link_issuer, now, skew) {
577            return Some("delegation_signature_invalid".into());
578        }
579        let Some(key) = resolve_chain_key(link_issuer, grant_keys) else {
580            return Some("delegation_issuer_key_unresolved".into());
581        };
582        // With post-quantum required and no ML-DSA-44 key known, the grant's
583        // proof cannot meet it: verify_grant_proof refuses it.
584        let mldsa_key = opts
585            .mldsa_keys
586            .and_then(|m| m.get(link_issuer))
587            .map(|k| k.as_slice());
588        if !verify_grant_proof(
589            grant,
590            link_issuer,
591            &key,
592            mldsa_key,
593            opts.require_pq,
594            now,
595            skew,
596        ) {
597            return Some("delegation_signature_invalid".into());
598        }
599        if let Some(bound) = link.get("parentProofValue") {
600            // Present but null or not text is malformed, never "absent" (D29).
601            let Some(bound) = bound.as_str() else {
602                return malformed();
603            };
604            if bound != first_64(&parent_proof_binding_value(grant)) {
605                return Some("delegation_link_tampered".into());
606            }
607        }
608        let delegatee = grant
609            .get("credentialSubject")
610            .and_then(|s| s.get("intent"))
611            .and_then(|i| i.get("delegatee"))
612            .and_then(|d| d.as_str())
613            .filter(|d| !d.is_empty());
614        let Some(delegatee) = delegatee else {
615            return Some("delegation_no_delegatee".into());
616        };
617        if delegatee != link_subject {
618            return Some("delegation_subject_mismatch".into());
619        }
620        let window = (
621            grant
622                .get("validFrom")
623                .and_then(|v| v.as_str())
624                .map(parse_protocol_time_ns),
625            grant
626                .get("validUntil")
627                .and_then(|v| v.as_str())
628                .map(parse_protocol_time_ns),
629        );
630        let (Some(Ok(from)), Some(Ok(until))) = window else {
631            return malformed();
632        };
633        match window_state_ns(now, Some(from), Some(until), skew) {
634            WindowState::Ok => {}
635            WindowState::Expired => return Some("delegation_expired".into()),
636            WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
637            WindowState::Inverted => return malformed(),
638        }
639        grants.push(grant);
640    }
641
642    let last_subject = chain[chain.len() - 1]
643        .get("subject")
644        .and_then(|v| v.as_str());
645    if last_subject.map(String::from) != issuer_did(credential) {
646        return Some("delegation_subject_issuer_mismatch".into());
647    }
648
649    let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
650    views.push(capability_view(credential, true));
651    if let Err(dim) = attenuation::first_broader_step(&views) {
652        return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
653    }
654    None
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660
661    fn link(vf: &str, vu: &str) -> Value {
662        build_delegation_link(&DelegationLinkInput {
663            issuer: "did:web:a".into(),
664            subject: "did:web:b".into(),
665            intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
666            valid_from: Some(vf.into()),
667            valid_until: Some(vu.into()),
668            parent_proof_value: None,
669        })
670    }
671
672    #[test]
673    fn nested_windows_pass() {
674        let chain = vec![
675            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
676            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
677        ];
678        assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
679    }
680
681    #[test]
682    fn child_wider_than_parent_fails() {
683        let chain = vec![
684            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
685            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), // wider
686        ];
687        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
688    }
689
690    #[test]
691    fn now_outside_leaf_window_fails() {
692        let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
693        assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
694    }
695
696    #[test]
697    fn a_window_less_middle_link_stays_bounded_by_the_root() {
698        let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
699                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
700        let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
701        let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
702                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
703        let chain = vec![root.clone(), mid, leaf];
704        assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
705        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
706        // A bound that is not a time string is an error, not "no bound".
707        let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
708                         "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
709        assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
710        // Inverted, and skew out of range.
711        let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
712        assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
713        assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
714    }
715
716    // --- Signed chains: roots, size guard, and the post-quantum profile ---
717
718    struct Party {
719        seed: [u8; 32],
720        did: String,
721    }
722
723    fn party(n: u8) -> Party {
724        let seed = [n; 32];
725        let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
726        Party { seed, did }
727    }
728
729    fn vm(p: &Party) -> String {
730        format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
731    }
732
733    fn grant_body(from: &Party, to: &Party) -> Value {
734        json!({
735            "@context": ["https://www.w3.org/ns/credentials/v2"],
736            "type": ["VerifiableCredential", "VouchCredential"],
737            "issuer": from.did,
738            "validFrom": "2026-04-26T09:00:00Z",
739            "validUntil": "2026-04-26T12:00:00Z",
740            "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
741                "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
742        })
743    }
744
745    fn leaf_credential(leaf: &Party, link: Value) -> Value {
746        json!({
747            "@context": ["https://www.w3.org/ns/credentials/v2"],
748            "type": ["VerifiableCredential", "VouchCredential"],
749            "issuer": leaf.did,
750            "validFrom": "2026-04-26T10:00:00Z",
751            "validUntil": "2026-04-26T10:05:00Z",
752            "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
753                "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
754                "delegationChain": [link]}
755        })
756    }
757
758    const NOW: &str = "2026-04-26T10:01:00Z";
759
760    fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
761        ChainOptions {
762            trusted_roots: Some(roots),
763            ..Default::default()
764        }
765    }
766
767    #[test]
768    fn signed_chain_needs_roots_and_respects_the_size_guard() {
769        let (root, leaf) = (party(1), party(2));
770        let grant = data_integrity::sign(
771            &grant_body(&root, &leaf),
772            &root.seed,
773            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
774        )
775        .unwrap();
776        let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
777        let cred = leaf_credential(&leaf, link.clone());
778        let roots = vec![root.did.clone()];
779        assert_eq!(
780            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
781            None
782        );
783        assert_eq!(
784            verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
785            Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
786        );
787        // An empty list trusts nobody.
788        assert_eq!(
789            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
790            Some("untrusted_principal".into())
791        );
792        // A bare domain means its did:web; it never matches a did:key root.
793        let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
794        assert_eq!(
795            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
796            Some("untrusted_principal".into())
797        );
798        assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
799        assert!(!root_matches(
800            "yourcompany.com",
801            "did:web:yourcompany.com.evil"
802        ));
803        assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
804        assert_eq!(
805            root_did("yourcompany.com").as_deref(),
806            Some("did:web:yourcompany.com")
807        );
808        assert_eq!(
809            root_did("yourcompany.com:8443").as_deref(),
810            Some("did:web:yourcompany.com%3A8443")
811        );
812        assert!(root_did("127.0.0.1").is_none());
813        let other = vec!["did:web:someone-else".to_string()];
814        assert_eq!(
815            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
816            Some("untrusted_principal".into())
817        );
818        // No fixed depth limit, but an explicit budget still applies.
819        let budget = ChainOptions {
820            max_depth: Some(0),
821            ..opts_with(&roots)
822        };
823        assert_eq!(
824            verify_delegation_chain_with(&cred, NOW, 30, &budget),
825            Some(REASON_BUDGET_EXCEEDED.into())
826        );
827        // More than 1 MiB encoded is refused before any signature is checked.
828        let mut big = link;
829        big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
830        let cred = leaf_credential(&leaf, big);
831        assert_eq!(
832            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
833            Some(REASON_BUDGET_EXCEEDED.into())
834        );
835    }
836
837    #[test]
838    fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
839        let (root, leaf) = (party(3), party(4));
840        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
841        let body = grant_body(&root, &leaf);
842        let dual = hybrid::sign_dual(
843            &body,
844            &root.seed,
845            &ml,
846            &vm(&root),
847            &format!("{}#mldsa", root.did),
848            "2026-04-26T09:00:00Z",
849        )
850        .unwrap();
851        let single = data_integrity::sign(
852            &body,
853            &root.seed,
854            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
855        )
856        .unwrap();
857        let roots = vec![root.did.clone()];
858        let mut mldsa_keys = BTreeMap::new();
859        mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
860        let pq = ChainOptions {
861            trusted_roots: Some(&roots),
862            mldsa_keys: Some(&mldsa_keys),
863            require_pq: true,
864            ..Default::default()
865        };
866        let chain_of = |grant: &Value| {
867            leaf_credential(
868                &leaf,
869                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
870            )
871        };
872        assert_eq!(
873            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
874            None
875        );
876        // A classical-only grant does not meet the post-quantum profile.
877        assert_eq!(
878            verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
879            Some("delegation_signature_invalid".into())
880        );
881        // A broken ML-DSA member fails it too.
882        let mut broken = dual.clone();
883        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
884        assert_eq!(
885            verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
886            Some("delegation_signature_invalid".into())
887        );
888        // Post-quantum required and no ML-DSA key known: the proof cannot meet it.
889        let none = ChainOptions {
890            mldsa_keys: None,
891            ..pq
892        };
893        assert_eq!(
894            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
895            Some("delegation_signature_invalid".into())
896        );
897        // Without the requirement the classical member is what is checked.
898        assert_eq!(
899            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
900            None
901        );
902        // Every member must be the issuer's own: a member naming another DID fails.
903        let mut foreign = dual.clone();
904        foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
905        assert_eq!(
906            verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
907            Some("delegation_signature_invalid".into())
908        );
909    }
910
911    /// A one-link chain whose grant carries `proof`, signed over the grant body.
912    fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
913        let mut grant = grant_body(root, leaf);
914        grant["proof"] = proof;
915        leaf_credential(
916            leaf,
917            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
918        )
919    }
920
921    fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
922        data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
923    }
924
925    #[test]
926    fn grant_proofs_follow_the_top_level_rules() {
927        let (root, leaf) = (party(5), party(6));
928        let roots = vec![root.did.clone()];
929        let o = opts_with(&roots);
930        let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
931        let good = eddsa_proof(&root, &leaf, base());
932        let check = |proof: Value| {
933            verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
934        };
935        assert_eq!(check(good.clone()), None);
936        let invalid = Some("delegation_signature_invalid".to_string());
937        // An expires that has passed, or is null (both inside the signed proof).
938        for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
939            let mut p = good.clone();
940            p["expires"] = expires.clone();
941            let mut unsigned = p.clone();
942            unsigned.as_object_mut().unwrap().remove("proofValue");
943            let input =
944                data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
945                    .unwrap();
946            let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
947            p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
948            assert_eq!(check(p), invalid, "expires {expires}");
949        }
950        // A created that is not a time.
951        let mut opts = base();
952        opts.created = "yesterday".into();
953        assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
954        // An unknown cryptosuite, a missing proofValue, a member that is not an object.
955        let mut p = good.clone();
956        p["cryptosuite"] = json!("some-unregistered-suite-2030");
957        assert_eq!(check(p), invalid);
958        let mut p = good.clone();
959        p.as_object_mut().unwrap().remove("proofValue");
960        assert_eq!(check(p), invalid);
961        assert_eq!(check(json!([good.clone(), 7])), invalid);
962        // A set is exactly one eddsa-jcs-2022 and one ML-DSA-44 member.
963        assert_eq!(check(json!([good.clone()])), invalid);
964        assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
965    }
966
967    #[test]
968    fn grant_issuer_is_a_did_string_or_id() {
969        let (root, leaf) = (party(7), party(8));
970        let roots = vec![root.did.clone()];
971        let mut body = grant_body(&root, &leaf);
972        body["issuer"] = json!([root.did.clone()]);
973        let grant = data_integrity::sign(
974            &body,
975            &root.seed,
976            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
977        )
978        .unwrap();
979        let cred = leaf_credential(
980            &leaf,
981            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
982        );
983        assert_eq!(
984            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
985            Some("delegation_link_issuer_mismatch".into())
986        );
987    }
988
989    #[test]
990    fn a_known_mldsa_key_checks_the_grant_member() {
991        let (root, leaf) = (party(9), party(10));
992        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
993        let body = grant_body(&root, &leaf);
994        let dual = hybrid::sign_dual(
995            &body,
996            &root.seed,
997            &ml,
998            &vm(&root),
999            &format!("{}#mldsa", root.did),
1000            "2026-04-26T09:00:00Z",
1001        )
1002        .unwrap();
1003        let roots = vec![root.did.clone()];
1004        let mut keys = BTreeMap::new();
1005        keys.insert(root.did.clone(), ml.public_key().to_vec());
1006        let known = ChainOptions {
1007            trusted_roots: Some(&roots),
1008            mldsa_keys: Some(&keys),
1009            ..Default::default()
1010        };
1011        let link = |g: &Value| {
1012            leaf_credential(
1013                &leaf,
1014                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1015            )
1016        };
1017        assert_eq!(
1018            verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
1019            None
1020        );
1021        // A broken ML-DSA-44 member fails once its key is known, PQ required or not.
1022        let mut broken = dual.clone();
1023        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1024        assert_eq!(
1025            verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
1026            Some("delegation_signature_invalid".into())
1027        );
1028        // The earlier composite proof on a grant: accepted with the ML key only.
1029        #[allow(deprecated)]
1030        let composite =
1031            hybrid::sign_composite(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z")
1032                .unwrap();
1033        assert_eq!(
1034            verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1035            None
1036        );
1037        assert_eq!(
1038            verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1039            Some("delegation_signature_invalid".into())
1040        );
1041    }
1042
1043    #[test]
1044    fn a_did_key_grant_issuer_keeps_its_own_key() {
1045        let (root, leaf, other) = (party(11), party(12), party(13));
1046        let grant = data_integrity::sign(
1047            &grant_body(&root, &leaf),
1048            &root.seed,
1049            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1050        )
1051        .unwrap();
1052        let cred = leaf_credential(
1053            &leaf,
1054            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1055        );
1056        let roots = vec![root.did.clone()];
1057        let mut keys = BTreeMap::new();
1058        keys.insert(
1059            root.did.clone(),
1060            crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1061                .public_key()
1062                .to_vec(),
1063        );
1064        let pinned = ChainOptions {
1065            trusted_roots: Some(&roots),
1066            grant_keys: Some(&keys),
1067            ..Default::default()
1068        };
1069        assert_eq!(
1070            verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1071            Some("delegation_issuer_key_unresolved".into())
1072        );
1073    }
1074
1075    #[test]
1076    fn link_fields_are_checked_before_any_key() {
1077        // A chain from an untrusted start, or with a gap, is refused before the
1078        // (unresolvable) grant keys are looked at.
1079        let link = |iss: &str, sub: &str| {
1080            json!({"issuer": iss, "subject": sub,
1081                   "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1082        };
1083        let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1084        let roots = vec!["did:web:root".to_string()];
1085        assert_eq!(
1086            verify_delegation_chain_with(
1087                &cred(json!([link("did:web:other", "did:web:c")])),
1088                NOW,
1089                30,
1090                &opts_with(&roots)
1091            ),
1092            Some("untrusted_principal".into())
1093        );
1094        assert_eq!(
1095            verify_delegation_chain_with(
1096                &cred(json!([
1097                    link("did:web:root", "did:web:a"),
1098                    link("did:web:b", "did:web:c")
1099                ])),
1100                NOW,
1101                30,
1102                &opts_with(&roots)
1103            ),
1104            Some("delegation_subject_issuer_mismatch".into())
1105        );
1106        // The last link must name the credential's issuer, before any key.
1107        assert_eq!(
1108            verify_delegation_chain_with(
1109                &cred(json!([link("did:web:root", "did:web:other")])),
1110                NOW,
1111                30,
1112                &opts_with(&roots)
1113            ),
1114            Some("delegation_subject_issuer_mismatch".into())
1115        );
1116        // With a trusted, continuous chain, a bare proof is refused by its own
1117        // fields before any key is looked up.
1118        assert_eq!(
1119            verify_delegation_chain_with(
1120                &cred(json!([link("did:web:root", "did:web:c")])),
1121                NOW,
1122                30,
1123                &opts_with(&roots)
1124            ),
1125            Some("delegation_signature_invalid".into())
1126        );
1127        // null and other non-array chains are malformed, never "absent".
1128        for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1129            assert_eq!(
1130                verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1131                Some("malformed_delegation".into()),
1132                "{chain}"
1133            );
1134        }
1135        // The size guard runs before the roots check.
1136        let big =
1137            cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1138        assert_eq!(
1139            verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1140            Some(REASON_BUDGET_EXCEEDED.into())
1141        );
1142    }
1143
1144    #[test]
1145    fn grant_binding_is_checked_before_any_key() {
1146        // did:web grant issuers with no keys known: anything that reached a key
1147        // lookup would be delegation_signature_invalid or key_unresolved.
1148        let grant = |iss: &str, sub: &str, extra: Value| {
1149            let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
1150                "credentialSubject": {"intent": {"delegatee": sub}}});
1151            for (k, v) in extra.as_object().unwrap() {
1152                g["credentialSubject"][k] = v.clone();
1153            }
1154            g
1155        };
1156        let link = |g: &Value| {
1157            json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
1158                   "parentCredential": g})
1159        };
1160        let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1161        let roots = vec!["did:web:root".to_string()];
1162        let check = |chain: Vec<Value>| {
1163            verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
1164        };
1165        let g1 = grant("did:web:root", "did:web:a", json!({}));
1166        let digest = grant_chain::grant_digest(&g1).unwrap();
1167        let bound = grant(
1168            "did:web:a",
1169            "did:web:c",
1170            json!({ "parentGrantDigest": digest }),
1171        );
1172        let unbound = grant("did:web:a", "did:web:c", json!({}));
1173        // Bound: the per-link checks run and refuse the bare proof.
1174        assert_eq!(
1175            check(vec![link(&g1), link(&bound)]),
1176            Some("delegation_signature_invalid".into())
1177        );
1178        assert_eq!(
1179            check(vec![link(&g1), link(&unbound)]),
1180            Some("delegation_parent_mismatch".into())
1181        );
1182        // A root grant that names a parent (the chain above it cut off).
1183        let cut = grant(
1184            "did:web:root",
1185            "did:web:c",
1186            json!({ "parentGrantDigest": "uEiAAAA" }),
1187        );
1188        assert_eq!(
1189            check(vec![link(&cut)]),
1190            Some("delegation_parent_mismatch".into())
1191        );
1192        // A digest of the wrong type, or both bindings: malformed.
1193        for extra in [
1194            json!({ "parentGrantDigest": null }),
1195            json!({ "delegationChain": null }),
1196            json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
1197        ] {
1198            let g2 = grant("did:web:a", "did:web:c", extra.clone());
1199            assert_eq!(
1200                check(vec![link(&g1), link(&g2)]),
1201                Some("malformed_delegation".into()),
1202                "{extra}"
1203            );
1204        }
1205        // The pre-filter's earlier checks still come first.
1206        assert_eq!(
1207            verify_delegation_chain_with(
1208                &cred(vec![link(&g1), link(&unbound)]),
1209                NOW,
1210                30,
1211                &opts_with(&["did:web:other".to_string()])
1212            ),
1213            Some("untrusted_principal".into())
1214        );
1215        // A link without its grant skips the binding rule (which would call the
1216        // unbound second grant a mismatch) and is refused as unsigned.
1217        for missing in [None, Some(json!("grant")), Some(Value::Null)] {
1218            let mut first = link(&g1);
1219            match &missing {
1220                None => {
1221                    first.as_object_mut().unwrap().remove("parentCredential");
1222                }
1223                Some(v) => first["parentCredential"] = v.clone(),
1224            }
1225            assert_eq!(
1226                check(vec![first, link(&unbound)]),
1227                Some("delegation_link_unsigned".into()),
1228                "{missing:?}"
1229            );
1230        }
1231    }
1232}