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