hyprstream_workers_wasmtime/vfs.rs
1//! VFS capability backing for the sandbox (#483 P2 — REAL, not a sketch).
2//!
3//! This is the proof the sandbox capability is real: a guest `vfs_*` call is
4//! bridged, synchronously, to the canonical `hyprstream_vfs` [`Namespace`] through
5//! the [`spawn_vfs_proxy`] seam, and is scoped to the [`Subject`] the `Sandbox` is
6//! bound to — never to any identity the guest supplies.
7//!
8//! ## Wiring
9//!
10//! ```text
11//! guest env::vfs_cat(path) -> VfsOp::Cat { path } -> Namespace::cat
12//! guest env::vfs_ls(path) -> VfsOp::Ls { path } -> Namespace::ls
13//! guest env::vfs_echo(path,data) -> VfsOp::Echo { path, data } -> Namespace::echo
14//! guest env::vfs_ctl(path,cmd) -> VfsOp::Ctl { path, cmd } -> Namespace::ctl
15//! ```
16//!
17//! The host fns (in `build_linker`) read `caller.data().subject` and submit a
18//! [`VfsRequest`] whose `op` carries the Subject IMPLICITLY: the proxy task is
19//! `spawn_vfs_proxy(ns, subject)` — i.e. each proxy is pinned to ONE Subject at
20//! spawn time, so every request through it is executed as that Subject. The guest
21//! has no way to name or forge an identity.
22//!
23//! ## Why path-based ops, not the P1 fid-based sketch
24//!
25//! The P1 `vfs.rs` sketched a fid-based `VfsCapability` (walk/open/read/write/…),
26//! mirroring [`hyprstream_vfs::Mount`]. The CANONICAL sync seam, however, is the
27//! proxy's [`VfsOp`] enum, which is PATH-based (`Cat`/`Ls`/`Echo`/`Ctl`) and
28//! DELIBERATELY excludes `mount`/`bind`/`unmount` (its security invariant: scripts
29//! cannot remount). We back the capability against that real seam rather than the
30//! sketch, so the #483 capability is exactly the proxy's bounded surface.
31//!
32//! ## Sync-over-async bridge
33//!
34//! wasm host fns are synchronous; the `Namespace` is async. The proxy
35//! ([`spawn_vfs_proxy`]) bridges: it returns a `tokio::sync::mpsc::Sender<VfsRequest>`
36//! and each [`VfsRequest`] carries a `std::sync::mpsc::SyncSender` reply channel. A
37//! host fn does `blocking_send` of the request, then blocks on the std reply
38//! receiver — never touching the async runtime directly. (`blocking_send` requires
39//! we are NOT on a tokio worker thread; the `Sandbox` is driven from a plain thread,
40//! and the proxy task runs on a separate runtime — see the tests.)
41
42use hyprstream_rpc::Subject;
43use hyprstream_vfs::proxy::{VfsOp, VfsRequest};
44use tokio::sync::mpsc::Sender as TokioSender;
45
46/// A handle to a Subject-scoped VFS proxy.
47///
48/// Created by [`spawn_vfs_proxy`] (one per Subject) and stored in
49/// [`crate::SandboxState`]. The host `vfs_*` fns submit ops over it and block on
50/// the reply. The Subject is implicit in the proxy itself, so this handle does NOT
51/// re-pass a Subject per call — which is exactly the property we want: the guest
52/// cannot change identity.
53#[derive(Clone)]
54pub struct VfsProxyHandle {
55 tx: TokioSender<VfsRequest>,
56 /// The Subject this proxy is pinned to (kept for auditing / introspection only;
57 /// it is NOT sent per-request — the proxy already runs as this Subject).
58 subject: Subject,
59}
60
61/// Result of a VFS op exposed to the guest: a status tag + a UTF-8 payload.
62///
63/// `ok == true` -> payload is the result bytes; `ok == false` -> payload is the
64/// error string. This is the shape the host fns serialise into the guest reply
65/// buffer (status byte + payload).
66pub struct VfsReply {
67 pub ok: bool,
68 pub body: Vec<u8>,
69}
70
71impl VfsProxyHandle {
72 /// Wrap a proxy `Sender` pinned to `subject`.
73 pub fn new(tx: TokioSender<VfsRequest>, subject: Subject) -> Self {
74 Self { tx, subject }
75 }
76
77 /// The Subject every op through this handle runs as.
78 pub fn subject(&self) -> &Subject {
79 &self.subject
80 }
81
82 /// Submit one op and block on the reply (sync-over-async bridge).
83 ///
84 /// Returns `Err(String)` only for transport failures (proxy gone / no reply);
85 /// VFS-level errors come back as `VfsReply { ok: false, .. }`.
86 fn submit(&self, op: VfsOp) -> VfsReply {
87 // std::sync::mpsc rendezvous channel for the reply (the proxy's reply type).
88 let (reply_tx, reply_rx) = std::sync::mpsc::sync_channel(1);
89 let req = VfsRequest {
90 op,
91 reply: reply_tx,
92 };
93 // `blocking_send`: the host fn is on a non-async thread; this parks until
94 // the proxy task accepts the request. If the proxy is gone, surface it as
95 // a VFS error rather than panicking the guest call.
96 if self.tx.blocking_send(req).is_err() {
97 return VfsReply {
98 ok: false,
99 body: b"vfs: proxy unavailable".to_vec(),
100 };
101 }
102 match reply_rx.recv() {
103 Ok(Ok(bytes)) => VfsReply {
104 ok: true,
105 body: bytes,
106 },
107 Ok(Err(msg)) => VfsReply {
108 ok: false,
109 body: msg.into_bytes(),
110 },
111 Err(_) => VfsReply {
112 ok: false,
113 body: b"vfs: proxy did not respond".to_vec(),
114 },
115 }
116 }
117
118 /// `cat` — read the whole contents of a file path.
119 pub fn cat(&self, path: &str) -> VfsReply {
120 self.submit(VfsOp::Cat {
121 path: path.to_owned(),
122 })
123 }
124
125 /// `ls` — list a directory path (newline-joined names, `name/` for dirs).
126 pub fn ls(&self, path: &str) -> VfsReply {
127 self.submit(VfsOp::Ls {
128 path: path.to_owned(),
129 })
130 }
131
132 /// `echo` — write `data` to a file path. Reply body is empty on success.
133 pub fn echo(&self, path: &str, data: &[u8]) -> VfsReply {
134 self.submit(VfsOp::Echo {
135 path: path.to_owned(),
136 data: data.to_vec(),
137 })
138 }
139
140 /// `ctl` — write `cmd` to a ctl file path and read the response.
141 pub fn ctl(&self, path: &str, cmd: &[u8]) -> VfsReply {
142 self.submit(VfsOp::Ctl {
143 path: path.to_owned(),
144 cmd: cmd.to_vec(),
145 })
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use hyprstream_vfs::proxy::spawn_vfs_proxy;
153 use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Namespace, Stat};
154 use std::collections::HashMap;
155 use std::sync::Arc;
156
157 /// In-memory `Mount` for the seam test: a flat file map under one prefix.
158 /// Walk records the requested path; read returns the file (or the write buffer);
159 /// write stores into the per-fid buffer. A `denied` Subject is refused at every
160 /// op so we can prove Subject-scoping reaches the backend.
161 struct MemMount {
162 files: parking_lot::Mutex<HashMap<String, Vec<u8>>>,
163 }
164
165 struct MemFid {
166 path: String,
167 write_buf: parking_lot::Mutex<Vec<u8>>,
168 }
169
170 impl MemMount {
171 fn new(files: Vec<(&str, &[u8])>) -> Self {
172 Self {
173 files: parking_lot::Mutex::new(
174 files
175 .into_iter()
176 .map(|(k, v)| (k.to_owned(), v.to_vec()))
177 .collect(),
178 ),
179 }
180 }
181
182 fn check(caller: &Subject) -> Result<(), MountError> {
183 if caller.name() == Some("denied") {
184 return Err(MountError::PermissionDenied("denied subject".into()));
185 }
186 Ok(())
187 }
188 }
189
190 #[async_trait::async_trait]
191 impl Mount for MemMount {
192 async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError> {
193 Self::check(caller)?;
194 Ok(Fid::new(MemFid {
195 path: components.join("/"),
196 write_buf: parking_lot::Mutex::new(Vec::new()),
197 }))
198 }
199 async fn open(
200 &self,
201 _fid: &mut Fid,
202 _mode: u8,
203 caller: &Subject,
204 ) -> Result<(), MountError> {
205 Self::check(caller)
206 }
207 async fn read(
208 &self,
209 fid: &Fid,
210 offset: u64,
211 _count: u32,
212 caller: &Subject,
213 ) -> Result<Vec<u8>, MountError> {
214 Self::check(caller)?;
215 let inner = fid
216 .downcast_ref::<MemFid>()
217 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
218 let data = self
219 .files
220 .lock()
221 .get(&inner.path)
222 .cloned()
223 .ok_or_else(|| MountError::NotFound(inner.path.clone()))?;
224 let start = (offset as usize).min(data.len());
225 Ok(data[start..].to_vec())
226 }
227 async fn write(
228 &self,
229 fid: &Fid,
230 _offset: u64,
231 data: &[u8],
232 caller: &Subject,
233 ) -> Result<u32, MountError> {
234 Self::check(caller)?;
235 let inner = fid
236 .downcast_ref::<MemFid>()
237 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
238 inner.write_buf.lock().extend_from_slice(data);
239 // Persist so a later cat() sees it.
240 self.files
241 .lock()
242 .insert(inner.path.clone(), inner.write_buf.lock().clone());
243 Ok(data.len() as u32)
244 }
245 async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
246 Self::check(caller)?;
247 let inner = fid
248 .downcast_ref::<MemFid>()
249 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
250 let prefix = if inner.path.is_empty() {
251 String::new()
252 } else {
253 format!("{}/", inner.path)
254 };
255 let mut entries = Vec::new();
256 for key in self.files.lock().keys() {
257 if let Some(rest) = key.strip_prefix(&prefix) {
258 if !rest.contains('/') {
259 entries.push(DirEntry {
260 name: rest.to_owned(),
261 is_dir: false,
262 size: 0,
263 stat: None,
264 });
265 }
266 }
267 }
268 Ok(entries)
269 }
270 async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError> {
271 Self::check(caller)?;
272 let inner = fid
273 .downcast_ref::<MemFid>()
274 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
275 Ok(Stat {
276 qtype: 0,
277 version: 0,
278 path: 0,
279 size: 0,
280 name: inner.path.clone(),
281 mtime: 0,
282 })
283 }
284 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
285 }
286
287 fn make_ns() -> Arc<Namespace> {
288 let mut ns = Namespace::new();
289 ns.mount(
290 "/config",
291 Arc::new(MemMount::new(vec![("temperature", b"0.7")])),
292 )
293 .unwrap();
294 Arc::new(ns)
295 }
296
297 /// An allowed Subject can cat/echo through the proxy-backed handle, and a
298 /// `denied` Subject is refused at the Mount — proving the Subject reaches the
299 /// backend. The proxy runs on its own tokio runtime; the handle is driven from
300 /// a plain (non-async) thread, exactly like the wasm host fns.
301 #[test]
302 fn proxy_handle_is_subject_scoped() {
303 // Dedicated runtime thread to host the proxy tasks.
304 let rt = tokio::runtime::Builder::new_multi_thread()
305 .worker_threads(1)
306 .enable_all()
307 .build()
308 .unwrap();
309 let ns = make_ns();
310
311 let alice = Subject::new("alice");
312 let denied = Subject::new("denied");
313
314 // spawn_vfs_proxy MUST run inside a runtime context.
315 let alice_tx = rt.block_on(async { spawn_vfs_proxy(Arc::clone(&ns), alice.clone()) });
316 let denied_tx = rt.block_on(async { spawn_vfs_proxy(Arc::clone(&ns), denied.clone()) });
317
318 let alice_h = VfsProxyHandle::new(alice_tx, alice);
319 let denied_h = VfsProxyHandle::new(denied_tx, denied);
320
321 // Drive the handles from a plain thread (blocking_send forbidden on a
322 // tokio worker; this mirrors the Sandbox's non-async driving thread).
323 let result = std::thread::spawn(move || {
324 // Allowed subject reads an existing file.
325 let r = alice_h.cat("/config/temperature");
326 assert!(r.ok, "alice cat should succeed");
327 assert_eq!(r.body, b"0.7");
328
329 // Allowed subject writes, then reads back (echo persists in the mount).
330 let w = alice_h.echo("/config/temperature", b"0.9");
331 assert!(w.ok, "alice echo should succeed");
332 let r2 = alice_h.cat("/config/temperature");
333 assert!(r2.ok);
334 assert_eq!(r2.body, b"0.9");
335
336 // Denied subject is refused at the backend (Subject reached the Mount).
337 let d = denied_h.cat("/config/temperature");
338 assert!(!d.ok, "denied subject must be refused");
339 assert!(
340 String::from_utf8_lossy(&d.body).contains("permission denied"),
341 "got: {}",
342 String::from_utf8_lossy(&d.body)
343 );
344 })
345 .join();
346 assert!(result.is_ok());
347 }
348}