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