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