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.
400pub fn rate_within(
401    child_limit: i64,
402    child_window: i64,
403    parent_limit: i64,
404    parent_window: i64,
405) -> bool {
406    if child_window <= 0 || parent_window <= 0 {
407        return false;
408    }
409    let (cl, cw, pl, pw) = (
410        i128::from(child_limit),
411        i128::from(child_window),
412        i128::from(parent_limit),
413        i128::from(parent_window),
414    );
415    let repeats = (pw + cw - 1) / cw; // ceil for positive integers
416    cl <= pl && cl * repeats <= pl
417}
418
419/// Child policy must be equal to or stricter than the parent's. Numeric values
420/// narrow by the key's name: a key starting with "max" is a ceiling (the child
421/// may lower it, never raise it), a key starting with "min" is a floor (the
422/// child may raise it, never lower it), and any other numeric key must be
423/// restated unchanged. Other values must be equal in the JSON data model
424/// (`true` is not `1`). A parent key the child omits means the child dropped a
425/// constraint, which is broader, and is rejected.
426fn policy_not_weaker(parent: &Value, child: &Value) -> bool {
427    let (pobj, cobj) = match (parent.as_object(), child.as_object()) {
428        (Some(p), Some(c)) => (p, c),
429        _ => return false, // a policy that is not an object cannot be reasoned about
430    };
431    for (k, pv) in pobj {
432        let Some(cv) = cobj.get(k) else {
433            return false; // child dropped a parent constraint => weaker
434        };
435        match (is_number(pv), is_number(cv)) {
436            (true, true) => {
437                let (Some(pn), Some(cn)) = (pv.as_f64(), cv.as_f64()) else {
438                    return false;
439                };
440                let weaker = if k.starts_with("max") {
441                    cn > pn // a raised ceiling is broader
442                } else if k.starts_with("min") {
443                    cn < pn // a lowered floor is broader
444                } else {
445                    !json_equal(pv, cv) // unknown direction: must be restated
446                };
447                if weaker {
448                    return false;
449                }
450            }
451            (true, false) | (false, true) => return false, // type mismatch
452            (false, false) => {
453                if !json_equal(pv, cv) {
454                    return false; // non-numeric must match exactly
455                }
456            }
457        }
458    }
459    true
460}
461
462/// A link's window bound in nanoseconds: absent is None; present but null,
463/// not a string, or not a protocol time is an error.
464fn bound(link: &Value, key: &str) -> Result<Option<i128>> {
465    match link.get(key) {
466        None => Ok(None),
467        Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
468        Some(_) => Err(CoreError::Json(format!("{key} must be a time string"))),
469    }
470}
471
472fn window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
473    Ok((bound(link, "validFrom")?, bound(link, "validUntil")?))
474}
475
476/// The first dimension a link writes down in a form that cannot be compared,
477/// or None. A present dimension must be well formed: action and target a
478/// string or an array of strings; resource a string that is not unsafe;
479/// validFrom / validUntil protocol times; rate an object with an integer limit
480/// and a positive duration window; policy an object nested no deeper than 128
481/// levels. `null` is malformed everywhere.
482pub fn malformed_dimension(link: &Value) -> Option<Dimension> {
483    let Some(obj) = link.as_object() else {
484        return Some(Dimension::Action);
485    };
486    let intent = match obj.get("intent") {
487        None => None,
488        Some(Value::Object(i)) => Some(i),
489        Some(_) => return Some(Dimension::Action),
490    };
491    if let Some(i) = intent {
492        for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
493            if let Some(v) = i.get(key) {
494                if string_set(v).is_err() {
495                    return Some(dim);
496                }
497            }
498        }
499        if let Some(res) = i.get("resource") {
500            match res.as_str() {
501                Some(r) if !resource_is_unsafe(r) => {}
502                _ => return Some(Dimension::Resource),
503            }
504        }
505    }
506    if window(link).is_err() {
507        return Some(Dimension::Time);
508    }
509    if let Some(rate) = obj.get("rate") {
510        if parse_rate(rate).is_err() {
511            return Some(Dimension::Rate);
512        }
513    }
514    if let Some(policy) = obj.get("policy") {
515        if !policy.is_object() || json_nesting_exceeds(policy, MAX_JSON_NESTING) {
516            return Some(Dimension::Policy);
517        }
518    }
519    None
520}
521
522// --------------------------------------------------------------------------
523// Non-expansion between an adjacent (parent, child) pair
524// --------------------------------------------------------------------------
525
526/// Verify that `child` does not broaden `parent` on any dimension. Returns the
527/// offending [`Dimension`] on failure. A malformed dimension on either side
528/// ([`malformed_dimension`]) is reported as that dimension: a child cannot
529/// erase a bound with `null`, and nothing can be shown to sit inside a
530/// malformed parent bound.
531pub fn non_expansion(parent: &Value, child: &Value) -> std::result::Result<(), Dimension> {
532    if let Some(dim) = malformed_dimension(child) {
533        return Err(dim);
534    }
535    if let Some(dim) = malformed_dimension(parent) {
536        return Err(dim);
537    }
538    let empty = Map::new();
539    let p_intent = intent(parent).unwrap_or(&empty);
540    let c_intent = intent(child).unwrap_or(&empty);
541
542    // action / target: the child's set must be a subset of the parent's.
543    for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
544        if let (Some(c), Some(p)) = (c_intent.get(key), p_intent.get(key)) {
545            match (string_set(c), string_set(p)) {
546                (Ok(cs), Ok(ps)) if cs.is_subset(&ps) => {}
547                _ => return Err(dim),
548            }
549        }
550    }
551
552    // resource: the child's resource must be within the parent's.
553    if let (Some(c), Some(p)) = (c_intent.get("resource"), p_intent.get("resource")) {
554        match (c.as_str(), p.as_str()) {
555            (Some(cr), Some(pr)) if resource_within(cr, pr) => {}
556            _ => return Err(Dimension::Resource),
557        }
558    }
559
560    // time: the child's window must be within the parent's (to the nanosecond).
561    let (Ok((cf, cu)), Ok((pf, pu))) = (window(child), window(parent)) else {
562        return Err(Dimension::Time);
563    };
564    if let (Some(f), Some(pf)) = (cf, pf) {
565        if f < pf {
566            return Err(Dimension::Time);
567        }
568    }
569    if let (Some(u), Some(pu)) = (cu, pu) {
570        if u > pu {
571            return Err(Dimension::Time);
572        }
573    }
574
575    // rate: never a burst the parent forbids, in exact integers.
576    if let (Some(cr), Some(pr)) = (child.get("rate"), parent.get("rate")) {
577        let (Ok((c_limit, c_secs)), Ok((p_limit, p_secs))) = (parse_rate(cr), parse_rate(pr))
578        else {
579            return Err(Dimension::Rate);
580        };
581        if !rate_within(c_limit, c_secs, p_limit, p_secs) {
582            return Err(Dimension::Rate);
583        }
584    }
585
586    // policy: the child's policy must be equal to or stricter than the parent's.
587    let p_pol = parent.get("policy").filter(|p| !p.is_null());
588    if let (Some(cp), Some(pp)) = (child.get("policy"), p_pol) {
589        if !policy_not_weaker(pp, cp) {
590            return Err(Dimension::Policy);
591        }
592    }
593
594    // spend: an action's intent.amount stays within the parent's maxSpend.
595    if let Some(cap) = p_pol
596        .and_then(|p| p.as_object())
597        .and_then(|p| p.get("maxSpend"))
598    {
599        if let Some(amount) = c_intent.get("amount") {
600            match (amount.as_f64(), cap.as_f64()) {
601                (Some(a), Some(c)) if a <= c => {}
602                _ => return Err(Dimension::Policy),
603            }
604        }
605    }
606
607    Ok(())
608}
609
610/// The child's effective capability: any dimension it omits is inherited
611/// unchanged from its parent's effective capability (Specification 9.2).
612/// `amount` is per action and is never inherited.
613pub fn inherit(parent_effective: &Value, child: &Value) -> Value {
614    let mut out = child.as_object().cloned().unwrap_or_default();
615    let mut c_intent = child
616        .get("intent")
617        .and_then(|i| i.as_object())
618        .cloned()
619        .unwrap_or_default();
620    if let Some(p_intent) = parent_effective.get("intent").and_then(|i| i.as_object()) {
621        for k in ["action", "target", "resource"] {
622            if !c_intent.contains_key(k) {
623                if let Some(v) = p_intent.get(k) {
624                    c_intent.insert(k.into(), v.clone());
625                }
626            }
627        }
628    }
629    out.insert("intent".into(), Value::Object(c_intent));
630    for k in ["rate", "policy", "validFrom", "validUntil"] {
631        let absent = out.get(k).map(|v| v.is_null()).unwrap_or(true);
632        if absent {
633            if let Some(v) = parent_effective.get(k).filter(|v| !v.is_null()) {
634                out.insert(k.into(), v.clone());
635            }
636        }
637    }
638    Value::Object(out)
639}
640
641/// Walk root to leaf comparing each step against its parent's EFFECTIVE
642/// capability (inherited dimensions included). Returns the first offending
643/// dimension; a malformed dimension on the root is reported too.
644pub fn first_broader_step(views: &[Value]) -> std::result::Result<(), Dimension> {
645    let Some(first) = views.first() else {
646        return Ok(());
647    };
648    if let Some(dim) = malformed_dimension(first) {
649        return Err(dim);
650    }
651    let mut effective = first.clone();
652    for child in &views[1..] {
653        non_expansion(&effective, child)?;
654        effective = inherit(&effective, child);
655    }
656    Ok(())
657}
658
659// --------------------------------------------------------------------------
660// Full chain validation
661// --------------------------------------------------------------------------
662
663fn link_str<'a>(link: &'a Value, key: &str) -> Option<&'a str> {
664    link.get(key).and_then(|v| v.as_str())
665}
666
667fn malformed(detail: impl Into<String>) -> DelegationReject {
668    DelegationReject::Malformed {
669        detail: detail.into(),
670    }
671}
672
673/// Validate a delegation chain ordered root -> leaf under the v1.7 rules.
674///
675/// * `trusted_roots`: `None` skips the root-trust check (the caller anchors
676///   trust elsewhere); a list names the trusted roots (a bare domain stands
677///   for its did:web), and an empty list trusts nobody.
678/// * `revoked_link_indices` are links the caller has resolved as revoked
679///   (credential- or DID-level); any hit rejects the whole chain (cascade).
680/// * `budget` caps the verifier's work; `None` fields are unlimited. There is
681///   no default depth limit; an encoded chain over 1 MiB is always refused.
682/// * `clock_skew_seconds` must be 0 to 120.
683///
684/// Returns `Ok(())` when the chain is valid, or the first [`DelegationReject`].
685pub fn validate_chain(
686    chain: &[Value],
687    trusted_roots: Option<&[String]>,
688    revoked_link_indices: &[usize],
689    budget: &VerifierBudget,
690    now_iso: &str,
691    clock_skew_seconds: i64,
692) -> DResult {
693    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
694        return Err(malformed(format!(
695            "clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
696        )));
697    }
698    let skew = i128::from(clock_skew_seconds) * NS_PER_SECOND;
699    let now = parse_protocol_time_ns(now_iso).map_err(|e| malformed(format!("nowIso: {e}")))?;
700    if chain.is_empty() {
701        return Err(malformed("empty delegation chain"));
702    }
703
704    // Verifier budget, before anything else is looked at.
705    let chain_value = Value::Array(chain.to_vec());
706    match chain_budget_exceeded(&chain_value, budget.max_depth) {
707        Ok(None) => {}
708        Ok(Some(limit)) => {
709            return Err(DelegationReject::VerifierBudgetExceeded {
710                limit: limit.into(),
711            })
712        }
713        Err(detail) => return Err(malformed(detail)),
714    }
715
716    // Every link must be an object with issuer and subject strings, and an
717    // intent object when it has one.
718    for (i, link) in chain.iter().enumerate() {
719        let shape_ok = link.is_object()
720            && link_str(link, "issuer").is_some()
721            && link_str(link, "subject").is_some()
722            && link.get("intent").map(|v| v.is_object()).unwrap_or(true);
723        if !shape_ok {
724            return Err(malformed(format!("link {i} malformed")));
725        }
726    }
727
728    // Root trust.
729    if let Some(roots) = trusted_roots {
730        let root_issuer = link_str(&chain[0], "issuer").unwrap_or("");
731        if !roots
732            .iter()
733            .any(|r| crate::delegation::root_matches(r, root_issuer))
734        {
735            return Err(DelegationReject::UntrustedPrincipal);
736        }
737    }
738
739    // Cascade revocation: a revoked link invalidates the whole chain.
740    if let Some(&idx) = revoked_link_indices.iter().min() {
741        if idx < chain.len() {
742            return Err(DelegationReject::DelegationRevoked { link_index: idx });
743        }
744    }
745
746    // Linkage and non-expansion for each step against its parent's effective
747    // capability (dimensions a link omits are inherited).
748    if let Some(dimension) = malformed_dimension(&chain[0]) {
749        return Err(DelegationReject::ScopeExceedsParent { dimension });
750    }
751    let mut effective = chain[0].clone();
752    let mut windows = vec![window(&chain[0]).map_err(|e| malformed(e.to_string()))?];
753    for i in 1..chain.len() {
754        let parent = &chain[i - 1];
755        let child = &chain[i];
756        if link_str(parent, "subject") != link_str(child, "issuer") {
757            return Err(DelegationReject::SubjectIssuerMismatch { link_index: i });
758        }
759        non_expansion(&effective, child)
760            .map_err(|dimension| DelegationReject::ScopeExceedsParent { dimension })?;
761        effective = inherit(&effective, child);
762        windows.push(window(&effective).map_err(|e| malformed(e.to_string()))?);
763    }
764
765    // Effective validity window: the latest start and the earliest end.
766    let eff_start = windows.iter().filter_map(|w| w.0).max();
767    let eff_end = windows.iter().filter_map(|w| w.1).min();
768    if let (Some(f), Some(u)) = (eff_start, eff_end) {
769        if f > u {
770            return Err(DelegationReject::OutsideValidityWindow);
771        }
772    }
773    if let Some(f) = eff_start {
774        if now < f - skew {
775            return Err(DelegationReject::OutsideValidityWindow);
776        }
777    }
778    if let Some(u) = eff_end {
779        if now > u + skew {
780            return Err(DelegationReject::OutsideValidityWindow);
781        }
782    }
783
784    // Cumulative TTL over each link's effective (inherited) window. A link with
785    // an open end has no finite TTL, so a TTL budget refuses it.
786    if let Some(max) = budget.max_cumulative_ttl_seconds {
787        let exceeded = || DelegationReject::VerifierBudgetExceeded {
788            limit: "cumulative_ttl".into(),
789        };
790        let mut total: i128 = 0;
791        for (vf, vu) in &windows {
792            let (Some(f), Some(u)) = (vf, vu) else {
793                return Err(exceeded());
794            };
795            total += (u - f).max(0);
796        }
797        if total > i128::from(max) * NS_PER_SECOND {
798            return Err(exceeded());
799        }
800    }
801
802    Ok(())
803}
804
805// --------------------------------------------------------------------------
806// JSON boundary for the SDK bindings (uniffi / wasm)
807// --------------------------------------------------------------------------
808
809/// Validate a delegation chain from a single JSON request, returning a JSON
810/// verdict. Infallible: malformed input yields a `malformed_delegation` verdict
811/// rather than an error, so every caller gets a uniform verdict shape.
812///
813/// Request:  `{ "chain": [..links..], "trustedRoots"?: [str], "revokedIndices"?:
814/// [int], "budget"?: {"maxDepth"?: int, "maxCumulativeTtlSeconds"?: int},
815/// "nowIso": "..", "clockSkewSeconds"?: int (0..120, default 30) }`. An option
816/// that is present must be well formed (`null` included): integers are whole
817/// numbers (2 and 2.0 are both 2) in range, `trustedRoots` is a list of
818/// strings. There is no default depth limit.
819///
820/// Response: `{"valid": true}` or `{"valid": false, "code": "..", ..detail..}`.
821pub fn validate_chain_json(request_json: &str) -> String {
822    let req: Value = match serde_json::from_str(request_json) {
823        Ok(v) => v,
824        Err(e) => return verdict_malformed(&format!("request json: {e}")),
825    };
826    let Some(req) = req.as_object() else {
827        return verdict_malformed("request must be a JSON object");
828    };
829    let chain: Vec<Value> = match req.get("chain").and_then(|v| v.as_array()) {
830        Some(c) => c.clone(),
831        None => return verdict_malformed("missing chain array"),
832    };
833    for key in [
834        "trustedRoots",
835        "revokedIndices",
836        "budget",
837        "nowIso",
838        "clockSkewSeconds",
839    ] {
840        if matches!(req.get(key), Some(Value::Null)) {
841            return verdict_malformed(&format!("{key} must not be null"));
842        }
843    }
844    let trusted_roots: Option<Vec<String>> = match req.get("trustedRoots") {
845        None => None,
846        Some(Value::Array(a)) => {
847            let mut roots = Vec::with_capacity(a.len());
848            for r in a {
849                match r.as_str() {
850                    Some(s) => roots.push(s.to_string()),
851                    None => return verdict_malformed("trustedRoots must be a list of strings"),
852                }
853            }
854            Some(roots)
855        }
856        Some(_) => return verdict_malformed("trustedRoots must be a list of strings"),
857    };
858    let revoked: Vec<usize> = match req.get("revokedIndices") {
859        None => Vec::new(),
860        Some(Value::Array(a)) => {
861            let mut out = Vec::with_capacity(a.len());
862            for v in a {
863                match as_int(v, 0, MAX_SAFE_INTEGER) {
864                    Some(n) => out.push(n as usize),
865                    None => {
866                        return verdict_malformed(
867                            "revokedIndices must be integers from 0 to 2^53 - 1",
868                        )
869                    }
870                }
871            }
872            out
873        }
874        Some(_) => return verdict_malformed("revokedIndices must be a list of integers"),
875    };
876    let mut budget = VerifierBudget::default();
877    match req.get("budget") {
878        None => {}
879        Some(Value::Object(b)) => {
880            for key in ["maxDepth", "maxCumulativeTtlSeconds"] {
881                if let Some(v) = b.get(key) {
882                    let Some(n) = as_int(v, 0, MAX_SAFE_INTEGER) else {
883                        return verdict_malformed(&format!(
884                            "budget.{key} must be an integer from 0 to 2^53 - 1"
885                        ));
886                    };
887                    if key == "maxDepth" {
888                        budget.max_depth = Some(n as usize);
889                    } else {
890                        budget.max_cumulative_ttl_seconds = Some(n);
891                    }
892                }
893            }
894        }
895        Some(_) => return verdict_malformed("budget must be an object"),
896    }
897    let skew = match req.get("clockSkewSeconds") {
898        None => 30,
899        Some(v) => match as_int(v, 0, MAX_CLOCK_SKEW_SECONDS) {
900            Some(n) => n,
901            None => {
902                return verdict_malformed(&format!(
903                    "clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
904                ))
905            }
906        },
907    };
908    let now = match req.get("nowIso") {
909        None => "",
910        Some(Value::String(s)) => s.as_str(),
911        Some(_) => return verdict_malformed("nowIso must be a time string"),
912    };
913
914    match validate_chain(
915        &chain,
916        trusted_roots.as_deref(),
917        &revoked,
918        &budget,
919        now,
920        skew,
921    ) {
922        Ok(()) => json!({ "valid": true }).to_string(),
923        Err(r) => reject_to_json(&r).to_string(),
924    }
925}
926
927fn verdict_malformed(detail: &str) -> String {
928    json!({ "valid": false, "code": "malformed_delegation", "detail": detail }).to_string()
929}
930
931fn reject_to_json(r: &DelegationReject) -> Value {
932    let mut v = json!({ "valid": false, "code": r.code() });
933    let o = v.as_object_mut().unwrap();
934    match r {
935        DelegationReject::ScopeExceedsParent { dimension } => {
936            o.insert("dimension".into(), json!(dimension.as_str()));
937        }
938        DelegationReject::VerifierBudgetExceeded { limit } => {
939            o.insert("limit".into(), json!(limit));
940        }
941        DelegationReject::DelegationRevoked { link_index }
942        | DelegationReject::SubjectIssuerMismatch { link_index } => {
943            o.insert("linkIndex".into(), json!(link_index));
944        }
945        DelegationReject::Malformed { detail } => {
946            o.insert("detail".into(), json!(detail));
947        }
948        DelegationReject::UntrustedPrincipal | DelegationReject::OutsideValidityWindow => {}
949    }
950    v
951}
952
953#[cfg(test)]
954mod tests {
955    use super::*;
956    use serde_json::json;
957
958    fn link(issuer: &str, subject: &str, intent: Value) -> Value {
959        json!({
960            "issuer": issuer,
961            "subject": subject,
962            "intent": intent,
963            "validFrom": "2026-04-26T09:00:00Z",
964            "validUntil": "2026-04-26T12:00:00Z"
965        })
966    }
967
968    fn now() -> &'static str {
969        "2026-04-26T10:00:00Z"
970    }
971
972    #[test]
973    fn restate_unchanged_is_valid() {
974        let i = json!({"action":"read","target":"t","resource":"https://x/a"});
975        let chain = vec![
976            link("did:web:root", "did:web:a", i.clone()),
977            link("did:web:a", "did:web:b", i.clone()),
978        ];
979        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
980    }
981
982    #[test]
983    fn resource_narrowing_is_valid() {
984        let chain = vec![
985            link(
986                "did:web:root",
987                "did:web:a",
988                json!({"resource":"https://x/a"}),
989            ),
990            link(
991                "did:web:a",
992                "did:web:b",
993                json!({"resource":"https://x/a/b"}),
994            ),
995        ];
996        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
997    }
998
999    #[test]
1000    fn resource_widening_rejected_naming_dimension() {
1001        let chain = vec![
1002            link(
1003                "did:web:root",
1004                "did:web:a",
1005                json!({"resource":"https://x/a/b"}),
1006            ),
1007            link("did:web:a", "did:web:b", json!({"resource":"https://x/a"})),
1008        ];
1009        let err =
1010            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1011        assert_eq!(err.code(), "scope_exceeds_parent");
1012        assert_eq!(
1013            err,
1014            DelegationReject::ScopeExceedsParent {
1015                dimension: Dimension::Resource
1016            }
1017        );
1018    }
1019
1020    #[test]
1021    fn sibling_prefix_is_not_sub_resource() {
1022        assert!(!resource_within("https://x/a2", "https://x/a"));
1023        assert!(resource_within("https://x/a/b", "https://x/a"));
1024        assert!(resource_within("https://x/a", "https://x/a/"));
1025    }
1026
1027    #[test]
1028    fn action_superset_rejected() {
1029        let chain = vec![
1030            link("did:web:root", "did:web:a", json!({"action":"read"})),
1031            link("did:web:a", "did:web:b", json!({"action":["read","write"]})),
1032        ];
1033        let err =
1034            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1035        assert_eq!(
1036            err,
1037            DelegationReject::ScopeExceedsParent {
1038                dimension: Dimension::Action
1039            }
1040        );
1041    }
1042
1043    #[test]
1044    fn action_subset_ok() {
1045        let chain = vec![
1046            link(
1047                "did:web:root",
1048                "did:web:a",
1049                json!({"action":["read","write"]}),
1050            ),
1051            link("did:web:a", "did:web:b", json!({"action":"read"})),
1052        ];
1053        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1054    }
1055
1056    #[test]
1057    fn rate_widening_rejected() {
1058        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1059        a["rate"] = json!({"limit":100,"window":"PT1H"});
1060        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1061        b["rate"] = json!({"limit":100,"window":"PT30M"}); // twice the events/sec
1062        let chain = vec![a, b];
1063        let err =
1064            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1065        assert_eq!(
1066            err,
1067            DelegationReject::ScopeExceedsParent {
1068                dimension: Dimension::Rate
1069            }
1070        );
1071    }
1072
1073    #[test]
1074    fn rate_narrowing_ok() {
1075        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1076        a["rate"] = json!({"limit":100,"window":"PT1H"});
1077        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1078        b["rate"] = json!({"limit":50,"window":"PT1H"});
1079        let chain = vec![a, b];
1080        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1081    }
1082
1083    #[test]
1084    fn policy_weakening_rejected() {
1085        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1086        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
1087        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1088        b["policy"] = json!({"minHeartbeatAgeSeconds":100}); // weaker
1089        let chain = vec![a, b];
1090        let err =
1091            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1092        assert_eq!(
1093            err,
1094            DelegationReject::ScopeExceedsParent {
1095                dimension: Dimension::Policy
1096            }
1097        );
1098    }
1099
1100    #[test]
1101    fn policy_dropping_constraint_rejected() {
1102        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
1103        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
1104        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
1105        b["policy"] = json!({"unrelated":true}); // dropped the parent's constraint
1106        let chain = vec![a, b];
1107        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_err());
1108    }
1109
1110    #[test]
1111    fn time_widening_rejected() {
1112        let chain = vec![
1113            json!({"issuer":"did:web:root","subject":"did:web:a","intent":{"action":"read"},
1114                   "validFrom":"2026-04-26T10:00:00Z","validUntil":"2026-04-26T11:00:00Z"}),
1115            json!({"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"},
1116                   "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T12:00:00Z"}),
1117        ];
1118        let err = validate_chain(
1119            &chain,
1120            None,
1121            &[],
1122            &VerifierBudget::default(),
1123            "2026-04-26T10:30:00Z",
1124            30,
1125        )
1126        .unwrap_err();
1127        assert_eq!(
1128            err,
1129            DelegationReject::ScopeExceedsParent {
1130                dimension: Dimension::Time
1131            }
1132        );
1133    }
1134
1135    #[test]
1136    fn subject_issuer_mismatch_rejected() {
1137        let i = json!({"action":"read"});
1138        let chain = vec![
1139            link("did:web:root", "did:web:a", i.clone()),
1140            link("did:web:WRONG", "did:web:b", i.clone()),
1141        ];
1142        let err =
1143            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
1144        assert_eq!(
1145            err,
1146            DelegationReject::SubjectIssuerMismatch { link_index: 1 }
1147        );
1148    }
1149
1150    #[test]
1151    fn untrusted_root_rejected() {
1152        let i = json!({"action":"read"});
1153        let chain = vec![link("did:web:root", "did:web:a", i)];
1154        let err = validate_chain(
1155            &chain,
1156            Some(&["did:web:other".to_string()]),
1157            &[],
1158            &VerifierBudget::default(),
1159            now(),
1160            30,
1161        )
1162        .unwrap_err();
1163        assert_eq!(err, DelegationReject::UntrustedPrincipal);
1164    }
1165
1166    #[test]
1167    fn cascade_revocation_rejects_whole_chain() {
1168        let i = json!({"action":"read"});
1169        let chain = vec![
1170            link("did:web:root", "did:web:a", i.clone()),
1171            link("did:web:a", "did:web:b", i.clone()),
1172            link("did:web:b", "did:web:c", i.clone()),
1173        ];
1174        // middle link revoked
1175        let err =
1176            validate_chain(&chain, None, &[1], &VerifierBudget::default(), now(), 30).unwrap_err();
1177        assert_eq!(err, DelegationReject::DelegationRevoked { link_index: 1 });
1178    }
1179
1180    #[test]
1181    fn budget_depth_exceeded() {
1182        let i = json!({"action":"read"});
1183        let chain = vec![
1184            link("did:web:root", "did:web:a", i.clone()),
1185            link("did:web:a", "did:web:b", i.clone()),
1186            link("did:web:b", "did:web:c", i.clone()),
1187        ];
1188        let budget = VerifierBudget {
1189            max_depth: Some(2),
1190            max_cumulative_ttl_seconds: None,
1191        };
1192        let err = validate_chain(&chain, None, &[], &budget, now(), 30).unwrap_err();
1193        assert_eq!(
1194            err,
1195            DelegationReject::VerifierBudgetExceeded {
1196                limit: "depth".into()
1197            }
1198        );
1199    }
1200
1201    #[test]
1202    fn deep_but_attenuating_chain_is_valid_without_depth_cap() {
1203        // Ten hops, each restating the same authority: valid now that the fixed
1204        // depth limit is gone (this is the whole point of v1.7).
1205        let mut chain = Vec::new();
1206        let i = json!({"action":"read","resource":"https://x/a"});
1207        for n in 0..10 {
1208            let issuer = if n == 0 {
1209                "did:web:root".to_string()
1210            } else {
1211                format!("did:web:h{}", n - 1)
1212            };
1213            let subject = format!("did:web:h{n}");
1214            chain.push(link(&issuer, &subject, i.clone()));
1215        }
1216        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1217    }
1218
1219    #[test]
1220    fn now_outside_effective_window_rejected() {
1221        let chain = vec![link("did:web:root", "did:web:a", json!({"action":"read"}))];
1222        let err = validate_chain(
1223            &chain,
1224            None,
1225            &[],
1226            &VerifierBudget::default(),
1227            "2026-04-26T20:00:00Z",
1228            30,
1229        )
1230        .unwrap_err();
1231        assert_eq!(err, DelegationReject::OutsideValidityWindow);
1232    }
1233
1234    #[test]
1235    fn absent_child_dimension_inherits_and_passes() {
1236        let chain = vec![
1237            link(
1238                "did:web:root",
1239                "did:web:a",
1240                json!({"action":"read","resource":"https://x/a"}),
1241            ),
1242            link(
1243                "did:web:a",
1244                "did:web:b",
1245                json!({"resource":"https://x/a/b"}),
1246            ), // action omitted => inherit
1247        ];
1248        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
1249    }
1250
1251    #[test]
1252    fn duration_parser() {
1253        assert_eq!(parse_duration_seconds("PT1H").unwrap(), 3600);
1254        assert_eq!(parse_duration_seconds("PT30M").unwrap(), 1800);
1255        assert_eq!(parse_duration_seconds("PT1H30M15S").unwrap(), 5415);
1256        assert_eq!(parse_duration_seconds("P1D").unwrap(), 86400);
1257        assert!(parse_duration_seconds("1H").is_err());
1258        assert!(parse_duration_seconds("PT").is_err());
1259    }
1260
1261    #[test]
1262    fn duration_parser_is_strict_and_never_overflows() {
1263        assert_eq!(parse_duration_seconds("P1M").unwrap(), 2_592_000);
1264        assert_eq!(parse_duration_seconds("P1DT1S").unwrap(), 86_401);
1265        for bad in [
1266            "P",
1267            "PT",
1268            "P1DT",
1269            "P1H",
1270            "PT1D",
1271            "P1D1M",
1272            "PT1S1M",
1273            "P\u{0661}D",
1274            "PT-1S",
1275            "PT1.5S",
1276            "p1D",
1277            "P1DTT1S",
1278        ] {
1279            assert!(parse_duration_seconds(bad).is_err(), "{bad}");
1280        }
1281        // Huge fields refuse cleanly (no panic, no wrap).
1282        assert!(parse_duration_seconds("P9999999999999999D").is_err());
1283        assert!(parse_duration_seconds("P99999999999999999D").is_err());
1284        assert!(parse_duration_seconds(&format!("PT{}S", "9".repeat(40))).is_err());
1285    }
1286
1287    #[test]
1288    fn unsafe_resources_never_sit_inside_a_parent() {
1289        for r in [
1290            "https://x/a/../b",
1291            "https://x/a/./b",
1292            "https://x/a/%2e%2E/b",
1293            "https://x/a/.%2e",
1294            "https://x/a\\..\\b",
1295            "https://x/a/..%2Fb",
1296            "https://x/a/%5c",
1297            "https://x/a/\u{0007}",
1298        ] {
1299            assert!(resource_is_unsafe(r), "{r}");
1300            assert!(!resource_within(r, "https://x/a"), "{r}");
1301        }
1302        // Dots after '?' or '#' are data, not path segments.
1303        assert!(resource_within("https://x/a/b?next=../c", "https://x/a"));
1304    }
1305
1306    #[test]
1307    fn integers_are_whole_numbers_in_range() {
1308        assert_eq!(as_int(&json!(2), 0, 10), Some(2));
1309        assert_eq!(as_int(&json!(2.0), 0, 10), Some(2));
1310        for v in [
1311            json!(2.5),
1312            json!(-1),
1313            json!(11),
1314            json!(true),
1315            json!("2"),
1316            Value::Null,
1317        ] {
1318            assert_eq!(as_int(&v, 0, 10), None, "{v}");
1319        }
1320        assert_eq!(as_int(&json!(u64::MAX), 0, MAX_SAFE_INTEGER), None);
1321        // A revoked index written as 1.0 still revokes link 1.
1322        let verdict: Value = serde_json::from_str(&validate_chain_json(
1323            &json!({"chain": [
1324                {"issuer":"did:web:r","subject":"did:web:a","intent":{"action":"read"}},
1325                {"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"}}],
1326                "revokedIndices": [1.0], "nowIso": "2026-04-26T10:00:00Z"})
1327            .to_string(),
1328        ))
1329        .unwrap();
1330        assert_eq!(verdict["code"], json!("delegation_revoked"));
1331        let verdict: Value = serde_json::from_str(&validate_chain_json(
1332            &json!({"chain": [{"issuer":"did:web:r","subject":"did:web:a"}],
1333                    "budget": {"maxDepth": -1}, "nowIso": "2026-04-26T10:00:00Z"})
1334            .to_string(),
1335        ))
1336        .unwrap();
1337        assert_eq!(verdict["code"], json!("malformed_delegation"));
1338    }
1339}