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