Skip to main content

hyprstream_workers_wasmtime/
lib.rs

1//! Embedded wasmtime host for sandboxing untrusted wasm guests behind capability
2//! profiles.
3//!
4//! This crate is a GENERIC capability-sandbox host: it loads an arbitrary wasm guest
5//! module and runs it under wasmtime with a deny-by-default capability surface plus
6//! DoS bounds. Two profiles are provided:
7//!
8//! * **Profile A** ([`Sandbox`], this module): a bespoke `Linker` that exposes
9//!   exactly the host functions we choose — `env::host_random` plus the
10//!   Subject-scoped `env::vfs_*` capabilities (see [`vfs`]) — and wires EVERY other
11//!   declared import to a trap via `define_unknown_imports_as_traps`. No
12//!   `wasmtime-wasi`, no preopens, no syscall surface: a guest that reaches for any
13//!   un-granted host function traps. [`Sandbox::call_export`] drives an arbitrary
14//!   guest export over the guest's `alloc`/`memory` ABI; language profiles (e.g. the
15//!   `hyprstream-workers-python` crate's `eval`/shell) build on top of it. This crate
16//!   is LANGUAGE-AGNOSTIC: it carries no Python (or other language) awareness.
17//! * **Profile B** ([`wasi_sandbox::WasiSandbox`]): a real WASI preview1 surface whose
18//!   ONLY filesystem is a Subject-scoped [`hyprstream_vfs::Mount`] — no host preopen,
19//!   clocks/random/sockets/sched withheld.
20//!
21//! Capabilities are Subject-scoped BY CONSTRUCTION: the per-call [`SandboxState`]
22//! carries the [`Subject`] the call runs as, and host functions read it out of the
23//! `Store` rather than trusting any guest-supplied identity. There is no
24//! global/thread-local identity state.
25//!
26//! DoS guards on the `Store` (wasmtime 46.0.1 spellings):
27//!   * fuel  (`Config::consume_fuel(true)` + `Store::set_fuel(u64)`)
28//!   * epoch (`Config::epoch_interruption(true)` + `Store::set_epoch_deadline(u64)`
29//!     + `Engine::increment_epoch()`)
30//!
31//! wasmtime 46 ships its own error type (`wasmtime::Error` / `wasmtime::Result`, not
32//! `anyhow::Error`) with an inherent `wasmtime::Context` trait; this crate uses those.
33
34use std::sync::Arc;
35use std::time::Duration;
36
37/// Boxed entropy source: fills a byte buffer. Boxed so [`SandboxState`] can hold an
38/// OS-backed or deterministic-test RNG behind the same field.
39type RngFill = Box<dyn FnMut(&mut [u8]) + Send>;
40
41use wasmtime::error::Context as _;
42use wasmtime::{bail, Caller, Config, Engine, Extern, Linker, Memory, Module, Result, Store};
43
44pub mod vfs;
45pub mod wasi_fs;
46pub mod wasi_sandbox;
47
48// ---------------------------------------------------------------------------
49// Subject: the identity/tenant a sandbox call runs as.
50// ---------------------------------------------------------------------------
51
52/// The identity a sandbox evaluation runs as.
53///
54/// This is the canonical [`hyprstream_rpc::Subject`] (also re-exported via
55/// `hyprstream_vfs::Subject`), so the VFS proxy the sandbox talks to is scoped to the
56/// SAME identity the rest of the daemon uses. Confirmed torch-free: `hyprstream-vfs
57/// -> hyprstream-rpc` pulls no `tch`/libtorch, so this crate builds without LIBTORCH.
58pub use hyprstream_rpc::Subject;
59
60// ---------------------------------------------------------------------------
61// Per-call Store data.
62// ---------------------------------------------------------------------------
63
64/// Per-call host state carried in the wasmtime `Store` data.
65///
66/// Carries the [`Subject`] the call runs as. Every capability host function gets a
67/// `Caller<'_, SandboxState>` and so can read `caller.data().subject` — the
68/// capability surface is Subject-parameterized without any global/thread-local
69/// state.
70pub struct SandboxState {
71    /// The identity this evaluation runs as. Capability host-fns (`host_random`,
72    /// `vfs_*`) are authorized/scoped against this.
73    pub subject: Subject,
74    /// Entropy source for the single `host_random` capability. The HOST has OS
75    /// entropy; the guest only ever sees it through this function.
76    rng_bytes: RngFill,
77    /// The Subject-scoped VFS proxy handle backing `env::vfs_*`. `None` = the
78    /// sandbox was created without a VFS capability (the `vfs_*` host fns then
79    /// return a "no vfs capability" error to the guest — deny-by-default).
80    vfs: Option<vfs::VfsProxyHandle>,
81}
82
83impl SandboxState {
84    /// Host state for the given subject, drawing randomness from the OS. No VFS.
85    pub fn new(subject: Subject) -> Self {
86        Self {
87            subject,
88            rng_bytes: Box::new(|buf| {
89                use rand::RngCore;
90                rand::thread_rng().fill_bytes(buf);
91            }),
92            vfs: None,
93        }
94    }
95
96    /// Host state with a Subject-scoped VFS capability backing `env::vfs_*`.
97    pub fn with_vfs(subject: Subject, vfs: vfs::VfsProxyHandle) -> Self {
98        let mut s = Self::new(subject);
99        s.vfs = Some(vfs);
100        s
101    }
102
103    /// Deterministic host state for tests (fills with a fixed pattern).
104    pub fn deterministic(subject: Subject, seed: u8) -> Self {
105        Self {
106            subject,
107            rng_bytes: Box::new(move |buf| {
108                for (i, b) in buf.iter_mut().enumerate() {
109                    *b = seed.wrapping_add(i as u8);
110                }
111            }),
112            vfs: None,
113        }
114    }
115
116    /// The subject this state is bound to.
117    pub fn subject(&self) -> &Subject {
118        &self.subject
119    }
120}
121
122/// Build the wasmtime `Engine` with both DoS guards enabled.
123pub fn build_engine() -> Result<Engine> {
124    let mut config = Config::new();
125    // Epoch interruption: cooperative deadline interruption (cheap, no per-op cost).
126    config.epoch_interruption(true);
127    // Fuel: deterministic instruction budget (used by the deterministic DoS test).
128    config.consume_fuel(true);
129    Engine::new(&config).context("build wasmtime engine")
130}
131
132// ---------------------------------------------------------------------------
133// Epoch timer: the real wall-clock DoS bound.
134// ---------------------------------------------------------------------------
135
136/// A background thread that advances an [`Engine`]'s epoch at a fixed cadence.
137///
138/// wasmtime's epoch interruption is the cheap, production-grade way to enforce a
139/// WALL-CLOCK timeout (fuel is deterministic but instruction-count based, which is
140/// the right tool for tests, not for "kill anything that runs longer than N ms").
141/// This timer ticks every `tick`; a per-call `Store::set_epoch_deadline(n)` then
142/// means the guest traps with "interrupt" after roughly `n * tick` of wall time.
143///
144/// Dropping the timer stops the thread (cooperatively, within one tick).
145pub struct EpochTimer {
146    handle: Option<std::thread::JoinHandle<()>>,
147    stop: Arc<std::sync::atomic::AtomicBool>,
148    tick: Duration,
149}
150
151impl EpochTimer {
152    /// Spawn a timer that calls `engine.increment_epoch()` every `tick`.
153    pub fn spawn(engine: &Engine, tick: Duration) -> Self {
154        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
155        // The Engine is cheaply cloneable (Arc inside) and the clone shares the
156        // same epoch counter, so the timer's increments are observed by stores
157        // created from the original engine.
158        let engine = engine.clone();
159        let stop_clone = stop.clone();
160        let handle = std::thread::Builder::new()
161            .name("hyprstream-workers-wasmtime-epoch".into())
162            .spawn(move || {
163                while !stop_clone.load(std::sync::atomic::Ordering::Relaxed) {
164                    std::thread::sleep(tick);
165                    engine.increment_epoch();
166                }
167            })
168            .expect("spawn epoch timer thread");
169        Self {
170            handle: Some(handle),
171            stop,
172            tick,
173        }
174    }
175
176    /// The cadence at which this timer advances the epoch.
177    pub fn tick(&self) -> Duration {
178        self.tick
179    }
180}
181
182impl Drop for EpochTimer {
183    fn drop(&mut self) {
184        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
185        if let Some(h) = self.handle.take() {
186            let _ = h.join();
187        }
188    }
189}
190
191/// Construct the bespoke Linker exposing ONLY `env::host_random`.
192///
193/// Every other import the guest declares is wired to a trap via
194/// `define_unknown_imports_as_traps` — so if guest code ever actually reached for
195/// them it would trap rather than silently linking to nothing. This is what keeps
196/// the capability surface to exactly one function. (With rustpython-vm 0.5 the guest
197/// declares EXACTLY `env::host_random` and nothing else — but the trap-everything
198/// fence stays as a deny-by-default belt-and-suspenders for any future guest.)
199pub fn build_linker(engine: &Engine, module: &Module) -> Result<Linker<SandboxState>> {
200    let mut linker: Linker<SandboxState> = Linker::new(engine);
201
202    // The ONE capability: fill guest memory[ptr..ptr+len] with host randomness.
203    // It reads its Subject from the Store data (`caller.data().subject`), so it is
204    // Subject-scoped by construction — the seam future capability fns reuse.
205    linker.func_wrap(
206        "env",
207        "host_random",
208        |mut caller: Caller<'_, SandboxState>, ptr: i32, len: i32| -> Result<()> {
209            // Subject is available here for scoping/auditing (RNG is granted to all
210            // subjects; the point is the seam, not a denial for entropy).
211            let _subject = caller.data().subject.clone();
212            let memory = match caller.get_export("memory") {
213                Some(Extern::Memory(m)) => m,
214                _ => bail!("guest has no exported memory"),
215            };
216            let len = len as usize;
217            let mut scratch = vec![0u8; len];
218            (caller.data_mut().rng_bytes)(&mut scratch);
219            write_memory(&memory, &mut caller, ptr as usize, &scratch)?;
220            Ok(())
221        },
222    )?;
223
224    // ── The VFS capability host fns ─────────────────────────────────────────
225    //
226    // Each reads `caller.data().subject` (NEVER a guest-supplied identity) and
227    // submits the op to the Subject-scoped proxy handle in the Store data. The op
228    // result is written back into a guest buffer (allocated via the guest's own
229    // `alloc` export) as `[status_byte][payload...]` and returned packed as
230    // `(out_ptr<<32)|out_len` — the i64 ABI the guest's `take_reply` decodes.
231    //
232    // If the sandbox has NO vfs handle, the call returns a deny reply
233    // (deny-by-default): the capability is only present when explicitly granted.
234
235    // vfs_cat(path_ptr, path_len) -> i64
236    linker.func_wrap(
237        "env",
238        "vfs_cat",
239        |mut caller: Caller<'_, SandboxState>, ptr: i32, len: i32| -> Result<i64> {
240            let path = read_guest_string(&mut caller, ptr, len)?;
241            let reply = match caller.data().vfs.clone() {
242                Some(h) => h.cat(&path),
243                None => no_vfs_reply(),
244            };
245            write_reply(&mut caller, reply)
246        },
247    )?;
248
249    // vfs_ls(path_ptr, path_len) -> i64
250    linker.func_wrap(
251        "env",
252        "vfs_ls",
253        |mut caller: Caller<'_, SandboxState>, ptr: i32, len: i32| -> Result<i64> {
254            let path = read_guest_string(&mut caller, ptr, len)?;
255            let reply = match caller.data().vfs.clone() {
256                Some(h) => h.ls(&path),
257                None => no_vfs_reply(),
258            };
259            write_reply(&mut caller, reply)
260        },
261    )?;
262
263    // vfs_echo(path_ptr, path_len, data_ptr, data_len) -> i64
264    linker.func_wrap(
265        "env",
266        "vfs_echo",
267        |mut caller: Caller<'_, SandboxState>,
268         pptr: i32,
269         plen: i32,
270         dptr: i32,
271         dlen: i32|
272         -> Result<i64> {
273            let path = read_guest_string(&mut caller, pptr, plen)?;
274            let data = read_guest_bytes(&mut caller, dptr, dlen)?;
275            let reply = match caller.data().vfs.clone() {
276                Some(h) => h.echo(&path, &data),
277                None => no_vfs_reply(),
278            };
279            write_reply(&mut caller, reply)
280        },
281    )?;
282
283    // vfs_ctl(path_ptr, path_len, cmd_ptr, cmd_len) -> i64
284    linker.func_wrap(
285        "env",
286        "vfs_ctl",
287        |mut caller: Caller<'_, SandboxState>,
288         pptr: i32,
289         plen: i32,
290         cptr: i32,
291         clen: i32|
292         -> Result<i64> {
293            let path = read_guest_string(&mut caller, pptr, plen)?;
294            let cmd = read_guest_bytes(&mut caller, cptr, clen)?;
295            let reply = match caller.data().vfs.clone() {
296                Some(h) => h.ctl(&path, &cmd),
297                None => no_vfs_reply(),
298            };
299            write_reply(&mut caller, reply)
300        },
301    )?;
302
303    // Wire every OTHER declared import to a trap. This is the explicit, auditable
304    // statement that the guest gets NO other host capability.
305    linker.define_unknown_imports_as_traps(module)?;
306
307    Ok(linker)
308}
309
310/// The deny-by-default reply when a sandbox has no VFS capability granted.
311fn no_vfs_reply() -> vfs::VfsReply {
312    vfs::VfsReply {
313        ok: false,
314        body: b"vfs: no capability granted to this sandbox".to_vec(),
315    }
316}
317
318/// Read `len` bytes of guest memory at `ptr` as a (lossy) UTF-8 string.
319fn read_guest_string(caller: &mut Caller<'_, SandboxState>, ptr: i32, len: i32) -> Result<String> {
320    let bytes = read_guest_bytes(caller, ptr, len)?;
321    Ok(String::from_utf8_lossy(&bytes).into_owned())
322}
323
324/// Read `len` bytes of guest memory at `ptr`.
325fn read_guest_bytes(caller: &mut Caller<'_, SandboxState>, ptr: i32, len: i32) -> Result<Vec<u8>> {
326    if len <= 0 {
327        return Ok(Vec::new());
328    }
329    let memory = match caller.get_export("memory") {
330        Some(Extern::Memory(m)) => m,
331        _ => bail!("guest has no exported memory"),
332    };
333    let data = memory.data(&caller);
334    let start = ptr as usize;
335    let end = start
336        .checked_add(len as usize)
337        .ok_or_else(|| wasmtime::Error::msg("vfs arg length overflow"))?;
338    if end > data.len() {
339        bail!("vfs arg out of bounds");
340    }
341    Ok(data[start..end].to_vec())
342}
343
344/// Serialise a [`vfs::VfsReply`] into a freshly guest-`alloc`ated buffer as
345/// `[status_byte][payload...]` and return the packed `(ptr<<32)|len` i64. The
346/// guest reads it back and `dealloc`s the buffer (see the guest's `take_reply`).
347fn write_reply(caller: &mut Caller<'_, SandboxState>, reply: vfs::VfsReply) -> Result<i64> {
348    // status: 0 = ok, 1 = err (matches the guest's TAG_OK / TAG_ERR).
349    let status: u8 = if reply.ok { 0 } else { 1 };
350    let total = 1 + reply.body.len();
351
352    // Allocate the reply buffer inside the guest via its own allocator so the
353    // guest's `dealloc(ptr, len)` matches.
354    let alloc = caller
355        .get_export("alloc")
356        .and_then(Extern::into_func)
357        .ok_or_else(|| wasmtime::Error::msg("guest has no alloc export"))?
358        .typed::<i32, i32>(&caller)?;
359    let out_ptr = alloc.call(&mut *caller, total as i32)?;
360
361    let memory = match caller.get_export("memory") {
362        Some(Extern::Memory(m)) => m,
363        _ => bail!("guest has no exported memory"),
364    };
365    let mem = memory.data_mut(&mut *caller);
366    let start = out_ptr as usize;
367    let end = start
368        .checked_add(total)
369        .ok_or_else(|| wasmtime::Error::msg("reply length overflow"))?;
370    if end > mem.len() {
371        bail!("reply write out of bounds");
372    }
373    mem[start] = status;
374    mem[start + 1..end].copy_from_slice(&reply.body);
375
376    Ok(((out_ptr as u64) << 32 | total as u64) as i64)
377}
378
379fn write_memory(
380    memory: &Memory,
381    store: &mut Caller<'_, SandboxState>,
382    offset: usize,
383    data: &[u8],
384) -> Result<()> {
385    let mem = memory.data_mut(store);
386    let end = match offset.checked_add(data.len()) {
387        Some(e) => e,
388        None => bail!("host_random length overflow"),
389    };
390    if end > mem.len() {
391        bail!("host_random write out of bounds");
392    }
393    mem[offset..end].copy_from_slice(data);
394    Ok(())
395}
396
397/// A loaded, ready-to-run sandbox over a single guest module, bound to one
398/// [`Subject`].
399///
400/// Constructing a `Sandbox` binds it to a Subject; every call on it runs as that
401/// Subject. Two `Sandbox`es bound to different Subjects keep independent Store
402/// identity (no shared global/thread-local state) — see the `subject_isolation`
403/// test.
404///
405/// This is the GENERIC Profile-A core: [`call_export`](Self::call_export) ships a
406/// byte payload to a named guest export over the guest's `alloc`/`memory` ABI. Language
407/// profile crates (e.g. `hyprstream-workers-python`) build typed APIs on top of it.
408pub struct Sandbox {
409    engine: Engine,
410    module: Module,
411    linker: Linker<SandboxState>,
412    subject: Subject,
413    /// Optional Subject-scoped VFS capability handed to every `Store` this sandbox
414    /// builds. `None` = no VFS capability (deny-by-default).
415    vfs: Option<vfs::VfsProxyHandle>,
416}
417
418impl Sandbox {
419    /// Load a guest module from raw wasm bytes, bound to the anonymous subject.
420    pub fn from_bytes(wasm: &[u8]) -> Result<Self> {
421        Self::from_bytes_for(wasm, Subject::anonymous())
422    }
423
424    /// Load a guest module from raw wasm bytes, bound to `subject`.
425    pub fn from_bytes_for(wasm: &[u8], subject: Subject) -> Result<Self> {
426        let engine = build_engine()?;
427        let module = Module::new(&engine, wasm).context("compile guest module")?;
428        let linker = build_linker(&engine, &module)?;
429        Ok(Self {
430            engine,
431            module,
432            linker,
433            subject,
434            vfs: None,
435        })
436    }
437
438    /// Grant this sandbox a Subject-scoped VFS capability (`env::vfs_*`).
439    ///
440    /// The `handle` should be a [`vfs::VfsProxyHandle`] from
441    /// `spawn_vfs_proxy(ns, subject)` with the SAME subject the sandbox is bound to,
442    /// so the capability is scoped to this sandbox's identity. Builder-style.
443    pub fn with_vfs(mut self, handle: vfs::VfsProxyHandle) -> Self {
444        self.vfs = Some(handle);
445        self
446    }
447
448    /// The subject this sandbox is bound to.
449    pub fn subject(&self) -> &Subject {
450        &self.subject
451    }
452
453    /// Build the per-call host state (subject + optional VFS capability).
454    fn make_state(&self) -> SandboxState {
455        match self.vfs.clone() {
456            Some(h) => SandboxState::with_vfs(self.subject.clone(), h),
457            None => SandboxState::new(self.subject.clone()),
458        }
459    }
460
461    /// Fresh per-call Store for this sandbox's subject, with the epoch pushed out
462    /// of the way (so the caller chooses fuel- or epoch-bounding explicitly).
463    pub(crate) fn new_store(&self) -> Store<SandboxState> {
464        Store::new(&self.engine, self.make_state())
465    }
466
467    /// Call the named guest export with `input` shipped into guest memory, under the
468    /// given fuel budget.
469    ///
470    /// This is the GENERIC Profile-A entry point. It instantiates a fresh guest
471    /// instance, allocates a buffer via the guest's `alloc` export, writes `input`
472    /// into it, calls `export(ptr, len) -> i32`, then `dealloc`s the buffer. Returns
473    /// the export's i32 status on normal completion, or `Err` if the guest TRAPPED
474    /// (e.g. ran out of fuel, or reached an un-granted, trap-wired import).
475    /// Deterministic (fuel-bounded); the building block profile modules call.
476    ///
477    /// The guest must export `alloc(i32)->i32`, `dealloc(i32,i32)`, `memory`, and the
478    /// named export with signature `(i32,i32)->i32`.
479    pub fn call_export(&self, name: &str, input: &[u8], fuel: u64) -> Result<i32> {
480        let mut store = self.new_store();
481        // DoS guard #1: instruction budget.
482        store.set_fuel(fuel).context("set fuel")?;
483        // The engine has epoch_interruption(true), so EVERY store defaults to an epoch
484        // deadline of 0 and would trap immediately ("wasm trap: interrupt") unless we
485        // push it out. For the fuel-bounded path the epoch is set effectively infinite
486        // so fuel is the only limiter.
487        store.set_epoch_deadline(u64::MAX);
488        self.run_export(store, name, input)
489    }
490
491    /// Like [`call_export`](Self::call_export) but driven by a pre-configured `store`
492    /// (the caller has set fuel and/or the epoch deadline). Used internally by the
493    /// fuel- and epoch-bounded entry points. See [`new_store`](Self::new_store).
494    fn run_export(&self, mut store: Store<SandboxState>, name: &str, input: &[u8]) -> Result<i32> {
495        let instance = self
496            .linker
497            .instantiate(&mut store, &self.module)
498            .context("instantiate guest")?;
499
500        let alloc = instance.get_typed_func::<i32, i32>(&mut store, "alloc")?;
501        let dealloc = instance.get_typed_func::<(i32, i32), ()>(&mut store, "dealloc")?;
502        let export = instance.get_typed_func::<(i32, i32), i32>(&mut store, name)?;
503        let memory = match instance.get_memory(&mut store, "memory") {
504            Some(m) => m,
505            None => bail!("guest memory export"),
506        };
507
508        let len = input.len() as i32;
509        let ptr = alloc.call(&mut store, len)?;
510        memory
511            .write(&mut store, ptr as usize, input)
512            .context("write input into guest")?;
513
514        let status = export.call(&mut store, (ptr, len));
515        let _ = dealloc.call(&mut store, (ptr, len));
516        status.with_context(|| format!("guest export `{name}` trapped"))
517    }
518
519    /// The engine backing this sandbox. Spawn an [`EpochTimer`] on it to enable the
520    /// wall-clock bound used by epoch-deadline call paths (e.g.
521    /// [`Sandbox::call_export_with_epoch`]).
522    pub fn engine(&self) -> &Engine {
523        &self.engine
524    }
525
526    /// Like [`call_export`](Self::call_export) but bounded by a WALL-CLOCK epoch
527    /// deadline of `ticks` epoch increments instead of fuel.
528    ///
529    /// This is the PRODUCTION DoS bound: paired with an [`EpochTimer`] spawned on
530    /// [`engine`](Self::engine) ticking every `t`, the guest traps with "interrupt"
531    /// after roughly `ticks * t` of wall time. Fuel is set effectively infinite so the
532    /// epoch (not fuel) is the limiter. The caller owns the [`EpochTimer`]; this method
533    /// does not start one. Generic over the named `(i32,i32)->i32` export — language
534    /// profiles (e.g. python `eval`) drive their entry through it.
535    pub fn call_export_with_epoch(&self, name: &str, input: &[u8], ticks: u64) -> Result<i32> {
536        let mut store = self.new_store();
537        // Give plenty of fuel so the EPOCH deadline (not fuel) is the limiter here.
538        store.set_fuel(u64::MAX).context("set fuel")?;
539        // DoS guard: epoch deadline. Trap once the engine epoch advances `ticks`.
540        store.set_epoch_deadline(ticks);
541        self.run_export(store, name, input)
542    }
543
544    /// Open a PERSISTENT guest instance over this sandbox for the packed-op ABI.
545    ///
546    /// Unlike [`call_export`](Self::call_export) (a fresh instance per call), the
547    /// returned [`PersistentInstance`] holds ONE long-lived `Store` + `Instance`, so
548    /// guest interpreter state survives across calls. This is the generic substrate a
549    /// language profile (e.g. the python shell's persistent interpreter, whose
550    /// `/lang/python/vars` + `/defs` semantics depend on persistence) builds on.
551    ///
552    /// `per_call_fuel` is applied per [`PersistentInstance::call_op`] (a fresh budget
553    /// each invocation); the store itself is reused. The epoch is pushed out (fuel is
554    /// the limiter for this path). The guest must export `alloc(i32)->i32`,
555    /// `dealloc(i32,i32)`, `memory`, and the packed-op export named in `call_op`.
556    pub fn open_instance(&self, per_call_fuel: u64) -> Result<PersistentInstance> {
557        let mut store = self.new_store();
558        store.set_fuel(per_call_fuel).context("set fuel")?;
559        store.set_epoch_deadline(u64::MAX);
560        let instance = self
561            .linker
562            .instantiate(&mut store, &self.module)
563            .context("instantiate guest")?;
564        let memory = instance
565            .get_memory(&mut store, "memory")
566            .ok_or_else(|| wasmtime::Error::msg("guest memory export"))?;
567        let alloc = instance.get_typed_func::<i32, i32>(&mut store, "alloc")?;
568        let dealloc = instance.get_typed_func::<(i32, i32), ()>(&mut store, "dealloc")?;
569        Ok(PersistentInstance {
570            store,
571            memory,
572            alloc,
573            dealloc,
574            instance,
575            per_call_fuel,
576        })
577    }
578
579    /// Drive the guest's `vfs_probe` export: make the GUEST call an `env::vfs_*`
580    /// host fn, proving the capability is real end-to-end (guest -> host fn ->
581    /// Subject-scoped proxy -> `Namespace`).
582    ///
583    /// `op`: 0=cat, 1=ls, 2=echo, 3=ctl. `path` + optional `body` (echo/ctl). Returns
584    /// the decoded `[status][payload]` reply the host fn produced — the minimal
585    /// "a guest call against a VFS path goes through the Mount" exercise of the
586    /// `env::vfs_*` capability.
587    pub fn probe_vfs(&self, op: i32, path: &str, body: &[u8]) -> Result<vfs::VfsReply> {
588        let mut store = self.new_store();
589        store.set_fuel(u64::MAX).context("set fuel")?;
590        store.set_epoch_deadline(u64::MAX);
591        let instance = self
592            .linker
593            .instantiate(&mut store, &self.module)
594            .context("instantiate guest")?;
595        let memory = instance
596            .get_memory(&mut store, "memory")
597            .ok_or_else(|| wasmtime::Error::msg("guest memory export"))?;
598        let alloc = instance.get_typed_func::<i32, i32>(&mut store, "alloc")?;
599        let probe =
600            instance.get_typed_func::<(i32, i32, i32, i32, i32), i64>(&mut store, "vfs_probe")?;
601
602        // Ship path + body into guest memory.
603        let pbytes = path.as_bytes();
604        let plen = pbytes.len() as i32;
605        let pptr = if plen > 0 {
606            let p = alloc.call(&mut store, plen)?;
607            memory.write(&mut store, p as usize, pbytes)?;
608            p
609        } else {
610            0
611        };
612        let blen = body.len() as i32;
613        let bptr = if blen > 0 {
614            let p = alloc.call(&mut store, blen)?;
615            memory.write(&mut store, p as usize, body)?;
616            p
617        } else {
618            0
619        };
620
621        let packed = probe
622            .call(&mut store, (op, pptr, plen, bptr, blen))
623            .context("guest vfs_probe trapped")?;
624
625        // The host wrote the reply via the guest allocator; decode it.
626        let p = packed as u64;
627        let out_ptr = (p >> 32) as usize;
628        let out_len = (p & 0xffff_ffff) as usize;
629        if out_ptr == 0 || out_len == 0 {
630            bail!("vfs_probe empty reply");
631        }
632        let data = memory.data(&store);
633        if out_ptr + out_len > data.len() {
634            bail!("vfs_probe reply out of bounds");
635        }
636        let status = data[out_ptr];
637        let payload = data[out_ptr + 1..out_ptr + out_len].to_vec();
638        Ok(vfs::VfsReply {
639            ok: status == TAG_OK,
640            body: payload,
641        })
642    }
643}
644
645/// A persistent guest instance over a single [`Sandbox`], driving the generic
646/// packed-op ABI.
647///
648/// Holds the long-lived `Store`/`Instance` so guest state survives across calls.
649/// [`call_op`](Self::call_op) ships the argument into guest memory, calls
650/// `op(op_code, ptr, len) -> i64`, decodes the packed `(out_ptr<<32)|out_len` reply,
651/// reads `[tag][payload]`, then `dealloc`s the reply buffer — returning `(tag,
652/// payload)`. This crate assigns NO meaning to `op_code` or `tag` beyond the shared
653/// [`TAG_OK`] convention; a language profile crate (e.g. `hyprstream-workers-python`)
654/// layers its own op codes / result decoding on top.
655///
656/// A `PersistentInstance` must be driven from a NON-async thread if its sandbox holds
657/// a VFS capability (the `vfs_*` host fns `blocking_send`).
658pub struct PersistentInstance {
659    store: Store<SandboxState>,
660    memory: Memory,
661    alloc: wasmtime::TypedFunc<i32, i32>,
662    dealloc: wasmtime::TypedFunc<(i32, i32), ()>,
663    instance: wasmtime::Instance,
664    per_call_fuel: u64,
665}
666
667impl PersistentInstance {
668    /// Call the named packed-op export `(i32 op, i32 ptr, i32 len) -> i64` with `arg`
669    /// shipped into guest memory under a fresh per-call fuel budget; decode the
670    /// `(out_ptr<<32)|out_len` reply into `(tag, payload)`.
671    ///
672    /// Returns `Err` if the guest TRAPPED (fuel exhaustion, un-granted import, etc.)
673    /// or the reply was malformed (empty / out of bounds).
674    pub fn call_op(&mut self, export: &str, op: i32, arg: &[u8]) -> Result<(u8, Vec<u8>)> {
675        // Fresh fuel budget per call (the store is reused, fuel is not).
676        self.store
677            .set_fuel(self.per_call_fuel)
678            .context("set fuel")?;
679
680        let op_fn = self
681            .instance
682            .get_typed_func::<(i32, i32, i32), i64>(&mut self.store, export)?;
683
684        let len = arg.len() as i32;
685        let ptr = if len > 0 {
686            let p = self.alloc.call(&mut self.store, len)?;
687            self.memory
688                .write(&mut self.store, p as usize, arg)
689                .context("write packed-op arg")?;
690            p
691        } else {
692            0
693        };
694
695        let packed = op_fn
696            .call(&mut self.store, (op, ptr, len))
697            .with_context(|| format!("guest packed-op `{export}` trapped"))?;
698        if len > 0 {
699            let _ = self.dealloc.call(&mut self.store, (ptr, len));
700        }
701
702        let p = packed as u64;
703        let out_ptr = (p >> 32) as usize;
704        let out_len = (p & 0xffff_ffff) as usize;
705        if out_ptr == 0 || out_len == 0 {
706            bail!("packed-op empty reply");
707        }
708        let data = self.memory.data(&self.store);
709        if out_ptr + out_len > data.len() {
710            bail!("packed-op reply out of bounds");
711        }
712        let tag = data[out_ptr];
713        let body = data[out_ptr + 1..out_ptr + out_len].to_vec();
714        let _ = self
715            .dealloc
716            .call(&mut self.store, (out_ptr as i32, out_len as i32));
717        Ok((tag, body))
718    }
719}
720
721/// Status tag for an "ok" reply in the first byte of a host-serialised guest reply
722/// buffer (the `vfs_*` and packed-op ABIs share this convention: 0 = ok). Used by
723/// [`Sandbox::probe_vfs`] and the generic [`PersistentInstance`] packed-op decoder.
724/// Public so language profile crates (e.g. `hyprstream-workers-python`) can match
725/// the shared ABI tag without redefining it.
726pub const TAG_OK: u8 = 0;