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::new(),
111                flow_cells: HashMap::new(),
112                table_cells: HashMap::new(),
113                reply_index: HashMap::new(),
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    /// Revoke every Cap that addresses `id` and drop the table cell.
322    pub fn revoke_table(&self, id: u64) -> Result<(), RuntimeError> {
323        let mut table = self.lock("CapTable::revoke_table")?;
324        if let Some(cell) = table.table_cells.remove(&id) {
325            cell.revoke();
326        }
327        table
328            .entries
329            .retain(|_, entry| entry.cap.target() != CapTarget::Table(id));
330        Ok(())
331    }
332
333    /// New token, attenuated rights, `to_holder` becomes the holder.
334    /// Sole bytecode derivation path — calls [`Cap::attenuate`].
335    pub fn attenuate(
336        &self,
337        id: CapId,
338        from_holder: FlowId,
339        to_holder: FlowId,
340        want_rights: CapRights,
341        want_native: Option<&NativeMask>,
342    ) -> Result<CapId, CapError> {
343        let src = self.resolve(id, from_holder, CapRights::empty())?;
344        let cell = match src.cap.target() {
345            CapTarget::Flow(fid) => self
346                .lock("CapTable::attenuate")?
347                .flow_cells
348                .get(&fid)
349                .cloned()
350                .ok_or(CapError::Unknown)?,
351            CapTarget::Table(tid) => self
352                .lock("CapTable::attenuate")?
353                .table_cells
354                .get(&tid)
355                .cloned()
356                .ok_or(CapError::Unknown)?,
357            CapTarget::NativeTable | CapTarget::Scheduler => {
358                return Err(CapError::WrongTarget);
359            }
360        };
361        let narrowed =
362            match super::delegate::exec_delegate(&src.cap, cell.as_ref(), want_rights, want_native)
363            {
364                Ok(c) => c,
365                Err(super::delegate::DelegateError::SourceRevoked) => {
366                    return Err(CapError::Unknown)
367                }
368                Err(super::delegate::DelegateError::SourceLacksNative) => {
369                    return Err(CapError::InsufficientRights)
370                }
371            };
372        if !narrowed.is_valid(cell.as_ref()) {
373            return Err(CapError::Unknown);
374        }
375        self.insert(to_holder, narrowed).map_err(CapError::from)
376    }
377
378    /// New token, same target/rights (attenuation with `want = src.rights`).
379    pub fn delegate(
380        &self,
381        id: CapId,
382        from_holder: FlowId,
383        to_holder: FlowId,
384    ) -> Result<CapId, CapError> {
385        let src = self.resolve(id, from_holder, CapRights::empty())?;
386        self.attenuate(
387            id,
388            from_holder,
389            to_holder,
390            src.cap.rights(),
391            src.cap.native_mask(),
392        )
393    }
394
395    /// Host spawn: re-issue a live Cap so `new_holder` can use it.
396    /// Does not require the caller to be the current holder (trusted host).
397    /// Still goes through [`Cap::attenuate`] (identity attenuation).
398    pub fn reissue_for(&self, id: CapId, new_holder: FlowId) -> Result<CapId, CapError> {
399        let cap = self.lookup(id)?.ok_or(CapError::Unknown)?;
400        let table = self.lock("CapTable::reissue_for")?;
401        let valid = match cap.cap.target() {
402            CapTarget::Flow(fid) => match table.flow_cells.get(&fid) {
403                Some(cell) => cap.cap.is_valid(cell.as_ref()),
404                None => false,
405            },
406            CapTarget::NativeTable => cap.cap.is_valid(self.native_cell.as_ref()),
407            CapTarget::Scheduler => cap.cap.is_valid(self.scheduler_cell.as_ref()),
408            CapTarget::Table(tid) => match table.table_cells.get(&tid) {
409                Some(cell) => cap.cap.is_valid(cell.as_ref()),
410                None => false,
411            },
412        };
413        drop(table);
414        if !valid {
415            return Err(CapError::Unknown);
416        }
417        let narrowed = cap.cap.attenuate(cap.cap.rights(), cap.cap.native_mask());
418        self.insert(new_holder, narrowed).map_err(CapError::from)
419    }
420
421    /// Drop every capability held by or targeting `flow` (flow exited).
422    /// Bumps the flow's epoch first so leaked tokens fail in O(1).
423    pub fn revoke_flow(&self, flow: FlowId) -> Result<usize, RuntimeError> {
424        let mut g = self.lock("CapTable::revoke_flow")?;
425        if let Some(cell) = g.flow_cells.get(&flow.as_u64()) {
426            cell.revoke();
427        }
428        g.flow_cells.remove(&flow.as_u64());
429        let before = g.entries.len();
430        let fid = flow.as_u64();
431        g.entries
432            .retain(|_, e| e.holder != flow && e.cap.target() != CapTarget::Flow(fid));
433        g.reply_index.retain(|(h, t), _| *h != flow && *t != flow);
434        Ok(before - g.entries.len())
435    }
436
437    #[cfg(test)]
438    fn entry_count(&self) -> Result<usize, RuntimeError> {
439        Ok(self.lock("CapTable::entry_count")?.entries.len())
440    }
441
442    #[cfg(test)]
443    fn reply_index_len(&self) -> Result<usize, RuntimeError> {
444        Ok(self.lock("CapTable::reply_index_len")?.reply_index.len())
445    }
446
447    #[cfg(test)]
448    fn reply_index_mentions(&self, flow: FlowId) -> Result<bool, RuntimeError> {
449        Ok(self
450            .lock("CapTable::reply_index_mentions")?
451            .reply_index
452            .keys()
453            .any(|(h, t)| *h == flow || *t == flow))
454    }
455}
456
457impl Default for CapTable {
458    fn default() -> Self {
459        Self::new()
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466    use crate::scheduler::process::next_flow_id;
467
468    #[test]
469    fn random_ids_are_not_sequential() -> Result<(), Box<dyn std::error::Error>> {
470        let table = CapTable::new();
471        let h = next_flow_id();
472        let t = next_flow_id();
473        let a = table.mint(h, t, CapRights::SEND)?;
474        let b = table.mint(h, t, CapRights::SEND)?;
475        assert_ne!(a, b);
476        assert!(!a.is_none());
477        assert_eq!(
478            table.resolve(CapId::from_raw(1), h, CapRights::SEND),
479            Err(CapError::Unknown)
480        );
481        Ok(())
482    }
483
484    #[test]
485    fn resolve_requires_holder_and_rights() -> Result<(), Box<dyn std::error::Error>> {
486        let table = CapTable::new();
487        let holder = next_flow_id();
488        let other = next_flow_id();
489        let target = next_flow_id();
490        let cap = table.mint(holder, target, CapRights::SEND)?;
491        assert_eq!(
492            table.resolve(cap, holder, CapRights::SEND)?.target(),
493            Some(target)
494        );
495        assert_eq!(
496            table.resolve(cap, other, CapRights::SEND),
497            Err(CapError::NotHolder)
498        );
499        assert_eq!(
500            table.resolve(cap, holder, CapRights::ASK),
501            Err(CapError::InsufficientRights)
502        );
503        Ok(())
504    }
505
506    #[test]
507    fn capability_isolation_is_per_table() -> Result<(), Box<dyn std::error::Error>> {
508        let a = CapTable::new();
509        let b = CapTable::new();
510        let holder = next_flow_id();
511        let target = next_flow_id();
512        let cap = a.mint(holder, target, CapRights::SEND)?;
513        assert_eq!(
514            b.resolve(cap, holder, CapRights::SEND),
515            Err(CapError::Unknown)
516        );
517        Ok(())
518    }
519
520    #[test]
521    fn finalizing_flow_revokes_held_and_targeted_caps() -> Result<(), Box<dyn std::error::Error>> {
522        let table = CapTable::new();
523        let dead = next_flow_id();
524        let alive = next_flow_id();
525        let target = next_flow_id();
526
527        let held_by_dead = table.mint(dead, target, CapRights::SEND)?;
528        let targeting_dead = table.mint(alive, dead, CapRights::SEND)?;
529        let unrelated = table.mint(alive, target, CapRights::SEND)?;
530
531        let removed = table.revoke_flow(dead)?;
532        assert_eq!(removed, 2);
533        assert_eq!(
534            table.resolve(held_by_dead, dead, CapRights::SEND),
535            Err(CapError::Unknown)
536        );
537        assert_eq!(
538            table.resolve(targeting_dead, alive, CapRights::SEND),
539            Err(CapError::Unknown)
540        );
541        assert!(table.resolve(unrelated, alive, CapRights::SEND).is_ok());
542        Ok(())
543    }
544
545    #[test]
546    fn delegate_issues_a_new_id_for_the_child() -> Result<(), Box<dyn std::error::Error>> {
547        let table = CapTable::new();
548        let parent = next_flow_id();
549        let child = next_flow_id();
550        let target = next_flow_id();
551        let original = table.mint(parent, target, CapRights::SEND_ASK)?;
552        let granted = table.delegate(original, parent, child)?;
553        assert_ne!(granted, original);
554        assert_eq!(
555            table.resolve(granted, child, CapRights::SEND)?.target(),
556            Some(target)
557        );
558        assert_eq!(
559            table.resolve(original, child, CapRights::SEND),
560            Err(CapError::NotHolder)
561        );
562        assert!(table.resolve(original, parent, CapRights::ASK).is_ok());
563        Ok(())
564    }
565
566    #[test]
567    fn attenuate_cannot_escalate() -> Result<(), Box<dyn std::error::Error>> {
568        let table = CapTable::new();
569        let parent = next_flow_id();
570        let child = next_flow_id();
571        let target = next_flow_id();
572        let original = table.mint(parent, target, CapRights::SEND)?;
573        let granted = table.attenuate(
574            original,
575            parent,
576            child,
577            CapRights::SEND.union(CapRights::ADMIN),
578            None,
579        )?;
580        let got = table.resolve(granted, child, CapRights::SEND)?;
581        assert!(!got.rights().contains(CapRights::ADMIN));
582        assert!(got.rights().contains(CapRights::SEND));
583        Ok(())
584    }
585
586    #[test]
587    fn mint_or_reuse_is_stable_per_pair() -> Result<(), Box<dyn std::error::Error>> {
588        let table = CapTable::new();
589        let holder = next_flow_id();
590        let target = next_flow_id();
591        let first = table.mint_or_reuse(holder, target, CapRights::SEND)?;
592        for _ in 0..1_000 {
593            let again = table.mint_or_reuse(holder, target, CapRights::SEND)?;
594            assert_eq!(again, first);
595        }
596        assert_eq!(table.entry_count()?, 1);
597        assert_eq!(table.reply_index_len()?, 1);
598        assert!(table.resolve(first, holder, CapRights::SEND).is_ok());
599        Ok(())
600    }
601
602    #[test]
603    fn mint_or_reuse_distinct_pairs_are_independent() -> Result<(), Box<dyn std::error::Error>> {
604        let table = CapTable::new();
605        let a = next_flow_id();
606        let b = next_flow_id();
607        let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
608        let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
609        assert_ne!(ab, ba);
610        assert_eq!(table.entry_count()?, 2);
611        assert_eq!(table.reply_index_len()?, 2);
612        Ok(())
613    }
614
615    #[test]
616    fn revoke_flow_clears_reply_index_for_holder_and_target(
617    ) -> Result<(), Box<dyn std::error::Error>> {
618        let table = CapTable::new();
619        let a = next_flow_id();
620        let b = next_flow_id();
621        let alive = next_flow_id();
622        let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
623        let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
624        let kept = table.mint_or_reuse(alive, b, CapRights::SEND)?;
625
626        table.revoke_flow(a)?;
627        assert!(!table.reply_index_mentions(a)?);
628        assert_eq!(
629            table.resolve(ab, b, CapRights::SEND),
630            Err(CapError::Unknown)
631        );
632        assert_eq!(
633            table.resolve(ba, a, CapRights::SEND),
634            Err(CapError::Unknown)
635        );
636        assert!(table.resolve(kept, alive, CapRights::SEND).is_ok());
637        assert!(!table.reply_index_mentions(a)?);
638        assert!(table.reply_index_mentions(b)?);
639
640        table.revoke_flow(b)?;
641        assert!(!table.reply_index_mentions(a)?);
642        assert!(!table.reply_index_mentions(b)?);
643        Ok(())
644    }
645
646    #[test]
647    fn mint_or_reuse_after_revoke_issues_a_fresh_id() -> Result<(), Box<dyn std::error::Error>> {
648        let table = CapTable::new();
649        let holder = next_flow_id();
650        let target = next_flow_id();
651        let old = table.mint_or_reuse(holder, target, CapRights::SEND)?;
652        table.revoke_flow(target)?;
653        assert!(!table.reply_index_mentions(target)?);
654        let fresh = table.mint_or_reuse(holder, target, CapRights::SEND)?;
655        assert_ne!(fresh, old);
656        assert_eq!(
657            table.resolve(old, holder, CapRights::SEND),
658            Err(CapError::Unknown)
659        );
660        assert!(table.resolve(fresh, holder, CapRights::SEND).is_ok());
661        Ok(())
662    }
663}
664
665#[cfg(test)]
666mod properties {
667    //! CapTable invariants (Tier 1 stress suite — in-house PRNG).
668
669    use super::*;
670    use crate::prng::XorShift64;
671    use crate::scheduler::process::next_flow_id;
672
673    #[test]
674    fn mint_resolves_for_holder() -> Result<(), String> {
675        let mut rng = XorShift64::new(0xCA90_0001);
676        for _ in 0..64 {
677            let table = CapTable::new();
678            let holder = next_flow_id();
679            let target = next_flow_id();
680            let extra = rng.next_u32() & 0b10;
681            let rights = CapRights::SEND.union(CapRights::from_bits(extra));
682            let id = table
683                .mint(holder, target, rights)
684                .map_err(|e| e.to_string())?;
685            let cap = table
686                .resolve(id, holder, CapRights::SEND)
687                .map_err(|e| e.to_string())?;
688            if cap.holder != holder {
689                return Err("holder mismatch".into());
690            }
691            if !cap.cap.rights().contains(CapRights::SEND) {
692                return Err("missing SEND".into());
693            }
694        }
695        Ok(())
696    }
697
698    #[test]
699    fn resolve_rejects_non_holder() -> Result<(), String> {
700        for _ in 0..32 {
701            let table = CapTable::new();
702            let holder = next_flow_id();
703            let stranger = next_flow_id();
704            let target = next_flow_id();
705            let id = table
706                .mint(holder, target, CapRights::SEND)
707                .map_err(|e| e.to_string())?;
708            match table.resolve(id, stranger, CapRights::SEND) {
709                Err(CapError::NotHolder) => {}
710                Ok(_) => return Err("stranger must not resolve".into()),
711                Err(e) => return Err(format!("expected NotHolder, got {e}")),
712            }
713        }
714        Ok(())
715    }
716
717    #[test]
718    fn mint_or_reuse_is_stable_for_pair() -> Result<(), String> {
719        for _ in 0..32 {
720            let table = CapTable::new();
721            let holder = next_flow_id();
722            let target = next_flow_id();
723            let a = table
724                .mint_or_reuse(holder, target, CapRights::SEND)
725                .map_err(|e| e.to_string())?;
726            let b = table
727                .mint_or_reuse(holder, target, CapRights::SEND)
728                .map_err(|e| e.to_string())?;
729            if a != b {
730                return Err("mint_or_reuse not stable".into());
731            }
732            table
733                .resolve(a, holder, CapRights::SEND)
734                .map_err(|e| e.to_string())?;
735        }
736        Ok(())
737    }
738
739    #[test]
740    fn revoke_invalidates_prior_token() -> Result<(), String> {
741        for _ in 0..32 {
742            let table = CapTable::new();
743            let holder = next_flow_id();
744            let target = next_flow_id();
745            let old = table
746                .mint(holder, target, CapRights::SEND)
747                .map_err(|e| e.to_string())?;
748            table.revoke_flow(target).map_err(|e| e.to_string())?;
749            match table.resolve(old, holder, CapRights::SEND) {
750                Err(CapError::Unknown) => {}
751                Ok(_) => return Err("revoked Cap must not resolve".into()),
752                Err(e) => return Err(format!("expected Unknown, got {e}")),
753            }
754            let fresh = table
755                .mint(holder, target, CapRights::SEND)
756                .map_err(|e| e.to_string())?;
757            if fresh == old {
758                return Err("fresh CapId collided with revoked".into());
759            }
760            table
761                .resolve(fresh, holder, CapRights::SEND)
762                .map_err(|e| e.to_string())?;
763        }
764        Ok(())
765    }
766}