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::hybrid;
18use crate::multikey;
19use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
20
21/// Inputs for one delegation link.
22#[derive(Debug, Clone)]
23pub struct DelegationLinkInput {
24    pub issuer: String,
25    pub subject: String,
26    pub intent: Value,
27    pub valid_from: Option<String>,
28    pub valid_until: Option<String>,
29    pub parent_proof_value: Option<String>,
30}
31
32/// Build a delegation link object (field order matches the SDK).
33pub fn build_delegation_link(input: &DelegationLinkInput) -> Value {
34    let mut link = Map::new();
35    link.insert("issuer".into(), json!(input.issuer));
36    link.insert("subject".into(), json!(input.subject));
37    link.insert("intent".into(), input.intent.clone());
38    if let Some(vf) = &input.valid_from {
39        link.insert("validFrom".into(), json!(vf));
40    }
41    if let Some(vu) = &input.valid_until {
42        link.insert("validUntil".into(), json!(vu));
43    }
44    if let Some(pp) = &input.parent_proof_value {
45        link.insert("parentProofValue".into(), json!(pp));
46    }
47    Value::Object(link)
48}
49
50/// A link's window bound: absent is open, a protocol-time string is parsed,
51/// and anything else (null, a number, an object) is an error.
52fn link_bound(obj: &Map<String, Value>, key: &str) -> Result<Option<i128>> {
53    match obj.get(key) {
54        None => Ok(None),
55        Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
56        Some(_) => Err(CoreError::Json(format!(
57            "delegation link {key} must be a time string"
58        ))),
59    }
60}
61
62fn link_window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
63    let obj = link
64        .as_object()
65        .ok_or_else(|| CoreError::Json("delegation link must be an object".into()))?;
66    Ok((
67        link_bound(obj, "validFrom")?,
68        link_bound(obj, "validUntil")?,
69    ))
70}
71
72/// Validate the time-bound rule over a chain ordered root -> leaf. Every
73/// link's window must sit inside the window of EVERY link above it (the
74/// running intersection, so a middle link with no window does not detach the
75/// leaf from the root's window), no window may be inverted, and `now_iso` must
76/// fall inside the intersection of all the windows (allowing the skew).
77/// Returns Ok(true) if the chain is time-valid. Errors on a bound that is not a
78/// time string, a malformed time, or a skew outside 0..120 seconds.
79pub fn verify_chain_time_bound(
80    chain: &[Value],
81    now_iso: &str,
82    clock_skew_seconds: i64,
83) -> Result<bool> {
84    let skew = check_clock_skew(clock_skew_seconds)?;
85    let now = parse_protocol_time_ns(now_iso)?;
86    let mut eff_from: Option<i128> = None;
87    let mut eff_until: Option<i128> = None;
88
89    for link in chain {
90        let (vf, vu) = link_window(link)?;
91        if let (Some(f), Some(u)) = (vf, vu) {
92            if f > u {
93                return Ok(false); // inverted window
94            }
95        }
96        if let (Some(f), Some(ef)) = (vf, eff_from) {
97            if f < ef {
98                return Ok(false); // starts before an ancestor
99            }
100        }
101        if let (Some(u), Some(eu)) = (vu, eff_until) {
102            if u > eu {
103                return Ok(false); // ends after an ancestor
104            }
105        }
106        if let Some(f) = vf {
107            eff_from = Some(eff_from.map_or(f, |cur| cur.max(f)));
108        }
109        if let Some(u) = vu {
110            eff_until = Some(eff_until.map_or(u, |cur| cur.min(u)));
111        }
112    }
113    Ok(window_state_ns(now, eff_from, eff_until, skew) == WindowState::Ok)
114}
115
116// ---------------------------------------------------------------------------
117// Delegation chain verification (Specification 9.3)
118// ---------------------------------------------------------------------------
119//
120// A faithful port of `vouch.verifier.verify_delegation_chain` (Python is the
121// reference). Every step and reason code matches it exactly; the shared vectors
122// in `test-vectors/delegation-chain/vector.json` are the contract.
123
124/// Map a signed Vouch credential onto the six-dimension link shape that
125/// `attenuation::non_expansion` compares: action / target / resource from
126/// `credentialSubject.intent`, time from `validFrom` / `validUntil`, rate and
127/// policy from `intent.rate` / `intent.policy`, subject from `intent.delegatee`.
128pub fn capability_view(credential: &Value, include_time: bool) -> Value {
129    let intent = credential
130        .get("credentialSubject")
131        .and_then(|s| s.get("intent"))
132        .and_then(|i| i.as_object())
133        .cloned()
134        .unwrap_or_default();
135    let mut view = Map::new();
136    view.insert(
137        "issuer".into(),
138        issuer_did(credential)
139            .map(Value::String)
140            .unwrap_or(Value::Null),
141    );
142    view.insert(
143        "subject".into(),
144        intent.get("delegatee").cloned().unwrap_or(Value::Null),
145    );
146    let mut dims = Map::new();
147    for k in ["action", "target", "resource", "amount"] {
148        if let Some(v) = intent.get(k) {
149            dims.insert(k.into(), v.clone());
150        }
151    }
152    view.insert("intent".into(), Value::Object(dims));
153    if include_time {
154        for k in ["validFrom", "validUntil"] {
155            if let Some(v) = credential.get(k) {
156                view.insert(k.into(), v.clone());
157            }
158        }
159    }
160    for k in ["rate", "policy"] {
161        if let Some(v) = intent.get(k) {
162            view.insert(k.into(), v.clone());
163        }
164    }
165    Value::Object(view)
166}
167
168/// The issuer DID of a grant or credential: the `issuer` string, or the `id` of
169/// an issuer object. An array or any other shape has no issuer.
170fn issuer_did(credential: &Value) -> Option<String> {
171    crate::credentials::issuer_did(credential).map(String::from)
172}
173
174/// The Ed25519 key of a grant issuer: from the caller's map, else (for a
175/// `did:key`) the key the DID encodes. For a `did:key` issuer a key in the
176/// caller's map must equal the DID's own key, and a `did:key` that does not
177/// decode resolves to nothing.
178fn resolve_chain_key(did: &str, root_keys: &BTreeMap<String, Vec<u8>>) -> Option<Vec<u8>> {
179    let from_did = match did.strip_prefix("did:key:") {
180        Some(mk) => {
181            let decoded = multikey::decode(mk).ok()?;
182            if decoded.algorithm != "Ed25519" {
183                return None;
184            }
185            Some(decoded.raw_key)
186        }
187        None => None,
188    };
189    match (root_keys.get(did), from_did) {
190        (Some(k), Some(d)) => (k == &d).then_some(d),
191        (Some(k), None) => Some(k.clone()),
192        (None, d) => d,
193    }
194}
195
196/// The proof value a link binds to its parent: the eddsa-jcs-2022 member of a
197/// proof set, else the first proof value, else a single proof's value.
198fn parent_proof_binding_value(grant: &Value) -> String {
199    match grant.get("proof") {
200        Some(Value::Array(items)) => {
201            for p in items {
202                if p.get("cryptosuite").and_then(|v| v.as_str())
203                    == Some(data_integrity::CRYPTOSUITE_ID)
204                {
205                    return p
206                        .get("proofValue")
207                        .and_then(|v| v.as_str())
208                        .unwrap_or("")
209                        .to_string();
210                }
211            }
212            for p in items {
213                if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
214                    if !v.is_empty() {
215                        return v.to_string();
216                    }
217                }
218            }
219            String::new()
220        }
221        Some(Value::Object(p)) => p
222            .get("proofValue")
223            .and_then(|v| v.as_str())
224            .unwrap_or("")
225            .to_string(),
226        _ => String::new(),
227    }
228}
229
230/// Check a grant's proof with the top-level proof rules.
231///
232/// Every member is an object with type "DataIntegrityProof", a known
233/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
234/// grant issuer's DID, a proofValue, a valid `created` and an `expires` (when
235/// present) that has not passed. The shape is one `eddsa-jcs-2022` proof, the
236/// earlier composite proof (accepted only when the issuer's ML-DSA-44 key is
237/// known), or a set of exactly one `eddsa-jcs-2022` and one ML-DSA-44 member.
238/// The Ed25519 proof always verifies with `key`; the ML-DSA-44 member is
239/// checked whenever `mldsa_key` is known and is required when `require_pq` is
240/// set (a single classical proof then fails).
241fn verify_grant_proof(
242    grant: &Value,
243    issuer: &str,
244    key: &[u8],
245    mldsa_key: Option<&[u8]>,
246    require_pq: bool,
247    now: i128,
248    skew: i128,
249) -> bool {
250    let Some(proof) = grant.get("proof") else {
251        return false;
252    };
253    let members: Vec<&Value> = match proof {
254        Value::Array(items) => items.iter().collect(),
255        other => vec![other],
256    };
257    if members.is_empty()
258        || !members
259            .iter()
260            .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
261    {
262        return false;
263    }
264    let suite = |p: &Value| {
265        p.get("cryptosuite")
266            .and_then(|v| v.as_str())
267            .unwrap_or_default()
268            .to_string()
269    };
270    match proof {
271        Value::Object(_) => match suite(proof).as_str() {
272            data_integrity::CRYPTOSUITE_ID => {
273                !require_pq && matches!(data_integrity::verify_proof(grant, key), Ok(true))
274            }
275            hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa_key {
276                Some(ml) => matches!(hybrid::verify_composite(grant, key, ml), Ok(true)),
277                None => false,
278            },
279            _ => false,
280        },
281        Value::Array(items) => {
282            let mut suites: Vec<String> = items
283                .iter()
284                .map(|p| {
285                    let s = suite(p);
286                    if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
287                        hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
288                    } else {
289                        s
290                    }
291                })
292                .collect();
293            suites.sort();
294            if suites != [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID] {
295                return false;
296            }
297            match mldsa_key {
298                Some(ml) => matches!(hybrid::verify_dual(grant, key, ml), Ok(true)),
299                None if require_pq => false,
300                None => {
301                    // Only the Ed25519 member can be checked: it must verify.
302                    let Some(ed) = items
303                        .iter()
304                        .find(|p| suite(p) == data_integrity::CRYPTOSUITE_ID)
305                    else {
306                        return false;
307                    };
308                    let mut single = grant.clone();
309                    single["proof"] = (*ed).clone();
310                    matches!(data_integrity::verify_proof(&single, key), Ok(true))
311                }
312            }
313        }
314        _ => false,
315    }
316}
317
318/// The checks of [`verify_grant_proof`] that need no key: every member passes
319/// the top-level proof rules, and the shape is one `eddsa-jcs-2022` proof, the
320/// earlier composite proof, or a set of exactly one `eddsa-jcs-2022` and one
321/// ML-DSA-44 member.
322fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
323    let Some(proof) = grant.get("proof") else {
324        return false;
325    };
326    let members: Vec<&Value> = match proof {
327        Value::Array(items) => items.iter().collect(),
328        other => vec![other],
329    };
330    if members.is_empty()
331        || !members
332            .iter()
333            .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
334    {
335        return false;
336    }
337    let suite = |p: &Value| {
338        let s = p
339            .get("cryptosuite")
340            .and_then(|v| v.as_str())
341            .unwrap_or_default();
342        if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
343            hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
344        } else {
345            s.to_string()
346        }
347    };
348    match proof {
349        Value::Object(_) => matches!(
350            suite(proof).as_str(),
351            data_integrity::CRYPTOSUITE_ID | hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
352        ),
353        Value::Array(items) => {
354            let mut suites: Vec<String> = items.iter().map(suite).collect();
355            suites.sort();
356            suites == [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID]
357        }
358        _ => false,
359    }
360}
361
362fn first_64(s: &str) -> String {
363    s.chars().take(64).collect()
364}
365
366/// The reason a chain is refused when the caller named no trusted starting
367/// point (trusted roots) for it.
368pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
369    "the chain's starting point is not trusted: pass trusted roots";
370
371/// The reason a chain is refused by the verifier's resource guard or an
372/// explicit budget the caller set.
373pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
374
375/// An encoded delegation chain (its JCS form) larger than this is refused
376/// before any signature is checked. This is a resource guard only: there is no
377/// fixed depth limit, since a chain is limited by narrowing scope, never by its
378/// number of links.
379pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
380
381/// A trusted root as the caller wrote it, as a DID, read exactly as the Python
382/// reference reads it ([`crate::did_web::normalize_root`]): a bare domain such
383/// as "yourcompany.com" means "did:web:yourcompany.com" ("host:8443" means
384/// "did:web:host%3A8443"); a full DID is used as it is. None when the root is
385/// neither (an IP literal, a URL, a trailing dot, a bad port, ...).
386pub fn root_did(root: &str) -> Option<String> {
387    crate::did_web::normalize_root(root).ok()
388}
389
390/// True when the caller's trusted root names `issuer` exactly (see
391/// [`root_did`]); a root that does not parse names nobody.
392pub fn root_matches(root: &str, issuer: &str) -> bool {
393    root_did(root).as_deref() == Some(issuer)
394}
395
396/// How a verifier checks an embedded delegation chain.
397#[derive(Debug, Clone, Copy, Default)]
398pub struct ChainOptions<'a> {
399    /// The trusted starting points: the chain's first grant must be issued by
400    /// one of them. A chain is refused when this is `None`
401    /// ([`REASON_TRUSTED_ROOTS_REQUIRED`]); an empty list trusts nobody
402    /// ("untrusted_principal"). A bare domain stands for its did:web
403    /// ([`root_did`]).
404    pub trusted_roots: Option<&'a [String]>,
405    /// Ed25519 keys for grant issuers that are not `did:key` (a `did:key`
406    /// issuer always resolves offline from the DID itself).
407    pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
408    /// ML-DSA-44 public keys by grant issuer DID. A grant whose issuer has a
409    /// key here has its ML-DSA-44 member checked (and the earlier composite
410    /// proof accepted).
411    pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
412    /// Require the post-quantum profile on every grant: each must carry a
413    /// valid dual proof (Ed25519 and ML-DSA-44), with its ML-DSA-44 key known.
414    pub require_pq: bool,
415    /// An explicit depth budget chosen by the caller. `None` means no depth
416    /// limit (there is no default one).
417    pub max_depth: Option<usize>,
418}
419
420/// Verify a credential's embedded `delegationChain`. Returns `None` when the
421/// chain is valid (or absent), otherwise the reason code.
422///
423/// `root_keys` supplies Ed25519 keys for non-`did:key` grant issuers (for a
424/// `did:key` issuer it must equal the DID's own key); `root_dids` is the set of
425/// trusted root DIDs the chain must start from. A credential that carries a
426/// chain is refused when `root_dids` is `None`, and an empty list trusts
427/// nobody. See [`verify_delegation_chain_with`] for every option.
428pub fn verify_delegation_chain(
429    credential: &Value,
430    now_iso: &str,
431    clock_skew_seconds: i64,
432    root_keys: &BTreeMap<String, Vec<u8>>,
433    root_dids: Option<&[String]>,
434) -> Option<String> {
435    let opts = ChainOptions {
436        trusted_roots: root_dids,
437        grant_keys: Some(root_keys),
438        ..Default::default()
439    };
440    verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
441}
442
443/// Verify a credential's embedded `delegationChain` under `opts`. Returns
444/// `None` when the chain is valid (or absent), otherwise the reason code.
445///
446/// Order: the chain's shape (a `delegationChain` of null, `{}`, `""`, 0 or
447/// false is malformed), the size guard (1 MiB of JCS) and any explicit depth
448/// budget, the trusted roots, then a pre-filter from the link fields alone
449/// (each link's issuer is the previous link's subject, and the first issuer
450/// is a trusted root), all before any key is resolved or signature checked.
451/// The pre-filter also checks that the last link's subject is the credential's
452/// issuer. Then each link's signed grant: issuer, the proof's own fields and
453/// shape (before any key is looked up), the key, the signatures (post-quantum
454/// required with no ML-DSA-44 key known is "delegation_signature_invalid"),
455/// parent binding, delegatee and window; and non-expansion across every
456/// dimension.
457pub fn verify_delegation_chain_with(
458    credential: &Value,
459    now_iso: &str,
460    clock_skew_seconds: i64,
461    opts: &ChainOptions,
462) -> Option<String> {
463    let malformed = || Some("malformed_delegation".to_string());
464    if !credential.is_object() {
465        return malformed();
466    }
467    let chain_value = match credential
468        .get("credentialSubject")
469        .and_then(|s| s.get("delegationChain"))
470    {
471        None => return None,
472        Some(Value::Array(a)) if a.is_empty() => return None,
473        Some(v @ Value::Array(_)) => v,
474        // null is never "absent" (D29); any other shape is malformed.
475        Some(_) => return malformed(),
476    };
477    let chain = chain_value.as_array().expect("checked above");
478    match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
479        Ok(None) => {}
480        Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
481        Err(_) => return malformed(),
482    }
483    let Some(roots) = opts.trusted_roots else {
484        return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
485    };
486    let Ok(skew) = check_clock_skew(clock_skew_seconds) else {
487        return malformed();
488    };
489    let Ok(now) = parse_protocol_time_ns(now_iso) else {
490        return malformed();
491    };
492
493    // Pre-filter from the link fields alone, before any key is resolved.
494    for link in chain {
495        let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
496            && link.get("subject").is_some_and(|v| v.is_string());
497        if !shape_ok {
498            return malformed();
499        }
500    }
501    for i in 1..chain.len() {
502        if chain[i - 1].get("subject") != chain[i].get("issuer") {
503            return Some("delegation_subject_issuer_mismatch".into());
504        }
505    }
506    let last_subject = chain[chain.len() - 1]
507        .get("subject")
508        .and_then(|v| v.as_str());
509    if last_subject.map(String::from) != issuer_did(credential) {
510        return Some("delegation_subject_issuer_mismatch".into());
511    }
512    let root = chain[0]
513        .get("issuer")
514        .and_then(|v| v.as_str())
515        .unwrap_or("");
516    if !roots.iter().any(|d| root_matches(d, root)) {
517        return Some("untrusted_principal".into());
518    }
519
520    let empty = BTreeMap::new();
521    let grant_keys = opts.grant_keys.unwrap_or(&empty);
522
523    let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
524    for link in chain {
525        let link_issuer = link["issuer"].as_str().unwrap_or_default();
526        let link_subject = link["subject"].as_str().unwrap_or_default();
527        let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
528            return Some("delegation_link_unsigned".into());
529        };
530        if !matches!(
531            grant.get("proof"),
532            Some(Value::Object(_)) | Some(Value::Array(_))
533        ) {
534            return Some("delegation_link_unsigned".into());
535        }
536        let grant_issuer = issuer_did(grant);
537        if grant_issuer.as_deref() != Some(link_issuer) {
538            return Some("delegation_link_issuer_mismatch".into());
539        }
540        // The proof's own fields and shape are checked before any key is
541        // looked up, so a malformed proof reads the same in every language.
542        if !grant_proof_well_formed(grant, link_issuer, now, skew) {
543            return Some("delegation_signature_invalid".into());
544        }
545        let Some(key) = resolve_chain_key(link_issuer, grant_keys) else {
546            return Some("delegation_issuer_key_unresolved".into());
547        };
548        // With post-quantum required and no ML-DSA-44 key known, the grant's
549        // proof cannot meet it: verify_grant_proof refuses it.
550        let mldsa_key = opts
551            .mldsa_keys
552            .and_then(|m| m.get(link_issuer))
553            .map(|k| k.as_slice());
554        if !verify_grant_proof(
555            grant,
556            link_issuer,
557            &key,
558            mldsa_key,
559            opts.require_pq,
560            now,
561            skew,
562        ) {
563            return Some("delegation_signature_invalid".into());
564        }
565        if let Some(bound) = link.get("parentProofValue") {
566            // Present but null or not text is malformed, never "absent" (D29).
567            let Some(bound) = bound.as_str() else {
568                return malformed();
569            };
570            if bound != first_64(&parent_proof_binding_value(grant)) {
571                return Some("delegation_link_tampered".into());
572            }
573        }
574        let delegatee = grant
575            .get("credentialSubject")
576            .and_then(|s| s.get("intent"))
577            .and_then(|i| i.get("delegatee"))
578            .and_then(|d| d.as_str())
579            .filter(|d| !d.is_empty());
580        let Some(delegatee) = delegatee else {
581            return Some("delegation_no_delegatee".into());
582        };
583        if delegatee != link_subject {
584            return Some("delegation_subject_mismatch".into());
585        }
586        let window = (
587            grant
588                .get("validFrom")
589                .and_then(|v| v.as_str())
590                .map(parse_protocol_time_ns),
591            grant
592                .get("validUntil")
593                .and_then(|v| v.as_str())
594                .map(parse_protocol_time_ns),
595        );
596        let (Some(Ok(from)), Some(Ok(until))) = window else {
597            return malformed();
598        };
599        match window_state_ns(now, Some(from), Some(until), skew) {
600            WindowState::Ok => {}
601            WindowState::Expired => return Some("delegation_expired".into()),
602            WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
603            WindowState::Inverted => return malformed(),
604        }
605        grants.push(grant);
606    }
607
608    let last_subject = chain[chain.len() - 1]
609        .get("subject")
610        .and_then(|v| v.as_str());
611    if last_subject.map(String::from) != issuer_did(credential) {
612        return Some("delegation_subject_issuer_mismatch".into());
613    }
614
615    let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
616    views.push(capability_view(credential, true));
617    if let Err(dim) = attenuation::first_broader_step(&views) {
618        return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
619    }
620    None
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626
627    fn link(vf: &str, vu: &str) -> Value {
628        build_delegation_link(&DelegationLinkInput {
629            issuer: "did:web:a".into(),
630            subject: "did:web:b".into(),
631            intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
632            valid_from: Some(vf.into()),
633            valid_until: Some(vu.into()),
634            parent_proof_value: None,
635        })
636    }
637
638    #[test]
639    fn nested_windows_pass() {
640        let chain = vec![
641            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
642            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
643        ];
644        assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
645    }
646
647    #[test]
648    fn child_wider_than_parent_fails() {
649        let chain = vec![
650            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
651            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), // wider
652        ];
653        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
654    }
655
656    #[test]
657    fn now_outside_leaf_window_fails() {
658        let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
659        assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
660    }
661
662    #[test]
663    fn a_window_less_middle_link_stays_bounded_by_the_root() {
664        let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
665                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
666        let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
667        let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
668                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
669        let chain = vec![root.clone(), mid, leaf];
670        assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
671        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
672        // A bound that is not a time string is an error, not "no bound".
673        let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
674                         "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
675        assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
676        // Inverted, and skew out of range.
677        let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
678        assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
679        assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
680    }
681
682    // --- Signed chains: roots, size guard, and the post-quantum profile ---
683
684    struct Party {
685        seed: [u8; 32],
686        did: String,
687    }
688
689    fn party(n: u8) -> Party {
690        let seed = [n; 32];
691        let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
692        Party { seed, did }
693    }
694
695    fn vm(p: &Party) -> String {
696        format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
697    }
698
699    fn grant_body(from: &Party, to: &Party) -> Value {
700        json!({
701            "@context": ["https://www.w3.org/ns/credentials/v2"],
702            "type": ["VerifiableCredential", "VouchCredential"],
703            "issuer": from.did,
704            "validFrom": "2026-04-26T09:00:00Z",
705            "validUntil": "2026-04-26T12:00:00Z",
706            "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
707                "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
708        })
709    }
710
711    fn leaf_credential(leaf: &Party, link: Value) -> Value {
712        json!({
713            "@context": ["https://www.w3.org/ns/credentials/v2"],
714            "type": ["VerifiableCredential", "VouchCredential"],
715            "issuer": leaf.did,
716            "validFrom": "2026-04-26T10:00:00Z",
717            "validUntil": "2026-04-26T10:05:00Z",
718            "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
719                "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
720                "delegationChain": [link]}
721        })
722    }
723
724    const NOW: &str = "2026-04-26T10:01:00Z";
725
726    fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
727        ChainOptions {
728            trusted_roots: Some(roots),
729            ..Default::default()
730        }
731    }
732
733    #[test]
734    fn signed_chain_needs_roots_and_respects_the_size_guard() {
735        let (root, leaf) = (party(1), party(2));
736        let grant = data_integrity::sign(
737            &grant_body(&root, &leaf),
738            &root.seed,
739            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
740        )
741        .unwrap();
742        let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
743        let cred = leaf_credential(&leaf, link.clone());
744        let roots = vec![root.did.clone()];
745        assert_eq!(
746            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
747            None
748        );
749        assert_eq!(
750            verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
751            Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
752        );
753        // An empty list trusts nobody.
754        assert_eq!(
755            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
756            Some("untrusted_principal".into())
757        );
758        // A bare domain means its did:web; it never matches a did:key root.
759        let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
760        assert_eq!(
761            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
762            Some("untrusted_principal".into())
763        );
764        assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
765        assert!(!root_matches(
766            "yourcompany.com",
767            "did:web:yourcompany.com.evil"
768        ));
769        assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
770        assert_eq!(
771            root_did("yourcompany.com").as_deref(),
772            Some("did:web:yourcompany.com")
773        );
774        assert_eq!(
775            root_did("yourcompany.com:8443").as_deref(),
776            Some("did:web:yourcompany.com%3A8443")
777        );
778        assert!(root_did("127.0.0.1").is_none());
779        let other = vec!["did:web:someone-else".to_string()];
780        assert_eq!(
781            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
782            Some("untrusted_principal".into())
783        );
784        // No fixed depth limit, but an explicit budget still applies.
785        let budget = ChainOptions {
786            max_depth: Some(0),
787            ..opts_with(&roots)
788        };
789        assert_eq!(
790            verify_delegation_chain_with(&cred, NOW, 30, &budget),
791            Some(REASON_BUDGET_EXCEEDED.into())
792        );
793        // More than 1 MiB encoded is refused before any signature is checked.
794        let mut big = link;
795        big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
796        let cred = leaf_credential(&leaf, big);
797        assert_eq!(
798            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
799            Some(REASON_BUDGET_EXCEEDED.into())
800        );
801    }
802
803    #[test]
804    fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
805        let (root, leaf) = (party(3), party(4));
806        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
807        let body = grant_body(&root, &leaf);
808        let dual = hybrid::sign_dual(
809            &body,
810            &root.seed,
811            &ml,
812            &vm(&root),
813            &format!("{}#mldsa", root.did),
814            "2026-04-26T09:00:00Z",
815        )
816        .unwrap();
817        let single = data_integrity::sign(
818            &body,
819            &root.seed,
820            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
821        )
822        .unwrap();
823        let roots = vec![root.did.clone()];
824        let mut mldsa_keys = BTreeMap::new();
825        mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
826        let pq = ChainOptions {
827            trusted_roots: Some(&roots),
828            mldsa_keys: Some(&mldsa_keys),
829            require_pq: true,
830            ..Default::default()
831        };
832        let chain_of = |grant: &Value| {
833            leaf_credential(
834                &leaf,
835                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
836            )
837        };
838        assert_eq!(
839            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
840            None
841        );
842        // A classical-only grant does not meet the post-quantum profile.
843        assert_eq!(
844            verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
845            Some("delegation_signature_invalid".into())
846        );
847        // A broken ML-DSA member fails it too.
848        let mut broken = dual.clone();
849        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
850        assert_eq!(
851            verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
852            Some("delegation_signature_invalid".into())
853        );
854        // Post-quantum required and no ML-DSA key known: the proof cannot meet it.
855        let none = ChainOptions {
856            mldsa_keys: None,
857            ..pq
858        };
859        assert_eq!(
860            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
861            Some("delegation_signature_invalid".into())
862        );
863        // Without the requirement the classical member is what is checked.
864        assert_eq!(
865            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
866            None
867        );
868        // Every member must be the issuer's own: a member naming another DID fails.
869        let mut foreign = dual.clone();
870        foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
871        assert_eq!(
872            verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
873            Some("delegation_signature_invalid".into())
874        );
875    }
876
877    /// A one-link chain whose grant carries `proof`, signed over the grant body.
878    fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
879        let mut grant = grant_body(root, leaf);
880        grant["proof"] = proof;
881        leaf_credential(
882            leaf,
883            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
884        )
885    }
886
887    fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
888        data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
889    }
890
891    #[test]
892    fn grant_proofs_follow_the_top_level_rules() {
893        let (root, leaf) = (party(5), party(6));
894        let roots = vec![root.did.clone()];
895        let o = opts_with(&roots);
896        let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
897        let good = eddsa_proof(&root, &leaf, base());
898        let check = |proof: Value| {
899            verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
900        };
901        assert_eq!(check(good.clone()), None);
902        let invalid = Some("delegation_signature_invalid".to_string());
903        // An expires that has passed, or is null (both inside the signed proof).
904        for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
905            let mut p = good.clone();
906            p["expires"] = expires.clone();
907            let mut unsigned = p.clone();
908            unsigned.as_object_mut().unwrap().remove("proofValue");
909            let input =
910                data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
911                    .unwrap();
912            let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
913            p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
914            assert_eq!(check(p), invalid, "expires {expires}");
915        }
916        // A created that is not a time.
917        let mut opts = base();
918        opts.created = "yesterday".into();
919        assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
920        // An unknown cryptosuite, a missing proofValue, a member that is not an object.
921        let mut p = good.clone();
922        p["cryptosuite"] = json!("some-unregistered-suite-2030");
923        assert_eq!(check(p), invalid);
924        let mut p = good.clone();
925        p.as_object_mut().unwrap().remove("proofValue");
926        assert_eq!(check(p), invalid);
927        assert_eq!(check(json!([good.clone(), 7])), invalid);
928        // A set is exactly one eddsa-jcs-2022 and one ML-DSA-44 member.
929        assert_eq!(check(json!([good.clone()])), invalid);
930        assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
931    }
932
933    #[test]
934    fn grant_issuer_is_a_did_string_or_id() {
935        let (root, leaf) = (party(7), party(8));
936        let roots = vec![root.did.clone()];
937        let mut body = grant_body(&root, &leaf);
938        body["issuer"] = json!([root.did.clone()]);
939        let grant = data_integrity::sign(
940            &body,
941            &root.seed,
942            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
943        )
944        .unwrap();
945        let cred = leaf_credential(
946            &leaf,
947            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
948        );
949        assert_eq!(
950            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
951            Some("delegation_link_issuer_mismatch".into())
952        );
953    }
954
955    #[test]
956    fn a_known_mldsa_key_checks_the_grant_member() {
957        let (root, leaf) = (party(9), party(10));
958        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
959        let body = grant_body(&root, &leaf);
960        let dual = hybrid::sign_dual(
961            &body,
962            &root.seed,
963            &ml,
964            &vm(&root),
965            &format!("{}#mldsa", root.did),
966            "2026-04-26T09:00:00Z",
967        )
968        .unwrap();
969        let roots = vec![root.did.clone()];
970        let mut keys = BTreeMap::new();
971        keys.insert(root.did.clone(), ml.public_key().to_vec());
972        let known = ChainOptions {
973            trusted_roots: Some(&roots),
974            mldsa_keys: Some(&keys),
975            ..Default::default()
976        };
977        let link = |g: &Value| {
978            leaf_credential(
979                &leaf,
980                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
981            )
982        };
983        assert_eq!(
984            verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
985            None
986        );
987        // A broken ML-DSA-44 member fails once its key is known, PQ required or not.
988        let mut broken = dual.clone();
989        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
990        assert_eq!(
991            verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
992            Some("delegation_signature_invalid".into())
993        );
994        // The earlier composite proof on a grant: accepted with the ML key only.
995        #[allow(deprecated)]
996        let composite =
997            hybrid::sign_composite(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z")
998                .unwrap();
999        assert_eq!(
1000            verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1001            None
1002        );
1003        assert_eq!(
1004            verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1005            Some("delegation_signature_invalid".into())
1006        );
1007    }
1008
1009    #[test]
1010    fn a_did_key_grant_issuer_keeps_its_own_key() {
1011        let (root, leaf, other) = (party(11), party(12), party(13));
1012        let grant = data_integrity::sign(
1013            &grant_body(&root, &leaf),
1014            &root.seed,
1015            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1016        )
1017        .unwrap();
1018        let cred = leaf_credential(
1019            &leaf,
1020            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1021        );
1022        let roots = vec![root.did.clone()];
1023        let mut keys = BTreeMap::new();
1024        keys.insert(
1025            root.did.clone(),
1026            crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1027                .public_key()
1028                .to_vec(),
1029        );
1030        let pinned = ChainOptions {
1031            trusted_roots: Some(&roots),
1032            grant_keys: Some(&keys),
1033            ..Default::default()
1034        };
1035        assert_eq!(
1036            verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1037            Some("delegation_issuer_key_unresolved".into())
1038        );
1039    }
1040
1041    #[test]
1042    fn link_fields_are_checked_before_any_key() {
1043        // A chain from an untrusted start, or with a gap, is refused before the
1044        // (unresolvable) grant keys are looked at.
1045        let link = |iss: &str, sub: &str| {
1046            json!({"issuer": iss, "subject": sub,
1047                   "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1048        };
1049        let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1050        let roots = vec!["did:web:root".to_string()];
1051        assert_eq!(
1052            verify_delegation_chain_with(
1053                &cred(json!([link("did:web:other", "did:web:c")])),
1054                NOW,
1055                30,
1056                &opts_with(&roots)
1057            ),
1058            Some("untrusted_principal".into())
1059        );
1060        assert_eq!(
1061            verify_delegation_chain_with(
1062                &cred(json!([
1063                    link("did:web:root", "did:web:a"),
1064                    link("did:web:b", "did:web:c")
1065                ])),
1066                NOW,
1067                30,
1068                &opts_with(&roots)
1069            ),
1070            Some("delegation_subject_issuer_mismatch".into())
1071        );
1072        // The last link must name the credential's issuer, before any key.
1073        assert_eq!(
1074            verify_delegation_chain_with(
1075                &cred(json!([link("did:web:root", "did:web:other")])),
1076                NOW,
1077                30,
1078                &opts_with(&roots)
1079            ),
1080            Some("delegation_subject_issuer_mismatch".into())
1081        );
1082        // With a trusted, continuous chain, a bare proof is refused by its own
1083        // fields before any key is looked up.
1084        assert_eq!(
1085            verify_delegation_chain_with(
1086                &cred(json!([link("did:web:root", "did:web:c")])),
1087                NOW,
1088                30,
1089                &opts_with(&roots)
1090            ),
1091            Some("delegation_signature_invalid".into())
1092        );
1093        // null and other non-array chains are malformed, never "absent".
1094        for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1095            assert_eq!(
1096                verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1097                Some("malformed_delegation".into()),
1098                "{chain}"
1099            );
1100        }
1101        // The size guard runs before the roots check.
1102        let big =
1103            cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1104        assert_eq!(
1105            verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1106            Some(REASON_BUDGET_EXCEEDED.into())
1107        );
1108    }
1109}