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    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    /// Drop every capability held by or targeting `flow` (flow exited).
428    /// Bumps the flow's epoch first so leaked tokens fail in O(1).
429    pub fn revoke_flow(&self, flow: FlowId) -> Result<usize, RuntimeError> {
430        let mut g = self.lock("CapTable::revoke_flow")?;
431        if let Some(cell) = g.flow_cells.get(&flow.as_u64()) {
432            cell.revoke();
433        }
434        g.flow_cells.remove(&flow.as_u64());
435        let before = g.entries.len();
436        let fid = flow.as_u64();
437        g.entries
438            .retain(|_, e| e.holder != flow && e.cap.target() != CapTarget::Flow(fid));
439        g.reply_index.retain(|(h, t), _| *h != flow && *t != flow);
440        Ok(before - g.entries.len())
441    }
442
443    #[cfg(test)]
444    fn entry_count(&self) -> Result<usize, RuntimeError> {
445        Ok(self.lock("CapTable::entry_count")?.entries.len())
446    }
447
448    #[cfg(test)]
449    fn reply_index_len(&self) -> Result<usize, RuntimeError> {
450        Ok(self.lock("CapTable::reply_index_len")?.reply_index.len())
451    }
452
453    #[cfg(test)]
454    fn reply_index_mentions(&self, flow: FlowId) -> Result<bool, RuntimeError> {
455        Ok(self
456            .lock("CapTable::reply_index_mentions")?
457            .reply_index
458            .keys()
459            .any(|(h, t)| *h == flow || *t == flow))
460    }
461}
462
463impl Default for CapTable {
464    fn default() -> Self {
465        Self::new()
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472    use crate::scheduler::process::next_flow_id;
473
474    #[test]
475    fn random_ids_are_not_sequential() -> Result<(), Box<dyn std::error::Error>> {
476        let table = CapTable::new();
477        let h = next_flow_id();
478        let t = next_flow_id();
479        let a = table.mint(h, t, CapRights::SEND)?;
480        let b = table.mint(h, t, CapRights::SEND)?;
481        assert_ne!(a, b);
482        assert!(!a.is_none());
483        assert_eq!(
484            table.resolve(CapId::from_raw(1), h, CapRights::SEND),
485            Err(CapError::Unknown)
486        );
487        Ok(())
488    }
489
490    #[test]
491    fn resolve_requires_holder_and_rights() -> Result<(), Box<dyn std::error::Error>> {
492        let table = CapTable::new();
493        let holder = next_flow_id();
494        let other = next_flow_id();
495        let target = next_flow_id();
496        let cap = table.mint(holder, target, CapRights::SEND)?;
497        assert_eq!(
498            table.resolve(cap, holder, CapRights::SEND)?.target(),
499            Some(target)
500        );
501        assert_eq!(
502            table.resolve(cap, other, CapRights::SEND),
503            Err(CapError::NotHolder)
504        );
505        assert_eq!(
506            table.resolve(cap, holder, CapRights::ASK),
507            Err(CapError::InsufficientRights)
508        );
509        Ok(())
510    }
511
512    #[test]
513    fn capability_isolation_is_per_table() -> Result<(), Box<dyn std::error::Error>> {
514        let a = CapTable::new();
515        let b = CapTable::new();
516        let holder = next_flow_id();
517        let target = next_flow_id();
518        let cap = a.mint(holder, target, CapRights::SEND)?;
519        assert_eq!(
520            b.resolve(cap, holder, CapRights::SEND),
521            Err(CapError::Unknown)
522        );
523        Ok(())
524    }
525
526    #[test]
527    fn finalizing_flow_revokes_held_and_targeted_caps() -> Result<(), Box<dyn std::error::Error>> {
528        let table = CapTable::new();
529        let dead = next_flow_id();
530        let alive = next_flow_id();
531        let target = next_flow_id();
532
533        let held_by_dead = table.mint(dead, target, CapRights::SEND)?;
534        let targeting_dead = table.mint(alive, dead, CapRights::SEND)?;
535        let unrelated = table.mint(alive, target, CapRights::SEND)?;
536
537        let removed = table.revoke_flow(dead)?;
538        assert_eq!(removed, 2);
539        assert_eq!(
540            table.resolve(held_by_dead, dead, CapRights::SEND),
541            Err(CapError::Unknown)
542        );
543        assert_eq!(
544            table.resolve(targeting_dead, alive, CapRights::SEND),
545            Err(CapError::Unknown)
546        );
547        assert!(table.resolve(unrelated, alive, CapRights::SEND).is_ok());
548        Ok(())
549    }
550
551    #[test]
552    fn delegate_issues_a_new_id_for_the_child() -> Result<(), Box<dyn std::error::Error>> {
553        let table = CapTable::new();
554        let parent = next_flow_id();
555        let child = next_flow_id();
556        let target = next_flow_id();
557        let original = table.mint(parent, target, CapRights::SEND_ASK)?;
558        let granted = table.delegate(original, parent, child)?;
559        assert_ne!(granted, original);
560        assert_eq!(
561            table.resolve(granted, child, CapRights::SEND)?.target(),
562            Some(target)
563        );
564        assert_eq!(
565            table.resolve(original, child, CapRights::SEND),
566            Err(CapError::NotHolder)
567        );
568        assert!(table.resolve(original, parent, CapRights::ASK).is_ok());
569        Ok(())
570    }
571
572    #[test]
573    fn attenuate_cannot_escalate() -> 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)?;
579        let granted = table.attenuate(
580            original,
581            parent,
582            child,
583            CapRights::SEND.union(CapRights::ADMIN),
584            None,
585        )?;
586        let got = table.resolve(granted, child, CapRights::SEND)?;
587        assert!(!got.rights().contains(CapRights::ADMIN));
588        assert!(got.rights().contains(CapRights::SEND));
589        Ok(())
590    }
591
592    #[test]
593    fn mint_or_reuse_is_stable_per_pair() -> Result<(), Box<dyn std::error::Error>> {
594        let table = CapTable::new();
595        let holder = next_flow_id();
596        let target = next_flow_id();
597        let first = table.mint_or_reuse(holder, target, CapRights::SEND)?;
598        for _ in 0..1_000 {
599            let again = table.mint_or_reuse(holder, target, CapRights::SEND)?;
600            assert_eq!(again, first);
601        }
602        assert_eq!(table.entry_count()?, 1);
603        assert_eq!(table.reply_index_len()?, 1);
604        assert!(table.resolve(first, holder, CapRights::SEND).is_ok());
605        Ok(())
606    }
607
608    #[test]
609    fn mint_or_reuse_distinct_pairs_are_independent() -> Result<(), Box<dyn std::error::Error>> {
610        let table = CapTable::new();
611        let a = next_flow_id();
612        let b = next_flow_id();
613        let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
614        let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
615        assert_ne!(ab, ba);
616        assert_eq!(table.entry_count()?, 2);
617        assert_eq!(table.reply_index_len()?, 2);
618        Ok(())
619    }
620
621    #[test]
622    fn revoke_flow_clears_reply_index_for_holder_and_target(
623    ) -> Result<(), Box<dyn std::error::Error>> {
624        let table = CapTable::new();
625        let a = next_flow_id();
626        let b = next_flow_id();
627        let alive = next_flow_id();
628        let ab = table.mint_or_reuse(b, a, CapRights::SEND)?;
629        let ba = table.mint_or_reuse(a, b, CapRights::SEND)?;
630        let kept = table.mint_or_reuse(alive, b, CapRights::SEND)?;
631
632        table.revoke_flow(a)?;
633        assert!(!table.reply_index_mentions(a)?);
634        assert_eq!(
635            table.resolve(ab, b, CapRights::SEND),
636            Err(CapError::Unknown)
637        );
638        assert_eq!(
639            table.resolve(ba, a, CapRights::SEND),
640            Err(CapError::Unknown)
641        );
642        assert!(table.resolve(kept, alive, CapRights::SEND).is_ok());
643        assert!(!table.reply_index_mentions(a)?);
644        assert!(table.reply_index_mentions(b)?);
645
646        table.revoke_flow(b)?;
647        assert!(!table.reply_index_mentions(a)?);
648        assert!(!table.reply_index_mentions(b)?);
649        Ok(())
650    }
651
652    #[test]
653    fn mint_or_reuse_after_revoke_issues_a_fresh_id() -> Result<(), Box<dyn std::error::Error>> {
654        let table = CapTable::new();
655        let holder = next_flow_id();
656        let target = next_flow_id();
657        let old = table.mint_or_reuse(holder, target, CapRights::SEND)?;
658        table.revoke_flow(target)?;
659        assert!(!table.reply_index_mentions(target)?);
660        let fresh = table.mint_or_reuse(holder, target, CapRights::SEND)?;
661        assert_ne!(fresh, old);
662        assert_eq!(
663            table.resolve(old, holder, CapRights::SEND),
664            Err(CapError::Unknown)
665        );
666        assert!(table.resolve(fresh, holder, CapRights::SEND).is_ok());
667        Ok(())
668    }
669}
670
671#[cfg(test)]
672mod properties {
673    //! CapTable invariants (Tier 1 stress suite — in-house PRNG).
674
675    use super::*;
676    use crate::prng::XorShift64;
677    use crate::scheduler::process::next_flow_id;
678
679    #[test]
680    fn mint_resolves_for_holder() -> Result<(), String> {
681        let mut rng = XorShift64::new(0xCA90_0001);
682        for _ in 0..64 {
683            let table = CapTable::new();
684            let holder = next_flow_id();
685            let target = next_flow_id();
686            let extra = rng.next_u32() & 0b10;
687            let rights = CapRights::SEND.union(CapRights::from_bits(extra));
688            let id = table
689                .mint(holder, target, rights)
690                .map_err(|e| e.to_string())?;
691            let cap = table
692                .resolve(id, holder, CapRights::SEND)
693                .map_err(|e| e.to_string())?;
694            if cap.holder != holder {
695                return Err("holder mismatch".into());
696            }
697            if !cap.cap.rights().contains(CapRights::SEND) {
698                return Err("missing SEND".into());
699            }
700        }
701        Ok(())
702    }
703
704    #[test]
705    fn resolve_rejects_non_holder() -> Result<(), String> {
706        for _ in 0..32 {
707            let table = CapTable::new();
708            let holder = next_flow_id();
709            let stranger = next_flow_id();
710            let target = next_flow_id();
711            let id = table
712                .mint(holder, target, CapRights::SEND)
713                .map_err(|e| e.to_string())?;
714            match table.resolve(id, stranger, CapRights::SEND) {
715                Err(CapError::NotHolder) => {}
716                Ok(_) => return Err("stranger must not resolve".into()),
717                Err(e) => return Err(format!("expected NotHolder, got {e}")),
718            }
719        }
720        Ok(())
721    }
722
723    #[test]
724    fn mint_or_reuse_is_stable_for_pair() -> Result<(), String> {
725        for _ in 0..32 {
726            let table = CapTable::new();
727            let holder = next_flow_id();
728            let target = next_flow_id();
729            let a = table
730                .mint_or_reuse(holder, target, CapRights::SEND)
731                .map_err(|e| e.to_string())?;
732            let b = table
733                .mint_or_reuse(holder, target, CapRights::SEND)
734                .map_err(|e| e.to_string())?;
735            if a != b {
736                return Err("mint_or_reuse not stable".into());
737            }
738            table
739                .resolve(a, holder, CapRights::SEND)
740                .map_err(|e| e.to_string())?;
741        }
742        Ok(())
743    }
744
745    #[test]
746    fn revoke_invalidates_prior_token() -> Result<(), String> {
747        for _ in 0..32 {
748            let table = CapTable::new();
749            let holder = next_flow_id();
750            let target = next_flow_id();
751            let old = table
752                .mint(holder, target, CapRights::SEND)
753                .map_err(|e| e.to_string())?;
754            table.revoke_flow(target).map_err(|e| e.to_string())?;
755            match table.resolve(old, holder, CapRights::SEND) {
756                Err(CapError::Unknown) => {}
757                Ok(_) => return Err("revoked Cap must not resolve".into()),
758                Err(e) => return Err(format!("expected Unknown, got {e}")),
759            }
760            let fresh = table
761                .mint(holder, target, CapRights::SEND)
762                .map_err(|e| e.to_string())?;
763            if fresh == old {
764                return Err("fresh CapId collided with revoked".into());
765            }
766            table
767                .resolve(fresh, holder, CapRights::SEND)
768                .map_err(|e| e.to_string())?;
769        }
770        Ok(())
771    }
772}