Skip to main content

hyprstream_workers_wasmtime/
wasi_fs.rs

1//! Profile B (#506): preview1 `WasiDir`/`WasiFile` backed by a Subject-scoped
2//! `hyprstream_vfs::Mount`.
3//!
4//! This runs a WASI guest whose ENTIRE filesystem is a virtual VFS [`Mount`] (not the
5//! host). It backs a WASI preopen with an arbitrary async `Mount` via the legacy
6//! **preview1** [`wasi_common::WasiDir`] / [`wasi_common::WasiFile`] trait objects,
7//! NOT preview2's `wasmtime-wasi` (whose preopen only takes a concrete
8//! `cap_std::fs::Dir`). See the crate README for the preview1-vs-preview2 rationale.
9//!
10//! ## The ONE policy enforcement point (MAC invariant)
11//!
12//! The [`MountDir`]/[`MountFile`] adapters do **NOT** authorize. They thread the
13//! `Sandbox`-bound [`Subject`] into every `Mount` call and nothing more. The
14//! [`Mount`] is the single PEP (a future S2/#568 label check lands THERE). There
15//! is deliberately NO parallel capability/permission check in this layer — adding
16//! one would create a second, divergent policy surface. The Subject is fixed at
17//! construction (`MountDir { mount, subject, .. }`); the guest can neither name nor
18//! forge an identity, exactly mirroring the Profile-A proxy seam.
19//!
20//! ## Async/sync bridge
21//!
22//! `wasi-common`'s `WasiDir`/`WasiFile` are **async traits**, but we link them via
23//! `wasi_common::sync::add_to_linker` whose wiggle integration uses the `block_on`
24//! executor: it expects every async fn to poll to `Ready` essentially immediately
25//! (no real async suspension). The [`Mount`] is genuinely async, so each adapter
26//! method drives the Mount future to completion on a dedicated current-thread
27//! tokio [`Runtime`] via `rt.block_on(...)`. The `WasiSandbox` is driven from a
28//! plain (non-async) thread (like Profile A), so this nested `block_on` is NOT on a
29//! tokio worker and does not panic. From the wiggle executor's view the adapter
30//! future resolves immediately — the contract holds.
31//!
32//! ## Path model
33//!
34//! `Mount` is fid-based (`walk` -> open -> read/write). WASI is path-based relative
35//! to a preopen dir. [`MountDir`] holds a base path (the preopen root, e.g. the
36//! Mount root) and, per `open_file`/`get_path_filestat`, splits the guest-supplied
37//! relative path into components, `walk`s the Mount, then opens/reads/writes. We
38//! reject `..` components (no upward traversal past the preopen) — the WASI ABI
39//! also forbids it, but we enforce it here too as defense in depth (this is a path
40//! shape check, NOT an authz check; authz stays in the Mount).
41
42use std::any::Any;
43use std::sync::Arc;
44
45use hyprstream_vfs::{Mount, MountError, Subject};
46use wasi_common::dir::{OpenResult, ReaddirCursor, ReaddirEntity, WasiDir};
47use wasi_common::file::{FdFlags, FileType, Filestat, OFlags, WasiFile};
48use wasi_common::{Error as WasiError, ErrorExt};
49
50use tokio::runtime::Runtime;
51
52/// Map a [`MountError`] to a preview1 `wasi_common::Error` (errno-tagged).
53fn map_err(e: MountError) -> WasiError {
54    match e {
55        MountError::NotFound(_) => WasiError::not_found(),
56        MountError::PermissionDenied(_) => WasiError::perm(),
57        MountError::NotDirectory(_) => WasiError::not_dir(),
58        MountError::IsDirectory(_) => WasiError::badf().context("is a directory"),
59        MountError::InvalidArgument(_) => WasiError::invalid_argument(),
60        MountError::NotSupported(_) => WasiError::not_supported(),
61        MountError::AlreadyExists(_) => WasiError::exist(),
62        MountError::Io(_) => WasiError::io(),
63    }
64}
65
66/// Split a WASI-relative path (`a/b/c`, possibly with a leading/trailing slash) into
67/// Mount path components, joined onto `base`. Rejects `..` (no upward traversal past
68/// the preopen). Empty components and `.` are dropped, so a leading `/` is treated as
69/// relative-to-`base` rather than rejected — there is no escape because every
70/// component still lands under `base`, and the Mount remains the policy point. This is
71/// a defense-in-depth path-shape check, NOT an authz check.
72fn resolve(base: &[String], path: &str) -> Result<Vec<String>, WasiError> {
73    let mut out = base.to_vec();
74    for comp in path.split('/') {
75        match comp {
76            "" | "." => {}
77            ".." => return Err(WasiError::not_supported().context("`..` traversal denied")),
78            other => out.push(other.to_owned()),
79        }
80    }
81    Ok(out)
82}
83
84/// A WASI preopen directory backed by a Subject-scoped [`Mount`].
85///
86/// The Subject is FIXED at construction and threaded into every Mount call — the
87/// single MAC threading point, no parallel check.
88pub struct MountDir {
89    mount: Arc<dyn Mount>,
90    subject: Subject,
91    /// Mount path components this dir is rooted at (the preopen root = `[]`).
92    base: Vec<String>,
93    /// Shared current-thread runtime to drive the async Mount synchronously.
94    rt: Arc<Runtime>,
95}
96
97impl MountDir {
98    /// Create a preopen `WasiDir` over `mount`, rooted at the Mount root, running
99    /// as `subject`. `rt` is the dedicated runtime used to `block_on` Mount futures.
100    pub fn new(mount: Arc<dyn Mount>, subject: Subject, rt: Arc<Runtime>) -> Self {
101        Self {
102            mount,
103            subject,
104            base: Vec::new(),
105            rt,
106        }
107    }
108
109    fn child(&self, components: Vec<String>) -> Self {
110        Self {
111            mount: Arc::clone(&self.mount),
112            subject: self.subject.clone(),
113            base: components,
114            rt: Arc::clone(&self.rt),
115        }
116    }
117}
118
119#[async_trait::async_trait]
120impl WasiDir for MountDir {
121    fn as_any(&self) -> &dyn Any {
122        self
123    }
124
125    async fn open_file(
126        &self,
127        _symlink_follow: bool,
128        path: &str,
129        oflags: OFlags,
130        read: bool,
131        write: bool,
132        _fdflags: FdFlags,
133    ) -> Result<OpenResult, WasiError> {
134        let components = resolve(&self.base, path)?;
135        let comp_refs: Vec<&str> = components.iter().map(String::as_str).collect();
136
137        // Walk + stat to classify file vs directory. The Subject threads through
138        // EVERY call — the Mount is the policy point. A `NotFound` is NOT fatal: it
139        // means "no such entry yet", which `path_open` with O_CREAT turns into a new
140        // regular file. We map only PermissionDenied (and other hard errors) to a
141        // failure here — that is the Mount enforcing policy, which must surface.
142        let classified = self.rt.block_on(async {
143            let fid = self.mount.walk(&comp_refs, &self.subject).await?;
144            let st = self.mount.stat(&fid, &self.subject).await;
145            self.mount.clunk(fid, &self.subject).await;
146            st
147        });
148        let (exists, is_dir, size) = match classified {
149            Ok(st) => (true, st.qtype & 0x80 != 0, st.size),
150            // Absent entry: treat as a to-be-created regular file (path_open O_CREAT).
151            Err(MountError::NotFound(_)) => (false, false, 0),
152            // Policy denial / other hard error: surface it (Mount is the PEP).
153            Err(e) => return Err(map_err(e)),
154        };
155
156        if is_dir {
157            // Opening a directory yields a dirfd (a child WasiDir scoped deeper).
158            return Ok(OpenResult::Dir(Box::new(self.child(components))));
159        }
160
161        if oflags.contains(OFlags::DIRECTORY) {
162            return Err(WasiError::not_dir());
163        }
164        if exists && oflags.contains(OFlags::EXCLUSIVE) {
165            return Err(WasiError::exist());
166        }
167        if !exists && !oflags.contains(OFlags::CREATE) && !write {
168            // Read of a non-existent file with no O_CREAT.
169            return Err(WasiError::not_found());
170        }
171
172        // Open the file fid through the Mount (Subject-scoped). Truncation is
173        // applied via OTRUNC on the Mount open mode when requested.
174        let mode = match (read, write) {
175            (true, true) => hyprstream_vfs::ORDWR,
176            (false, true) => hyprstream_vfs::OWRITE,
177            _ => hyprstream_vfs::OREAD,
178        } | if oflags.contains(OFlags::TRUNCATE) {
179            hyprstream_vfs::OTRUNC
180        } else {
181            0
182        };
183
184        let fid = self
185            .rt
186            .block_on(async {
187                let mut fid = self.mount.walk(&comp_refs, &self.subject).await?;
188                self.mount.open(&mut fid, mode, &self.subject).await?;
189                Ok::<_, MountError>(fid)
190            })
191            .map_err(map_err)?;
192
193        Ok(OpenResult::File(Box::new(MountFile {
194            mount: Arc::clone(&self.mount),
195            subject: self.subject.clone(),
196            fid: Arc::new(parking_lot::Mutex::new(Some(fid))),
197            rt: Arc::clone(&self.rt),
198            initial_size: size,
199            pos: parking_lot::Mutex::new(0),
200        })))
201    }
202
203    async fn readdir(
204        &self,
205        cursor: ReaddirCursor,
206    ) -> Result<Box<dyn Iterator<Item = Result<ReaddirEntity, WasiError>> + Send>, WasiError> {
207        let comp_refs: Vec<&str> = self.base.iter().map(String::as_str).collect();
208        let entries = self
209            .rt
210            .block_on(async {
211                let fid = self.mount.walk(&comp_refs, &self.subject).await?;
212                let e = self.mount.readdir(&fid, &self.subject).await?;
213                self.mount.clunk(fid, &self.subject).await;
214                Ok::<_, MountError>(e)
215            })
216            .map_err(map_err)?;
217
218        // Build absolute entries (`.` and `..` are conventionally elided here; the
219        // wiggle layer synthesizes them as needed). Honor the cursor for resumption.
220        let start: u64 = cursor.into();
221        let mut out: Vec<Result<ReaddirEntity, WasiError>> = Vec::new();
222        for (i, de) in entries.into_iter().enumerate() {
223            let next = (i as u64) + 1;
224            if next <= start {
225                continue;
226            }
227            out.push(Ok(ReaddirEntity {
228                next: ReaddirCursor::from(next),
229                inode: 0,
230                name: de.name,
231                filetype: if de.is_dir {
232                    FileType::Directory
233                } else {
234                    FileType::RegularFile
235                },
236            }));
237        }
238        Ok(Box::new(out.into_iter()))
239    }
240
241    async fn get_filestat(&self) -> Result<Filestat, WasiError> {
242        let comp_refs: Vec<&str> = self.base.iter().map(String::as_str).collect();
243        let st = self
244            .rt
245            .block_on(async {
246                let fid = self.mount.walk(&comp_refs, &self.subject).await?;
247                let s = self.mount.stat(&fid, &self.subject).await?;
248                self.mount.clunk(fid, &self.subject).await;
249                Ok::<_, MountError>(s)
250            })
251            .map_err(map_err)?;
252        Ok(Filestat {
253            device_id: 0,
254            inode: 0,
255            filetype: FileType::Directory,
256            nlink: 1,
257            size: st.size,
258            atim: None,
259            mtim: None,
260            ctim: None,
261        })
262    }
263
264    async fn get_path_filestat(
265        &self,
266        path: &str,
267        _follow_symlinks: bool,
268    ) -> Result<Filestat, WasiError> {
269        let components = resolve(&self.base, path)?;
270        let comp_refs: Vec<&str> = components.iter().map(String::as_str).collect();
271        let st = self
272            .rt
273            .block_on(async {
274                let fid = self.mount.walk(&comp_refs, &self.subject).await?;
275                let s = self.mount.stat(&fid, &self.subject).await?;
276                self.mount.clunk(fid, &self.subject).await;
277                Ok::<_, MountError>(s)
278            })
279            .map_err(map_err)?;
280        let is_dir = st.qtype & 0x80 != 0;
281        Ok(Filestat {
282            device_id: 0,
283            inode: 0,
284            filetype: if is_dir {
285                FileType::Directory
286            } else {
287                FileType::RegularFile
288            },
289            nlink: 1,
290            size: st.size,
291            atim: None,
292            mtim: None,
293            ctim: None,
294        })
295    }
296
297    // create_dir / unlink_file / rename / symlink / hard_link / read_link /
298    // set_times all default to `Err(not_supported)` from the trait. The base Mount
299    // surface (walk/open/read/write/readdir/stat) is what we expose; mutation of
300    // the namespace shape is deliberately out of the Profile-B fs surface (mirrors
301    // the proxy seam excluding mount/bind/unmount). A future revision can route
302    // create/unlink through `Mount::as_fsmount()` if a guest needs them.
303}
304
305/// A WASI file backed by an open [`Mount`] fid, Subject-scoped.
306pub struct MountFile {
307    mount: Arc<dyn Mount>,
308    subject: Subject,
309    /// The open Mount fid. `Option` so `Drop` can `clunk` it exactly once.
310    fid: Arc<parking_lot::Mutex<Option<hyprstream_vfs::Fid>>>,
311    rt: Arc<Runtime>,
312    initial_size: u64,
313    /// Sequential cursor for the non-`_at` `fd_read`/`fd_write`/`fd_seek` ABI (std
314    /// `File::read`/`write` use these, not the positional `pread`/`pwrite`).
315    pos: parking_lot::Mutex<u64>,
316}
317
318#[async_trait::async_trait]
319impl WasiFile for MountFile {
320    fn as_any(&self) -> &dyn Any {
321        self
322    }
323
324    async fn get_filetype(&self) -> Result<FileType, WasiError> {
325        Ok(FileType::RegularFile)
326    }
327
328    async fn get_filestat(&self) -> Result<Filestat, WasiError> {
329        let guard = self.fid.lock();
330        let fid = guard
331            .as_ref()
332            .ok_or_else(|| WasiError::badf().context("file closed"))?;
333        let st = self
334            .rt
335            .block_on(self.mount.stat(fid, &self.subject))
336            .map_err(map_err)?;
337        Ok(Filestat {
338            device_id: 0,
339            inode: 0,
340            filetype: FileType::RegularFile,
341            nlink: 1,
342            size: st.size,
343            atim: None,
344            mtim: None,
345            ctim: None,
346        })
347    }
348
349    async fn read_vectored_at<'a>(
350        &self,
351        bufs: &mut [std::io::IoSliceMut<'a>],
352        offset: u64,
353    ) -> Result<u64, WasiError> {
354        let total: usize = bufs.iter().map(|b| b.len()).sum();
355        if total == 0 {
356            return Ok(0);
357        }
358        let data = {
359            let guard = self.fid.lock();
360            let fid = guard
361                .as_ref()
362                .ok_or_else(|| WasiError::badf().context("file closed"))?;
363            self.rt
364                .block_on(self.mount.read(fid, offset, total as u32, &self.subject))
365                .map_err(map_err)?
366        };
367        // Scatter the contiguous Mount read across the guest iovecs.
368        let mut copied = 0usize;
369        for buf in bufs.iter_mut() {
370            if copied >= data.len() {
371                break;
372            }
373            let n = buf.len().min(data.len() - copied);
374            buf[..n].copy_from_slice(&data[copied..copied + n]);
375            copied += n;
376        }
377        Ok(copied as u64)
378    }
379
380    async fn write_vectored_at<'a>(
381        &self,
382        bufs: &[std::io::IoSlice<'a>],
383        offset: u64,
384    ) -> Result<u64, WasiError> {
385        // Gather the guest iovecs into one contiguous buffer for the Mount write.
386        let mut data = Vec::new();
387        for b in bufs {
388            data.extend_from_slice(b);
389        }
390        if data.is_empty() {
391            return Ok(0);
392        }
393        let n = {
394            let guard = self.fid.lock();
395            let fid = guard
396                .as_ref()
397                .ok_or_else(|| WasiError::badf().context("file closed"))?;
398            self.rt
399                .block_on(self.mount.write(fid, offset, &data, &self.subject))
400                .map_err(map_err)?
401        };
402        Ok(n as u64)
403    }
404
405    async fn read_vectored<'a>(
406        &self,
407        bufs: &mut [std::io::IoSliceMut<'a>],
408    ) -> Result<u64, WasiError> {
409        // Sequential read: read at the cursor, then advance it.
410        let offset = *self.pos.lock();
411        let n = self.read_vectored_at(bufs, offset).await?;
412        *self.pos.lock() = offset + n;
413        Ok(n)
414    }
415
416    async fn write_vectored<'a>(&self, bufs: &[std::io::IoSlice<'a>]) -> Result<u64, WasiError> {
417        // Sequential write: write at the cursor, then advance it.
418        let offset = *self.pos.lock();
419        let n = self.write_vectored_at(bufs, offset).await?;
420        *self.pos.lock() = offset + n;
421        Ok(n)
422    }
423
424    async fn seek(&self, pos: std::io::SeekFrom) -> Result<u64, WasiError> {
425        use std::io::SeekFrom;
426        let new = match pos {
427            SeekFrom::Start(o) => o,
428            SeekFrom::Current(d) => {
429                let cur = *self.pos.lock() as i64;
430                (cur + d).max(0) as u64
431            }
432            SeekFrom::End(d) => {
433                // Resolve the end from the current Mount size.
434                let size = {
435                    let guard = self.fid.lock();
436                    let fid = guard
437                        .as_ref()
438                        .ok_or_else(|| WasiError::badf().context("file closed"))?;
439                    self.rt
440                        .block_on(self.mount.stat(fid, &self.subject))
441                        .map_err(map_err)?
442                        .size
443                };
444                ((size as i64) + d).max(0) as u64
445            }
446        };
447        *self.pos.lock() = new;
448        Ok(new)
449    }
450
451    async fn get_fdflags(&self) -> Result<FdFlags, WasiError> {
452        Ok(FdFlags::empty())
453    }
454
455    fn num_ready_bytes(&self) -> Result<u64, WasiError> {
456        Ok(self.initial_size)
457    }
458}
459
460impl Drop for MountFile {
461    fn drop(&mut self) {
462        // Clunk the fid through the Mount as the bound Subject, exactly once.
463        if let Some(fid) = self.fid.lock().take() {
464            self.rt.block_on(self.mount.clunk(fid, &self.subject));
465        }
466    }
467}