Skip to main content

hyprstream_rpc/auth/ucan/
chain.rs

1//! **Delegation-chain + ceiling/attenuation validation** — the core correctness
2//! component of S5 (#571).
3//!
4//! Per the epic (#547, design "ceiling/attenuation"): *every* delegation in a
5//! UCAN chain must be a SUBSET (attenuation) of its delegator's authority — a
6//! child can never widen. This module walks the proof chain of a UCAN and
7//! enforces, at each link, the two structural invariants that make the chain a
8//! genuine ceiling:
9//!
10//! 1. **Linkage:** the delegate UCAN's *issuer* must equal the delegator
11//!    (proof) UCAN's *audience*. Authority flows `proof.audience → ucan.issuer`;
12//!    a chain where the issuer was not the party the proof delegated to is
13//!    forged.
14//! 2. **Attenuation (⊆):** every capability the delegate UCAN claims must be
15//!    authorized by the delegator's capability set
16//!    ([`super::capability::set_attenuates`]). A delegate that widens on
17//!    resource, ability, or caveats is rejected.
18//!
19//! Plus the temporal and structural gates, which are TWO independent checks:
20//!
21//! - **Relative window containment** ([`window_within`]): a child cannot outlive
22//!   its parent — its `[not_before, expiration]` window must be within the
23//!   delegator's. This bounds the chain *shape* but says nothing about the
24//!   wall-clock.
25//! - **Absolute validity at `now`** ([`super::token::Ucan::is_valid_at`]): EVERY
26//!   link must be live at the validation instant — not expired and not
27//!   future-dated (`not_before <= now <= expiration`). Relative containment alone
28//!   is NOT sufficient: a fully-attenuating, correctly-linked chain in which
29//!   every link has already EXPIRED still satisfies window containment, so
30//!   without the absolute check it would validate and could be replayed/compiled
31//!   into a ceiling. Both gates are therefore enforced, per link.
32//!
33//! And recursion to the root (a root has no proofs and grants whatever it
34//! self-asserts), with a bounded proof depth ([`MAX_PROOF_DEPTH`]) so a
35//! maliciously deep nested-proof chain cannot exhaust the stack (a DoS guard, not
36//! an authority concern).
37//!
38//! **Fail-closed everywhere.** Any malformation, missing link, widening,
39//! out-of-window, expired/not-yet-valid, or over-depth condition rejects the
40//! entire chain. This is intentionally conservative TCB code: a false reject is a
41//! denied request; a false accept is a privilege escalation, so the asymmetry is
42//! always resolved toward rejection.
43//!
44//! ## Scope (milestone 1)
45//!
46//! Signature verification is assumed already done by
47//! [`super::token::Ucan::verify_signatures`] — `validate_chain` covers linkage,
48//! attenuation, relative window containment, absolute validity at `now`, and the
49//! depth bound. Callers run signatures first, then this; the combined entry point
50//! [`validate`] does both in the correct order. Revocation lists and a richer
51//! multi-proof "any-path" model are milestone-2 seams; M1 validates the
52//! single-delegator-per-link chain (each UCAN's `proofs[i]` is *a* delegator that
53//! must independently cover the claims).
54
55use super::capability::set_attenuates;
56use super::token::{Ucan, UcanError, UcanVerifier};
57use std::fmt;
58
59/// Why a delegation chain was rejected. Every variant is a fail-closed denial.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ChainError {
62    /// A signature failed to verify (wraps [`UcanError`]).
63    Signature(UcanError),
64    /// Structural malformation (wraps [`UcanError`]).
65    Structure(UcanError),
66    /// The delegate's issuer is not the delegator's audience — broken linkage.
67    BrokenLinkage {
68        /// The delegate UCAN's issuer (who claims to wield the authority).
69        delegate_issuer: String,
70        /// The delegator (proof) UCAN's audience (who the authority was given to).
71        delegator_audience: String,
72    },
73    /// The delegate claims a capability its delegator does not authorize — an
74    /// attempt to WIDEN authority across a delegation. The cardinal violation.
75    Widening {
76        /// 0-based index of the offending link from the leaf (0 = leaf→its proof).
77        link: usize,
78    },
79    /// The child's validity window is not contained within its delegator's
80    /// (a child cannot be valid when its parent is not).
81    WindowEscape {
82        /// 0-based link index.
83        link: usize,
84    },
85    /// A link is not live at the validation instant `now`: it has expired
86    /// (`now > expiration`) or is not yet valid (`now < not_before`). Absolute
87    /// time check — independent of relative window containment. Fail-closed: an
88    /// expired chain MUST deny.
89    Expired {
90        /// 0-based link index (0 = leaf).
91        link: usize,
92    },
93    /// The proof chain is nested deeper than [`MAX_PROOF_DEPTH`]. A DoS guard
94    /// against stack exhaustion from a maliciously deep chain — not an
95    /// authority-widening concern, but rejected fail-closed all the same.
96    DepthExceeded {
97        /// The depth at which the bound was exceeded.
98        depth: usize,
99    },
100    /// A non-root UCAN carried no proofs (cannot be authorized) — only a root
101    /// may have an empty proof set, and a root is the *top* of the chain.
102    MissingProof,
103}
104
105/// Maximum delegation-chain (nested-proof) depth this validator will walk. A
106/// chain deeper than this is rejected fail-closed ([`ChainError::DepthExceeded`])
107/// before recursion can exhaust the stack. UCAN delegation chains are short by
108/// construction (a handful of hops); this bound is generous for legitimate use
109/// while capping a hostile `proofs`-within-`proofs` nesting (a DoS vector at both
110/// parse time and walk time). The same bound is enforced at CBOR decode in
111/// [`super::token::Ucan::from_cbor`] so an over-deep token is refused before it
112/// is ever walked.
113pub const MAX_PROOF_DEPTH: usize = 32;
114
115impl fmt::Display for ChainError {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            ChainError::Signature(e) => write!(f, "chain signature invalid: {e}"),
119            ChainError::Structure(e) => write!(f, "chain structurally invalid: {e}"),
120            ChainError::BrokenLinkage { delegate_issuer, delegator_audience } => write!(
121                f,
122                "broken delegation linkage: delegate issuer {delegate_issuer} != delegator audience {delegator_audience}"
123            ),
124            ChainError::Widening { link } => {
125                write!(f, "attenuation violation (widening) at chain link {link}")
126            }
127            ChainError::WindowEscape { link } => {
128                write!(f, "validity window escapes delegator at chain link {link}")
129            }
130            ChainError::Expired { link } => {
131                write!(
132                    f,
133                    "chain link {link} is not live at the validation instant (expired or not yet valid)"
134                )
135            }
136            ChainError::DepthExceeded { depth } => {
137                write!(
138                    f,
139                    "delegation chain exceeds maximum proof depth {MAX_PROOF_DEPTH} (at depth {depth})"
140                )
141            }
142            ChainError::MissingProof => {
143                write!(f, "non-root UCAN has no delegating proof (cannot authorize)")
144            }
145        }
146    }
147}
148
149impl std::error::Error for ChainError {}
150
151/// Is the child's validity window contained within the parent's? A child may not
152/// start before the parent or end after it. `None` bounds are treated as the
153/// widest possible on that side, so:
154/// - child unbounded-below + parent bounded-below ⇒ escape.
155/// - child unbounded-above + parent bounded-above ⇒ escape.
156fn window_within(child: &Ucan, parent: &Ucan) -> bool {
157    // not_before: child must not begin earlier than parent.
158    let nbf_ok = match (child.payload.not_before, parent.payload.not_before) {
159        (_, None) => true,        // parent unbounded below
160        (None, Some(_)) => false, // child unbounded below, parent not
161        (Some(c), Some(p)) => c >= p,
162    };
163    // expiration: child must not end later than parent.
164    let exp_ok = match (child.payload.expiration, parent.payload.expiration) {
165        (_, None) => true,        // parent unbounded above
166        (None, Some(_)) => false, // child unbounded above, parent not
167        (Some(c), Some(p)) => c <= p,
168    };
169    nbf_ok && exp_ok
170}
171
172/// Validate ONE delegation edge: `delegate` is authorized by `delegator`
173/// (`delegate`'s proof). Enforces linkage, attenuation, and window containment.
174/// `link` is the index used in error reporting.
175fn validate_edge(delegate: &Ucan, delegator: &Ucan, link: usize) -> Result<(), ChainError> {
176    // 1. Linkage: authority flows delegator.audience → delegate.issuer.
177    if delegate.issuer() != delegator.audience() {
178        return Err(ChainError::BrokenLinkage {
179            delegate_issuer: delegate.issuer().as_str().to_owned(),
180            delegator_audience: delegator.audience().as_str().to_owned(),
181        });
182    }
183    // 2. Attenuation: the delegator's capabilities must cover the delegate's.
184    if !set_attenuates(delegator.capabilities(), delegate.capabilities()) {
185        return Err(ChainError::Widening { link });
186    }
187    // 3. Window containment: child cannot outlive its parent.
188    if !window_within(delegate, delegator) {
189        return Err(ChainError::WindowEscape { link });
190    }
191    Ok(())
192}
193
194/// Recursively validate the delegation chain rooted at `ucan` (structural +
195/// temporal — run signatures separately, or use [`validate`]).
196///
197/// Checks, on EVERY node (the leaf, every intermediate, and the root):
198/// - **absolute validity at `now`** via [`Ucan::is_valid_at`] — the link must be
199///   live (not expired, not future-dated) at the single caller-supplied instant;
200/// - for each `proof` in `ucan.proofs`, the edge `ucan ⟶ proof` (linkage +
201///   attenuation + relative window containment), then recurses into the proof.
202///
203/// A UCAN with no proofs is a **root** and authorizes whatever it self-asserts
204/// (its capabilities become the ceiling) — but it is STILL clock-checked.
205///
206/// `now` is a **single trusted clock value supplied by the caller**, threaded
207/// down UNCHANGED to every link. It is never taken from a token's own fields, so
208/// a forged `not_before`/`expiration` cannot self-certify validity — it can only
209/// narrow (the relative-window check) or fail the absolute check against the one
210/// authoritative `now`.
211///
212/// `link` is the depth from the original leaf, used both for diagnostics and as
213/// the [`MAX_PROOF_DEPTH`] DoS bound.
214pub fn validate_chain(ucan: &Ucan, now: u64) -> Result<(), ChainError> {
215    validate_chain_at(ucan, now, 0)
216}
217
218fn validate_chain_at(ucan: &Ucan, now: u64, link: usize) -> Result<(), ChainError> {
219    // Depth bound FIRST — cap recursion before doing any work at this level so a
220    // hostile deep chain cannot exhaust the stack (DoS guard, fail-closed).
221    if link >= MAX_PROOF_DEPTH {
222        return Err(ChainError::DepthExceeded { depth: link });
223    }
224    // Absolute time on THIS node (covers leaf, intermediates, and the root). The
225    // same `now` is used at every level — never derived from the token.
226    if !ucan.is_valid_at(now) {
227        return Err(ChainError::Expired { link });
228    }
229    if ucan.proofs.is_empty() {
230        // Root: self-asserted authority is the top of the ceiling. Nothing above
231        // to attenuate against. (Whether a given root DID is *trusted* to assert
232        // is the verifier/trust-anchor concern, handled at signature time and by
233        // the approval binding — not structural attenuation.) Still clock-checked
234        // above.
235        return Ok(());
236    }
237    for proof in &ucan.proofs {
238        validate_edge(ucan, proof, link)?;
239        validate_chain_at(proof, now, link + 1)?;
240    }
241    Ok(())
242}
243
244/// The full fail-closed validation a compiler front-end runs before lowering a
245/// UCAN into a ceiling: **(1) structure, (2) signatures, (3) delegation chain +
246/// attenuation + temporal validity at `now`**, in that order. Returns `Ok(())`
247/// only if every link is structurally sound, correctly signed under the hybrid
248/// policy, properly linked, strictly attenuating, within its delegator's window,
249/// AND live at `now` (not expired, not future-dated), with the chain no deeper
250/// than [`MAX_PROOF_DEPTH`].
251///
252/// `now` is the single trusted current time (unix seconds) the caller supplies;
253/// it is threaded unchanged to every link. The caller is responsible for sourcing
254/// a trustworthy clock — the validator never reads "now" from the token.
255///
256/// This is the single entry point S5's compiler calls; it guarantees that only a
257/// genuine, currently-live ceiling reaches the (deferred) bundle-emission stage.
258pub fn validate<V: UcanVerifier + ?Sized>(
259    ucan: &Ucan,
260    verifier: &V,
261    now: u64,
262) -> Result<(), ChainError> {
263    ucan.validate_structure().map_err(ChainError::Structure)?;
264    ucan.verify_signatures(verifier)
265        .map_err(ChainError::Signature)?;
266    validate_chain(ucan, now)
267}
268
269#[cfg(test)]
270#[allow(clippy::unwrap_used)]
271mod tests {
272    use super::super::token::test_support::*;
273    use super::*;
274    use crate::auth::ucan::capability::{Ability, Capability, CaveatValue, Caveats, Resource};
275    use crate::auth::ucan::token::{Did, Ucan, UcanPayload, UCAN_AAD};
276    use crate::crypto::cose_sign::sign_composite;
277    use std::collections::BTreeMap;
278
279    /// Re-sign a (possibly mutated) payload so we can test *structural* chain
280    /// rejections without the signature failing first.
281    fn resign(issuer: &TestIdentity, payload: UcanPayload, proofs: Vec<Ucan>) -> Ucan {
282        let bytes = payload.signing_bytes().unwrap();
283        let signature =
284            sign_composite(&issuer.ed_sk, Some(&issuer.pq_sk), &bytes, UCAN_AAD).unwrap();
285        Ucan {
286            payload,
287            proofs,
288            signature,
289        }
290    }
291
292    fn store(ids: &[&TestIdentity]) -> TestTrustStore {
293        let mut s = TestTrustStore::new();
294        for id in ids {
295            s.anchor(id);
296        }
297        s
298    }
299
300    /// A wall-clock instant that is within the validity window of every UCAN the
301    /// `signed_ucan` helper mints (`not_before: None`, `expiration:
302    /// 9_999_999_999`) and within the explicit windows used by the temporal
303    /// tests. Passed as the trusted `now` to `validate`/`validate_chain`.
304    const NOW: u64 = 1_000;
305
306    // ---- Happy path: a properly attenuating chain ------------------------
307
308    #[test]
309    fn valid_attenuating_chain_accepted() {
310        // root: mac://* / *   →  alice: mac://model/* / model/*  →  bob: mac://model/qwen / model/read
311        let root = TestIdentity::generate();
312        let alice = TestIdentity::generate();
313        let bob = TestIdentity::generate();
314
315        let root_ucan = signed_ucan(&root, &alice.did(), vec![cap("mac://*", "*")], vec![]);
316        let alice_ucan = signed_ucan(
317            &alice,
318            &bob.did(),
319            vec![cap("mac://model/*", "model/*")],
320            vec![root_ucan],
321        );
322        let bob_ucan = signed_ucan(
323            &bob,
324            &bob.did(),
325            vec![cap("mac://model/qwen", "model/read")],
326            vec![alice_ucan],
327        );
328
329        let s = store(&[&root, &alice, &bob]);
330        assert!(
331            validate(&bob_ucan, &s, NOW).is_ok(),
332            "a strictly-attenuating chain must validate"
333        );
334    }
335
336    #[test]
337    fn root_with_no_proofs_is_self_authorizing() {
338        let root = TestIdentity::generate();
339        let u = signed_ucan(&root, &root.did(), vec![cap("mac://anything", "*")], vec![]);
340        let s = store(&[&root]);
341        assert!(validate(&u, &s, NOW).is_ok());
342    }
343
344    // ---- Widening: the cardinal rejection --------------------------------
345
346    #[test]
347    fn widening_resource_rejected() {
348        // alice was delegated mac://model/* but bob claims mac://other/x.
349        let root = TestIdentity::generate();
350        let alice = TestIdentity::generate();
351        let bob = TestIdentity::generate();
352        let root_ucan = signed_ucan(&root, &alice.did(), vec![cap("mac://model/*", "*")], vec![]);
353        let alice_ucan = signed_ucan(
354            &alice,
355            &bob.did(),
356            vec![cap("mac://other/x", "model/read")],
357            vec![root_ucan],
358        );
359        let s = store(&[&root, &alice]);
360        match validate(&alice_ucan, &s, NOW) {
361            Err(ChainError::Widening { link: 0 }) => {}
362            other => panic!("expected Widening at link 0, got {other:?}"),
363        }
364    }
365
366    #[test]
367    fn widening_ability_rejected() {
368        let root = TestIdentity::generate();
369        let alice = TestIdentity::generate();
370        let bob = TestIdentity::generate();
371        let root_ucan = signed_ucan(
372            &root,
373            &alice.did(),
374            vec![cap("mac://*", "model/read")],
375            vec![],
376        );
377        // bob tries to gain model/* from a model/read delegation.
378        let alice_ucan = signed_ucan(
379            &alice,
380            &bob.did(),
381            vec![cap("mac://model/qwen", "model/*")],
382            vec![root_ucan],
383        );
384        let s = store(&[&root, &alice]);
385        assert!(matches!(
386            validate(&alice_ucan, &s, NOW),
387            Err(ChainError::Widening { .. })
388        ));
389    }
390
391    #[test]
392    fn widening_deep_in_chain_rejected() {
393        // root→alice valid, alice→bob widens. Reject at link 1 (the alice→its-proof edge
394        // is fine; the bob→alice edge — link 0 here — is the widening one).
395        let root = TestIdentity::generate();
396        let alice = TestIdentity::generate();
397        let bob = TestIdentity::generate();
398        let root_ucan = signed_ucan(
399            &root,
400            &alice.did(),
401            vec![cap("mac://model/*", "model/*")],
402            vec![],
403        );
404        let alice_ucan = signed_ucan(
405            &alice,
406            &bob.did(),
407            vec![cap("mac://model/qwen", "model/read")],
408            vec![root_ucan],
409        );
410        // bob legitimately attenuates from alice, but we then tamper alice's claim to widen
411        // beyond root and re-sign so signatures still pass.
412        let mut alice_payload = alice_ucan.payload.clone();
413        alice_payload.capabilities = vec![cap("mac://admin/*", "admin/*")]; // widens past root
414        let widened_alice = resign(&alice, alice_payload, alice_ucan.proofs.clone());
415        let bob_ucan = signed_ucan(
416            &bob,
417            &bob.did(),
418            vec![cap("mac://admin/x", "admin/*")],
419            vec![widened_alice],
420        );
421        let s = store(&[&root, &alice, &bob]);
422        // The bob→alice edge passes (bob ⊆ widened alice), but alice→root widens at link 1.
423        assert!(matches!(
424            validate(&bob_ucan, &s, NOW),
425            Err(ChainError::Widening { link: 1 })
426        ));
427    }
428
429    #[test]
430    fn caveat_drop_is_widening() {
431        // root delegates with a tenant caveat; alice drops it.
432        let root = TestIdentity::generate();
433        let alice = TestIdentity::generate();
434        let mut cv = BTreeMap::new();
435        cv.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
436        let restricted = Capability::with_caveats(
437            Resource::new("mac://model/*"),
438            Ability::new("*"),
439            Caveats(cv),
440        );
441        let root_ucan = signed_ucan(&root, &alice.did(), vec![restricted], vec![]);
442        // alice claims the same resource/ability but WITHOUT the tenant caveat → widening.
443        let alice_ucan = signed_ucan(
444            &alice,
445            &alice.did(),
446            vec![cap("mac://model/qwen", "infer")],
447            vec![root_ucan],
448        );
449        let s = store(&[&root, &alice]);
450        assert!(matches!(
451            validate(&alice_ucan, &s, NOW),
452            Err(ChainError::Widening { .. })
453        ));
454    }
455
456    // ---- Linkage ---------------------------------------------------------
457
458    #[test]
459    fn broken_linkage_rejected() {
460        // root delegates to alice, but bob (not alice) presents root as its proof.
461        let root = TestIdentity::generate();
462        let alice = TestIdentity::generate();
463        let bob = TestIdentity::generate();
464        let root_to_alice = signed_ucan(&root, &alice.did(), vec![cap("mac://*", "*")], vec![]);
465        // bob issues a UCAN citing root_to_alice as proof — but bob != alice.
466        let bob_ucan = signed_ucan(
467            &bob,
468            &bob.did(),
469            vec![cap("mac://model/x", "infer")],
470            vec![root_to_alice],
471        );
472        let s = store(&[&root, &bob]);
473        assert!(matches!(
474            validate(&bob_ucan, &s, NOW),
475            Err(ChainError::BrokenLinkage { .. })
476        ));
477    }
478
479    // ---- Temporal window -------------------------------------------------
480
481    #[test]
482    fn child_outliving_parent_rejected() {
483        let root = TestIdentity::generate();
484        let alice = TestIdentity::generate();
485        // root expires at 1000.
486        let mut root_payload = UcanPayload {
487            issuer: root.did(),
488            audience: alice.did(),
489            capabilities: vec![cap("mac://*", "*")],
490            not_before: None,
491            expiration: Some(1000),
492            nonce: vec![],
493        };
494        let root_ucan = resign(&root, root_payload.clone(), vec![]);
495        // alice expires at 2000 — outlives root → window escape.
496        let alice_payload = UcanPayload {
497            issuer: alice.did(),
498            audience: alice.did(),
499            capabilities: vec![cap("mac://model/x", "infer")],
500            not_before: None,
501            expiration: Some(2000),
502            nonce: vec![],
503        };
504        let alice_ucan = resign(&alice, alice_payload, vec![root_ucan]);
505        let s = store(&[&root, &alice]);
506        assert!(matches!(
507            validate(&alice_ucan, &s, NOW),
508            Err(ChainError::WindowEscape { .. })
509        ));
510
511        // Same window (alice within root) is fine.
512        root_payload.expiration = Some(2000);
513        let root_ok = resign(&root, root_payload, vec![]);
514        let alice_ok_payload = UcanPayload {
515            issuer: alice.did(),
516            audience: alice.did(),
517            capabilities: vec![cap("mac://model/x", "infer")],
518            not_before: None,
519            expiration: Some(2000),
520            nonce: vec![],
521        };
522        let alice_ok = resign(&alice, alice_ok_payload, vec![root_ok]);
523        let _ = Did::new("did:key:placeholder".to_owned()); // keep Did import used
524        assert!(validate(&alice_ok, &store(&[&root, &alice]), NOW).is_ok());
525    }
526
527    // ---- Signature ordering ----------------------------------------------
528
529    #[test]
530    fn validate_runs_signatures_before_chain() {
531        // A widening chain whose signatures are ALSO invalid should report a
532        // signature error (signatures gate first).
533        let root = TestIdentity::generate();
534        let alice = TestIdentity::generate();
535        let root_ucan = signed_ucan(&root, &alice.did(), vec![cap("mac://model/*", "*")], vec![]);
536        let mut alice_ucan = signed_ucan(
537            &alice,
538            &alice.did(),
539            vec![cap("mac://other/x", "*")],
540            vec![root_ucan],
541        );
542        alice_ucan.signature[0] ^= 0xFF; // break alice's signature
543        let s = store(&[&root, &alice]);
544        assert!(matches!(
545            validate(&alice_ucan, &s, NOW),
546            Err(ChainError::Signature(_))
547        ));
548    }
549
550    // ---- Absolute time at `now` (the fail-open fix, #590) ----------------
551
552    /// Mint a self-issued (root) UCAN with an explicit validity window, properly
553    /// hybrid-signed, plus its trust store.
554    fn windowed_root(nbf: Option<u64>, exp: Option<u64>) -> (Ucan, TestTrustStore) {
555        let id = TestIdentity::generate();
556        let payload = UcanPayload {
557            issuer: id.did(),
558            audience: id.did(),
559            capabilities: vec![cap("mac://model/*", "infer")],
560            not_before: nbf,
561            expiration: exp,
562            nonce: vec![],
563        };
564        let u = resign(&id, payload, vec![]);
565        (u, store(&[&id]))
566    }
567
568    #[test]
569    fn expired_chain_denied() {
570        // A perfectly signed, linked, self-asserting chain that EXPIRED at 500.
571        // Relative window containment is satisfied (root has no parent), so before
572        // the absolute check this validated — the fail-open. Now: deny at now=1000.
573        let (u, s) = windowed_root(None, Some(500));
574        assert!(matches!(
575            validate(&u, &s, 1000),
576            Err(ChainError::Expired { link: 0 })
577        ));
578    }
579
580    #[test]
581    fn future_nbf_denied() {
582        // Not-yet-valid: not_before is in the future relative to `now`.
583        let (u, s) = windowed_root(Some(5000), Some(9000));
584        assert!(matches!(
585            validate(&u, &s, 1000),
586            Err(ChainError::Expired { link: 0 })
587        ));
588    }
589
590    #[test]
591    fn valid_at_now_accepted() {
592        // Live window straddling `now` validates.
593        let (u, s) = windowed_root(Some(500), Some(2000));
594        assert!(validate(&u, &s, 1000).is_ok());
595        // Boundary instants are inclusive (now == nbf and now == exp).
596        assert!(validate(&u, &s, 500).is_ok());
597        assert!(validate(&u, &s, 2000).is_ok());
598    }
599
600    #[test]
601    fn expiry_checked_across_a_multi_link_chain() {
602        // A 2-link root → leaf chain that is fully within-window (containment OK).
603        // It validates while live and is denied once expired — exercising the
604        // per-link absolute check through the recursion (not just a 1-node chain).
605        //
606        // Note on why "leaf live but a deeper proof expired" is NOT testable here:
607        // window containment forces leaf.window ⊆ proof.window, so the leaf can
608        // never outlive its proof. The per-link check on deeper nodes is therefore
609        // exercised by (a) `expired_chain_denied` — a root (the *bottom* link) is
610        // clock-checked — and (b) this multi-link chain denying when expired.
611        let root = TestIdentity::generate();
612        let leaf = TestIdentity::generate();
613        let root_payload = UcanPayload {
614            issuer: root.did(),
615            audience: leaf.did(),
616            capabilities: vec![cap("mac://*", "*")],
617            not_before: Some(100),
618            expiration: Some(2000),
619            nonce: vec![],
620        };
621        let root_ucan = resign(&root, root_payload, vec![]);
622        let leaf_payload = UcanPayload {
623            issuer: leaf.did(),
624            audience: leaf.did(),
625            capabilities: vec![cap("mac://model/x", "infer")],
626            not_before: Some(100),
627            expiration: Some(2000),
628            nonce: vec![],
629        };
630        let leaf_ucan = resign(&leaf, leaf_payload, vec![root_ucan]);
631        let s = store(&[&root, &leaf]);
632        // Live: validates.
633        assert!(validate(&leaf_ucan, &s, 1000).is_ok());
634        // Expired: denied on the clock.
635        assert!(matches!(
636            validate(&leaf_ucan, &s, 3000),
637            Err(ChainError::Expired { .. })
638        ));
639        // Not yet valid: denied.
640        assert!(matches!(
641            validate(&leaf_ucan, &s, 50),
642            Err(ChainError::Expired { .. })
643        ));
644    }
645
646    // ---- Proof-depth DoS bound ------------------------------------------
647
648    /// Build a linear self-delegating chain of `n` links (leaf has `n-1` nested
649    /// proofs), all hybrid-signed and live at `NOW`. Returns (leaf, store).
650    fn linear_chain(n: usize) -> (Ucan, TestTrustStore) {
651        let id = TestIdentity::generate();
652        let mk = |proofs: Vec<Ucan>| {
653            let payload = UcanPayload {
654                issuer: id.did(),
655                audience: id.did(),
656                capabilities: vec![cap("mac://model/*", "infer")],
657                not_before: None,
658                expiration: Some(9_999_999_999),
659                nonce: vec![],
660            };
661            resign(&id, payload, proofs)
662        };
663        let mut u = mk(vec![]);
664        for _ in 1..n {
665            u = mk(vec![u]);
666        }
667        (u, store(&[&id]))
668    }
669
670    #[test]
671    fn max_depth_chain_accepted_one_over_rejected() {
672        // A chain exactly at the bound walks fine.
673        let (ok, s) = linear_chain(MAX_PROOF_DEPTH);
674        assert!(validate(&ok, &s, NOW).is_ok());
675        // One link deeper than the bound is rejected fail-closed.
676        let (deep, s2) = linear_chain(MAX_PROOF_DEPTH + 1);
677        assert!(matches!(
678            validate(&deep, &s2, NOW),
679            Err(ChainError::DepthExceeded { .. })
680        ));
681    }
682
683    #[test]
684    fn over_deep_chain_rejected_at_cbor_decode() {
685        // The DoS bound is also enforced at parse time: an over-deep token is
686        // refused by `from_cbor` before it can ever be walked.
687        let (deep, _) = linear_chain(MAX_PROOF_DEPTH + 1);
688        let bytes = deep.to_cbor().unwrap();
689        assert!(matches!(
690            Ucan::from_cbor(&bytes),
691            Err(crate::auth::ucan::token::UcanError::Malformed(_))
692        ));
693        // A chain within the bound round-trips through from_cbor fine.
694        let (ok, _) = linear_chain(MAX_PROOF_DEPTH);
695        let ok_bytes = ok.to_cbor().unwrap();
696        assert!(Ucan::from_cbor(&ok_bytes).is_ok());
697    }
698}