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