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