hyprstream_workers_python/lib.rs
1//! RustPython engine + `/lang/python` 9P shell for the hyprstream VFS namespace.
2//!
3//! This crate is the ONE python-aware layer over the generic, language-agnostic
4//! wasm sandbox engine ([`hyprstream_workers_wasmtime`]). It runs untrusted Python on
5//! the RustPython guest (`hyprstream-workers-python-guest`, compiled to
6//! `wasm32-unknown-unknown`) inside a Profile-A
7//! [`Sandbox`](hyprstream_workers_wasmtime::Sandbox). The engine knows nothing about
8//! Python; everything python-specific (the `eval`/`py_op` ABI, the result decoding,
9//! the `/lang/python` mount) lives here.
10//!
11//! Module shape mirrors `hyprstream-workers-tcl`:
12//! - `lib.rs` — the [`PythonShell`] + re-exports of the mount items.
13//! - `mount.rs` — [`PythonMount`] (`impl Mount`), [`PyCommand`], [`PythonMount::spawn`].
14//!
15//! ## Guest ABI used here
16//!
17//! * `eval(ptr,len) -> i32` — run UTF-8 source in a FRESH interpreter; 0 = ok,
18//! nonzero = a Python error. Driven via
19//! [`Sandbox::call_export`](hyprstream_workers_wasmtime::Sandbox::call_export).
20//! * `py_op(op, ptr, len) -> i64` — run an operation against the PERSISTENT
21//! interpreter, returning a packed `(out_ptr<<32)|out_len` reply whose first byte is
22//! a status tag. Driven by [`PythonShell`] over the generic
23//! [`PersistentInstance`](hyprstream_workers_wasmtime::PersistentInstance).
24//!
25//! ## Security
26//!
27//! The guest only ever reaches the host capabilities the engine's `Linker` grants
28//! (`env::host_random` + the Subject-scoped `env::vfs_*`); everything else traps. DoS
29//! bounds (fuel / epoch) are enforced by the engine. `import os; os.system(...)` is
30//! inert — there is no syscall surface.
31
32use hyprstream_workers_wasmtime::{PersistentInstance, Sandbox, TAG_OK};
33use wasmtime::Result;
34
35pub mod mount;
36
37pub use mount::{PyCommand, PythonMount};
38
39/// The packed-op export name on the python guest (the PERSISTENT interpreter ABI).
40const PY_OP_EXPORT: &str = "py_op";
41
42/// Status tag for "name absent" in a `py_op` reply (`TAG_NONE=2`), matching the
43/// guest. `TAG_OK=0` is the shared engine ABI tag
44/// ([`hyprstream_workers_wasmtime::TAG_OK`]); any other tag (i.e. ERR=1) decodes to
45/// [`PyResult::Err`].
46const TAG_NONE: u8 = 2;
47
48/// Run Python `source` in a FRESH interpreter with the given fuel budget.
49///
50/// Returns the guest `eval` status (0 = ok, nonzero = python error) on normal
51/// completion, or `Err` if the guest TRAPPED (e.g. ran out of fuel, or reached a
52/// trap-wired import). Deterministic; preferred for tests. Built on the generic
53/// [`Sandbox::call_export`](hyprstream_workers_wasmtime::Sandbox::call_export) over
54/// the `"eval"` export.
55pub fn eval(sandbox: &Sandbox, source: &str, fuel: u64) -> Result<i32> {
56 sandbox.call_export("eval", source.as_bytes(), fuel)
57}
58
59/// Run Python `source` (FRESH interpreter) with a WALL-CLOCK epoch deadline of
60/// `ticks` epoch increments.
61///
62/// This is the PRODUCTION DoS bound: paired with an
63/// [`EpochTimer`](hyprstream_workers_wasmtime::EpochTimer) spawned on the sandbox's
64/// engine ticking every `t`, the guest traps with "interrupt" after roughly
65/// `ticks * t` of wall time. The caller owns the timer; this fn does not start one.
66pub fn eval_with_epoch_deadline(sandbox: &Sandbox, source: &str, ticks: u64) -> Result<i32> {
67 sandbox.call_export_with_epoch("eval", source.as_bytes(), ticks)
68}
69
70/// The op codes the guest's `py_op` export understands (must match the guest's
71/// `Op` enum byte-for-byte).
72#[derive(Clone, Copy, Debug)]
73#[repr(i32)]
74enum PyOp {
75 Eval = 0,
76 Exec = 1,
77 ListVars = 2,
78 GetVar = 3,
79 ListDefs = 4,
80 GetDef = 5,
81}
82
83/// The outcome of a `py_op`: a status tag plus the UTF-8 payload.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub enum PyResult {
86 /// Success — the payload (repr / stdout / newline-joined names).
87 Ok(String),
88 /// A Python-level error — the message.
89 Err(String),
90 /// The requested name was absent (get_var / get_def).
91 None,
92}
93
94impl PyResult {
95 /// The success payload, or `None` for Err/None.
96 pub fn ok(&self) -> Option<&str> {
97 match self {
98 PyResult::Ok(s) => Some(s),
99 _ => None,
100 }
101 }
102}
103
104/// A persistent python shell over a single wasm guest instance.
105///
106/// Holds the engine's generic
107/// [`PersistentInstance`](hyprstream_workers_wasmtime::PersistentInstance) so the
108/// guest interpreter's state survives across calls (the `/lang/python/vars/` +
109/// `/defs/` semantics depend on this). Each method drives the guest's `py_op` ABI via
110/// the generic [`PersistentInstance::call_op`] and decodes the `(tag, payload)` reply
111/// into a [`PyResult`].
112///
113/// A `PythonShell` must be driven from a NON-async thread if its sandbox holds a VFS
114/// capability (the `vfs_*` host fns `blocking_send`).
115pub struct PythonShell {
116 instance: PersistentInstance,
117}
118
119impl PythonShell {
120 /// Open a persistent python shell over `sandbox`.
121 ///
122 /// `per_call_fuel` is the fuel budget per `eval`/`exec` (a fresh budget each call;
123 /// the underlying store is reused so the interpreter scope persists).
124 pub fn open(sandbox: &Sandbox, per_call_fuel: u64) -> Result<Self> {
125 Ok(Self {
126 instance: sandbox.open_instance(per_call_fuel)?,
127 })
128 }
129
130 /// Run one op with `arg` as the UTF-8 argument; decode the reply.
131 fn call(&mut self, op: PyOp, arg: &str) -> Result<PyResult> {
132 let (tag, body) = self
133 .instance
134 .call_op(PY_OP_EXPORT, op as i32, arg.as_bytes())?;
135 let body = String::from_utf8_lossy(&body).into_owned();
136 Ok(match tag {
137 TAG_OK => PyResult::Ok(body),
138 TAG_NONE => PyResult::None,
139 _ => PyResult::Err(body),
140 })
141 }
142
143 /// Evaluate an expression -> `repr(result)` (with `\n---\n<stdout>` appended if
144 /// the expression printed anything), mirroring the `/lang/python/eval` file.
145 pub fn eval(&mut self, expr: &str) -> Result<PyResult> {
146 self.call(PyOp::Eval, expr)
147 }
148
149 /// Execute statements -> captured stdout, mirroring the `/lang/python/stdout` file.
150 pub fn exec(&mut self, src: &str) -> Result<PyResult> {
151 self.call(PyOp::Exec, src)
152 }
153
154 /// Newline-joined non-dunder global variable names (`vars/`).
155 pub fn list_vars(&mut self) -> Result<Vec<String>> {
156 Ok(split_names(self.call(PyOp::ListVars, "")?))
157 }
158
159 /// `repr` of one global variable (`vars/<name>`), or `None` if absent.
160 pub fn get_var(&mut self, name: &str) -> Result<PyResult> {
161 self.call(PyOp::GetVar, name)
162 }
163
164 /// Newline-joined callable global names (`defs/`).
165 pub fn list_defs(&mut self) -> Result<Vec<String>> {
166 Ok(split_names(self.call(PyOp::ListDefs, "")?))
167 }
168
169 /// `repr` of one callable global (`defs/<name>`), or `None` if absent/not callable.
170 pub fn get_def(&mut self, name: &str) -> Result<PyResult> {
171 self.call(PyOp::GetDef, name)
172 }
173
174 /// Serve one [`PyCommand`] against this shell (runs on the shell-owning thread).
175 ///
176 /// Mirrors `TclShell::process_command`: the [`PythonMount`] forwards each request
177 /// over the mount channel; the owner drains the channel and calls this.
178 pub fn process_command(&mut self, cmd: PyCommand) {
179 match cmd {
180 PyCommand::Eval { code, resp } => {
181 let _ = resp.send(self.eval(&code).unwrap_or_else(err_result));
182 }
183 PyCommand::Exec { code, resp } => {
184 let _ = resp.send(self.exec(&code).unwrap_or_else(err_result));
185 }
186 PyCommand::ListVars { resp } => {
187 let _ = resp.send(self.list_vars().unwrap_or_default());
188 }
189 PyCommand::GetVar { name, resp } => {
190 let _ = resp.send(self.get_var(&name).unwrap_or_else(err_result));
191 }
192 PyCommand::ListDefs { resp } => {
193 let _ = resp.send(self.list_defs().unwrap_or_default());
194 }
195 PyCommand::GetDef { name, resp } => {
196 let _ = resp.send(self.get_def(&name).unwrap_or_else(err_result));
197 }
198 }
199 }
200}
201
202/// A trapped/host-side error surfaces to the guest as a Python-level error string.
203fn err_result(e: wasmtime::Error) -> PyResult {
204 PyResult::Err(format!("sandbox: {e}"))
205}
206
207/// Split a newline-joined name list reply into a `Vec<String>` (empty if not Ok).
208fn split_names(r: PyResult) -> Vec<String> {
209 match r {
210 PyResult::Ok(s) if !s.is_empty() => s.lines().map(|l| l.to_owned()).collect(),
211 _ => Vec::new(),
212 }
213}