Skip to main content

byteflow/scheduler/
sandbox.rs

1//! Sandbox policy surface — fingerprint, counters, and capability attestation.
2//!
3//! The sandbox is **opt-in** via [`crate::RuntimeConfig::sandbox`]. Default
4//! [`crate::RuntimeConfig`] stays permissive (unlimited process-wide caps,
5//! generous per-flow quotas). This module does **not** replace
6//! [`super::capability::CapTable`], [`super::quota::FlowQuota`], or
7//! [`crate::MemoryBudget`]; it exposes host-facing policy identity and
8//! observability on top of those enforcement points.
9//!
10//! Isolation is **in-process**. Native code and the host remain inside the
11//! same trust boundary — see `docs/sandbox/limitations.md`.
12
13use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
14use std::sync::mpsc::{sync_channel, RecvTimeoutError, SyncSender};
15use std::sync::Arc;
16use std::thread::{self, JoinHandle};
17use std::time::Duration;
18
19use crate::bytecode::{CapId, CapRights, CapTarget, TrustLevel};
20
21use super::capability::{CapTable, Capability};
22use super::error::RuntimeError;
23use super::process::FlowId;
24use super::runtime::RuntimeConfig;
25
26/// Canonical encoding version mixed into [`policy_fingerprint`].
27const POLICY_VERSION: u8 = 1;
28
29/// Stable identity of the security-relevant knobs on a [`RuntimeConfig`].
30///
31/// The 16 bytes are the leading half of SHA-256 over a fixed-width encoding
32/// (see [`policy_fingerprint`]). The same config yields the same bytes on
33/// every rustc, OS, and pointer width. It is **not** a cryptographic
34/// attestation of process integrity. A value stored before this encoding
35/// (std `DefaultHasher`) will not match and must be recomputed.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub struct PolicyFingerprint([u8; 16]);
38
39impl PolicyFingerprint {
40    pub fn as_bytes(&self) -> &[u8; 16] {
41        &self.0
42    }
43
44    pub fn to_hex(&self) -> String {
45        let mut s = String::with_capacity(32);
46        for b in &self.0 {
47            use std::fmt::Write as _;
48            let _ = write!(s, "{b:02x}");
49        }
50        s
51    }
52}
53
54impl std::fmt::Display for PolicyFingerprint {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.write_str(&self.to_hex())
57    }
58}
59
60/// Compute a fingerprint over the security-relevant fields of `config`.
61///
62/// Encoding (`POLICY_VERSION` = 1), little-endian, fixed widths so a 32-bit
63/// host matches a 64-bit host:
64///
65/// `b"BFQP" | version | trust | root_authority | max_flows u32 | max_ask_waits u32 |
66/// max_host_awaits u32 | max_links u32 | max_monitors u32 | max_registry_names u32 |
67/// max_runtime_bytes u64 | mailbox capacity u32 | mailbox bytes u64 | overflow u8 |
68/// cpu_budget i64 | mem_limit u64 | spawn_burst i64 | spawn_per_sec i64 |
69/// send_burst i64 | send_per_sec i64`
70///
71/// Workers, quantum, JIT, sinks, and bridges are not part of the policy
72/// identity. The returned value is SHA-256 of that buffer, truncated to 16
73/// bytes.
74pub fn policy_fingerprint(config: &RuntimeConfig) -> PolicyFingerprint {
75    let digest = crate::digest::sha256(&canonical_policy_bytes(config));
76    let mut out = [0u8; 16];
77    out.copy_from_slice(&digest[..16]);
78    PolicyFingerprint(out)
79}
80
81fn canonical_policy_bytes(config: &RuntimeConfig) -> Vec<u8> {
82    let mut buf = Vec::with_capacity(100);
83    buf.extend_from_slice(b"BFQP");
84    buf.push(POLICY_VERSION);
85    buf.push(trust_tag(config.trust));
86    buf.push(root_authority_tag(config.root_authority));
87    push_u32(&mut buf, config.max_flows);
88    push_u32(&mut buf, config.max_ask_waits);
89    push_u32(&mut buf, config.max_host_awaits);
90    push_u32(&mut buf, config.max_links);
91    push_u32(&mut buf, config.max_monitors);
92    push_u32(&mut buf, config.max_registry_names);
93    push_u64(&mut buf, as_u64(config.max_runtime_bytes));
94    push_u32(&mut buf, config.mailbox.capacity().get_u32());
95    push_u64(&mut buf, as_u64(config.mailbox.bytes().get()));
96    buf.push(config.mailbox.overflow() as u8);
97    let q = &config.quota;
98    push_i64(&mut buf, q.cpu_budget);
99    push_u64(&mut buf, as_u64(q.mem_limit));
100    push_i64(&mut buf, q.spawn_burst);
101    push_i64(&mut buf, q.spawn_per_sec);
102    push_i64(&mut buf, q.send_burst);
103    push_i64(&mut buf, q.send_per_sec);
104    buf
105}
106
107fn as_u64(n: usize) -> u64 {
108    match u64::try_from(n) {
109        Ok(v) => v,
110        Err(_) => u64::MAX,
111    }
112}
113
114fn push_u32(buf: &mut Vec<u8>, value: u32) {
115    buf.extend_from_slice(&value.to_le_bytes());
116}
117
118fn push_u64(buf: &mut Vec<u8>, value: u64) {
119    buf.extend_from_slice(&value.to_le_bytes());
120}
121
122fn push_i64(buf: &mut Vec<u8>, value: i64) {
123    buf.extend_from_slice(&value.to_le_bytes());
124}
125
126fn trust_tag(trust: TrustLevel) -> u8 {
127    match trust {
128        TrustLevel::Trusted => 0,
129        TrustLevel::Restricted => 1,
130        TrustLevel::Untrusted => 2,
131    }
132}
133
134fn root_authority_tag(policy: crate::scheduler::RootAuthorityPolicy) -> u8 {
135    match policy {
136        crate::scheduler::RootAuthorityPolicy::TrustedHost => 0,
137        crate::scheduler::RootAuthorityPolicy::Restricted => 1,
138        crate::scheduler::RootAuthorityPolicy::Untrusted => 2,
139    }
140}
141
142/// Host-visible security counters. Untrusted bytecode cannot write these.
143#[derive(Default, Debug)]
144pub struct SecurityCounters {
145    pub denied_operations: AtomicU64,
146    pub quota_exceeded: AtomicU64,
147    pub capabilities_created: AtomicU64,
148    pub capabilities_revoked: AtomicU64,
149    pub invalid_modules: AtomicU64,
150    pub native_denied: AtomicU64,
151    pub active_untrusted_flows: AtomicU64,
152}
153
154impl SecurityCounters {
155    #[inline]
156    pub fn inc(counter: &AtomicU64) {
157        counter.fetch_add(1, Ordering::Relaxed);
158    }
159
160    /// Saturating decrement for [`Self::active_untrusted_flows`].
161    pub fn dec_active_untrusted(&self) {
162        let mut cur = self.active_untrusted_flows.load(Ordering::Relaxed);
163        while cur > 0 {
164            match self.active_untrusted_flows.compare_exchange_weak(
165                cur,
166                cur - 1,
167                Ordering::Relaxed,
168                Ordering::Relaxed,
169            ) {
170                Ok(_) => return,
171                Err(actual) => cur = actual,
172            }
173        }
174    }
175
176    pub fn snapshot(&self) -> SecurityCountersSnapshot {
177        SecurityCountersSnapshot {
178            denied_operations: self.denied_operations.load(Ordering::Relaxed),
179            quota_exceeded: self.quota_exceeded.load(Ordering::Relaxed),
180            capabilities_created: self.capabilities_created.load(Ordering::Relaxed),
181            capabilities_revoked: self.capabilities_revoked.load(Ordering::Relaxed),
182            invalid_modules: self.invalid_modules.load(Ordering::Relaxed),
183            native_denied: self.native_denied.load(Ordering::Relaxed),
184            active_untrusted_flows: self.active_untrusted_flows.load(Ordering::Relaxed),
185        }
186    }
187}
188
189/// Point-in-time copy of [`SecurityCounters`].
190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
191pub struct SecurityCountersSnapshot {
192    pub denied_operations: u64,
193    pub quota_exceeded: u64,
194    pub capabilities_created: u64,
195    pub capabilities_revoked: u64,
196    pub invalid_modules: u64,
197    pub native_denied: u64,
198    pub active_untrusted_flows: u64,
199}
200
201impl std::fmt::Display for SecurityCountersSnapshot {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        write!(
204            f,
205            "denied={} quota={} caps_created={} caps_revoked={} invalid_modules={} native_denied={} untrusted_flows={}",
206            self.denied_operations,
207            self.quota_exceeded,
208            self.capabilities_created,
209            self.capabilities_revoked,
210            self.invalid_modules,
211            self.native_denied,
212            self.active_untrusted_flows,
213        )
214    }
215}
216
217/// One live capability as seen by host attestation.
218#[derive(Clone, Debug, PartialEq, Eq)]
219pub struct CapabilityGrantView {
220    pub id: CapId,
221    pub holder: FlowId,
222    pub target: CapTarget,
223    pub rights: CapRights,
224}
225
226impl CapabilityGrantView {
227    pub fn from_entry(id: CapId, cap: &Capability) -> Self {
228        Self {
229            id,
230            holder: cap.holder,
231            target: cap.cap.target(),
232            rights: cap.cap.rights(),
233        }
234    }
235}
236
237/// Host inspection of what a flow currently holds.
238///
239/// Not a cryptographic proof of process integrity — only a table snapshot.
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct CapabilityAttestation {
242    pub flow: FlowId,
243    pub trust: TrustLevel,
244    pub policy: PolicyFingerprint,
245    pub grants: Vec<CapabilityGrantView>,
246}
247
248impl CapabilityAttestation {
249    pub fn from_table(
250        table: &CapTable,
251        flow: FlowId,
252        trust: TrustLevel,
253        policy: PolicyFingerprint,
254    ) -> Result<Self, RuntimeError> {
255        Ok(Self {
256            flow,
257            trust,
258            policy,
259            grants: table.list_held_by(flow)?,
260        })
261    }
262}
263
264/// Compact security event for an optional host audit sink.
265#[derive(Clone, Debug, PartialEq, Eq)]
266pub enum SecurityEvent {
267    CapabilityCreated { holder: u64 },
268    CapabilityDelegated { from: u64, to: u64 },
269    CapabilityRevoked { flow: u64, removed: usize },
270    AccessDenied { reason: &'static str },
271    QuotaExceeded { kind: &'static str },
272    ModuleRejected { reason: &'static str },
273    NativeDenied { index: u32 },
274    FlowFinalized { flow: u64 },
275}
276
277impl std::fmt::Display for SecurityEvent {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        match self {
280            SecurityEvent::CapabilityCreated { holder } => {
281                write!(f, "cap_created holder={holder}")
282            }
283            SecurityEvent::CapabilityDelegated { from, to } => {
284                write!(f, "cap_delegated from={from} to={to}")
285            }
286            SecurityEvent::CapabilityRevoked { flow, removed } => {
287                write!(f, "cap_revoked flow={flow} removed={removed}")
288            }
289            SecurityEvent::AccessDenied { reason } => write!(f, "access_denied {reason}"),
290            SecurityEvent::QuotaExceeded { kind } => write!(f, "quota_exceeded {kind}"),
291            SecurityEvent::ModuleRejected { reason } => write!(f, "module_rejected {reason}"),
292            SecurityEvent::NativeDenied { index } => write!(f, "native_denied idx={index}"),
293            SecurityEvent::FlowFinalized { flow } => write!(f, "flow_finalized id={flow}"),
294        }
295    }
296}
297
298/// Optional host callback for security events (never receives full CapId tokens).
299///
300/// The runtime delivers events on a **dedicated audit thread** with a bounded
301/// queue. `record` on the host sink may block that
302/// thread but must not block scheduler workers. Prefer fast, non-panicking
303/// sinks; a full queue drops the newest event (fail-open for observability).
304pub trait SecurityAuditSink: Send + Sync + std::fmt::Debug + 'static {
305    fn record(&self, event: &SecurityEvent);
306}
307
308/// Default capacity for the async audit queue between workers and the sink.
309pub const DEFAULT_AUDIT_QUEUE: usize = 1024;
310
311/// Join handle for the audit dispatcher started by [`wrap_audit_sink`].
312pub(crate) struct AuditWorkerHandle {
313    stop: Arc<AtomicBool>,
314    join: Option<JoinHandle<()>>,
315}
316
317impl AuditWorkerHandle {
318    pub(crate) fn stop(mut self) {
319        self.shutdown();
320    }
321
322    fn shutdown(&mut self) {
323        self.stop.store(true, Ordering::Release);
324        if let Some(join) = self.join.take() {
325            let _ = join.join();
326        }
327    }
328}
329
330impl Drop for AuditWorkerHandle {
331    fn drop(&mut self) {
332        self.shutdown();
333    }
334}
335
336#[derive(Debug)]
337struct QueuedAuditSink {
338    tx: SyncSender<SecurityEvent>,
339}
340
341impl SecurityAuditSink for QueuedAuditSink {
342    fn record(&self, event: &SecurityEvent) {
343        let _ = self.tx.try_send(event.clone());
344    }
345}
346
347/// Wrap a host [`SecurityAuditSink`] so worker `record` never blocks on it.
348///
349/// Returns a sink suitable for [`crate::RuntimeConfig::security_audit`] /
350/// `Shared`, plus a handle the runtime joins on shutdown (drains remaining
351/// events after `stop`).
352pub(crate) fn wrap_audit_sink(
353    sink: Arc<dyn SecurityAuditSink>,
354    capacity: usize,
355) -> (Arc<dyn SecurityAuditSink>, AuditWorkerHandle) {
356    let capacity = capacity.max(1);
357    let (tx, rx) = sync_channel::<SecurityEvent>(capacity);
358    let stop = Arc::new(AtomicBool::new(false));
359    let stop_worker = Arc::clone(&stop);
360    let join = thread::Builder::new()
361        .name("byteflow-audit".into())
362        .spawn(move || {
363            while !stop_worker.load(Ordering::Acquire) {
364                match rx.recv_timeout(Duration::from_millis(50)) {
365                    Ok(event) => sink.record(&event),
366                    Err(RecvTimeoutError::Timeout) => {}
367                    Err(RecvTimeoutError::Disconnected) => break,
368                }
369            }
370            while let Ok(event) = rx.try_recv() {
371                sink.record(&event);
372            }
373        })
374        .ok();
375    (
376        Arc::new(QueuedAuditSink { tx }),
377        AuditWorkerHandle { stop, join },
378    )
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use crate::bytecode::TrustLevel;
385    use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
386
387    #[test]
388    fn sandbox_fingerprint_differs_from_default() {
389        let permissive = RuntimeConfig::default();
390        let sandboxed = RuntimeConfig::sandbox();
391        assert_ne!(
392            policy_fingerprint(&permissive),
393            policy_fingerprint(&sandboxed)
394        );
395    }
396
397    #[test]
398    fn fingerprint_is_stable_for_identical_config() {
399        let a = RuntimeConfig::sandbox();
400        let b = RuntimeConfig::sandbox();
401        assert_eq!(policy_fingerprint(&a), policy_fingerprint(&b));
402    }
403
404    /// Pinned SHA-256 prefixes. A rustc or pointer-width change must not move these.
405    #[test]
406    fn fingerprint_matches_canonical_sha256_prefix() {
407        assert_eq!(
408            policy_fingerprint(&RuntimeConfig::default()).to_hex(),
409            "2e1be905f47892334e759d3327a05d46"
410        );
411        assert_eq!(
412            policy_fingerprint(&RuntimeConfig::sandbox()).to_hex(),
413            "d59bbad5eefb7b525a0cdeaf6708be36"
414        );
415    }
416
417    #[test]
418    fn fingerprint_changes_when_trust_changes() {
419        let mut a = RuntimeConfig::sandbox();
420        let mut b = RuntimeConfig::sandbox();
421        a.trust = TrustLevel::Untrusted;
422        b.trust = TrustLevel::Restricted;
423        assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
424    }
425
426    #[test]
427    fn fingerprint_changes_when_mailbox_changes() {
428        let a = RuntimeConfig::sandbox();
429        let mut b = RuntimeConfig::sandbox();
430        b.mailbox = MailboxConfig::new(MailboxCapacity::DEFAULT, OverflowPolicy::DropNewest);
431        assert_ne!(policy_fingerprint(&a), policy_fingerprint(&b));
432    }
433}