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//! A dimension absent on a child link is inherited unchanged from its parent;
12//! it can never be widened by omission. A dimension the parent leaves unbounded
13//! may be narrowed by a child. Only when the child *specifies* a dimension that
14//! the parent also bounds do we compare them.
15
16use std::collections::BTreeSet;
17
18use serde_json::{json, Value};
19
20use crate::error::{CoreError, Result};
21use crate::time::iso_to_epoch_seconds;
22
23/// A small tolerance for rate comparison so exact-equal rates are not rejected
24/// by floating-point noise.
25const RATE_EPSILON: f64 = 1e-9;
26
27/// The six capability dimensions a delegation link may carry.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Dimension {
30    Action,
31    Target,
32    Resource,
33    Time,
34    Rate,
35    Policy,
36}
37
38impl Dimension {
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Dimension::Action => "action",
42            Dimension::Target => "target",
43            Dimension::Resource => "resource",
44            Dimension::Time => "time",
45            Dimension::Rate => "rate",
46            Dimension::Policy => "policy",
47        }
48    }
49}
50
51/// A structured reason a delegation chain is rejected. `code()` yields the
52/// on-the-wire reason string used across the SDKs.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum DelegationReject {
55    /// A child link is broader than its parent on the named dimension.
56    ScopeExceedsParent { dimension: Dimension },
57    /// The verifier's local cost budget was exceeded; `limit` names which one.
58    VerifierBudgetExceeded { limit: String },
59    /// A link (0-indexed from the root) is revoked; the whole chain and every
60    /// authority below it is rejected.
61    DelegationRevoked { link_index: usize },
62    /// A link's `subject` does not match the next link's `issuer`.
63    SubjectIssuerMismatch { link_index: usize },
64    /// The root link's issuer is not in the verifier's trusted set.
65    UntrustedPrincipal,
66    /// The current instant is outside the chain's effective validity window.
67    OutsideValidityWindow,
68    /// The chain or a link is structurally malformed.
69    Malformed { detail: String },
70}
71
72impl DelegationReject {
73    pub fn code(&self) -> &'static str {
74        match self {
75            DelegationReject::ScopeExceedsParent { .. } => "scope_exceeds_parent",
76            DelegationReject::VerifierBudgetExceeded { .. } => "verifier_budget_exceeded",
77            DelegationReject::DelegationRevoked { .. } => "delegation_revoked",
78            DelegationReject::SubjectIssuerMismatch { .. } => "subject_issuer_mismatch",
79            DelegationReject::UntrustedPrincipal => "untrusted_principal",
80            DelegationReject::OutsideValidityWindow => "outside_validity_window",
81            DelegationReject::Malformed { .. } => "malformed_delegation",
82        }
83    }
84}
85
86/// Verifier-local cost budget (Specification 9.4). `None` means unlimited.
87/// These are the verifier's configurable choice, not a protocol requirement.
88#[derive(Debug, Clone, Default)]
89pub struct VerifierBudget {
90    pub max_depth: Option<usize>,
91    pub max_cumulative_ttl_seconds: Option<i64>,
92}
93
94type DResult = std::result::Result<(), DelegationReject>;
95
96// --------------------------------------------------------------------------
97// Dimension helpers
98// --------------------------------------------------------------------------
99
100fn intent<'a>(link: &'a Value) -> Option<&'a Value> {
101    link.get("intent")
102}
103
104/// Normalize an action/target field to a set of strings.
105/// `Ok(None)`  => absent (inherit from parent).
106/// `Ok(Some)`  => a string or an array of strings.
107/// `Err`       => present but malformed (default-deny).
108fn string_set(v: Option<&Value>) -> Result<Option<BTreeSet<String>>> {
109    match v {
110        None | Some(Value::Null) => Ok(None),
111        Some(Value::String(s)) => {
112            let mut set = BTreeSet::new();
113            set.insert(s.clone());
114            Ok(Some(set))
115        }
116        Some(Value::Array(arr)) => {
117            let mut set = BTreeSet::new();
118            for item in arr {
119                match item.as_str() {
120                    Some(s) => {
121                        set.insert(s.to_string());
122                    }
123                    None => {
124                        return Err(CoreError::Json(
125                            "action/target array must be strings".into(),
126                        ))
127                    }
128                }
129            }
130            Ok(Some(set))
131        }
132        Some(_) => Err(CoreError::Json(
133            "action/target must be a string or array".into(),
134        )),
135    }
136}
137
138/// Path-component-wise sub-resource test. `child` is within `parent` when it is
139/// equal to it, or extends it at a path boundary. Trailing slashes are ignored.
140fn is_sub_resource(child: &str, parent: &str) -> bool {
141    let c = child.trim_end_matches('/');
142    let p = parent.trim_end_matches('/');
143    if c == p {
144        return true;
145    }
146    // child must extend parent at a "/" boundary, not merely share a prefix
147    // (so "https://x/a2" is NOT under "https://x/a").
148    c.len() > p.len() && c.starts_with(p) && c.as_bytes()[p.len()] == b'/'
149}
150
151/// Parse an ISO-8601 duration (the subset used by rate windows: days, hours,
152/// minutes, seconds, e.g. `PT1H`, `PT30M`, `PT1H30M15S`, `P1D`) to seconds.
153fn parse_duration_seconds(s: &str) -> Result<i64> {
154    let bytes = s.as_bytes();
155    if bytes.is_empty() || bytes[0] != b'P' {
156        return Err(CoreError::Json(format!("invalid duration: {s}")));
157    }
158    let mut total: i64 = 0;
159    let mut num = String::new();
160    let mut in_time = false;
161    let mut saw_field = false;
162    for &b in &bytes[1..] {
163        match b {
164            b'T' => in_time = true,
165            b'0'..=b'9' => num.push(b as char),
166            b'D' | b'H' | b'M' | b'S' => {
167                if num.is_empty() {
168                    return Err(CoreError::Json(format!("invalid duration: {s}")));
169                }
170                let n: i64 = num
171                    .parse()
172                    .map_err(|_| CoreError::Json(format!("invalid duration: {s}")))?;
173                let secs = match b {
174                    b'D' => n * 86_400,
175                    b'H' => n * 3_600,
176                    b'M' if in_time => n * 60, // minute in the time section
177                    b'M' => n * 2_592_000,     // month in the date section (approx 30d)
178                    b'S' => n,
179                    _ => unreachable!(),
180                };
181                total += secs;
182                num.clear();
183                saw_field = true;
184            }
185            _ => return Err(CoreError::Json(format!("invalid duration: {s}"))),
186        }
187    }
188    if !saw_field || !num.is_empty() {
189        return Err(CoreError::Json(format!("invalid duration: {s}")));
190    }
191    Ok(total)
192}
193
194/// Rate as events per second: `limit / window_seconds`. Higher is broader.
195fn rate_events_per_sec(rate: &Value) -> Result<f64> {
196    let obj = rate
197        .as_object()
198        .ok_or_else(|| CoreError::Json("rate must be an object".into()))?;
199    let limit = obj
200        .get("limit")
201        .and_then(|v| v.as_f64())
202        .ok_or_else(|| CoreError::Json("rate.limit must be a number".into()))?;
203    if limit < 0.0 {
204        return Err(CoreError::Json("rate.limit must be non-negative".into()));
205    }
206    let window = obj
207        .get("window")
208        .and_then(|v| v.as_str())
209        .ok_or_else(|| CoreError::Json("rate.window must be an ISO-8601 duration".into()))?;
210    let secs = parse_duration_seconds(window)?;
211    if secs <= 0 {
212        return Err(CoreError::Json("rate.window must be positive".into()));
213    }
214    Ok(limit / secs as f64)
215}
216
217/// Child policy must be equal to or stricter than the parent's. Numeric values
218/// narrow by the key's name: a key starting with "max" is a ceiling (the child
219/// may lower it, never raise it), a key starting with "min" is a floor (the
220/// child may raise it, never lower it), and any other numeric key must be
221/// restated unchanged. Non-numeric constraints require exact equality. A parent key the child omits
222/// means the child dropped a constraint, which is broader, and is rejected.
223/// Conservative by construction: anything not provably at-least-as-strict fails.
224fn policy_not_weaker(parent: &Value, child: &Value) -> bool {
225    let (pobj, cobj) = match (parent.as_object(), child.as_object()) {
226        (Some(p), Some(c)) => (p, c),
227        _ => return false, // a policy that is not an object cannot be reasoned about
228    };
229    for (k, pv) in pobj {
230        match cobj.get(k) {
231            None => return false, // child dropped a parent constraint => weaker
232            Some(cv) => match (pv.as_f64(), cv.as_f64()) {
233                (Some(pn), Some(cn)) => {
234                    let weaker = if k.starts_with("max") {
235                        cn > pn // a raised ceiling is broader
236                    } else if k.starts_with("min") {
237                        cn < pn // a lowered floor is broader
238                    } else {
239                        cn != pn // unknown direction: must be restated
240                    };
241                    if weaker {
242                        return false;
243                    }
244                }
245                (Some(_), None) | (None, Some(_)) => return false, // type mismatch
246                (None, None) => {
247                    if pv != cv {
248                        return false; // non-numeric must match exactly
249                    }
250                }
251            },
252        }
253    }
254    true
255}
256
257fn window(link: &Value) -> Result<(Option<i64>, Option<i64>)> {
258    let vf = match link.get("validFrom").and_then(|v| v.as_str()) {
259        Some(s) => Some(iso_to_epoch_seconds(s)?),
260        None => None,
261    };
262    let vu = match link.get("validUntil").and_then(|v| v.as_str()) {
263        Some(s) => Some(iso_to_epoch_seconds(s)?),
264        None => None,
265    };
266    Ok((vf, vu))
267}
268
269// --------------------------------------------------------------------------
270// Non-expansion between an adjacent (parent, child) pair
271// --------------------------------------------------------------------------
272
273/// Verify that `child` does not broaden `parent` on any dimension. Returns the
274/// offending [`Dimension`] on failure. Malformed inputs reject as `Resource` or
275/// the relevant dimension via the error-to-reject mapping in [`validate_chain`].
276pub fn non_expansion(parent: &Value, child: &Value) -> std::result::Result<(), Dimension> {
277    let p_intent = intent(parent);
278    let c_intent = intent(child);
279
280    // action: child actions must be a subset of the parent's.
281    if let Ok(Some(c_actions)) = string_set(c_intent.and_then(|v| v.get("action"))) {
282        if let Ok(Some(p_actions)) = string_set(p_intent.and_then(|v| v.get("action"))) {
283            if !c_actions.is_subset(&p_actions) {
284                return Err(Dimension::Action);
285            }
286        }
287    } else if c_intent.map(|v| v.get("action").is_some()).unwrap_or(false) {
288        return Err(Dimension::Action); // present but malformed
289    }
290
291    // target: child targets must be a subset of the parent's.
292    if let Ok(Some(c_targets)) = string_set(c_intent.and_then(|v| v.get("target"))) {
293        if let Ok(Some(p_targets)) = string_set(p_intent.and_then(|v| v.get("target"))) {
294            if !c_targets.is_subset(&p_targets) {
295                return Err(Dimension::Target);
296            }
297        }
298    } else if c_intent.map(|v| v.get("target").is_some()).unwrap_or(false) {
299        return Err(Dimension::Target);
300    }
301
302    // resource: child resource must be a sub-resource of the parent's.
303    let c_res = c_intent
304        .and_then(|v| v.get("resource"))
305        .and_then(|v| v.as_str());
306    if let Some(cr) = c_res {
307        if let Some(pr) = p_intent
308            .and_then(|v| v.get("resource"))
309            .and_then(|v| v.as_str())
310        {
311            if !is_sub_resource(cr, pr) {
312                return Err(Dimension::Resource);
313            }
314        }
315    } else if c_intent
316        .and_then(|v| v.get("resource"))
317        .map(|v| !v.is_null())
318        .unwrap_or(false)
319    {
320        return Err(Dimension::Resource); // present but not a string
321    }
322
323    // time: child window must be within the parent's.
324    let (cf, cu) = match window(child) {
325        Ok(w) => w,
326        Err(_) => return Err(Dimension::Time),
327    };
328    let (pf, pu) = match window(parent) {
329        Ok(w) => w,
330        Err(_) => return Err(Dimension::Time),
331    };
332    if let (Some(f), Some(pf)) = (cf, pf) {
333        if f < pf {
334            return Err(Dimension::Time);
335        }
336    }
337    if let (Some(u), Some(pu)) = (cu, pu) {
338        if u > pu {
339            return Err(Dimension::Time);
340        }
341    }
342
343    // rate: child events-per-second must not exceed the parent's.
344    if let Some(cr) = child.get("rate") {
345        if !cr.is_null() {
346            let ce = match rate_events_per_sec(cr) {
347                Ok(e) => e,
348                Err(_) => return Err(Dimension::Rate),
349            };
350            if let Some(pr) = parent.get("rate") {
351                if !pr.is_null() {
352                    let pe = match rate_events_per_sec(pr) {
353                        Ok(e) => e,
354                        Err(_) => return Err(Dimension::Rate),
355                    };
356                    if ce > pe + RATE_EPSILON {
357                        return Err(Dimension::Rate);
358                    }
359                }
360            }
361        }
362    }
363
364    // policy: child policy must be equal to or stricter than the parent's.
365    if let Some(cp) = child.get("policy") {
366        if !cp.is_null() {
367            if let Some(pp) = parent.get("policy") {
368                if !pp.is_null() && !policy_not_weaker(pp, cp) {
369                    return Err(Dimension::Policy);
370                }
371            }
372        }
373    }
374
375    // spend: an action's intent.amount stays within the parent's maxSpend.
376    if let Some(cap) = parent.get("policy").and_then(|p| p.get("maxSpend")) {
377        if let Some(amount) = c_intent.and_then(|i| i.get("amount")) {
378            match (amount.as_f64(), cap.as_f64()) {
379                (Some(a), Some(c)) if a <= c => {}
380                _ => return Err(Dimension::Policy),
381            }
382        }
383    }
384
385    Ok(())
386}
387
388/// The child's effective capability: any dimension it omits is inherited
389/// unchanged from its parent's effective capability (Specification 9.2).
390/// `amount` is per action and is never inherited.
391pub fn inherit(parent_effective: &Value, child: &Value) -> Value {
392    let mut out = child.as_object().cloned().unwrap_or_default();
393    let mut c_intent = child
394        .get("intent")
395        .and_then(|i| i.as_object())
396        .cloned()
397        .unwrap_or_default();
398    if let Some(p_intent) = parent_effective.get("intent").and_then(|i| i.as_object()) {
399        for k in ["action", "target", "resource"] {
400            if !c_intent.contains_key(k) {
401                if let Some(v) = p_intent.get(k) {
402                    c_intent.insert(k.into(), v.clone());
403                }
404            }
405        }
406    }
407    out.insert("intent".into(), Value::Object(c_intent));
408    for k in ["rate", "policy", "validFrom", "validUntil"] {
409        let absent = out.get(k).map(|v| v.is_null()).unwrap_or(true);
410        if absent {
411            if let Some(v) = parent_effective.get(k).filter(|v| !v.is_null()) {
412                out.insert(k.into(), v.clone());
413            }
414        }
415    }
416    Value::Object(out)
417}
418
419/// Walk root to leaf comparing each step against its parent's EFFECTIVE
420/// capability (inherited dimensions included). Returns the first offending
421/// dimension.
422pub fn first_broader_step(views: &[Value]) -> std::result::Result<(), Dimension> {
423    let Some(first) = views.first() else {
424        return Ok(());
425    };
426    let mut effective = first.clone();
427    for child in &views[1..] {
428        non_expansion(&effective, child)?;
429        effective = inherit(&effective, child);
430    }
431    Ok(())
432}
433
434// --------------------------------------------------------------------------
435// Full chain validation
436// --------------------------------------------------------------------------
437
438fn link_str<'a>(link: &'a Value, key: &str) -> Option<&'a str> {
439    link.get(key).and_then(|v| v.as_str())
440}
441
442/// Validate a delegation chain ordered root -> leaf under the v1.7 rules.
443///
444/// * `trusted_roots` empty => the root-trust check is skipped (the caller
445///   anchors trust elsewhere); otherwise the root issuer must be present.
446/// * `revoked_link_indices` are links the caller has resolved as revoked
447///   (credential- or DID-level); any hit rejects the whole chain (cascade).
448/// * `budget` caps the verifier's work; `None` fields are unlimited.
449///
450/// Returns `Ok(())` when the chain is valid, or the first [`DelegationReject`].
451pub fn validate_chain(
452    chain: &[Value],
453    trusted_roots: &[String],
454    revoked_link_indices: &[usize],
455    budget: &VerifierBudget,
456    now_iso: &str,
457    clock_skew_seconds: i64,
458) -> DResult {
459    if chain.is_empty() {
460        return Err(DelegationReject::Malformed {
461            detail: "empty delegation chain".into(),
462        });
463    }
464
465    // Verifier budget: depth.
466    if let Some(max) = budget.max_depth {
467        if chain.len() > max {
468            return Err(DelegationReject::VerifierBudgetExceeded {
469                limit: "depth".into(),
470            });
471        }
472    }
473
474    // Every link must be an object with issuer and subject.
475    for (i, link) in chain.iter().enumerate() {
476        if link.as_object().is_none() {
477            return Err(DelegationReject::Malformed {
478                detail: format!("link {i} is not an object"),
479            });
480        }
481        if link_str(link, "issuer").is_none() || link_str(link, "subject").is_none() {
482            return Err(DelegationReject::Malformed {
483                detail: format!("link {i} missing issuer/subject"),
484            });
485        }
486    }
487
488    // Root trust.
489    if !trusted_roots.is_empty() {
490        let root_issuer = link_str(&chain[0], "issuer").unwrap();
491        if !trusted_roots.iter().any(|r| r == root_issuer) {
492            return Err(DelegationReject::UntrustedPrincipal);
493        }
494    }
495
496    // Cascade revocation: a revoked link invalidates the whole chain.
497    if let Some(&idx) = revoked_link_indices.iter().min() {
498        if idx < chain.len() {
499            return Err(DelegationReject::DelegationRevoked { link_index: idx });
500        }
501    }
502
503    // Linkage and non-expansion for each step against its parent's effective
504    // capability (dimensions a link omits are inherited).
505    let mut effective = chain[0].clone();
506    for i in 1..chain.len() {
507        let parent = &chain[i - 1];
508        let child = &chain[i];
509        if link_str(parent, "subject") != link_str(child, "issuer") {
510            return Err(DelegationReject::SubjectIssuerMismatch { link_index: i });
511        }
512        let checked = non_expansion(&effective, child);
513        effective = inherit(&effective, child);
514        checked.map_err(|dimension| DelegationReject::ScopeExceedsParent { dimension })?;
515    }
516
517    // Effective validity window: the intersection of every link's window, i.e.
518    // the latest start and the earliest end. `now` must fall inside it.
519    let mut eff_start: Option<i64> = None;
520    let mut eff_end: Option<i64> = None;
521    let mut cumulative_ttl: i64 = 0;
522    for link in chain {
523        let (vf, vu) = window(link).map_err(|e| DelegationReject::Malformed {
524            detail: e.to_string(),
525        })?;
526        if let Some(f) = vf {
527            eff_start = Some(eff_start.map_or(f, |cur| cur.max(f)));
528        }
529        if let Some(u) = vu {
530            eff_end = Some(eff_end.map_or(u, |cur| cur.min(u)));
531        }
532        if let (Some(f), Some(u)) = (vf, vu) {
533            if u >= f {
534                cumulative_ttl += u - f;
535            }
536        }
537    }
538    let now = iso_to_epoch_seconds(now_iso).map_err(|e| DelegationReject::Malformed {
539        detail: e.to_string(),
540    })?;
541    if let Some(f) = eff_start {
542        if now < f - clock_skew_seconds {
543            return Err(DelegationReject::OutsideValidityWindow);
544        }
545    }
546    if let Some(u) = eff_end {
547        if now > u + clock_skew_seconds {
548            return Err(DelegationReject::OutsideValidityWindow);
549        }
550    }
551
552    // Verifier budget: cumulative TTL across the chain.
553    if let Some(max) = budget.max_cumulative_ttl_seconds {
554        if cumulative_ttl > max {
555            return Err(DelegationReject::VerifierBudgetExceeded {
556                limit: "cumulative_ttl".into(),
557            });
558        }
559    }
560
561    Ok(())
562}
563
564// --------------------------------------------------------------------------
565// JSON boundary for the SDK bindings (uniffi / wasm)
566// --------------------------------------------------------------------------
567
568/// Validate a delegation chain from a single JSON request, returning a JSON
569/// verdict. Infallible: malformed input yields a `malformed_delegation` verdict
570/// rather than an error, so every caller gets a uniform verdict shape.
571///
572/// Request:  `{ "chain": [..links..], "trustedRoots"?: [..], "revokedIndices"?:
573/// [..], "budget"?: {"maxDepth"?: n, "maxCumulativeTtlSeconds"?: n}, "nowIso":
574/// "..", "clockSkewSeconds"?: 30 }`
575///
576/// Response: `{"valid": true}` or `{"valid": false, "code": "..", ..detail..}`.
577pub fn validate_chain_json(request_json: &str) -> String {
578    let req: Value = match serde_json::from_str(request_json) {
579        Ok(v) => v,
580        Err(e) => return verdict_malformed(&format!("request json: {e}")),
581    };
582    let chain: Vec<Value> = match req.get("chain").and_then(|v| v.as_array()) {
583        Some(c) => c.clone(),
584        None => return verdict_malformed("missing chain array"),
585    };
586    let trusted_roots: Vec<String> = req
587        .get("trustedRoots")
588        .and_then(|v| v.as_array())
589        .map(|a| {
590            a.iter()
591                .filter_map(|x| x.as_str().map(String::from))
592                .collect()
593        })
594        .unwrap_or_default();
595    let revoked: Vec<usize> = req
596        .get("revokedIndices")
597        .and_then(|v| v.as_array())
598        .map(|a| {
599            a.iter()
600                .filter_map(|x| x.as_u64().map(|n| n as usize))
601                .collect()
602        })
603        .unwrap_or_default();
604    let budget = VerifierBudget {
605        max_depth: req
606            .pointer("/budget/maxDepth")
607            .and_then(|v| v.as_u64())
608            .map(|n| n as usize),
609        max_cumulative_ttl_seconds: req
610            .pointer("/budget/maxCumulativeTtlSeconds")
611            .and_then(|v| v.as_i64()),
612    };
613    let now = req.get("nowIso").and_then(|v| v.as_str()).unwrap_or("");
614    let skew = req
615        .get("clockSkewSeconds")
616        .and_then(|v| v.as_i64())
617        .unwrap_or(30);
618
619    match validate_chain(&chain, &trusted_roots, &revoked, &budget, now, skew) {
620        Ok(()) => json!({ "valid": true }).to_string(),
621        Err(r) => reject_to_json(&r).to_string(),
622    }
623}
624
625fn verdict_malformed(detail: &str) -> String {
626    json!({ "valid": false, "code": "malformed_delegation", "detail": detail }).to_string()
627}
628
629fn reject_to_json(r: &DelegationReject) -> Value {
630    let mut v = json!({ "valid": false, "code": r.code() });
631    let o = v.as_object_mut().unwrap();
632    match r {
633        DelegationReject::ScopeExceedsParent { dimension } => {
634            o.insert("dimension".into(), json!(dimension.as_str()));
635        }
636        DelegationReject::VerifierBudgetExceeded { limit } => {
637            o.insert("limit".into(), json!(limit));
638        }
639        DelegationReject::DelegationRevoked { link_index }
640        | DelegationReject::SubjectIssuerMismatch { link_index } => {
641            o.insert("linkIndex".into(), json!(link_index));
642        }
643        DelegationReject::Malformed { detail } => {
644            o.insert("detail".into(), json!(detail));
645        }
646        DelegationReject::UntrustedPrincipal | DelegationReject::OutsideValidityWindow => {}
647    }
648    v
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654    use serde_json::json;
655
656    fn link(issuer: &str, subject: &str, intent: Value) -> Value {
657        json!({
658            "issuer": issuer,
659            "subject": subject,
660            "intent": intent,
661            "validFrom": "2026-04-26T09:00:00Z",
662            "validUntil": "2026-04-26T12:00:00Z"
663        })
664    }
665
666    fn now() -> &'static str {
667        "2026-04-26T10:00:00Z"
668    }
669
670    #[test]
671    fn restate_unchanged_is_valid() {
672        let i = json!({"action":"read","target":"t","resource":"https://x/a"});
673        let chain = vec![
674            link("did:web:root", "did:web:a", i.clone()),
675            link("did:web:a", "did:web:b", i.clone()),
676        ];
677        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
678    }
679
680    #[test]
681    fn resource_narrowing_is_valid() {
682        let chain = vec![
683            link(
684                "did:web:root",
685                "did:web:a",
686                json!({"resource":"https://x/a"}),
687            ),
688            link(
689                "did:web:a",
690                "did:web:b",
691                json!({"resource":"https://x/a/b"}),
692            ),
693        ];
694        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
695    }
696
697    #[test]
698    fn resource_widening_rejected_naming_dimension() {
699        let chain = vec![
700            link(
701                "did:web:root",
702                "did:web:a",
703                json!({"resource":"https://x/a/b"}),
704            ),
705            link("did:web:a", "did:web:b", json!({"resource":"https://x/a"})),
706        ];
707        let err =
708            validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
709        assert_eq!(err.code(), "scope_exceeds_parent");
710        assert_eq!(
711            err,
712            DelegationReject::ScopeExceedsParent {
713                dimension: Dimension::Resource
714            }
715        );
716    }
717
718    #[test]
719    fn sibling_prefix_is_not_sub_resource() {
720        assert!(!is_sub_resource("https://x/a2", "https://x/a"));
721        assert!(is_sub_resource("https://x/a/b", "https://x/a"));
722        assert!(is_sub_resource("https://x/a", "https://x/a/"));
723    }
724
725    #[test]
726    fn action_superset_rejected() {
727        let chain = vec![
728            link("did:web:root", "did:web:a", json!({"action":"read"})),
729            link("did:web:a", "did:web:b", json!({"action":["read","write"]})),
730        ];
731        let err =
732            validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
733        assert_eq!(
734            err,
735            DelegationReject::ScopeExceedsParent {
736                dimension: Dimension::Action
737            }
738        );
739    }
740
741    #[test]
742    fn action_subset_ok() {
743        let chain = vec![
744            link(
745                "did:web:root",
746                "did:web:a",
747                json!({"action":["read","write"]}),
748            ),
749            link("did:web:a", "did:web:b", json!({"action":"read"})),
750        ];
751        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
752    }
753
754    #[test]
755    fn rate_widening_rejected() {
756        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
757        a["rate"] = json!({"limit":100,"window":"PT1H"});
758        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
759        b["rate"] = json!({"limit":100,"window":"PT30M"}); // twice the events/sec
760        let chain = vec![a, b];
761        let err =
762            validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
763        assert_eq!(
764            err,
765            DelegationReject::ScopeExceedsParent {
766                dimension: Dimension::Rate
767            }
768        );
769    }
770
771    #[test]
772    fn rate_narrowing_ok() {
773        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
774        a["rate"] = json!({"limit":100,"window":"PT1H"});
775        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
776        b["rate"] = json!({"limit":50,"window":"PT1H"});
777        let chain = vec![a, b];
778        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
779    }
780
781    #[test]
782    fn policy_weakening_rejected() {
783        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
784        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
785        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
786        b["policy"] = json!({"minHeartbeatAgeSeconds":100}); // weaker
787        let chain = vec![a, b];
788        let err =
789            validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
790        assert_eq!(
791            err,
792            DelegationReject::ScopeExceedsParent {
793                dimension: Dimension::Policy
794            }
795        );
796    }
797
798    #[test]
799    fn policy_dropping_constraint_rejected() {
800        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
801        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
802        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
803        b["policy"] = json!({"unrelated":true}); // dropped the parent's constraint
804        let chain = vec![a, b];
805        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_err());
806    }
807
808    #[test]
809    fn time_widening_rejected() {
810        let chain = vec![
811            json!({"issuer":"did:web:root","subject":"did:web:a","intent":{"action":"read"},
812                   "validFrom":"2026-04-26T10:00:00Z","validUntil":"2026-04-26T11:00:00Z"}),
813            json!({"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"},
814                   "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T12:00:00Z"}),
815        ];
816        let err = validate_chain(
817            &chain,
818            &[],
819            &[],
820            &VerifierBudget::default(),
821            "2026-04-26T10:30:00Z",
822            30,
823        )
824        .unwrap_err();
825        assert_eq!(
826            err,
827            DelegationReject::ScopeExceedsParent {
828                dimension: Dimension::Time
829            }
830        );
831    }
832
833    #[test]
834    fn subject_issuer_mismatch_rejected() {
835        let i = json!({"action":"read"});
836        let chain = vec![
837            link("did:web:root", "did:web:a", i.clone()),
838            link("did:web:WRONG", "did:web:b", i.clone()),
839        ];
840        let err =
841            validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
842        assert_eq!(
843            err,
844            DelegationReject::SubjectIssuerMismatch { link_index: 1 }
845        );
846    }
847
848    #[test]
849    fn untrusted_root_rejected() {
850        let i = json!({"action":"read"});
851        let chain = vec![link("did:web:root", "did:web:a", i)];
852        let err = validate_chain(
853            &chain,
854            &["did:web:other".into()],
855            &[],
856            &VerifierBudget::default(),
857            now(),
858            30,
859        )
860        .unwrap_err();
861        assert_eq!(err, DelegationReject::UntrustedPrincipal);
862    }
863
864    #[test]
865    fn cascade_revocation_rejects_whole_chain() {
866        let i = json!({"action":"read"});
867        let chain = vec![
868            link("did:web:root", "did:web:a", i.clone()),
869            link("did:web:a", "did:web:b", i.clone()),
870            link("did:web:b", "did:web:c", i.clone()),
871        ];
872        // middle link revoked
873        let err =
874            validate_chain(&chain, &[], &[1], &VerifierBudget::default(), now(), 30).unwrap_err();
875        assert_eq!(err, DelegationReject::DelegationRevoked { link_index: 1 });
876    }
877
878    #[test]
879    fn budget_depth_exceeded() {
880        let i = json!({"action":"read"});
881        let chain = vec![
882            link("did:web:root", "did:web:a", i.clone()),
883            link("did:web:a", "did:web:b", i.clone()),
884            link("did:web:b", "did:web:c", i.clone()),
885        ];
886        let budget = VerifierBudget {
887            max_depth: Some(2),
888            max_cumulative_ttl_seconds: None,
889        };
890        let err = validate_chain(&chain, &[], &[], &budget, now(), 30).unwrap_err();
891        assert_eq!(
892            err,
893            DelegationReject::VerifierBudgetExceeded {
894                limit: "depth".into()
895            }
896        );
897    }
898
899    #[test]
900    fn deep_but_attenuating_chain_is_valid_without_depth_cap() {
901        // Ten hops, each restating the same authority: valid now that the fixed
902        // depth limit is gone (this is the whole point of v1.7).
903        let mut chain = Vec::new();
904        let i = json!({"action":"read","resource":"https://x/a"});
905        for n in 0..10 {
906            let issuer = if n == 0 {
907                "did:web:root".to_string()
908            } else {
909                format!("did:web:h{}", n - 1)
910            };
911            let subject = format!("did:web:h{n}");
912            chain.push(link(&issuer, &subject, i.clone()));
913        }
914        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
915    }
916
917    #[test]
918    fn now_outside_effective_window_rejected() {
919        let chain = vec![link("did:web:root", "did:web:a", json!({"action":"read"}))];
920        let err = validate_chain(
921            &chain,
922            &[],
923            &[],
924            &VerifierBudget::default(),
925            "2026-04-26T20:00:00Z",
926            30,
927        )
928        .unwrap_err();
929        assert_eq!(err, DelegationReject::OutsideValidityWindow);
930    }
931
932    #[test]
933    fn absent_child_dimension_inherits_and_passes() {
934        let chain = vec![
935            link(
936                "did:web:root",
937                "did:web:a",
938                json!({"action":"read","resource":"https://x/a"}),
939            ),
940            link(
941                "did:web:a",
942                "did:web:b",
943                json!({"resource":"https://x/a/b"}),
944            ), // action omitted => inherit
945        ];
946        assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
947    }
948
949    #[test]
950    fn duration_parser() {
951        assert_eq!(parse_duration_seconds("PT1H").unwrap(), 3600);
952        assert_eq!(parse_duration_seconds("PT30M").unwrap(), 1800);
953        assert_eq!(parse_duration_seconds("PT1H30M15S").unwrap(), 5415);
954        assert_eq!(parse_duration_seconds("P1D").unwrap(), 86400);
955        assert!(parse_duration_seconds("1H").is_err());
956        assert!(parse_duration_seconds("PT").is_err());
957    }
958}