hyprstream_workers_wasmtime/wasi_sandbox.rs
1//! Profile B (#506): a WASI (`wasm32-wasip1`) sandbox whose ENTIRE filesystem is a
2//! Subject-scoped [`hyprstream_vfs::Mount`] — and nothing else.
3//!
4//! Contrast with Profile A ([`crate::Sandbox`]): Profile A is a bespoke capability
5//! Linker granting ONLY `env::host_random` + `env::vfs_*`, zero WASI. Profile B
6//! grants a REAL WASI preview1 surface (so an off-the-shelf `wasm32-wasip1` guest
7//! that does `open`/`read`/`write`/`readdir` runs unmodified) — but every WASI
8//! filesystem op is routed to a [`MountDir`](crate::wasi_fs::MountDir) backed by the
9//! VFS Mount. The make-or-break property: **the VFS is the guest's ONLY filesystem.
10//! There is no host preopen.**
11//!
12//! ## The hard caveat — capability withholding
13//!
14//! A single host preopen or any ambient WASI capability that touches the host
15//! reopens the sandbox escape. So the Profile-B [`wasi_common::WasiCtx`] is built
16//! by hand (NOT via `sync::WasiCtxBuilder`, which only does `cap_std::fs::Dir` host
17//! preopens):
18//!
19//! - **Preopen set:** EXACTLY ONE — the VFS [`MountDir`] at guest path `/`. No
20//! `preopened_dir(host_dir)`, ever.
21//! - **Clocks:** withheld. `WasiClocks::new()` leaves both system + monotonic
22//! `None`; any `clock_time_get`/`clock_res_get` returns `badf` (a future revision
23//! can VFS-mediate a clock file). The [`crate::EpochTimer`] is the DoS bound, not
24//! a guest-visible clock.
25//! - **Randomness:** withheld from the host OS. The ctx random source is
26//! `wasi_common::random::Deterministic` (NOT OS entropy); `random_get` yields a
27//! deterministic stream, not host CSPRNG output.
28//! - **Scheduling:** [`DeniedSched`] — `poll_oneoff`/`sched_yield`/`sleep` all
29//! error (deny-by-default).
30//! - **stdio:** the [`WasiCtx::new`] default — stdin = empty, stdout/stderr = sink.
31//! No host fd inheritance.
32//! - **`wasi:sockets`, environ, args:** none. preview1 has no sockets; environ/args
33//! are left empty.
34//!
35//! The bound [`Subject`] is fixed at construction and threaded by [`MountDir`] into
36//! every Mount call — the Mount is the ONE policy enforcement point.
37
38use std::sync::Arc;
39
40use hyprstream_vfs::{Mount, Subject};
41use wasi_common::clocks::WasiClocks;
42use wasi_common::random::Deterministic;
43use wasi_common::sched::{Poll, WasiSched};
44use wasi_common::{Error as WasiError, ErrorExt, Table, WasiCtx};
45use wasmtime::error::Context as _;
46use wasmtime::{Engine, Linker, Module, Result, Store};
47
48use crate::wasi_fs::MountDir;
49
50/// A `WasiSched` that denies all scheduling — the Profile-B deny-by-default sched.
51///
52/// `poll_oneoff`/`sched_yield`/`sleep` are not part of the minimal fs-only surface
53/// and `sleep` in particular is a (weak) DoS lever, so we withhold all three. The
54/// [`crate::EpochTimer`] remains the real wall-clock bound.
55struct DeniedSched;
56
57#[async_trait::async_trait]
58impl WasiSched for DeniedSched {
59 async fn poll_oneoff<'a>(&self, _poll: &mut Poll<'a>) -> std::result::Result<(), WasiError> {
60 Err(WasiError::not_supported().context("poll_oneoff withheld in Profile B"))
61 }
62 async fn sched_yield(&self) -> std::result::Result<(), WasiError> {
63 Err(WasiError::not_supported().context("sched_yield withheld in Profile B"))
64 }
65 async fn sleep(
66 &self,
67 _duration: wasi_common::sched::Duration,
68 ) -> std::result::Result<(), WasiError> {
69 Err(WasiError::not_supported().context("sleep withheld in Profile B"))
70 }
71}
72
73/// Per-call host state for a Profile-B Store: the bound [`Subject`] + the WASI ctx
74/// (whose only preopen is the VFS [`MountDir`]).
75pub struct WasiState {
76 pub subject: Subject,
77 pub wasi: WasiCtx,
78}
79
80impl WasiState {
81 pub fn subject(&self) -> &Subject {
82 &self.subject
83 }
84}
85
86/// A Profile-B WASI sandbox: a `wasm32-wasip1` guest whose filesystem is a
87/// Subject-scoped VFS [`Mount`].
88pub struct WasiSandbox {
89 engine: Engine,
90 module: Module,
91 linker: Linker<WasiState>,
92 mount: Arc<dyn Mount>,
93 subject: Subject,
94 /// Dedicated current-thread runtime used by the `MountDir`/`MountFile` adapters
95 /// to drive the async Mount synchronously under the wiggle `block_on` executor.
96 rt: Arc<tokio::runtime::Runtime>,
97}
98
99impl WasiSandbox {
100 /// Build a Profile-B sandbox over `wasm` (a `wasm32-wasip1` module), bound to
101 /// `subject`, whose ONLY filesystem is `mount` (preopened at guest path `/`).
102 ///
103 /// No host preopen, no sockets, clocks+random withheld/VFS-mediated. The
104 /// returned sandbox MUST be driven from a plain (non-async) thread — the Mount
105 /// adapters `block_on` an inner runtime, which would panic on a tokio worker.
106 pub fn wasi_for(wasm: &[u8], subject: Subject, mount: Arc<dyn Mount>) -> Result<Self> {
107 let engine = crate::build_engine()?;
108 let module = Module::new(&engine, wasm).context("compile wasip1 guest module")?;
109
110 // Link the preview1 WASI surface (sync wiggle = `block_on` executor). The
111 // ctx getter hands out `&mut state.wasi` — that is the WASI surface the
112 // guest sees, and its ONLY filesystem is the VFS preopen built in `run`.
113 let mut linker: Linker<WasiState> = Linker::new(&engine);
114 wasi_common::sync::add_to_linker(&mut linker, |s: &mut WasiState| &mut s.wasi)
115 .context("add wasi preview1 to linker")?;
116
117 // A current-thread runtime is enough: every Mount op is `block_on`'d to
118 // completion synchronously (the adapters never spawn).
119 let rt = tokio::runtime::Builder::new_current_thread()
120 .enable_all()
121 .build()
122 .context("build mount-bridge runtime")?;
123
124 Ok(Self {
125 engine,
126 module,
127 linker,
128 mount,
129 subject,
130 rt: Arc::new(rt),
131 })
132 }
133
134 /// The subject this sandbox runs as.
135 pub fn subject(&self) -> &Subject {
136 &self.subject
137 }
138
139 /// The engine (spawn a [`crate::EpochTimer`] on it for the wall-clock bound).
140 pub fn engine(&self) -> &Engine {
141 &self.engine
142 }
143
144 /// Build the hand-rolled, capability-withholding [`WasiCtx`]: deterministic
145 /// random, NO clocks, denied sched, sink stdio, and EXACTLY one preopen — the
146 /// VFS [`MountDir`] at guest path `/`. No host preopen.
147 fn make_ctx(&self) -> Result<WasiCtx> {
148 // Random: deterministic, NOT host OS entropy (withheld). The byte cycle is
149 // arbitrary; the point is "no host CSPRNG".
150 let random: Box<dyn wasi_rand::Rng + Send + Sync> =
151 Box::new(Deterministic::new(vec![0xA5, 0x5A, 0x3C, 0xC3]));
152 // Clocks: both None -> clock_*_get returns badf (withheld).
153 let clocks = WasiClocks::new();
154 let sched = Box::new(DeniedSched);
155 let ctx = WasiCtx::new(random, clocks, sched, Table::new());
156
157 // The ONLY preopen: the Subject-scoped VFS Mount, at guest path "/".
158 let dir = MountDir::new(
159 Arc::clone(&self.mount),
160 self.subject.clone(),
161 Arc::clone(&self.rt),
162 );
163 ctx.push_preopened_dir(Box::new(dir), "/")
164 .context("push VFS preopen")?;
165 Ok(ctx)
166 }
167
168 /// Fresh per-call Store bound to this sandbox's Subject + a freshly built ctx.
169 fn new_store(&self) -> Result<Store<WasiState>> {
170 let ctx = self.make_ctx()?;
171 Ok(Store::new(
172 &self.engine,
173 WasiState {
174 subject: self.subject.clone(),
175 wasi: ctx,
176 },
177 ))
178 }
179
180 /// Run the guest's `_start` (a wasip1 *command*) under a fuel budget.
181 ///
182 /// Returns `Ok(())` on clean exit (or `I32Exit(0)`); a nonzero `proc_exit`
183 /// surfaces as an error carrying the exit code. The guest's filesystem side
184 /// effects land in the VFS Mount.
185 pub fn run_start(&self, fuel: u64) -> Result<()> {
186 let mut store = self.new_store()?;
187 store.set_fuel(fuel).context("set fuel")?;
188 // Epoch defaults to deadline 0 with epoch_interruption(true); push it out so
189 // fuel is the limiter on this path (mirrors Profile A `eval`).
190 store.set_epoch_deadline(u64::MAX);
191
192 let instance = self
193 .linker
194 .instantiate(&mut store, &self.module)
195 .context("instantiate wasip1 guest")?;
196 let start = instance
197 .get_typed_func::<(), ()>(&mut store, "_start")
198 .context("guest has no _start (not a wasip1 command?)")?;
199
200 match start.call(&mut store, ()) {
201 Ok(()) => Ok(()),
202 Err(e) => {
203 // A clean `exit(0)` shows up as an I32Exit(0) trap — treat as success.
204 if let Some(exit) = e.downcast_ref::<wasi_common::I32Exit>() {
205 if exit.0 == 0 {
206 return Ok(());
207 }
208 }
209 Err(e).context("guest _start trapped")
210 }
211 }
212 }
213
214 /// Run `_start` under a WALL-CLOCK epoch deadline of `ticks` (paired with an
215 /// [`crate::EpochTimer`] on [`Self::engine`]). Fuel is set effectively infinite
216 /// so the epoch is the limiter — the production DoS bound for Profile B.
217 pub fn run_start_with_epoch_deadline(&self, ticks: u64) -> Result<()> {
218 let mut store = self.new_store()?;
219 store.set_fuel(u64::MAX).context("set fuel")?;
220 store.set_epoch_deadline(ticks);
221 let instance = self
222 .linker
223 .instantiate(&mut store, &self.module)
224 .context("instantiate wasip1 guest")?;
225 let start = instance
226 .get_typed_func::<(), ()>(&mut store, "_start")
227 .context("guest has no _start")?;
228 match start.call(&mut store, ()) {
229 Ok(()) => Ok(()),
230 Err(e) => {
231 if let Some(exit) = e.downcast_ref::<wasi_common::I32Exit>() {
232 if exit.0 == 0 {
233 return Ok(());
234 }
235 }
236 Err(e).context("guest _start trapped")
237 }
238 }
239 }
240}