Skip to main content

byteflow/scheduler/
delegate.rs

1//! Opcode DELEGATE — attenuation as a first-class ISA operation.
2//!
3//! `DELEGATE dst, src_cap, rights_mask, native_mask_cap?`
4//!
5//! # Authority path (do not bypass)
6//!
7//! ```text
8//! Opcode::Delegate
9//!        │
10//!        ▼
11//! exec_delegate()          ← revocation + NATIVE gate
12//!        │
13//!        ▼
14//! Cap::attenuate()         ← rights ∩ + native ∩ ; same epoch
15//!        │
16//!        ▼
17//! CapTable insert → Value::Cap
18//! ```
19//!
20//! The ISA requests an operation; [`Cap::attenuate`] is the only place that
21//! transforms authority. There is **no separate grant** — only intersection.
22//!
23//! # Formal invariants
24//!
25//! For every successful `DELEGATE(src, want_rights, want_native)`:
26//!
27//! - `rights(result) ⊆ rights(src)`
28//! - `native(result) ⊆ native(src)` (see [`Cap::attenuate`])
29//! - never `rights(result) ⊃ rights(src)` nor `native(result) ⊃ native(src)`
30//!
31//! If `src` is revoked at the check (or becomes revoked before use):
32//! `Err(SourceRevoked)`. A Cap produced mid-revoke still carries the old
33//! epoch and is immediately invalid against the bumped cell — fail-closed.
34//!
35//! # `want_native` vs `NATIVE`
36//!
37//! `want_native = Some(...)` means “attenuate the native mask”, **not**
38//! “grant NATIVE”. Specifying a mask without holding [`CapRights::NATIVE`]
39//! is rejected as [`DelegateError::SourceLacksNative`].
40
41use crate::bytecode::{Cap, CapRights, NativeMask, RevocationCell};
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum DelegateError {
45    SourceRevoked,
46    /// Caller passed `want_native = Some(...)` but `src` lacks
47    /// [`CapRights::NATIVE`]. Specifying a native attenuation requires that
48    /// right; it does not invent native authority.
49    SourceLacksNative,
50}
51
52impl std::fmt::Display for DelegateError {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        match self {
55            DelegateError::SourceRevoked => f.write_str("delegate: source capability revoked"),
56            DelegateError::SourceLacksNative => {
57                f.write_str("delegate: cannot specify native-mask attenuation without NATIVE right")
58            }
59        }
60    }
61}
62
63impl std::error::Error for DelegateError {}
64
65/// Security gate for `Opcode::Delegate`. All authority math is
66/// [`Cap::attenuate`]; this wrapper only enforces revocation and the
67/// native-mask precondition.
68pub fn exec_delegate(
69    src: &Cap,
70    src_cell: &RevocationCell,
71    want_rights: CapRights,
72    want_native: Option<&NativeMask>,
73) -> Result<Cap, DelegateError> {
74    if !src.is_valid(src_cell) {
75        return Err(DelegateError::SourceRevoked);
76    }
77    if want_native.is_some() && !src.rights().contains(CapRights::NATIVE) {
78        return Err(DelegateError::SourceLacksNative);
79    }
80    Ok(src.attenuate(want_rights, want_native))
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::bytecode::{CapTarget, NativeMask, RevocationCell};
87
88    #[test]
89    fn cannot_escalate_via_delegate_regardless_of_requested_mask() {
90        let cell = RevocationCell::new();
91        let src = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
92        let out = match exec_delegate(
93            &src,
94            &cell,
95            CapRights::SEND
96                .union(CapRights::ADMIN)
97                .union(CapRights::NATIVE),
98            None,
99        ) {
100            Ok(c) => c,
101            Err(err) => panic!("delegate of live SEND cap must succeed: {err}"),
102        };
103        assert!(out.rights().contains(CapRights::SEND));
104        assert!(!out.rights().contains(CapRights::ADMIN));
105        assert!(!out.rights().contains(CapRights::NATIVE));
106        assert!(out.rights().is_subset_of(src.rights()));
107    }
108
109    #[test]
110    fn rights_result_is_always_intersection() {
111        let cell = RevocationCell::new();
112        for src_bits in 0u32..=255 {
113            for want_bits in 0u32..=255 {
114                let src = Cap::root(
115                    CapTarget::Flow(1),
116                    CapRights::from_bits(src_bits),
117                    None,
118                    &cell,
119                );
120                let out = match exec_delegate(&src, &cell, CapRights::from_bits(want_bits), None) {
121                    Ok(c) => c,
122                    Err(err) => panic!("live cap must delegate: {err}"),
123                };
124                assert_eq!(out.rights().bits(), src_bits & want_bits);
125                assert!(out.rights().is_subset_of(src.rights()));
126            }
127        }
128    }
129
130    #[test]
131    fn native_mask_can_only_be_narrowed() {
132        let cell = RevocationCell::new();
133        let src_mask = NativeMask::from_indices(64, &[1, 3, 5, 7]);
134        let requested = NativeMask::from_indices(64, &[3, 5, 9, 11]); // 9,11 not in src
135        let src = Cap::root(
136            CapTarget::Flow(1),
137            CapRights::NATIVE,
138            Some(src_mask.clone()),
139            &cell,
140        );
141        let out = match exec_delegate(&src, &cell, CapRights::NATIVE, Some(&requested)) {
142            Ok(cap) => cap,
143            Err(err) => panic!("live NATIVE capability should delegate: {err}"),
144        };
145        let got = match out.native_mask() {
146            Some(m) => m,
147            None => panic!("native mask present"),
148        };
149        assert!(got.is_subset_of(&src_mask));
150        assert!(got.allows(3));
151        assert!(got.allows(5));
152        assert!(!got.allows(1)); // dropped by request
153        assert!(!got.allows(9)); // never in source
154        assert!(!got.allows(11));
155    }
156
157    #[test]
158    fn cannot_delegate_native_from_non_native_source() {
159        let cell = RevocationCell::new();
160        let src = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
161        let requested = NativeMask::from_indices(32, &[0, 1]);
162        assert!(matches!(
163            exec_delegate(&src, &cell, CapRights::SEND, Some(&requested)),
164            Err(DelegateError::SourceLacksNative)
165        ));
166    }
167
168    #[test]
169    fn want_native_none_keeps_source_mask() {
170        let cell = RevocationCell::new();
171        let src_mask = NativeMask::from_indices(32, &[2, 4]);
172        let src = Cap::root(
173            CapTarget::Flow(1),
174            CapRights::NATIVE.union(CapRights::SEND),
175            Some(src_mask.clone()),
176            &cell,
177        );
178        let out = match exec_delegate(&src, &cell, CapRights::SEND, None) {
179            Ok(c) => c,
180            Err(err) => panic!("{err}"),
181        };
182        // SEND-only result still inherits the (unchanged) mask payload;
183        // NATIVE bit was intersected away.
184        assert!(!out.rights().contains(CapRights::NATIVE));
185        let got = match out.native_mask() {
186            Some(m) => m,
187            None => panic!("mask preserved"),
188        };
189        assert!(got.is_subset_of(&src_mask));
190        assert_eq!(got.allows(2), src_mask.allows(2));
191        assert_eq!(got.allows(4), src_mask.allows(4));
192    }
193
194    #[test]
195    fn delegated_cap_shares_revocation_cell_epoch() {
196        let cell = RevocationCell::new();
197        let src = Cap::root(
198            CapTarget::Flow(1),
199            CapRights::SEND.union(CapRights::NATIVE),
200            Some(NativeMask::from_indices(8, &[0])),
201            &cell,
202        );
203        let child = match exec_delegate(&src, &cell, CapRights::SEND, None) {
204            Ok(c) => c,
205            Err(err) => panic!("{err}"),
206        };
207        assert_eq!(child.epoch(), src.epoch());
208        assert!(child.is_valid(&cell));
209        cell.revoke();
210        assert!(!src.is_valid(&cell));
211        assert!(!child.is_valid(&cell));
212    }
213
214    #[test]
215    fn revoked_source_cannot_delegate() {
216        let cell = RevocationCell::new();
217        let src = Cap::root(CapTarget::Flow(1), CapRights::SEND, None, &cell);
218        cell.revoke();
219        assert!(matches!(
220            exec_delegate(&src, &cell, CapRights::SEND, None),
221            Err(DelegateError::SourceRevoked)
222        ));
223    }
224}