Skip to main content

byteflow/bytecode/
cap.rs

1//! Capability model.
2//!
3//! A [`CapId`] is still the bytecode-visible token. Authorization lives in a
4//! [`Cap`] record (target + rights + optional native mask + epoch).
5//!
6//! Design:
7//! - Rights are a fixed bitset (no dynamic strings): cheap to check, cheap
8//!   to attenuate, easy to audit.
9//! - Every Cap carries an `epoch`. One revocation counter per issuer
10//!   (flow, native table, scheduler) invalidates every derived Cap in O(1)
11//!   without scanning the live-flow table.
12//! - [`Cap::attenuate`] is the **only** way to derive a new Cap from an
13//!   existing one. There is no constructor that lets a flow synthesize
14//!   rights it does not already hold — that is where S7 closes: a
15//!   [`NativeMask`] only shrinks, never grows, on any code path.
16
17use std::fmt;
18use std::sync::atomic::{AtomicU64, Ordering};
19use std::sync::Arc;
20
21/// Unpredictable capability token. Never a flow id.
22///
23/// `0` is reserved as [`CapId::NONE`] (“no grant”, e.g. host hops without a
24/// reply address). Minted ids are never zero.
25#[derive(Clone, Copy, PartialEq, Eq, Hash)]
26pub struct CapId(u128);
27
28/// Why [`CapId::random`] could not produce a token.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum CapIdError {
31    /// The OS CSPRNG read failed. The inner error is the platform failure.
32    Entropy(crate::entropy::EntropyError),
33    /// Every draw in the retry budget was the reserved zero id.
34    ReservedZero,
35}
36
37impl CapId {
38    /// Placeholder used on unauthenticated / host-injected hops.
39    pub const NONE: CapId = CapId(0);
40
41    /// Draw a non-zero id from the OS CSPRNG. Never panics.
42    ///
43    /// A failed OS read returns immediately. The reserved zero id is drawn
44    /// again, up to eight times, and then reported as [`CapIdError::ReservedZero`]
45    /// rather than as a dead generator.
46    pub fn random() -> Result<Self, CapIdError> {
47        for _ in 0..8 {
48            let mut bytes = [0u8; 16];
49            crate::entropy::fill_bytes(&mut bytes)?;
50            let raw = u128::from_le_bytes(bytes);
51            if raw != 0 {
52                return Ok(CapId(raw));
53            }
54        }
55        Err(CapIdError::ReservedZero)
56    }
57
58    #[inline]
59    pub const fn is_none(self) -> bool {
60        self.0 == 0
61    }
62
63    #[inline]
64    pub const fn as_u128(self) -> u128 {
65        self.0
66    }
67
68    /// Wire / trusted-decode path only. Does **not** insert into any table.
69    #[inline]
70    pub(crate) const fn from_raw(raw: u128) -> Self {
71        CapId(raw)
72    }
73}
74
75impl fmt::Debug for CapId {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        write!(f, "CapId({:032x})", self.0)
78    }
79}
80
81impl fmt::Display for CapId {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        if self.is_none() {
84            f.write_str("cap#none")
85        } else {
86            write!(f, "cap#{:032x}", self.0)
87        }
88    }
89}
90
91impl From<crate::entropy::EntropyError> for CapIdError {
92    fn from(err: crate::entropy::EntropyError) -> Self {
93        CapIdError::Entropy(err)
94    }
95}
96
97impl std::error::Error for CapIdError {
98    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
99        match self {
100            CapIdError::Entropy(err) => Some(err),
101            CapIdError::ReservedZero => None,
102        }
103    }
104}
105
106impl fmt::Display for CapIdError {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            CapIdError::Entropy(err) => write!(f, "capability CSPRNG unavailable: {err}"),
110            CapIdError::ReservedZero => f.write_str("capability id draw was the reserved zero"),
111        }
112    }
113}
114
115/// Index into a [`crate::NativeTable`].
116pub type NativeIdx = u32;
117
118/// Fixed-width rights bitset. Keep this an explicit allow-list: every new
119/// bit here must be audited against the threat-model doc before production.
120///
121/// Low two bits stay `SEND` / `ASK` so ABI-era 0.9 addressing tokens remain
122/// compatible (`SEND_ASK == 0b11`).
123#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
124pub struct CapRights(u32);
125
126impl CapRights {
127    pub const NONE: CapRights = CapRights(0);
128    pub const SEND: CapRights = CapRights(1 << 0);
129    pub const ASK: CapRights = CapRights(1 << 1);
130    pub const RECV: CapRights = CapRights(1 << 2);
131    pub const SPAWN: CapRights = CapRights(1 << 3);
132    pub const LINK: CapRights = CapRights(1 << 4);
133    pub const MONITOR: CapRights = CapRights(1 << 5);
134    pub const ADMIN: CapRights = CapRights(1 << 6);
135    pub const NATIVE: CapRights = CapRights(1 << 7);
136
137    /// Addressing grant minted on `SelfPid` / `Spawn` / `grant_cap`.
138    pub const ADDRESSING: CapRights =
139        CapRights(Self::SEND.0 | Self::ASK.0 | Self::LINK.0 | Self::MONITOR.0);
140
141    /// Default child request from the high-level assembler (`Fn::spawn`).
142    /// Does **not** include `ADMIN`. The raw opcode with `c = 0` is confined
143    /// (`NONE`); the assembler writes this mask so existing actor samples
144    /// keep working without an implicit second grant path.
145    pub const FLOW: CapRights = CapRights(
146        Self::SEND.0
147            | Self::ASK.0
148            | Self::RECV.0
149            | Self::SPAWN.0
150            | Self::LINK.0
151            | Self::MONITOR.0
152            | Self::NATIVE.0,
153    );
154
155    /// Host-spawned root authority (init). Same as [`Self::FLOW`] — `ADMIN`
156    /// is never in the default set; the embedder mints it explicitly.
157    pub const ROOT: CapRights = Self::FLOW;
158
159    /// Historical alias: `SEND | ASK`.
160    pub const SEND_ASK: CapRights = CapRights(Self::SEND.0 | Self::ASK.0);
161
162    #[inline]
163    pub const fn empty() -> Self {
164        CapRights(0)
165    }
166
167    #[inline]
168    pub const fn union(self, other: CapRights) -> CapRights {
169        CapRights(self.0 | other.0)
170    }
171
172    #[inline]
173    pub const fn intersect(self, other: CapRights) -> CapRights {
174        CapRights(self.0 & other.0)
175    }
176
177    #[inline]
178    pub const fn contains(self, other: CapRights) -> bool {
179        self.0 & other.0 == other.0
180    }
181
182    #[inline]
183    pub const fn is_subset_of(self, other: CapRights) -> bool {
184        self.0 & !other.0 == 0
185    }
186
187    #[inline]
188    pub const fn bits(self) -> u32 {
189        self.0
190    }
191
192    /// Low 8 bits for the `Spawn` / `Delegate` immediate operand.
193    #[inline]
194    pub const fn bits_u8(self) -> u8 {
195        self.0 as u8
196    }
197
198    #[inline]
199    pub const fn from_bits(bits: u32) -> Self {
200        CapRights(bits)
201    }
202
203    #[inline]
204    pub const fn from_u8(bits: u8) -> Self {
205        CapRights(bits as u32)
206    }
207}
208
209/// Bitset over `NativeTable` indices, sized once at boot to
210/// `NativeTable::len()`. Shared via `Arc` because attenuation clones the Cap
211/// far more often than it clones the mask.
212#[derive(Clone, Debug, PartialEq, Eq)]
213pub struct NativeMask(Arc<[u64]>);
214
215impl NativeMask {
216    pub fn empty(native_count: usize) -> Self {
217        let words = native_count.div_ceil(64);
218        Self(Arc::from(vec![0u64; words].into_boxed_slice()))
219    }
220
221    pub fn full(native_count: usize) -> Self {
222        let words = native_count.div_ceil(64);
223        let mut v = vec![u64::MAX; words];
224        // Clear tail bits above `native_count`, otherwise `intersect` is
225        // imprecise near the upper bound.
226        let rem = native_count % 64;
227        if rem != 0 {
228            if let Some(last) = v.last_mut() {
229                *last &= (1u64 << rem) - 1;
230            }
231        }
232        Self(Arc::from(v.into_boxed_slice()))
233    }
234
235    pub fn from_indices(native_count: usize, idxs: &[NativeIdx]) -> Self {
236        let words = native_count.div_ceil(64);
237        let mut v = vec![0u64; words];
238        for &i in idxs {
239            let (w, b) = (i as usize / 64, i as usize % 64);
240            if w < v.len() && (i as usize) < native_count {
241                v[w] |= 1u64 << b;
242            }
243        }
244        Self(Arc::from(v.into_boxed_slice()))
245    }
246
247    pub fn word_len(&self) -> usize {
248        self.0.len()
249    }
250
251    #[inline]
252    pub fn allows(&self, idx: NativeIdx) -> bool {
253        let (w, b) = (idx as usize / 64, idx as usize % 64);
254        match self.0.get(w) {
255            Some(word) => word & (1u64 << b) != 0,
256            None => false,
257        }
258    }
259
260    /// Attenuation primitive: result ⊆ self AND ⊆ requested, always.
261    /// Bitwise AND — there is no OR path on this type.
262    pub fn intersect(&self, requested: &NativeMask) -> NativeMask {
263        let n = self.0.len().min(requested.0.len());
264        let words: Vec<u64> = self
265            .0
266            .iter()
267            .zip(requested.0.iter())
268            .take(n)
269            .map(|(a, b)| a & b)
270            .collect();
271        // If lengths differ, zip already truncated; pad remaining from the
272        // shorter side is all zeros under AND — nothing to keep.
273        NativeMask(Arc::from(words.into_boxed_slice()))
274    }
275
276    /// `true` iff every bit set in `self` is also set in `other`.
277    pub fn is_subset_of(&self, other: &NativeMask) -> bool {
278        let n = self.0.len().max(other.0.len());
279        (0..n).all(|idx| {
280            let a = match self.0.get(idx) {
281                Some(w) => *w,
282                None => 0,
283            };
284            let b = match other.0.get(idx) {
285                Some(w) => *w,
286                None => 0,
287            };
288            a & !b == 0
289        })
290    }
291}
292
293/// What a capability addresses. Bytecode never sees this enum — only the
294/// opaque [`CapId`] token.
295#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
296pub enum CapTarget {
297    /// Delivery / link / monitor / self-authority for one flow (`u64` = FlowId).
298    Flow(u64),
299    /// Native-table authority (S7). Rarely minted; usually the mask lives on
300    /// a flow-targeted Cap that also has [`CapRights::NATIVE`].
301    NativeTable,
302    /// Exclusive target of [`CapRights::ADMIN`]: kill / inspect / quota top-up.
303    Scheduler,
304}
305
306impl CapTarget {
307    pub fn flow_id(self) -> Option<u64> {
308        match self {
309            CapTarget::Flow(id) => Some(id),
310            CapTarget::NativeTable | CapTarget::Scheduler => None,
311        }
312    }
313}
314
315/// Authorization record stored in the runtime Cap table, never in bytecode.
316///
317/// Fields are private so authority can only change through [`Cap::root`]
318/// (trusted mint) or [`Cap::attenuate`] (strict intersection).
319#[derive(Clone, Debug, PartialEq, Eq)]
320pub struct Cap {
321    target: CapTarget,
322    rights: CapRights,
323    /// Meaningful only when `rights.contains(NATIVE)`.
324    native_mask: Option<NativeMask>,
325    /// Incremented by [`RevocationCell::revoke`]. A Cap is valid iff
326    /// `self.epoch == issuer.epoch()`.
327    epoch: u64,
328}
329
330/// One revocation counter per capability issuer (a flow, the native table,
331/// the scheduler). Revoke is O(1); every derived Cap dies with it.
332#[derive(Debug)]
333pub struct RevocationCell(AtomicU64);
334
335impl RevocationCell {
336    pub fn new() -> Self {
337        Self(AtomicU64::new(0))
338    }
339
340    pub fn epoch(&self) -> u64 {
341        self.0.load(Ordering::Acquire)
342    }
343
344    pub fn revoke(&self) {
345        self.0.fetch_add(1, Ordering::AcqRel);
346    }
347}
348
349impl Default for RevocationCell {
350    fn default() -> Self {
351        Self::new()
352    }
353}
354
355impl Cap {
356    /// Trusted root mint (runtime / host only). Bytecode cannot call this.
357    pub fn root(
358        target: CapTarget,
359        rights: CapRights,
360        native_mask: Option<NativeMask>,
361        cell: &RevocationCell,
362    ) -> Self {
363        Self {
364            target,
365            rights,
366            native_mask,
367            epoch: cell.epoch(),
368        }
369    }
370
371    #[inline]
372    pub fn target(&self) -> CapTarget {
373        self.target
374    }
375
376    #[inline]
377    pub fn rights(&self) -> CapRights {
378        self.rights
379    }
380
381    #[inline]
382    pub fn native_mask(&self) -> Option<&NativeMask> {
383        self.native_mask.as_ref()
384    }
385
386    pub fn epoch(&self) -> u64 {
387        self.epoch
388    }
389
390    pub fn is_valid(&self, cell: &RevocationCell) -> bool {
391        self.epoch == cell.epoch()
392    }
393
394    /// Produce a strictly narrower-or-equal Cap. Never panics, never grants
395    /// a bit the parent did not have. This is the single choke point the
396    /// rest of the model sits on — keep it boring and obvious.
397    ///
398    /// # Invariants
399    ///
400    /// - `rights(result) ⊆ rights(self)` (`intersect`)
401    /// - `native(result) ⊆ native(self)`:
402    ///   - `(Some(src), Some(want))` → `src ∩ want`
403    ///   - `(Some(src), None)` → keep `src` (no native change requested)
404    ///   - `(None, _)` → `None` (cannot invent a mask)
405    /// - `result.epoch == self.epoch` — same [`RevocationCell`]; revoke
406    ///   invalidates the whole derivation chain. No fresh cell is minted.
407    pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
408        let rights = self.rights.intersect(want_rights);
409        let native_mask = match (&self.native_mask, want_native) {
410            (Some(cur), Some(req)) => Some(cur.intersect(req)),
411            (Some(cur), None) => Some(cur.clone()),
412            (None, _) => None,
413        };
414        Cap {
415            target: self.target,
416            rights,
417            native_mask,
418            epoch: self.epoch,
419        }
420    }
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    #[test]
428    fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
429        assert!(CapId::NONE.is_none());
430        let a = CapId::random()?;
431        let b = CapId::random()?;
432        assert!(!a.is_none());
433        assert!(!b.is_none());
434        assert_ne!(a, b);
435        Ok(())
436    }
437
438    #[test]
439    fn from_raw_is_crate_internal() {
440        assert_eq!(CapId::from_raw(0), CapId::NONE);
441        assert!(!CapId::from_raw(1).is_none());
442    }
443
444    #[test]
445    fn send_ask_bits_stay_compatible() {
446        assert_eq!(CapRights::SEND.bits(), 0b01);
447        assert_eq!(CapRights::ASK.bits(), 0b10);
448        assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
449        assert!(CapRights::ADMIN.bits() > 0b11);
450    }
451
452    #[test]
453    fn attenuation_never_escalates() {
454        let cell = RevocationCell::new();
455        let nm = NativeMask::from_indices(128, &[3, 5, 9]);
456        let parent = Cap::root(
457            CapTarget::Flow(1),
458            CapRights::SEND.union(CapRights::NATIVE),
459            Some(nm),
460            &cell,
461        );
462
463        let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
464        assert!(!child.rights().contains(CapRights::ADMIN));
465        assert!(child.rights().contains(CapRights::SEND));
466
467        let wide = NativeMask::full(128);
468        let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
469        let child_mask = child2.native_mask();
470        assert!(child_mask.is_some_and(|m| m.allows(3)));
471        let parent_mask = parent.native_mask();
472        assert!(parent_mask.is_some_and(|m| !m.allows(7)));
473    }
474
475    #[test]
476    fn attenuation_is_subset_for_all_byte_masks() {
477        let cell = RevocationCell::new();
478        for src in 0u32..=255 {
479            for want in 0u32..=255 {
480                let parent = Cap::root(CapTarget::Flow(1), CapRights::from_bits(src), None, &cell);
481                let child = parent.attenuate(CapRights::from_bits(want), None);
482                assert!(
483                    child.rights().is_subset_of(parent.rights()),
484                    "escalation src={src:#x} want={want:#x} got={:#x}",
485                    child.rights().bits()
486                );
487                assert_eq!(child.rights().bits(), src & want);
488            }
489        }
490    }
491
492    #[test]
493    fn chained_delegate_never_gains_bits() {
494        let cell = RevocationCell::new();
495        let mut cap = Cap::root(
496            CapTarget::Flow(1),
497            CapRights::FLOW,
498            Some(NativeMask::from_indices(32, &[0, 1, 2])),
499            &cell,
500        );
501        let adversarial = [
502            CapRights::ADMIN,
503            CapRights::NATIVE.union(CapRights::ADMIN),
504            CapRights::from_bits(u32::MAX),
505            CapRights::NONE,
506            CapRights::FLOW,
507        ];
508        for want in adversarial {
509            cap = cap.attenuate(want, Some(&NativeMask::full(32)));
510            assert!(cap.rights().is_subset_of(CapRights::FLOW));
511            assert!(!cap.rights().contains(CapRights::ADMIN));
512            if let Some(mask) = cap.native_mask() {
513                assert!(!mask.allows(7));
514            }
515        }
516    }
517
518    #[test]
519    fn revocation_kills_all_derived_caps() {
520        let cell = RevocationCell::new();
521        let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
522        let child = root.attenuate(CapRights::SEND, None);
523        assert!(child.is_valid(&cell));
524        cell.revoke();
525        assert!(!child.is_valid(&cell));
526        assert!(!root.is_valid(&cell));
527    }
528}