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