Skip to main content

vouch_core/
attenuation.rs

1//! v1.7 capability attenuation: the non-expansion rule over the six delegation
2//! dimensions, verifier cost budgets, and chain-cascade revocation
3//! (Specification 9.3 to 9.6).
4//!
5//! Security posture: default-deny. Every check answers "is the child broader
6//! than its parent on this dimension?" and any malformed input, unknown shape,
7//! or ambiguous comparison rejects rather than admits. A delegation chain grants
8//! authority, so a false "valid" is an authority-escalation bug; a false
9//! "invalid" is only an availability issue. We bias hard toward rejection.
10//!
11//! The rules, in plain terms (the same in every language; the shared vectors
12//! in `test-vectors/delegation-attenuation/` are the contract):
13//!
14//! * A dimension a link leaves out is inherited unchanged from its parent; it
15//!   can never be widened by omission. A dimension a link writes down must be
16//!   well formed: `null` or the wrong type is refused on every link, so nobody
17//!   can erase a bound by writing `null`.
18//! * A parent bound that is malformed refuses the step: the child cannot be
19//!   shown to be inside it.
20//! * A resource is refused when it holds a backslash, `%2F` or `%5C` (any
21//!   case), an ASCII control character, or a `.` or `..` path segment (also
22//!   spelled with `%2e`), because a server that normalises the URL would land
23//!   outside the parent's resource.
24//! * A child rate never allows a burst its parent forbids, in exact integers:
25//!   `child.limit <= parent.limit` and `child.limit * ceil(parent.window /
26//!   child.window) <= parent.limit` ([`rate_within`]).
27//! * Every number in a budget or a rate is an integer of the right range.
28//! * Times follow the one strict grammar in [`crate::time`], compared to the
29//!   nanosecond.
30//! * There is no fixed depth limit; a caller may set `maxDepth`. An encoded
31//!   chain larger than 1 MiB is refused before anything else is checked.
32
33#[allow(unused_imports)]
34use crate::prelude::*;
35
36use alloc::collections::BTreeSet;
37
38use serde_json::{json, Map, Value};
39
40use crate::error::{CoreError, Result};
41use crate::time::{parse_protocol_time_ns, MAX_CLOCK_SKEW_SECONDS};
42
43/// The largest integer every language represents exactly (2^53 - 1).
44pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
45
46/// The deepest JSON nesting a delegation chain or policy may use.
47pub const MAX_JSON_NESTING: usize = 128;
48
49/// The largest encoded chain (JCS, UTF-8) a verifier will look at.
50pub const MAX_CHAIN_BYTES: usize = 1024 * 1024;
51
52const NS_PER_SECOND: i128 = 1_000_000_000;
53/// The most digits one duration field may carry.
54const MAX_DURATION_DIGITS: usize = 16;
55
56/// The six capability dimensions a delegation link may carry.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Dimension {
59    Action,
60    Target,
61    Resource,
62    Time,
63    Rate,
64    Policy,
65}
66
67impl Dimension {
68    pub fn as_str(self) -> &'static str {
69        match self {
70            Dimension::Action => "action",
71            Dimension::Target => "target",
72            Dimension::Resource => "resource",
73            Dimension::Time => "time",
74            Dimension::Rate => "rate",
75            Dimension::Policy => "policy",
76        }
77    }
78}
79
80/// A structured reason a delegation chain is rejected. `code()` yields the
81/// on-the-wire reason string used across the SDKs.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub enum DelegationReject {
84    /// A child link is broader than its parent on the named dimension.
85    ScopeExceedsParent { dimension: Dimension },
86    /// The verifier's local cost budget was exceeded; `limit` names which one.
87    VerifierBudgetExceeded { limit: String },
88    /// A link (0-indexed from the root) is revoked; the whole chain and every
89    /// authority below it is rejected.
90    DelegationRevoked { link_index: usize },
91    /// A link's `subject` does not match the next link's `issuer`.
92    SubjectIssuerMismatch { link_index: usize },
93    /// The root link's issuer is not in the verifier's trusted set.
94    UntrustedPrincipal,
95    /// The current instant is outside the chain's effective validity window.
96    OutsideValidityWindow,
97    /// The chain or a link is structurally malformed.
98    Malformed { detail: String },
99}
100
101impl DelegationReject {
102    pub fn code(&self) -> &'static str {
103        match self {
104            DelegationReject::ScopeExceedsParent { .. } => "scope_exceeds_parent",
105            DelegationReject::VerifierBudgetExceeded { .. } => "verifier_budget_exceeded",
106            DelegationReject::DelegationRevoked { .. } => "delegation_revoked",
107            DelegationReject::SubjectIssuerMismatch { .. } => "subject_issuer_mismatch",
108            DelegationReject::UntrustedPrincipal => "untrusted_principal",
109            DelegationReject::OutsideValidityWindow => "outside_validity_window",
110            DelegationReject::Malformed { .. } => "malformed_delegation",
111        }
112    }
113}
114
115/// Verifier-local cost budget (Specification 9.4). `None` means unlimited.
116/// These are the verifier's configurable choice, not a protocol requirement;
117/// there is no default depth limit.
118#[derive(Debug, Clone, Default)]
119pub struct VerifierBudget {
120    pub max_depth: Option<usize>,
121    pub max_cumulative_ttl_seconds: Option<i64>,
122}
123
124type DResult = core::result::Result<(), DelegationReject>;
125
126// --------------------------------------------------------------------------
127// Small value checks
128// --------------------------------------------------------------------------
129
130/// The integer value of `v` when it is a JSON number with an integral value in
131/// `[low, high]` (so 2 and 2.0 are both 2), else None. Booleans, strings, null
132/// and fractions are refused.
133pub fn as_int(v: &Value, low: i64, high: i64) -> Option<i64> {
134    let Value::Number(n) = v else {
135        return None;
136    };
137    let value: i64 = if let Some(i) = n.as_i64() {
138        i
139    } else if n.as_u64().is_some() {
140        return None; // above i64::MAX, so above every range used here
141    } else {
142        let f = n.as_f64()?;
143        if !f.is_finite() || crate::float::fract(f) != 0.0 || f.abs() > MAX_SAFE_INTEGER as f64 {
144            return None;
145        }
146        f as i64
147    };
148    (low..=high).contains(&value).then_some(value)
149}
150
151/// True when `value` nests arrays or objects deeper than `limit` levels. Walks
152/// with an explicit stack, so hostile input cannot exhaust the call stack. A
153/// scalar has depth 0 and `[]` has depth 1.
154pub fn json_nesting_exceeds(value: &Value, limit: usize) -> bool {
155    let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
156    while let Some((item, depth)) = stack.pop() {
157        let children: Box<dyn Iterator<Item = &Value>> = match item {
158            Value::Array(a) => Box::new(a.iter()),
159            Value::Object(o) => Box::new(o.values()),
160            _ => continue,
161        };
162        let depth = depth + 1;
163        if depth > limit {
164            return true;
165        }
166        for child in children {
167            if child.is_array() || child.is_object() {
168                stack.push((child, depth));
169            }
170        }
171    }
172    false
173}
174
175/// The UTF-8 length of `value` in its JCS (RFC 8785) form, the size every
176/// language measures a chain by.
177pub fn encoded_size(value: &Value) -> usize {
178    crate::jcs::canonicalize(value).len()
179}
180
181/// The cost limit a chain breaks, or None: `"depth"` when the caller set
182/// `max_depth` and the chain has more links, `"size"` when its JCS form is
183/// larger than [`MAX_CHAIN_BYTES`]. There is no default depth limit. An `Err`
184/// means the chain nests deeper than [`MAX_JSON_NESTING`] (malformed).
185pub fn chain_budget_exceeded(
186    chain: &Value,
187    max_depth: Option<usize>,
188) -> core::result::Result<Option<&'static str>, String> {
189    crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); chain);
190    if let (Some(max), Some(links)) = (max_depth, chain.as_array()) {
191        if links.len() > max {
192            return Ok(Some("depth"));
193        }
194    }
195    if json_nesting_exceeds(chain, MAX_JSON_NESTING) {
196        return Err("delegation chain nests too deeply".into());
197    }
198    if encoded_size(chain) > MAX_CHAIN_BYTES {
199        return Ok(Some("size"));
200    }
201    Ok(None)
202}
203
204fn is_number(v: &Value) -> bool {
205    matches!(v, Value::Number(_))
206}
207
208/// Equality in the JSON data model: numbers by value (9 == 9.0), a boolean is
209/// never a number, and containers compare element by element.
210pub fn json_equal(a: &Value, b: &Value) -> bool {
211    crate::nesting::deep_guard!(false; a, b);
212    match (a, b) {
213        (Value::Number(x), Value::Number(y)) => {
214            if let (Some(i), Some(j)) = (x.as_i64(), y.as_i64()) {
215                return i == j;
216            }
217            if let (Some(i), Some(j)) = (x.as_u64(), y.as_u64()) {
218                return i == j;
219            }
220            match (x.as_f64(), y.as_f64()) {
221                (Some(i), Some(j)) => i == j,
222                _ => false,
223            }
224        }
225        (Value::Array(x), Value::Array(y)) => {
226            x.len() == y.len() && x.iter().zip(y).all(|(i, j)| json_equal(i, j))
227        }
228        (Value::Object(x), Value::Object(y)) => {
229            x.len() == y.len()
230                && x.iter()
231                    .all(|(k, v)| y.get(k).map(|w| json_equal(v, w)).unwrap_or(false))
232        }
233        _ => a == b,
234    }
235}
236
237// --------------------------------------------------------------------------
238// Dimension helpers
239// --------------------------------------------------------------------------
240
241fn intent(link: &Value) -> Option<&Map<String, Value>> {
242    link.get("intent").and_then(|i| i.as_object())
243}
244
245/// An action/target field as a set of strings: a string or an array of
246/// strings. Anything else (null included) is an error.
247fn string_set(v: &Value) -> Result<BTreeSet<String>> {
248    match v {
249        Value::String(s) => Ok(BTreeSet::from([s.clone()])),
250        Value::Array(arr) => {
251            let mut set = BTreeSet::new();
252            for item in arr {
253                match item.as_str() {
254                    Some(s) => {
255                        set.insert(s.to_string());
256                    }
257                    None => {
258                        return Err(CoreError::Json(
259                            "action/target array must be strings".into(),
260                        ))
261                    }
262                }
263            }
264            Ok(set)
265        }
266        _ => Err(CoreError::Json(
267            "action/target must be a string or array of strings".into(),
268        )),
269    }
270}
271
272/// True when a resource could escape its parent once a server normalises it: a
273/// backslash, `%2F` or `%5C` in any case, an ASCII control character, or a `.`
274/// / `..` segment (with `%2e` read as `.`) in the part before the first `?` or
275/// `#`.
276pub fn resource_is_unsafe(resource: &str) -> bool {
277    let lowered = resource.to_ascii_lowercase();
278    if resource.contains('\\') || lowered.contains("%2f") || lowered.contains("%5c") {
279        return true;
280    }
281    if resource.bytes().any(|c| c < 0x20 || c == 0x7f) {
282        return true;
283    }
284    let path = lowered.split(['?', '#']).next().unwrap_or("");
285    path.split('/').any(|segment| {
286        let s = segment.replace("%2e", ".");
287        s == "." || s == ".."
288    })
289}
290
291/// True when `child` equals `parent` or extends it at a `/` boundary (trailing
292/// slashes ignored), and `child` is not an unsafe resource
293/// ([`resource_is_unsafe`]). "https://x/a2" is NOT under "https://x/a".
294pub fn resource_within(child: &str, parent: &str) -> bool {
295    if resource_is_unsafe(child) {
296        return false;
297    }
298    let c = child.trim_end_matches('/');
299    let p = parent.trim_end_matches('/');
300    if c == p {
301        return true;
302    }
303    c.len() > p.len() && c.starts_with(p) && c.as_bytes()[p.len()] == b'/'
304}
305
306/// Seconds in an ISO-8601 duration `P[nM][nD][T[nH][nM][nS]]`: ASCII digits
307/// only, each field at most 16 digits, the total at most 2^53 - 1, and at least
308/// one field. A month in the date part counts as 30 days. "P", "PT" and a
309/// trailing "T" are refused.
310pub fn parse_duration_seconds(s: &str) -> Result<i64> {
311    let bad = || {
312        CoreError::Json(format!(
313            "invalid duration: {:?}",
314            s.chars().take(64).collect::<String>()
315        ))
316    };
317    let b = s.as_bytes();
318    if b.first() != Some(&b'P') || s == "P" || s == "PT" || s.ends_with('T') {
319        return Err(bad());
320    }
321    // Units allowed in order: the date part, then the time part after 'T'.
322    const DATE: [(u8, i64); 2] = [(b'M', 2_592_000), (b'D', 86_400)];
323    const TIME: [(u8, i64); 3] = [(b'H', 3_600), (b'M', 60), (b'S', 1)];
324    let mut units: &[(u8, i64)] = &DATE;
325    let mut in_time = false;
326    let mut total: i64 = 0;
327    let mut saw_field = false;
328    let mut i = 1usize;
329    while i < b.len() {
330        if b[i] == b'T' {
331            if in_time {
332                return Err(bad());
333            }
334            in_time = true;
335            units = &TIME;
336            i += 1;
337            continue;
338        }
339        let start = i;
340        while i < b.len() && b[i].is_ascii_digit() {
341            i += 1;
342        }
343        let digits = &s[start..i];
344        if digits.is_empty() || i >= b.len() {
345            return Err(bad());
346        }
347        if digits.len() > MAX_DURATION_DIGITS {
348            return Err(CoreError::Json("duration field is too large".into()));
349        }
350        let unit = b[i];
351        let Some(pos) = units.iter().position(|(u, _)| *u == unit) else {
352            return Err(bad());
353        };
354        let n: i64 = digits.parse().map_err(|_| bad())?;
355        total = n
356            .checked_mul(units[pos].1)
357            .and_then(|v| total.checked_add(v))
358            .ok_or_else(|| CoreError::Json("duration is too large".into()))?;
359        units = &units[pos + 1..];
360        saw_field = true;
361        i += 1;
362    }
363    if !saw_field {
364        return Err(bad());
365    }
366    if total > MAX_SAFE_INTEGER {
367        return Err(CoreError::Json("duration is too large".into()));
368    }
369    Ok(total)
370}
371
372/// `(limit, window_seconds)` of a rate object: an integer limit from 0 to
373/// 2^53 - 1 and a positive duration window.
374fn parse_rate(rate: &Value) -> Result<(i64, i64)> {
375    let obj = rate
376        .as_object()
377        .ok_or_else(|| CoreError::Json("rate must be an object".into()))?;
378    let limit = obj
379        .get("limit")
380        .and_then(|v| as_int(v, 0, MAX_SAFE_INTEGER))
381        .ok_or_else(|| {
382            CoreError::Json("rate.limit must be an integer from 0 to 2^53 - 1".into())
383        })?;
384    let window = obj
385        .get("window")
386        .and_then(|v| v.as_str())
387        .ok_or_else(|| CoreError::Json("rate.window must be an ISO-8601 duration".into()))?;
388    let secs = parse_duration_seconds(window)?;
389    if secs <= 0 {
390        return Err(CoreError::Json("rate.window must be positive".into()));
391    }
392    Ok((limit, secs))
393}
394
395/// True when a child rate can never allow more events than its parent.
396///
397/// The parent allows `parent_limit` events in any `parent_window` seconds. A
398/// child window as long as the parent's (or longer) can spend its whole limit
399/// in one burst, so it needs `child_limit <= parent_limit`. A shorter child
400/// window repeats `ceil(parent_window / child_window)` times inside one parent
401/// window, so it also needs `child_limit * ceil(...) <= parent_limit`. Under
402/// 10 per hour: 240 per day is refused (240 at once), 1 per minute is refused
403/// (60 in an hour), 2 per 12 minutes is allowed (10 in an hour). Exact
404/// integers, no rounding, no overflow. Windows must be positive and limits
405/// not negative.
406pub fn rate_within(
407    child_limit: i64,
408    child_window: i64,
409    parent_limit: i64,
410    parent_window: i64,
411) -> bool {
412    // A negative limit is never a rate (parse_rate refuses one too).
413    if child_limit < 0 || parent_limit < 0 || child_window <= 0 || parent_window <= 0 {
414        return false;
415    }
416    let (cl, cw, pl, pw) = (
417        i128::from(child_limit),
418        i128::from(child_window),
419        i128::from(parent_limit),
420        i128::from(parent_window),
421    );
422    let repeats = (pw + cw - 1) / cw; // ceil for positive integers
423    cl <= pl && cl * repeats <= pl
424}
425
426/// Child policy must be equal to or stricter than the parent's. Numeric values
427/// narrow by the key's name: a key starting with "max" is a ceiling (the child
428/// may lower it, never raise it), a key starting with "min" is a floor (the
429/// child may raise it, never lower it), and any other numeric key must be
430/// restated unchanged. Other values must be equal in the JSON data model
431/// (`true` is not `1`). A parent key the child omits means the child dropped a
432/// constraint, which is broader, and is rejected.
433fn policy_not_weaker(parent: &Value, child: &Value) -> bool {
434    let (pobj, cobj) = match (parent.as_object(), child.as_object()) {
435        (Some(p), Some(c)) => (p, c),
436        _ => return false, // a policy that is not an object cannot be reasoned about
437    };
438    for (k, pv) in pobj {
439        let Some(cv) = cobj.get(k) else {
440            return false; // child dropped a parent constraint => weaker
441        };
442        match (is_number(pv), is_number(cv)) {
443            (true, true) => {
444                let (Some(pn), Some(cn)) = (pv.as_f64(), cv.as_f64()) else {
445                    return false;
446                };
447                let weaker = if k.starts_with("max") {
448                    cn > pn // a raised ceiling is broader
449                } else if k.starts_with("min") {
450                    cn < pn // a lowered floor is broader
451                } else {
452                    !json_equal(pv, cv) // unknown direction: must be restated
453                };
454                if weaker {
455                    return false;
456                }
457            }
458            (true, false) | (false, true) => return false, // type mismatch
459            (false, false) => {
460                if !json_equal(pv, cv) {
461                    return false; // non-numeric must match exactly
462                }
463            }
464        }
465    }
466    true
467}
468
469/// A link's window bound in nanoseconds: absent is None; present but null,
470/// not a string, or not a protocol time is an error.
471fn bound(link: &Value, key: &str) -> Result<Option<i128>> {
472    match link.get(key) {
473        None => Ok(None),
474        Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
475        Some(_) => Err(CoreError::Json(format!("{key} must be a time string"))),
476    }
477}
478
479fn window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
480    Ok((bound(link, "validFrom")?, bound(link, "validUntil")?))
481}
482
483/// The first dimension a link writes down in a form that cannot be compared,
484/// or None. A present dimension must be well formed: action and target a
485/// string or an array of strings; resource a string that is not unsafe;
486/// validFrom / validUntil protocol times; rate an object with an integer limit
487/// and a positive duration window; policy an object nested no deeper than 128
488/// levels. `null` is malformed everywhere.
489pub fn malformed_dimension(link: &Value) -> Option<Dimension> {
490    crate::nesting::deep_guard!(Some(Dimension::Action); link);
491    let Some(obj) = link.as_object() else {
492        return Some(Dimension::Action);
493    };
494    let intent = match obj.get("intent") {
495        None => None,
496        Some(Value::Object(i)) => Some(i),
497        Some(_) => return Some(Dimension::Action),
498    };
499    if let Some(i) = intent {
500        for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
501            if let Some(v) = i.get(key) {
502                if string_set(v).is_err() {
503                    return Some(dim);
504                }
505            }
506        }
507        if let Some(res) = i.get("resource") {
508            match res.as_str() {
509                Some(r) if !resource_is_unsafe(r) => {}
510                _ => return Some(Dimension::Resource),
511            }
512        }
513    }
514    if window(link).is_err() {
515        return Some(Dimension::Time);
516    }
517    if let Some(rate) = obj.get("rate") {
518        if parse_rate(rate).is_err() {
519            return Some(Dimension::Rate);
520        }
521    }
522    if let Some(policy) = obj.get("policy") {
523        if !policy.is_object() || json_nesting_exceeds(policy, MAX_JSON_NESTING) {
524            return Some(Dimension::Policy);
525        }
526    }
527    None
528}
529
530// --------------------------------------------------------------------------
531// Non-expansion between an adjacent (parent, child) pair
532// --------------------------------------------------------------------------
533
534/// Verify that `child` does not broaden `parent` on any dimension. Returns the
535/// offending [`Dimension`] on failure. A malformed dimension on either side
536/// ([`malformed_dimension`]) is reported as that dimension: a child cannot
537/// erase a bound with `null`, and nothing can be shown to sit inside a
538/// malformed parent bound.
539pub fn non_expansion(parent: &Value, child: &Value) -> core::result::Result<(), Dimension> {
540    crate::nesting::deep_guard!(Err(Dimension::Action); parent, child);
541    if let Some(dim) = malformed_dimension(child) {
542        return Err(dim);
543    }
544    if let Some(dim) = malformed_dimension(parent) {
545        return Err(dim);
546    }
547    let empty = Map::new();
548    let p_intent = intent(parent).unwrap_or(&empty);
549    let c_intent = intent(child).unwrap_or(&empty);
550
551    // action / target: the child's set must be a subset of the parent's.
552    for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
553        if let (Some(c), Some(p)) = (c_intent.get(key), p_intent.get(key)) {
554            match (string_set(c), string_set(p)) {
555                (Ok(cs), Ok(ps)) if cs.is_subset(&ps) => {}
556                _ => return Err(dim),
557            }
558        }
559    }
560
561    // resource: the child's resource must be within the parent's.
562    if let (Some(c), Some(p)) = (c_intent.get("resource"), p_intent.get("resource")) {
563        match (c.as_str(), p.as_str()) {
564            (Some(cr), Some(pr)) if resource_within(cr, pr) => {}
565            _ => return Err(Dimension::Resource),
566        }
567    }
568
569    // time: the child's window must be within the parent's (to the nanosecond).
570    let (Ok((cf, cu)), Ok((pf, pu))) = (window(child), window(parent)) else {
571        return Err(Dimension::Time);
572    };
573    if let (Some(f), Some(pf)) = (cf, pf) {
574        if f < pf {
575            return Err(Dimension::Time);
576        }
577    }
578    if let (Some(u), Some(pu)) = (cu, pu) {
579        if u > pu {
580            return Err(Dimension::Time);
581        }
582    }
583
584    // rate: never a burst the parent forbids, in exact integers.
585    if let (Some(cr), Some(pr)) = (child.get("rate"), parent.get("rate")) {
586        let (Ok((c_limit, c_secs)), Ok((p_limit, p_secs))) = (parse_rate(cr), parse_rate(pr))
587        else {
588            return Err(Dimension::Rate);
589        };
590        if !rate_within(c_limit, c_secs, p_limit, p_secs) {
591            return Err(Dimension::Rate);
592        }
593    }
594
595    // policy: the child's policy must be equal to or stricter than the parent's.
596    let p_pol = parent.get("policy").filter(|p| !p.is_null());
597    if let (Some(cp), Some(pp)) = (child.get("policy"), p_pol) {
598        if !policy_not_weaker(pp, cp) {
599            return Err(Dimension::Policy);
600        }
601    }
602
603    // spend: an action's intent.amount stays within the parent's maxSpend.
604    if let Some(cap) = p_pol
605        .and_then(|p| p.as_object())
606        .and_then(|p| p.get("maxSpend"))
607    {
608        if let Some(amount) = c_intent.get("amount") {
609            match (amount.as_f64(), cap.as_f64()) {
610                (Some(a), Some(c)) if a <= c => {}
611                _ => return Err(Dimension::Policy),
612            }
613        }
614    }
615
616    Ok(())
617}
618
619/// The child's effective capability: any dimension it omits is inherited
620/// unchanged from its parent's effective capability (Specification 9.2).
621/// `amount` is per action and is never inherited.
622pub fn inherit(parent_effective: &Value, child: &Value) -> Value {
623    crate::nesting::deep_guard!(Value::Null; parent_effective, child);
624    let mut out = child.as_object().cloned().unwrap_or_default();
625    let mut c_intent = child
626        .get("intent")
627        .and_then(|i| i.as_object())
628        .cloned()
629        .unwrap_or_default();
630    if let Some(p_intent) = parent_effective.get("intent").and_then(|i| i.as_object()) {
631        for k in ["action", "target", "resource"] {
632            if !c_intent.contains_key(k) {
633                if let Some(v) = p_intent.get(k) {
634                    c_intent.insert(k.into(), v.clone());
635                }
636            }
637        }
638    }
639    out.insert("intent".into(), Value::Object(c_intent));
640    for k in ["rate", "policy", "validFrom", "validUntil"] {
641        let absent = out.get(k).map(|v| v.is_null()).unwrap_or(true);
642        if absent {
643            if let Some(v) = parent_effective.get(k).filter(|v| !v.is_null()) {
644                out.insert(k.into(), v.clone());
645            }
646        }
647    }
648    Value::Object(out)
649}
650
651/// Walk root to leaf comparing each step against its parent's EFFECTIVE
652/// capability (inherited dimensions included). Returns the first offending
653/// dimension; a malformed dimension on the root is reported too.
654pub fn first_broader_step(views: &[Value]) -> core::result::Result<(), Dimension> {
655    crate::nesting::deep_guard!(Err(Dimension::Action); views);
656    let Some(first) = views.first() else {
657        return Ok(());
658    };
659    if let Some(dim) = malformed_dimension(first) {
660        return Err(dim);
661    }
662    let mut effective = first.clone();
663    for child in &views[1..] {
664        non_expansion(&effective, child)?;
665        effective = inherit(&effective, child);
666    }
667    Ok(())
668}
669
670// --------------------------------------------------------------------------
671// Full chain validation
672// --------------------------------------------------------------------------
673
674fn link_str<'a>(link: &'a Value, key: &str) -> Option<&'a str> {
675    link.get(key).and_then(|v| v.as_str())
676}
677
678fn malformed(detail: impl Into<String>) -> DelegationReject {
679    DelegationReject::Malformed {
680        detail: detail.into(),
681    }
682}
683
684/// Validate a delegation chain ordered root -> leaf under the v1.7 rules.
685///
686/// * `trusted_roots`: `None` skips the root-trust check (the caller anchors
687///   trust elsewhere); a list names the trusted roots (a bare domain stands
688///   for its did:web), and an empty list trusts nobody.
689/// * `revoked_link_indices` are links the caller has resolved as revoked
690///   (credential- or DID-level); any hit rejects the whole chain (cascade).
691/// * `budget` caps the verifier's work; `None` fields are unlimited. There is
692///   no default depth limit; an encoded chain over 1 MiB is always refused.
693/// * `clock_skew_seconds` must be 0 to 120.
694///
695/// Returns `Ok(())` when the chain is valid, or the first [`DelegationReject`].
696pub fn validate_chain(
697    chain: &[Value],
698    trusted_roots: Option<&[String]>,
699    revoked_link_indices: &[usize],
700    budget: &VerifierBudget,
701    now_iso: &str,
702    clock_skew_seconds: i64,
703) -> DResult {
704    crate::nesting::deep_guard!(Err(malformed(crate::nesting::TOO_DEEP)); chain);
705    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
706        return Err(malformed(format!(
707            "clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
708        )));
709    }
710    let skew = i128::from(clock_skew_seconds) * NS_PER_SECOND;
711    let now = parse_protocol_time_ns(now_iso).map_err(|e| malformed(format!("nowIso: {e}")))?;
712    if chain.is_empty() {
713        return Err(malformed("empty delegation chain"));
714    }
715
716    // Verifier budget, before anything else is looked at.
717    let chain_value = Value::Array(chain.to_vec());
718    match chain_budget_exceeded(&chain_value, budget.max_depth) {
719        Ok(None) => {}
720        Ok(Some(limit)) => {
721            return Err(DelegationReject::VerifierBudgetExceeded {
722                limit: limit.into(),
723            })
724        }
725        Err(detail) => return Err(malformed(detail)),
726    }
727
728    // Every link must be an object with issuer and subject strings, and an
729    // intent object when it has one.
730    for (i, link) in chain.iter().enumerate() {
731        let shape_ok = link.is_object()
732            && link_str(link, "issuer").is_some()
733            && link_str(link, "subject").is_some()
734            && link.get("intent").map(|v| v.is_object()).unwrap_or(true);
735        if !shape_ok {
736            return Err(malformed(format!("link {i} malformed")));
737        }
738    }
739
740    // Root trust.
741    if let Some(roots) = trusted_roots {
742        let root_issuer = link_str(&chain[0], "issuer").unwrap_or("");
743        if !roots
744            .iter()
745            .any(|r| crate::delegation::root_matches(r, root_issuer))
746        {
747            return Err(DelegationReject::UntrustedPrincipal);
748        }
749    }
750
751    // Cascade revocation: a revoked link invalidates the whole chain.
752    if let Some(&idx) = revoked_link_indices.iter().min() {
753        if idx < chain.len() {
754            return Err(DelegationReject::DelegationRevoked { link_index: idx });
755        }
756    }
757
758    // Linkage and non-expansion for each step against its parent's effective
759    // capability (dimensions a link omits are inherited).
760    if let Some(dimension) = malformed_dimension(&chain[0]) {
761        return Err(DelegationReject::ScopeExceedsParent { dimension });
762    }
763    let mut effective = chain[0].clone();
764    let mut windows = vec![window(&chain[0]).map_err(|e| malformed(e.to_string()))?];
765    for i in 1..chain.len() {
766        let parent = &chain[i - 1];
767        let child = &chain[i];
768        if link_str(parent, "subject") != link_str(child, "issuer") {
769            return Err(DelegationReject::SubjectIssuerMismatch { link_index: i });
770        }
771        non_expansion(&effective, child)
772            .map_err(|dimension| DelegationReject::ScopeExceedsParent { dimension })?;
773        effective = inherit(&effective, child);
774        windows.push(window(&effective).map_err(|e| malformed(e.to_string()))?);
775    }
776
777    // Effective validity window: the latest start and the earliest end.
778    let eff_start = windows.iter().filter_map(|w| w.0).max();
779    let eff_end = windows.iter().filter_map(|w| w.1).min();
780    if let (Some(f), Some(u)) = (eff_start, eff_end) {
781        if f > u {
782            return Err(DelegationReject::OutsideValidityWindow);
783        }
784    }
785    if let Some(f) = eff_start {
786        if now < f - skew {
787            return Err(DelegationReject::OutsideValidityWindow);
788        }
789    }
790    if let Some(u) = eff_end {
791        if now > u + skew {
792            return Err(DelegationReject::OutsideValidityWindow);
793        }
794    }
795
796    // Cumulative TTL over each link's effective (inherited) window. A link with
797    // an open end has no finite TTL, so a TTL budget refuses it.
798    if let Some(max) = budget.max_cumulative_ttl_seconds {
799        let exceeded = || DelegationReject::VerifierBudgetExceeded {
800            limit: "cumulative_ttl".into(),
801        };
802        let mut total: i128 = 0;
803        for (vf, vu) in &windows {
804            let (Some(f), Some(u)) = (vf, vu) else {
805                return Err(exceeded());
806            };
807            total += (u - f).max(0);
808        }
809        if total > i128::from(max) * NS_PER_SECOND {
810            return Err(exceeded());
811        }
812    }
813
814    Ok(())
815}
816
817// --------------------------------------------------------------------------
818// JSON boundary for the SDK bindings (uniffi / wasm)
819// --------------------------------------------------------------------------
820
821/// Validate a delegation chain from a single JSON request, returning a JSON
822/// verdict. Infallible: malformed input yields a `malformed_delegation` verdict
823/// rather than an error, so every caller gets a uniform verdict shape.
824///
825/// Request:  `{ "chain": [..links..], "trustedRoots"?: [str], "revokedIndices"?:
826/// [int], "budget"?: {"maxDepth"?: int, "maxCumulativeTtlSeconds"?: int},
827/// "nowIso": "..", "clockSkewSeconds"?: int (0..120, default 30) }`. An option
828/// that is present must be well formed (`null` included): integers are whole
829/// numbers (2 and 2.0 are both 2) in range, `trustedRoots` is a list of
830/// strings. There is no default depth limit.
831///
832/// Response: `{"valid": true}` or `{"valid": false, "code": "..", ..detail..}`.
833pub fn validate_chain_json(request_json: &str) -> String {
834    if let Err(e) = crate::nesting::check_text(request_json.as_bytes()) {
835        return verdict_malformed(&format!("request {e}"));
836    }
837    let req: Value = match serde_json::from_str(request_json) {
838        Ok(v) => v,
839        Err(e) => return verdict_malformed(&format!("request json: {e}")),
840    };
841    let Some(req) = req.as_object() else {
842        return verdict_malformed("request must be a JSON object");
843    };
844    let chain: Vec<Value> = match req.get("chain").and_then(|v| v.as_array()) {
845        Some(c) => c.clone(),
846        None => return verdict_malformed("missing chain array"),
847    };
848    for key in [
849        "trustedRoots",
850        "revokedIndices",
851        "budget",
852        "nowIso",
853        "clockSkewSeconds",
854    ] {
855        if matches!(req.get(key), Some(Value::Null)) {
856            return verdict_malformed(&format!("{key} must not be null"));
857        }
858    }
859    let trusted_roots: Option<Vec<String>> = match req.get("trustedRoots") {
860        None => None,
861        Some(Value::Array(a)) => {
862            let mut roots = Vec::with_capacity(a.len());
863            for r in a {
864                match r.as_str() {
865                    Some(s) => roots.push(s.to_string()),
866                    None => return verdict_malformed("trustedRoots must be a list of strings"),
867                }
868            }
869            Some(roots)
870        }
871        Some(_) => return verdict_malformed("trustedRoots must be a list of strings"),
872    };
873    let revoked: Vec<usize> = match req.get("revokedIndices") {
874        None => Vec::new(),
875        Some(Value::Array(a)) => {
876            let mut out = Vec::with_capacity(a.len());
877            for v in a {
878                match as_int(v, 0, MAX_SAFE_INTEGER) {
879                    Some(n) => out.push(n as usize),
880                    None => {
881                        return verdict_malformed(
882                            "revokedIndices must be integers from 0 to 2^53 - 1",
883                        )
884                    }
885                }
886            }
887            out
888        }
889        Some(_) => return verdict_malformed("revokedIndices must be a list of integers"),
890    };
891    let mut budget = VerifierBudget::default();
892    match req.get("budget") {
893        None => {}
894        Some(Value::Object(b)) => {
895            for key in ["maxDepth", "maxCumulativeTtlSeconds"] {
896                if let Some(v) = b.get(key) {
897                    let Some(n) = as_int(v, 0, MAX_SAFE_INTEGER) else {
898                        return verdict_malformed(&format!(
899                            "budget.{key} must be an integer from 0 to 2^53 - 1"
900                        ));
901                    };
902                    if key == "maxDepth" {
903                        budget.max_depth = Some(n as usize);
904                    } else {
905                        budget.max_cumulative_ttl_seconds = Some(n);
906                    }
907                }
908            }
909        }
910        Some(_) => return verdict_malformed("budget must be an object"),
911    }
912    let skew = match req.get("clockSkewSeconds") {
913        None => 30,
914        Some(v) => match as_int(v, 0, MAX_CLOCK_SKEW_SECONDS) {
915            Some(n) => n,
916            None => {
917                return verdict_malformed(&format!(
918                    "clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
919                ))
920            }
921        },
922    };
923    let now = match req.get("nowIso") {
924        None => "",
925        Some(Value::String(s)) => s.as_str(),
926        Some(_) => return verdict_malformed("nowIso must be a time string"),
927    };
928
929    match validate_chain(
930        &chain,
931        trusted_roots.as_deref(),
932        &revoked,
933        &budget,
934        now,
935        skew,
936    ) {
937        Ok(()) => json!({ "valid": true }).to_string(),
938        Err(r) => reject_to_json(&r).to_string(),
939    }
940}
941
942fn verdict_malformed(detail: &str) -> String {
943    json!({ "valid": false, "code": "malformed_delegation", "detail": detail }).to_string()
944}
945
946fn reject_to_json(r: &DelegationReject) -> Value {
947    let mut v = json!({ "valid": false, "code": r.code() });
948    let o = v.as_object_mut().unwrap();
949    match r {
950        DelegationReject::ScopeExceedsParent { dimension } => {
951            o.insert("dimension".into(), json!(dimension.as_str()));
952        }
953        DelegationReject::VerifierBudgetExceeded { limit } => {
954            o.insert("limit".into(), json!(limit));
955        }
956        DelegationReject::DelegationRevoked { link_index }
957        | DelegationReject::SubjectIssuerMismatch { link_index } => {
958            o.insert("linkIndex".into(), json!(link_index));
959        }
960        DelegationReject::Malformed { detail } => {
961            o.insert("detail".into(), json!(detail));
962        }
963        DelegationReject::UntrustedPrincipal | DelegationReject::OutsideValidityWindow => {}
964    }
965    v
966}
967
968/// A grant's effective capability: its own capability view, inheriting from
969/// the grants in its own embedded delegation chain (root first).
970pub fn effective_capability(credential: &Value, include_time: bool) -> Value {
971    crate::nesting::deep_guard!(Value::Null; credential);
972    let mut effective: Option<Value> = None;
973    if let Some(links) = credential
974        .get("credentialSubject")
975        .and_then(|s| s.get("delegationChain"))
976        .and_then(Value::as_array)
977    {
978        for link in links {
979            let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
980                continue;
981            };
982            let view = crate::delegation::capability_view(grant, include_time);
983            effective = Some(match effective {
984                None => view,
985                Some(e) => inherit(&e, &view),
986            });
987        }
988    }
989    let own = crate::delegation::capability_view(credential, include_time);
990    match effective {
991        None => own,
992        Some(e) => inherit(&e, &own),
993    }
994}
995
996/// The capability rules a binding's own walks use, as one JSON entry point:
997/// `{"fn": name, ...arguments}` to `{"ok": value}`. The names and arguments:
998///
999/// - `capabilityView` (`credential`, `includeTime`) -> the view;
1000/// - `nonExpansion` (`parent`, `child`) -> the broader dimension, or null;
1001/// - `inherit` (`parentEffective`, `child`) -> the child's effective view;
1002/// - `encodedSize` (`value`) -> the UTF-8 length of its JCS form;
1003/// - `chainBudgetExceeded` (`chain`, `maxDepth`) -> "depth", "size" or null
1004///   (`{"error"}` for a chain that nests too deeply);
1005/// - `resourceIsUnsafe` (`resource`), `resourceWithin` (`child`, `parent`)
1006///   -> true or false;
1007/// - `parseDurationSeconds` (`value`) -> seconds (`{"error"}` when invalid);
1008/// - `rateWithin` (`childLimit`, `childWindow`, `parentLimit`,
1009///   `parentWindow`) -> true or false;
1010/// - `malformedDimension` (`link`), `firstBroaderStep` (`views`) -> the
1011///   dimension, or null;
1012/// - `effectiveCapability` (`credential`, `includeTime`) -> the view.
1013pub fn rules_json(request: &Value) -> Result<Value> {
1014    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
1015    let arg = |name: &str| request.get(name).unwrap_or(&Value::Null);
1016    let name = request.get("fn").and_then(Value::as_str).unwrap_or("");
1017    let ok = match name {
1018        "capabilityView" => crate::delegation::capability_view(
1019            arg("credential"),
1020            arg("includeTime").as_bool().unwrap_or(true),
1021        ),
1022        "nonExpansion" => match non_expansion(arg("parent"), arg("child")) {
1023            Ok(()) => Value::Null,
1024            Err(dim) => json!(dim.as_str()),
1025        },
1026        "inherit" => inherit(arg("parentEffective"), arg("child")),
1027        "encodedSize" => json!(encoded_size(arg("value"))),
1028        "chainBudgetExceeded" => {
1029            let max_depth = arg("maxDepth")
1030                .as_u64()
1031                .and_then(|d| usize::try_from(d).ok());
1032            match chain_budget_exceeded(arg("chain"), max_depth) {
1033                Ok(limit) => json!(limit),
1034                Err(e) => return Ok(json!({ "error": e })),
1035            }
1036        }
1037        "resourceIsUnsafe" => json!(resource_is_unsafe(arg("resource").as_str().unwrap_or(""))),
1038        "resourceWithin" => json!(resource_within(
1039            arg("child").as_str().unwrap_or(""),
1040            arg("parent").as_str().unwrap_or("")
1041        )),
1042        "parseDurationSeconds" => match arg("value").as_str() {
1043            None => return Ok(json!({ "error": "a duration is a string" })),
1044            Some(s) => match parse_duration_seconds(s) {
1045                Ok(n) => json!(n),
1046                Err(e) => {
1047                    let msg = e.to_string();
1048                    let msg = msg.strip_prefix("json error: ").unwrap_or(&msg).to_string();
1049                    return Ok(json!({ "error": msg }));
1050                }
1051            },
1052        },
1053        "rateWithin" => {
1054            let n = |k: &str| arg(k).as_i64().unwrap_or(0);
1055            json!(rate_within(
1056                n("childLimit"),
1057                n("childWindow"),
1058                n("parentLimit"),
1059                n("parentWindow")
1060            ))
1061        }
1062        "malformedDimension" => json!(malformed_dimension(arg("link")).map(|d| d.as_str())),
1063        "firstBroaderStep" => {
1064            let views = arg("views").as_array().cloned().unwrap_or_default();
1065            match first_broader_step(&views) {
1066                Ok(()) => Value::Null,
1067                Err(dim) => json!(dim.as_str()),
1068            }
1069        }
1070        "effectiveCapability" => effective_capability(
1071            arg("credential"),
1072            arg("includeTime").as_bool().unwrap_or(true),
1073        ),
1074        other => {
1075            return Err(CoreError::Json(format!(
1076                "unknown capability rule {:?}",
1077                other.chars().take(40).collect::<String>()
1078            )))
1079        }
1080    };
1081    Ok(json!({ "ok": ok }))
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086    use super::*;
1087    use serde_json::json;
1088
1089    #[test]
1090    fn rules_json_answers_every_rule_a_binding_calls() {
1091        let ok = |req: Value| rules_json(&req).unwrap()["ok"].clone();
1092        assert_eq!(
1093            ok(json!({"fn": "resourceWithin", "child": "https://x/a/b", "parent": "https://x/a"})),
1094            json!(true)
1095        );
1096        assert_eq!(
1097            ok(
1098                json!({"fn": "resourceWithin", "child": "https://x/a/../b", "parent": "https://x/a"})
1099            ),
1100            json!(false)
1101        );
1102        assert_eq!(
1103            ok(json!({"fn": "resourceIsUnsafe", "resource": "https://x/a%2fb"})),
1104            json!(true)
1105        );
1106        assert_eq!(
1107            ok(json!({"fn": "parseDurationSeconds", "value": "PT1H"})),
1108            json!(3600)
1109        );
1110        assert!(
1111            rules_json(&json!({"fn": "parseDurationSeconds", "value": "PT"})).unwrap()["error"]
1112                .is_string()
1113        );
1114        assert!(
1115            rules_json(&json!({"fn": "parseDurationSeconds", "value": 5})).unwrap()["error"]
1116                .is_string()
1117        );
1118        assert_eq!(
1119            ok(
1120                json!({"fn": "rateWithin", "childLimit": 2, "childWindow": 720, "parentLimit": 10, "parentWindow": 3600})
1121            ),
1122            json!(true)
1123        );
1124        assert_eq!(
1125            ok(
1126                json!({"fn": "rateWithin", "childLimit": -1, "childWindow": 1, "parentLimit": 1, "parentWindow": 1})
1127            ),
1128            json!(false)
1129        );
1130        assert_eq!(
1131            ok(json!({"fn": "chainBudgetExceeded", "chain": [1, 2, 3], "maxDepth": 2})),
1132            json!("depth")
1133        );
1134        assert_eq!(
1135            ok(json!({"fn": "chainBudgetExceeded", "chain": [1]})),
1136            Value::Null
1137        );
1138        assert_eq!(
1139            ok(json!({"fn": "malformedDimension", "link": {"intent": {"action": null}}})),
1140            json!("action")
1141        );
1142        let views = json!([{"intent": {"action": "read"}}, {"intent": {"action": "write"}}]);
1143        assert_eq!(
1144            ok(json!({"fn": "firstBroaderStep", "views": views})),
1145            json!("action")
1146        );
1147        let grant =
1148            json!({"credentialSubject": {"intent": {"action": "read", "resource": "https://x/a"}}});
1149        let cred = json!({"credentialSubject": {"intent": {"resource": "https://x/a/b"},
1150            "delegationChain": [{"parentCredential": grant}]}});
1151        let eff =
1152            ok(json!({"fn": "effectiveCapability", "credential": cred, "includeTime": false}));
1153        assert_eq!(eff["intent"]["action"], json!("read"));
1154        assert_eq!(eff["intent"]["resource"], json!("https://x/a/b"));
1155        assert!(rules_json(&json!({"fn": "nope"})).is_err());
1156    }
1157
1158    fn link(issuer: &str, subject: &str, intent: Value) -> Value {
1159        json!({
1160            "issuer": issuer,
1161            "subject": subject,
1162            "intent": intent,
1163            "validFrom": "2026-04-26T09:00:00Z",
1164            "validUntil": "2026-04-26T12:00:00Z"
1165        })
1166    }
1167
1168    fn now() -> &'static str {
1169        "2026-04-26T10:00:00Z"
1170    }
1171
1172    #[test]
1173    fn restate_unchanged_is_valid() {
1174        let i = json!({"action":"read","target":"t","resource":"https://x/a"});
1175        let chain = vec![
1176            link("did:web:root", "did:web:a", i.clone()),
1177            link("did:web:a", "did:web:b", i.clone()),
1178        ];
1179        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1180    }
1181
1182    #[test]
1183    fn resource_narrowing_is_valid() {
1184        let chain = vec![
1185            link(
1186                "did:web:root",
1187                "did:web:a",
1188                json!({"resource":"https://x/a"}),
1189            ),
1190            link(
1191                "did:web:a",
1192                "did:web:b",
1193                json!({"resource":"https://x/a/b"}),
1194            ),
1195        ];
1196        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1197    }
1198
1199    #[test]
1200    fn resource_widening_rejected_naming_dimension() {
1201        let chain = vec![
1202            link(
1203                "did:web:root",
1204                "did:web:a",
1205                json!({"resource":"https://x/a/b"}),
1206            ),
1207            link("did:web:a", "did:web:b", json!({"resource":"https://x/a"})),
1208        ];
1209        let err =
1210            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1211        assert_eq!(err.code(), "scope_exceeds_parent");
1212        assert_eq!(
1213            err,
1214            DelegationReject::ScopeExceedsParent {
1215                dimension: Dimension::Resource
1216            }
1217        );
1218    }
1219
1220    #[test]
1221    fn sibling_prefix_is_not_sub_resource() {
1222        assert!(!resource_within("https://x/a2", "https://x/a"));
1223        assert!(resource_within("https://x/a/b", "https://x/a"));
1224        assert!(resource_within("https://x/a", "https://x/a/"));
1225    }
1226
1227    #[test]
1228    fn action_superset_rejected() {
1229        let chain = vec![
1230            link("did:web:root", "did:web:a", json!({"action":"read"})),
1231            link("did:web:a", "did:web:b", json!({"action":["read","write"]})),
1232        ];
1233        let err =
1234            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1235        assert_eq!(
1236            err,
1237            DelegationReject::ScopeExceedsParent {
1238                dimension: Dimension::Action
1239            }
1240        );
1241    }
1242
1243    #[test]
1244    fn action_subset_ok() {
1245        let chain = vec![
1246            link(
1247                "did:web:root",
1248                "did:web:a",
1249                json!({"action":["read","write"]}),
1250            ),
1251            link("did:web:a", "did:web:b", json!({"action":"read"})),
1252        ];
1253        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1254    }
1255
1256    #[test]
1257    fn rate_widening_rejected() {
1258        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1259        a["rate"] = json!({"limit":100,"window":"PT1H"});
1260        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1261        b["rate"] = json!({"limit":100,"window":"PT30M"}); // twice the events/sec
1262        let chain = vec![a, b];
1263        let err =
1264            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1265        assert_eq!(
1266            err,
1267            DelegationReject::ScopeExceedsParent {
1268                dimension: Dimension::Rate
1269            }
1270        );
1271    }
1272
1273    #[test]
1274    fn rate_narrowing_ok() {
1275        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1276        a["rate"] = json!({"limit":100,"window":"PT1H"});
1277        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1278        b["rate"] = json!({"limit":50,"window":"PT1H"});
1279        let chain = vec![a, b];
1280        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1281    }
1282
1283    #[test]
1284    fn policy_weakening_rejected() {
1285        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1286        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
1287        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1288        b["policy"] = json!({"minHeartbeatAgeSeconds":100}); // weaker
1289        let chain = vec![a, b];
1290        let err =
1291            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1292        assert_eq!(
1293            err,
1294            DelegationReject::ScopeExceedsParent {
1295                dimension: Dimension::Policy
1296            }
1297        );
1298    }
1299
1300    #[test]
1301    fn policy_dropping_constraint_rejected() {
1302        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1303        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
1304        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1305        b["policy"] = json!({"unrelated":true}); // dropped the parent's constraint
1306        let chain = vec![a, b];
1307        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_err());
1308    }
1309
1310    #[test]
1311    fn time_widening_rejected() {
1312        let chain = vec![
1313            json!({"issuer":"did:web:root","subject":"did:web:a","intent":{"action":"read"},
1314                   "validFrom":"2026-04-26T10:00:00Z","validUntil":"2026-04-26T11:00:00Z"}),
1315            json!({"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"},
1316                   "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T12:00:00Z"}),
1317        ];
1318        let err = validate_chain(
1319            &chain,
1320            None,
1321            &[],
1322            &VerifierBudget::default(),
1323            "2026-04-26T10:30:00Z",
1324            30,
1325        )
1326        .unwrap_err();
1327        assert_eq!(
1328            err,
1329            DelegationReject::ScopeExceedsParent {
1330                dimension: Dimension::Time
1331            }
1332        );
1333    }
1334
1335    #[test]
1336    fn subject_issuer_mismatch_rejected() {
1337        let i = json!({"action":"read"});
1338        let chain = vec![
1339            link("did:web:root", "did:web:a", i.clone()),
1340            link("did:web:WRONG", "did:web:b", i.clone()),
1341        ];
1342        let err =
1343            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1344        assert_eq!(
1345            err,
1346            DelegationReject::SubjectIssuerMismatch { link_index: 1 }
1347        );
1348    }
1349
1350    #[test]
1351    fn untrusted_root_rejected() {
1352        let i = json!({"action":"read"});
1353        let chain = vec![link("did:web:root", "did:web:a", i)];
1354        let err = validate_chain(
1355            &chain,
1356            Some(&["did:web:other".to_string()]),
1357            &[],
1358            &VerifierBudget::default(),
1359            now(),
1360            30,
1361        )
1362        .unwrap_err();
1363        assert_eq!(err, DelegationReject::UntrustedPrincipal);
1364    }
1365
1366    #[test]
1367    fn cascade_revocation_rejects_whole_chain() {
1368        let i = json!({"action":"read"});
1369        let chain = vec![
1370            link("did:web:root", "did:web:a", i.clone()),
1371            link("did:web:a", "did:web:b", i.clone()),
1372            link("did:web:b", "did:web:c", i.clone()),
1373        ];
1374        // middle link revoked
1375        let err =
1376            validate_chain(&chain, None, &[1], &VerifierBudget::default(), now(), 30).unwrap_err();
1377        assert_eq!(err, DelegationReject::DelegationRevoked { link_index: 1 });
1378    }
1379
1380    #[test]
1381    fn budget_depth_exceeded() {
1382        let i = json!({"action":"read"});
1383        let chain = vec![
1384            link("did:web:root", "did:web:a", i.clone()),
1385            link("did:web:a", "did:web:b", i.clone()),
1386            link("did:web:b", "did:web:c", i.clone()),
1387        ];
1388        let budget = VerifierBudget {
1389            max_depth: Some(2),
1390            max_cumulative_ttl_seconds: None,
1391        };
1392        let err = validate_chain(&chain, None, &[], &budget, now(), 30).unwrap_err();
1393        assert_eq!(
1394            err,
1395            DelegationReject::VerifierBudgetExceeded {
1396                limit: "depth".into()
1397            }
1398        );
1399    }
1400
1401    #[test]
1402    fn deep_but_attenuating_chain_is_valid_without_depth_cap() {
1403        // Ten hops, each restating the same authority: valid now that the fixed
1404        // depth limit is gone (this is the whole point of v1.7).
1405        let mut chain = Vec::new();
1406        let i = json!({"action":"read","resource":"https://x/a"});
1407        for n in 0..10 {
1408            let issuer = if n == 0 {
1409                "did:web:root".to_string()
1410            } else {
1411                format!("did:web:h{}", n - 1)
1412            };
1413            let subject = format!("did:web:h{n}");
1414            chain.push(link(&issuer, &subject, i.clone()));
1415        }
1416        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1417    }
1418
1419    #[test]
1420    fn now_outside_effective_window_rejected() {
1421        let chain = vec![link("did:web:root", "did:web:a", json!({"action":"read"}))];
1422        let err = validate_chain(
1423            &chain,
1424            None,
1425            &[],
1426            &VerifierBudget::default(),
1427            "2026-04-26T20:00:00Z",
1428            30,
1429        )
1430        .unwrap_err();
1431        assert_eq!(err, DelegationReject::OutsideValidityWindow);
1432    }
1433
1434    #[test]
1435    fn absent_child_dimension_inherits_and_passes() {
1436        let chain = vec![
1437            link(
1438                "did:web:root",
1439                "did:web:a",
1440                json!({"action":"read","resource":"https://x/a"}),
1441            ),
1442            link(
1443                "did:web:a",
1444                "did:web:b",
1445                json!({"resource":"https://x/a/b"}),
1446            ), // action omitted => inherit
1447        ];
1448        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1449    }
1450
1451    #[test]
1452    fn duration_parser() {
1453        assert_eq!(parse_duration_seconds("PT1H").unwrap(), 3600);
1454        assert_eq!(parse_duration_seconds("PT30M").unwrap(), 1800);
1455        assert_eq!(parse_duration_seconds("PT1H30M15S").unwrap(), 5415);
1456        assert_eq!(parse_duration_seconds("P1D").unwrap(), 86400);
1457        assert!(parse_duration_seconds("1H").is_err());
1458        assert!(parse_duration_seconds("PT").is_err());
1459    }
1460
1461    #[test]
1462    fn duration_parser_is_strict_and_never_overflows() {
1463        assert_eq!(parse_duration_seconds("P1M").unwrap(), 2_592_000);
1464        assert_eq!(parse_duration_seconds("P1DT1S").unwrap(), 86_401);
1465        for bad in [
1466            "P",
1467            "PT",
1468            "P1DT",
1469            "P1H",
1470            "PT1D",
1471            "P1D1M",
1472            "PT1S1M",
1473            "P\u{0661}D",
1474            "PT-1S",
1475            "PT1.5S",
1476            "p1D",
1477            "P1DTT1S",
1478        ] {
1479            assert!(parse_duration_seconds(bad).is_err(), "{bad}");
1480        }
1481        // Huge fields refuse cleanly (no panic, no wrap).
1482        assert!(parse_duration_seconds("P9999999999999999D").is_err());
1483        assert!(parse_duration_seconds("P99999999999999999D").is_err());
1484        assert!(parse_duration_seconds(&format!("PT{}S", "9".repeat(40))).is_err());
1485    }
1486
1487    #[test]
1488    fn unsafe_resources_never_sit_inside_a_parent() {
1489        for r in [
1490            "https://x/a/../b",
1491            "https://x/a/./b",
1492            "https://x/a/%2e%2E/b",
1493            "https://x/a/.%2e",
1494            "https://x/a\\..\\b",
1495            "https://x/a/..%2Fb",
1496            "https://x/a/%5c",
1497            "https://x/a/\u{0007}",
1498        ] {
1499            assert!(resource_is_unsafe(r), "{r}");
1500            assert!(!resource_within(r, "https://x/a"), "{r}");
1501        }
1502        // Dots after '?' or '#' are data, not path segments.
1503        assert!(resource_within("https://x/a/b?next=../c", "https://x/a"));
1504    }
1505
1506    #[test]
1507    fn integers_are_whole_numbers_in_range() {
1508        assert_eq!(as_int(&json!(2), 0, 10), Some(2));
1509        assert_eq!(as_int(&json!(2.0), 0, 10), Some(2));
1510        for v in [
1511            json!(2.5),
1512            json!(-1),
1513            json!(11),
1514            json!(true),
1515            json!("2"),
1516            Value::Null,
1517        ] {
1518            assert_eq!(as_int(&v, 0, 10), None, "{v}");
1519        }
1520        assert_eq!(as_int(&json!(u64::MAX), 0, MAX_SAFE_INTEGER), None);
1521        // A revoked index written as 1.0 still revokes link 1.
1522        let verdict: Value = serde_json::from_str(&validate_chain_json(
1523            &json!({"chain": [
1524                {"issuer":"did:web:r","subject":"did:web:a","intent":{"action":"read"}},
1525                {"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"}}],
1526                "revokedIndices": [1.0], "nowIso": "2026-04-26T10:00:00Z"})
1527            .to_string(),
1528        ))
1529        .unwrap();
1530        assert_eq!(verdict["code"], json!("delegation_revoked"));
1531        let verdict: Value = serde_json::from_str(&validate_chain_json(
1532            &json!({"chain": [{"issuer":"did:web:r","subject":"did:web:a"}],
1533                    "budget": {"maxDepth": -1}, "nowIso": "2026-04-26T10:00:00Z"})
1534            .to_string(),
1535        ))
1536        .unwrap();
1537        assert_eq!(verdict["code"], json!("malformed_delegation"));
1538    }
1539}