Skip to main content

byteflow/scheduler/
capability.rs

1//! Runtime-local capability table (Phase 3 — FlowCap + attenuate).
2//!
3//! A [`CapId`] is an opaque 128-bit token, **not** an authorization.
4//! Authorization lives in [`Cap`], owned by one [`crate::Runtime`]:
5//!
6//! ```text
7//! CapId  →  { holder, Cap { target, rights, native_mask, epoch } }
8//! ```
9//!
10//! Every derived grant goes through [`Cap::attenuate`]. `mint` is the
11//! trusted-runtime root path (self Cap, spawn addressing). Hop `reply_cap`
12//! uses [`CapTable::mint_or_reuse`] — one live SEND token per
13//! `(holder, target)` pair. `revoke_flow` sweeps every Cap that targets or
14//! is held by the exiting flow (including the reverse reply index).
15//!
16//! See `docs/security.md` (S6 / S7) and `docs/atomic-hop.md`.
17
18// Docs ratchet: public items here predate `missing_docs`. Delete this
19// allow once they are documented; new files get the lint by default.
20#![allow(missing_docs)]
21
22use std::collections::HashMap;
23use std::sync::{Arc, Mutex};
24
25use crate::bytecode::{Cap, CapId, CapTarget, NativeMask, RevocationCell};
26
27pub use crate::bytecode::CapRights;
28
29use super::error::RuntimeError;
30use super::process::FlowId;
31use super::sync_lock;
32
33const MINT_ATTEMPTS: u32 = 32;
34
35/// One live capability entry. The [`CapId`] is the map key, not a field.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Capability {
38    /// Flow allowed to *use* this token.
39    pub holder: FlowId,
40    pub cap: Cap,
41}
42
43impl Capability {
44    /// Flow this Cap addresses, if the target is a flow.
45    pub fn target(&self) -> Option<FlowId> {
46        self.cap.target().flow_id().map(FlowId)
47    }
48
49    pub fn rights(&self) -> CapRights {
50        self.cap.rights()
51    }
52}
53
54/// Why `CapTable::resolve` / `CapTable::delegate` refused.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum CapError {
57    Unknown,
58    NotHolder,
59    InsufficientRights,
60    WrongTarget,
61    /// Mutex poison — fail closed (never `into_inner`).
62    Unavailable,
63    /// `Message` payload nested past the decoder ceiling.
64    TooNested,
65    /// Host correlation counter wrapped. Further mints would reuse id `1`.
66    RequestIdsExhausted,
67}
68
69impl std::fmt::Display for CapError {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            CapError::Unknown => f.write_str("unknown or revoked capability"),
73            CapError::NotHolder => f.write_str("calling flow does not hold this capability"),
74            CapError::InsufficientRights => f.write_str("capability lacks required rights"),
75            CapError::WrongTarget => f.write_str("capability target is not a flow"),
76            CapError::Unavailable => f.write_str("capability table unavailable (poisoned lock)"),
77            CapError::TooNested => f.write_str("value nesting exceeds limit"),
78            CapError::RequestIdsExhausted => f.write_str("host request ids exhausted"),
79        }
80    }
81}
82
83impl std::error::Error for CapError {}
84
85impl From<RuntimeError> for CapError {
86    fn from(_err: RuntimeError) -> Self {
87        CapError::Unavailable
88    }
89}
90
91struct CapTableInner {
92    entries: HashMap<CapId, Capability>,
93    flow_cells: HashMap<u64, Arc<RevocationCell>>,
94    /// Revocation cell of each flow-owned table, keyed by table id.
95    table_cells: HashMap<u64, Arc<RevocationCell>>,
96    /// Stable reply address: `(holder, target) → CapId`.
97    ///
98    /// Hop `reply_cap` is an *address* (SEND back to the sender), not a
99    /// per-message ticket. Correlation stays on `Message.request_id`.
100    reply_index: HashMap<(FlowId, FlowId), CapId>,
101}
102
103/// Registry `CapId → Capability`, owned by one runtime's [`super::runtime::Shared`].
104pub struct CapTable {
105    inner: Mutex<CapTableInner>,
106    native_cell: Arc<RevocationCell>,
107    scheduler_cell: Arc<RevocationCell>,
108}
109
110impl CapTable {
111    pub fn new() -> Self {
112        Self {
113            inner: Mutex::new(CapTableInner {
114                entries: HashMap::with_capacity(128),
115                flow_cells: HashMap::with_capacity(64),
116                table_cells: HashMap::with_capacity(16),
117                reply_index: HashMap::with_capacity(64),
118            }),
119            native_cell: Arc::new(RevocationCell::new()),
120            scheduler_cell: Arc::new(RevocationCell::new()),
121        }
122    }
123
124    pub fn native_cell(&self) -> Arc<RevocationCell> {
125        Arc::clone(&self.native_cell)
126    }
127
128    fn lock(
129        &self,
130        where_: &'static str,
131    ) -> Result<std::sync::MutexGuard<'_, CapTableInner>, RuntimeError> {
132        sync_lock::lock(&self.inner, where_)
133    }
134
135    /// Get-or-create the revocation cell for `flow`.
136    pub fn bind_flow(&self, flow: FlowId) -> Result<Arc<RevocationCell>, RuntimeError> {
137        let mut g = self.lock("CapTable::bind_flow")?;
138        Ok(g.flow_cells
139            .entry(flow.as_u64())
140            .or_insert_with(|| Arc::new(RevocationCell::new()))
141            .clone())
142    }
143
144    pub fn flow_cell(&self, flow: FlowId) -> Result<Option<Arc<RevocationCell>>, RuntimeError> {
145        Ok(self
146            .lock("CapTable::flow_cell")?
147            .flow_cells
148            .get(&flow.as_u64())
149            .cloned())
150    }
151
152    pub fn scheduler_cell(&self) -> Arc<RevocationCell> {
153        Arc::clone(&self.scheduler_cell)
154    }
155
156    fn insert_fresh(
157        table: &mut HashMap<CapId, Capability>,
158        entry: Capability,
159    ) -> Result<CapId, RuntimeError> {
160        for _ in 0..MINT_ATTEMPTS {
161            let id = match CapId::random() {
162                Ok(id) if !id.is_none() => id,
163                Ok(_) | Err(crate::CapIdError::ReservedZero) => {
164                    return Err(RuntimeError::ReservedCapId);
165                }
166                Err(crate::CapIdError::Entropy(err)) => {
167                    return Err(RuntimeError::EntropyFailed(err));
168                }
169            };
170            if table.contains_key(&id) {
171                continue;
172            }
173            table.insert(id, entry);
174            return Ok(id);
175        }
176        Err(RuntimeError::CapIdCollision)
177    }
178
179    fn insert(&self, holder: FlowId, cap: Cap) -> Result<CapId, RuntimeError> {
180        let mut table = self.lock("CapTable::insert")?;
181        Self::insert_fresh(&mut table.entries, Capability { holder, cap })
182    }
183
184    /// Trusted root mint: always a **new** token.
185    ///
186    /// Used for self Cap (`SelfPid`) and child addressing (`Spawn`). Hop
187    /// `reply_cap` must go through [`Self::mint_or_reuse`] so the table
188    /// stays O(pairs), not O(hops).
189    pub fn mint(
190        &self,
191        holder: FlowId,
192        target: FlowId,
193        rights: CapRights,
194    ) -> Result<CapId, RuntimeError> {
195        let cell = self.bind_flow(target)?;
196        let cap = Cap::root(
197            CapTarget::Flow(target.as_u64()),
198            rights,
199            None,
200            cell.as_ref(),
201        );
202        self.grant(holder, cap)
203    }
204
205    /// Reply-address mint: reuse the live SEND Cap for `(holder, target)`.
206    ///
207    /// [`FlowId`] is never reused (`next_flow_id` is monotonic), so a cached
208    /// pair cannot alias a later incarnation. Stale index entries are dropped
209    /// after an epoch / holder / target check — never trusted blindly.
210    ///
211    /// One lock for lookup + insert so reuse is atomic on the existing
212    /// global mutex (no CAS / retry).
213    pub fn mint_or_reuse(
214        &self,
215        holder: FlowId,
216        target: FlowId,
217        rights: CapRights,
218    ) -> Result<CapId, RuntimeError> {
219        let mut g = self.lock("CapTable::mint_or_reuse")?;
220        if let Some(&id) = g.reply_index.get(&(holder, target)) {
221            if Self::reply_cap_is_live(&g, id, holder, target, rights) {
222                return Ok(id);
223            }
224            g.reply_index.remove(&(holder, target));
225        }
226        let cell = g
227            .flow_cells
228            .entry(target.as_u64())
229            .or_insert_with(|| Arc::new(RevocationCell::new()))
230            .clone();
231        let cap = Cap::root(
232            CapTarget::Flow(target.as_u64()),
233            rights,
234            None,
235            cell.as_ref(),
236        );
237        let id = Self::insert_fresh(&mut g.entries, Capability { holder, cap })?;
238        g.reply_index.insert((holder, target), id);
239        Ok(id)
240    }
241
242    fn reply_cap_is_live(
243        table: &CapTableInner,
244        id: CapId,
245        holder: FlowId,
246        target: FlowId,
247        rights: CapRights,
248    ) -> bool {
249        let Some(entry) = table.entries.get(&id) else {
250            return false;
251        };
252        if entry.holder != holder {
253            return false;
254        }
255        if entry.cap.target() != CapTarget::Flow(target.as_u64()) {
256            return false;
257        }
258        if !entry.cap.rights().contains(rights) {
259            return false;
260        }
261        match table.flow_cells.get(&target.as_u64()) {
262            Some(cell) => entry.cap.is_valid(cell.as_ref()),
263            None => false,
264        }
265    }
266
267    /// Insert a Cap that was already produced by [`Cap::attenuate`] or
268    /// [`Cap::root`] (trusted).
269    pub fn grant(&self, holder: FlowId, cap: Cap) -> Result<CapId, RuntimeError> {
270        self.insert(holder, cap)
271    }
272
273    /// Host / registry lookup: existence only, no holder check.
274    pub fn lookup(&self, id: CapId) -> Result<Option<Capability>, RuntimeError> {
275        if id.is_none() {
276            return Ok(None);
277        }
278        Ok(self.lock("CapTable::lookup")?.entries.get(&id).cloned())
279    }
280
281    /// Bytecode path: token + holder + rights + live epoch.
282    pub fn resolve(
283        &self,
284        id: CapId,
285        holder: FlowId,
286        required: CapRights,
287    ) -> Result<Capability, CapError> {
288        if id.is_none() {
289            return Err(CapError::Unknown);
290        }
291        let table = self.lock("CapTable::resolve")?;
292        let entry = table.entries.get(&id).cloned().ok_or(CapError::Unknown)?;
293        if entry.holder != holder {
294            return Err(CapError::NotHolder);
295        }
296        if !entry.cap.rights().contains(required) {
297            return Err(CapError::InsufficientRights);
298        }
299        let valid = match entry.cap.target() {
300            CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
301                Some(cell) => entry.cap.is_valid(cell.as_ref()),
302                None => false,
303            },
304            CapTarget::NativeTable => entry.cap.is_valid(self.native_cell.as_ref()),
305            CapTarget::Scheduler => entry.cap.is_valid(self.scheduler_cell.as_ref()),
306            CapTarget::Table(tid) => match table.table_cells.get(&tid) {
307                Some(cell) => entry.cap.is_valid(cell.as_ref()),
308                None => false,
309            },
310        };
311        if !valid {
312            return Err(CapError::Unknown);
313        }
314        Ok(entry)
315    }
316
317    /// Install the revocation cell for a new flow-owned table.
318    pub fn bind_table(&self, id: u64, cell: Arc<RevocationCell>) -> Result<(), RuntimeError> {
319        self.lock("CapTable::bind_table")?
320            .table_cells
321            .insert(id, cell);
322        Ok(())
323    }
324
325    pub(crate) fn table_cell(&self, id: u64) -> Option<Arc<RevocationCell>> {
326        self.lock("CapTable::table_cell")
327            .ok()
328            .and_then(|g| g.table_cells.get(&id).cloned())
329    }
330
331    /// Revoke every Cap that addresses `id` and drop the table cell.
332    pub fn revoke_table(&self, id: u64) -> Result<(), RuntimeError> {
333        let mut table = self.lock("CapTable::revoke_table")?;
334        if let Some(cell) = table.table_cells.remove(&id) {
335            cell.revoke();
336        }
337        table
338            .entries
339            .retain(|_, entry| entry.cap.target() != CapTarget::Table(id));
340        Ok(())
341    }
342
343    /// New token, attenuated rights, `to_holder` becomes the holder.
344    /// Sole bytecode derivation path — calls [`Cap::attenuate`].
345    pub fn attenuate(
346        &self,
347        id: CapId,
348        from_holder: FlowId,
349        to_holder: FlowId,
350        want_rights: CapRights,
351        want_native: Option<&NativeMask>,
352    ) -> Result<CapId, CapError> {
353        let src = self.resolve(id, from_holder, CapRights::empty())?;
354        let cell = match src.cap.target() {
355            CapTarget::Flow(fid) => self
356                .lock("CapTable::attenuate")?
357                .flow_cells
358                .get(&fid)
359                .cloned()
360                .ok_or(CapError::Unknown)?,
361            CapTarget::Table(tid) => self
362                .lock("CapTable::attenuate")?
363                .table_cells
364                .get(&tid)
365                .cloned()
366                .ok_or(CapError::Unknown)?,
367            CapTarget::NativeTable | CapTarget::Scheduler => {
368                return Err(CapError::WrongTarget);
369            }
370        };
371        let narrowed =
372            match super::delegate::exec_delegate(&src.cap, cell.as_ref(), want_rights, want_native)
373            {
374                Ok(c) => c,
375                Err(super::delegate::DelegateError::SourceRevoked) => {
376                    return Err(CapError::Unknown)
377                }
378                Err(super::delegate::DelegateError::SourceLacksNative) => {
379                    return Err(CapError::InsufficientRights)
380                }
381            };
382        if !narrowed.is_valid(cell.as_ref()) {
383            return Err(CapError::Unknown);
384        }
385        self.insert(to_holder, narrowed).map_err(CapError::from)
386    }
387
388    /// New token, same target/rights (attenuation with `want = src.rights`).
389    pub fn delegate(
390        &self,
391        id: CapId,
392        from_holder: FlowId,
393        to_holder: FlowId,
394    ) -> Result<CapId, CapError> {
395        let src = self.resolve(id, from_holder, CapRights::empty())?;
396        self.attenuate(
397            id,
398            from_holder,
399            to_holder,
400            src.cap.rights(),
401            src.cap.native_mask(),
402        )
403    }
404
405    /// Host spawn: re-issue a live Cap so `new_holder` can use it.
406    /// Does not require the caller to be the current holder (trusted host).
407    /// Still goes through [`Cap::attenuate`] (identity attenuation).
408    pub fn reissue_for(&self, id: CapId, new_holder: FlowId) -> Result<CapId, CapError> {
409        let cap = self.lookup(id)?.ok_or(CapError::Unknown)?;
410        let table = self.lock("CapTable::reissue_for")?;
411        let valid = match cap.cap.target() {
412            CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
413                Some(cell) => cap.cap.is_valid(cell.as_ref()),
414                None => false,
415            },
416            CapTarget::NativeTable => cap.cap.is_valid(self.native_cell.as_ref()),
417            CapTarget::Scheduler => cap.cap.is_valid(self.scheduler_cell.as_ref()),
418            CapTarget::Table(tid) => match table.table_cells.get(&tid) {
419                Some(cell) => cap.cap.is_valid(cell.as_ref()),
420                None => false,
421            },
422        };
423        drop(table);
424        if !valid {
425            return Err(CapError::Unknown);
426        }
427        let narrowed = cap.cap.attenuate(cap.cap.rights(), cap.cap.native_mask());
428        self.insert(new_holder, narrowed).map_err(CapError::from)
429    }
430
431    /// Snapshot every live Cap currently held by `flow` (host attestation).
432    pub fn list_held_by(
433        &self,
434        flow: FlowId,
435    ) -> Result<Vec<crate::scheduler::sandbox::CapabilityGrantView>, RuntimeError> {
436        let table = self.lock("CapTable::list_held_by")?;
437        let mut out = Vec::new();
438        for (id, entry) in table.entries.iter() {
439            if entry.holder == flow {
440                out.push(crate::scheduler::sandbox::CapabilityGrantView::from_entry(
441                    *id, entry,
442                ));
443            }
444        }
445        Ok(out)
446    }
447
448    /// Drop every capability held by or targeting `flow` (flow exited).
449    /// Bumps the flow's epoch first so leaked tokens fail in O(1).
450    pub fn revoke_flow(&self, flow: FlowId) -> Result<usize, RuntimeError> {
451        let mut g = self.lock("CapTable::revoke_flow")?;
452        if let Some(cell) = g.flow_cells.get(&flow.as_u64()) {
453            cell.revoke();
454        }
455        g.flow_cells.remove(&flow.as_u64());
456        let before = g.entries.len();
457        let fid = flow.as_u64();
458        g.entries
459            .retain(|_, e| e.holder != flow && e.cap.target() != CapTarget::Flow(fid));
460        g.reply_index.retain(|(h, t), _| *h != flow && *t != flow);
461        Ok(before - g.entries.len())
462    }
463
464    #[cfg(test)]
465    fn entry_count(&self) -> Result<usize, RuntimeError> {
466        Ok(self.lock("CapTable::entry_count")?.entries.len())
467    }
468
469    #[cfg(test)]
470    fn reply_index_len(&self) -> Result<usize, RuntimeError> {
471        Ok(self.lock("CapTable::reply_index_len")?.reply_index.len())
472    }
473
474    #[cfg(test)]
475    fn reply_index_mentions(&self, flow: FlowId) -> Result<bool, RuntimeError> {
476        Ok(self
477            .lock("CapTable::reply_index_mentions")?
478            .reply_index
479            .keys()
480            .any(|(h, t)| *h == flow || *t == flow))
481    }
482}
483
484impl Default for CapTable {
485    fn default() -> Self {
486        Self::new()
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use crate::scheduler::process::next_flow_id;
494
495    #[test]
496    fn random_ids_are_not_sequential() -> Result<(), Box<dyn std::error::Error>> {
497        let table = CapTable::new();
498        let h = next_flow_id();
499        let t = next_flow_id();
500        let a = table.mint(h, t, CapRights::SEND)?;
501        let b = table.mint(h, t, CapRights::SEND)?;
502        assert_ne!(a, b);
503        assert!(!a.is_none());
504        assert_eq!(
505            table.resolve(CapId::from_raw(1), h, CapRights::SEND),
506            Err(CapError::Unknown)
507        );
508        Ok(())
509    }
510
511    #[test]
512    fn resolve_requires_holder_and_rights() -> Result<(), Box<dyn std::error::Error>> {
513        let table = CapTable::new();
514        let holder = next_flow_id();
515        let other = next_flow_id();
516        let target = next_flow_id();
517        let cap = table.mint(holder, target, CapRights::SEND)?;
518        assert_eq!(
519            table.resolve(cap, holder, CapRights::SEND)?.target(),
520            Some(target)
521        );
522        assert_eq!(
523            table.resolve(cap, other, CapRights::SEND),
524            Err(CapError::NotHolder)
525        );
526        assert_eq!(
527            table.resolve(cap, holder, CapRights::ASK),
528            Err(CapError::InsufficientRights)
529        );
530        Ok(())
531    }
532
533    #[test]
534    fn capability_isolation_is_per_table() -> Result<(), Box<dyn std::error::Error>> {
535        let a = CapTable::new();
536        let b = CapTable::new();
537        let holder = next_flow_id();
538        let target = next_flow_id();
539        let cap = a.mint(holder, target, CapRights::SEND)?;
540        assert_eq!(
541            b.resolve(cap, holder, CapRights::SEND),
542            Err(CapError::Unknown)
543        );
544        Ok(())
545    }
546
547    #[test]
548    fn finalizing_flow_revokes_held_and_targeted_caps() -> Result<(), Box<dyn std::error::Error>> {
549        let table = CapTable::new();
550        let dead = next_flow_id();
551        let alive = next_flow_id();
552        let target = next_flow_id();
553
554        let held_by_dead = table.mint(dead, target, CapRights::SEND)?;
555        let targeting_dead = table.mint(alive, dead, CapRights::SEND)?;
556        let unrelated = table.mint(alive, target, CapRights::SEND)?;
557
558        let removed = table.revoke_flow(dead)?;
559        assert_eq!(removed, 2);
560        assert_eq!(
561            table.resolve(held_by_dead, dead, CapRights::SEND),
562            Err(CapError::Unknown)
563        );
564        assert_eq!(
565            table.resolve(targeting_dead, alive, CapRights::SEND),
566            Err(CapError::Unknown)
567        );
568        assert!(table.resolve(unrelated, alive, CapRights::SEND).is_ok());
569        Ok(())
570    }
571
572    #[test]
573    fn delegate_issues_a_new_id_for_the_child() -> Result<(), Box<dyn std::error::Error>> {
574        let table = CapTable::new();
575        let parent = next_flow_id();
576        let child = next_flow_id();
577        let target = next_flow_id();
578        let original = table.mint(parent, target, CapRights::SEND_ASK)?;
579        let granted = table.delegate(original, parent, child)?;
580        assert_ne!(granted, original);
581        assert_eq!(
582            table.resolve(granted, child, CapRights::SEND)?.target(),
583            Some(target)
584        );
585        assert_eq!(
586            table.resolve(original, child, CapRights::SEND),
587            Err(CapError::NotHolder)
588        );
589        assert!(table.resolve(original, parent, CapRights::ASK).is_ok());
590        Ok(())
591    }
592
593    #[test]
594    fn attenuate_cannot_escalate() -> Result<(), Box<dyn std::error::Error>> {
595        let table = CapTable::new();
596        let parent = next_flow_id();
597        let child = next_flow_id();
598        let target = next_flow_id();
599        let original = table.mint(parent, target, CapRights::SEND)?;
600        let granted = table.attenuate(
601            original,
602            parent,
603            child,
604            CapRights::SEND.union(CapRights::ADMIN),
605            None,
606        )?;
607        let got = table.resolve(granted, child, CapRights::SEND)?;
608        assert!(!got.rights().contains(CapRights::ADMIN));
609        assert!(got.rights().contains(CapRights::SEND));
610        Ok(())
611    }
612
613    #[test]
614    fn mint_or_reuse_is_stable_per_pair() -> Result<(), Box<dyn std::error::Error>> {
615        let table = CapTable::new();
616        let holder = next_flow_id();
617        let target = next_flow_id();
618        let first = table.mint_or_reuse(holder, target, CapRights::SEND)?;
619        for _ in 0..1_000 {
620            let again = table.mint_or_reuse(holder, target, CapRights::SEND)?;
621            assert_eq!(again, first);
622        }
623        assert_eq!(table.entry_count()?, 1);
624        assert_eq!(table.reply_index_len()?, 1);
625        assert!(table.resolve(first, holder, CapRights::SEND).is_ok());
626        Ok(())
627    }
628
629    #[test]
630    fn mint_or_reuse_distinct_pairs_are_independent() -> Result<(), Box<dyn std::error::Error>> {
631        let table = CapTable::new();
632        let a = next_flow_id();
633        let b = next_flow_id();
634        let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
635        let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
636        assert_ne!(ab, ba);
637        assert_eq!(table.entry_count()?, 2);
638        assert_eq!(table.reply_index_len()?, 2);
639        Ok(())
640    }
641
642    #[test]
643    fn revoke_flow_clears_reply_index_for_holder_and_target(
644    ) -> Result<(), Box<dyn std::error::Error>> {
645        let table = CapTable::new();
646        let a = next_flow_id();
647        let b = next_flow_id();
648        let alive = next_flow_id();
649        let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
650        let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
651        let kept = table.mint_or_reuse(alive, b, CapRights::SEND)?;
652
653        table.revoke_flow(a)?;
654        assert!(!table.reply_index_mentions(a)?);
655        assert_eq!(
656            table.resolve(ab, b, CapRights::SEND),
657            Err(CapError::Unknown)
658        );
659        assert_eq!(
660            table.resolve(ba, a, CapRights::SEND),
661            Err(CapError::Unknown)
662        );
663        assert!(table.resolve(kept, alive, CapRights::SEND).is_ok());
664        assert!(!table.reply_index_mentions(a)?);
665        assert!(table.reply_index_mentions(b)?);
666
667        table.revoke_flow(b)?;
668        assert!(!table.reply_index_mentions(a)?);
669        assert!(!table.reply_index_mentions(b)?);
670        Ok(())
671    }
672
673    #[test]
674    fn mint_or_reuse_after_revoke_issues_a_fresh_id() -> Result<(), Box<dyn std::error::Error>> {
675        let table = CapTable::new();
676        let holder = next_flow_id();
677        let target = next_flow_id();
678        let old = table.mint_or_reuse(holder, target, CapRights::SEND)?;
679        table.revoke_flow(target)?;
680        assert!(!table.reply_index_mentions(target)?);
681        let fresh = table.mint_or_reuse(holder, target, CapRights::SEND)?;
682        assert_ne!(fresh, old);
683        assert_eq!(
684            table.resolve(old, holder, CapRights::SEND),
685            Err(CapError::Unknown)
686        );
687        assert!(table.resolve(fresh, holder, CapRights::SEND).is_ok());
688        Ok(())
689    }
690}
691
692#[cfg(test)]
693mod properties {
694    //! CapTable invariants (Tier 1 stress suite — in-house PRNG).
695
696    use super::*;
697    use crate::prng::XorShift64;
698    use crate::scheduler::process::next_flow_id;
699
700    #[test]
701    fn mint_resolves_for_holder() -> Result<(), String> {
702        let mut rng = XorShift64::new(0xCA90_0001);
703        for _ in 0..64 {
704            let table = CapTable::new();
705            let holder = next_flow_id();
706            let target = next_flow_id();
707            let extra = rng.next_u32() & 0b10;
708            let rights = CapRights::SEND.union(CapRights::from_bits(extra));
709            let id = table
710                .mint(holder, target, rights)
711                .map_err(|e| e.to_string())?;
712            let cap = table
713                .resolve(id, holder, CapRights::SEND)
714                .map_err(|e| e.to_string())?;
715            if cap.holder != holder {
716                return Err("holder mismatch".into());
717            }
718            if !cap.cap.rights().contains(CapRights::SEND) {
719                return Err("missing SEND".into());
720            }
721        }
722        Ok(())
723    }
724
725    #[test]
726    fn resolve_rejects_non_holder() -> Result<(), String> {
727        for _ in 0..32 {
728            let table = CapTable::new();
729            let holder = next_flow_id();
730            let stranger = next_flow_id();
731            let target = next_flow_id();
732            let id = table
733                .mint(holder, target, CapRights::SEND)
734                .map_err(|e| e.to_string())?;
735            match table.resolve(id, stranger, CapRights::SEND) {
736                Err(CapError::NotHolder) => {}
737                Ok(_) => return Err("stranger must not resolve".into()),
738                Err(e) => return Err(format!("expected NotHolder, got {e}")),
739            }
740        }
741        Ok(())
742    }
743
744    #[test]
745    fn mint_or_reuse_is_stable_for_pair() -> Result<(), String> {
746        for _ in 0..32 {
747            let table = CapTable::new();
748            let holder = next_flow_id();
749            let target = next_flow_id();
750            let a = table
751                .mint_or_reuse(holder, target, CapRights::SEND)
752                .map_err(|e| e.to_string())?;
753            let b = table
754                .mint_or_reuse(holder, target, CapRights::SEND)
755                .map_err(|e| e.to_string())?;
756            if a != b {
757                return Err("mint_or_reuse not stable".into());
758            }
759            table
760                .resolve(a, holder, CapRights::SEND)
761                .map_err(|e| e.to_string())?;
762        }
763        Ok(())
764    }
765
766    #[test]
767    fn revoke_invalidates_prior_token() -> Result<(), String> {
768        for _ in 0..32 {
769            let table = CapTable::new();
770            let holder = next_flow_id();
771            let target = next_flow_id();
772            let old = table
773                .mint(holder, target, CapRights::SEND)
774                .map_err(|e| e.to_string())?;
775            table.revoke_flow(target).map_err(|e| e.to_string())?;
776            match table.resolve(old, holder, CapRights::SEND) {
777                Err(CapError::Unknown) => {}
778                Ok(_) => return Err("revoked Cap must not resolve".into()),
779                Err(e) => return Err(format!("expected Unknown, got {e}")),
780            }
781            let fresh = table
782                .mint(holder, target, CapRights::SEND)
783                .map_err(|e| e.to_string())?;
784            if fresh == old {
785                return Err("fresh CapId collided with revoked".into());
786            }
787            table
788                .resolve(fresh, holder, CapRights::SEND)
789                .map_err(|e| e.to_string())?;
790        }
791        Ok(())
792    }
793
794    #[test]
795    fn table_attenuate_never_escalates_rights() -> Result<(), String> {
796        let table = CapTable::new();
797        let holder = next_flow_id();
798        let peer = next_flow_id();
799        let target = next_flow_id();
800        let id = table
801            .mint(holder, target, CapRights::SEND)
802            .map_err(|e| e.to_string())?;
803        let child = table
804            .attenuate(
805                id,
806                holder,
807                peer,
808                CapRights::ADMIN.union(CapRights::SEND),
809                None,
810            )
811            .map_err(|e| e.to_string())?;
812        let entry = table
813            .resolve(child, peer, CapRights::SEND)
814            .map_err(|e| e.to_string())?;
815        if entry.cap.rights().contains(CapRights::ADMIN) {
816            return Err("attenuate must not grant ADMIN".into());
817        }
818        match table.resolve(child, peer, CapRights::ADMIN) {
819            Err(CapError::InsufficientRights) => {}
820            Ok(_) => return Err("child must not satisfy ADMIN".into()),
821            Err(e) => return Err(format!("expected InsufficientRights, got {e}")),
822        }
823        Ok(())
824    }
825
826    #[test]
827    fn delegated_cap_is_usable_until_target_revoked() -> Result<(), String> {
828        let table = CapTable::new();
829        let holder = next_flow_id();
830        let delegatee = next_flow_id();
831        let target = next_flow_id();
832        let root = table
833            .mint(holder, target, CapRights::SEND.union(CapRights::FLOW))
834            .map_err(|e| e.to_string())?;
835        let derived = table
836            .delegate(root, holder, delegatee)
837            .map_err(|e| e.to_string())?;
838        table
839            .resolve(derived, delegatee, CapRights::SEND)
840            .map_err(|e| e.to_string())?;
841        table.revoke_flow(target).map_err(|e| e.to_string())?;
842        match table.resolve(derived, delegatee, CapRights::SEND) {
843            Err(CapError::Unknown) => {}
844            Ok(_) => return Err("revoked derived cap must not resolve".into()),
845            Err(e) => return Err(format!("expected Unknown, got {e}")),
846        }
847        Ok(())
848    }
849
850    #[test]
851    fn concurrent_revoke_and_resolve_fail_closed() -> Result<(), String> {
852        use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
853        use std::sync::Arc;
854        use std::thread;
855
856        for _ in 0..48 {
857            let table = Arc::new(CapTable::new());
858            let holder = next_flow_id();
859            let target = next_flow_id();
860            let id = table
861                .mint(holder, target, CapRights::SEND)
862                .map_err(|e| e.to_string())?;
863            let stop = Arc::new(AtomicBool::new(false));
864            let mut handles = Vec::new();
865            for _ in 0..8 {
866                let table = Arc::clone(&table);
867                let stop = Arc::clone(&stop);
868                handles.push(thread::spawn(move || {
869                    while !stop.load(AtomicOrdering::Acquire) {
870                        let _ = table.resolve(id, holder, CapRights::SEND);
871                    }
872                }));
873            }
874            table.revoke_flow(target).map_err(|e| e.to_string())?;
875            stop.store(true, AtomicOrdering::Release);
876            for handle in handles {
877                handle.join().map_err(|_| "worker panicked".to_string())?;
878            }
879            match table.resolve(id, holder, CapRights::SEND) {
880                Err(CapError::Unknown) => {}
881                Ok(_) => return Err("post-revoke resolve must fail closed".into()),
882                Err(e) => return Err(format!("expected Unknown, got {e}")),
883            }
884        }
885        Ok(())
886    }
887}