Skip to main content

byteflow/bytecode/
cap.rs

1//! Capability model — Phase 3.
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#[derive(Clone, Debug, PartialEq, Eq)]
317pub struct Cap {
318    pub target: CapTarget,
319    pub rights: CapRights,
320    /// Meaningful only when `rights.contains(NATIVE)`.
321    pub native_mask: Option<NativeMask>,
322    /// Incremented by [`RevocationCell::revoke`]. A Cap is valid iff
323    /// `self.epoch == issuer.epoch()`.
324    epoch: u64,
325}
326
327/// One revocation counter per capability issuer (a flow, the native table,
328/// the scheduler). Revoke is O(1); every derived Cap dies with it.
329#[derive(Debug)]
330pub struct RevocationCell(AtomicU64);
331
332impl RevocationCell {
333    pub fn new() -> Self {
334        Self(AtomicU64::new(0))
335    }
336
337    pub fn epoch(&self) -> u64 {
338        self.0.load(Ordering::Acquire)
339    }
340
341    pub fn revoke(&self) {
342        self.0.fetch_add(1, Ordering::AcqRel);
343    }
344}
345
346impl Default for RevocationCell {
347    fn default() -> Self {
348        Self::new()
349    }
350}
351
352impl Cap {
353    /// Trusted root mint (runtime / host only). Bytecode cannot call this.
354    pub fn root(
355        target: CapTarget,
356        rights: CapRights,
357        native_mask: Option<NativeMask>,
358        cell: &RevocationCell,
359    ) -> Self {
360        Self {
361            target,
362            rights,
363            native_mask,
364            epoch: cell.epoch(),
365        }
366    }
367
368    pub fn epoch(&self) -> u64 {
369        self.epoch
370    }
371
372    pub fn is_valid(&self, cell: &RevocationCell) -> bool {
373        self.epoch == cell.epoch()
374    }
375
376    /// Produce a strictly narrower-or-equal Cap. Never panics, never grants
377    /// a bit the parent did not have. This is the single choke point the
378    /// rest of the model sits on — keep it boring and obvious.
379    ///
380    /// # Invariants
381    ///
382    /// - `rights(result) ⊆ rights(self)` (`intersect`)
383    /// - `native(result) ⊆ native(self)`:
384    ///   - `(Some(src), Some(want))` → `src ∩ want`
385    ///   - `(Some(src), None)` → keep `src` (no native change requested)
386    ///   - `(None, _)` → `None` (cannot invent a mask)
387    /// - `result.epoch == self.epoch` — same [`RevocationCell`]; revoke
388    ///   invalidates the whole derivation chain. No fresh cell is minted.
389    pub fn attenuate(&self, want_rights: CapRights, want_native: Option<&NativeMask>) -> Cap {
390        let rights = self.rights.intersect(want_rights);
391        let native_mask = match (&self.native_mask, want_native) {
392            (Some(cur), Some(req)) => Some(cur.intersect(req)),
393            (Some(cur), None) => Some(cur.clone()),
394            (None, _) => None,
395        };
396        Cap {
397            target: self.target,
398            rights,
399            native_mask,
400            epoch: self.epoch,
401        }
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn none_is_zero_and_random_is_not() -> Result<(), CapIdError> {
411        assert!(CapId::NONE.is_none());
412        let a = CapId::random()?;
413        let b = CapId::random()?;
414        assert!(!a.is_none());
415        assert!(!b.is_none());
416        assert_ne!(a, b);
417        Ok(())
418    }
419
420    #[test]
421    fn from_raw_is_crate_internal() {
422        assert_eq!(CapId::from_raw(0), CapId::NONE);
423        assert!(!CapId::from_raw(1).is_none());
424    }
425
426    #[test]
427    fn send_ask_bits_stay_compatible() {
428        assert_eq!(CapRights::SEND.bits(), 0b01);
429        assert_eq!(CapRights::ASK.bits(), 0b10);
430        assert_eq!(CapRights::SEND_ASK.bits(), 0b11);
431        assert!(CapRights::ADMIN.bits() > 0b11);
432    }
433
434    #[test]
435    fn attenuation_never_escalates() {
436        let cell = RevocationCell::new();
437        let nm = NativeMask::from_indices(128, &[3, 5, 9]);
438        let parent = Cap::root(
439            CapTarget::Flow(1),
440            CapRights::SEND.union(CapRights::NATIVE),
441            Some(nm),
442            &cell,
443        );
444
445        let child = parent.attenuate(CapRights::SEND.union(CapRights::ADMIN), None);
446        assert!(!child.rights.contains(CapRights::ADMIN));
447        assert!(child.rights.contains(CapRights::SEND));
448
449        let wide = NativeMask::full(128);
450        let child2 = parent.attenuate(CapRights::NATIVE, Some(&wide));
451        let child_mask = child2.native_mask.as_ref();
452        assert!(child_mask.is_some_and(|m| m.allows(3)));
453        let parent_mask = parent.native_mask.as_ref();
454        assert!(parent_mask.is_some_and(|m| !m.allows(7)));
455    }
456
457    #[test]
458    fn attenuation_is_subset_for_all_byte_masks() {
459        let cell = RevocationCell::new();
460        for src in 0u32..=255 {
461            for want in 0u32..=255 {
462                let parent = Cap::root(CapTarget::Flow(1), CapRights::from_bits(src), None, &cell);
463                let child = parent.attenuate(CapRights::from_bits(want), None);
464                assert!(
465                    child.rights.is_subset_of(parent.rights),
466                    "escalation src={src:#x} want={want:#x} got={:#x}",
467                    child.rights.bits()
468                );
469                assert_eq!(child.rights.bits(), src & want);
470            }
471        }
472    }
473
474    #[test]
475    fn chained_delegate_never_gains_bits() {
476        let cell = RevocationCell::new();
477        let mut cap = Cap::root(
478            CapTarget::Flow(1),
479            CapRights::FLOW,
480            Some(NativeMask::from_indices(32, &[0, 1, 2])),
481            &cell,
482        );
483        let adversarial = [
484            CapRights::ADMIN,
485            CapRights::NATIVE.union(CapRights::ADMIN),
486            CapRights::from_bits(u32::MAX),
487            CapRights::NONE,
488            CapRights::FLOW,
489        ];
490        for want in adversarial {
491            cap = cap.attenuate(want, Some(&NativeMask::full(32)));
492            assert!(cap.rights.is_subset_of(CapRights::FLOW));
493            assert!(!cap.rights.contains(CapRights::ADMIN));
494            if let Some(mask) = &cap.native_mask {
495                assert!(!mask.allows(7));
496            }
497        }
498    }
499
500    #[test]
501    fn revocation_kills_all_derived_caps() {
502        let cell = RevocationCell::new();
503        let root = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
504        let child = root.attenuate(CapRights::SEND, None);
505        assert!(child.is_valid(&cell));
506        cell.revoke();
507        assert!(!child.is_valid(&cell));
508        assert!(!root.is_valid(&cell));
509    }
510}