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