A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
wasmtime-wasi: replace FilePerms, DirPerms with single bit FsPerms (#14010)
Pat Hickey82f50a8b7d89
diff --git a/benches/wasi.rs b/benches/wasi.rsindex 5f7bd1434e..02467f3cb8 100644--- a/benches/wasi.rs+++ b/benches/wasi.rs@@ -3,7 +3,7 @@use criterion::{Criterion, criterion_group, criterion_main};use std::{fs::File, path::Path, time::Instant};use wasmtime::{Engine, Linker, Module, Store, TypedFunc};-use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, p1::WasiP1Ctx};+use wasmtime_wasi::{FsPerms, WasiCtx, p1::WasiP1Ctx};criterion_group!(benches, bench_wasi);criterion_main!(benches);@@ -74,7 +74,7 @@ fn wasi_context() -> WasiP1Ctx {"--flag3".to_string(),"--flag4".to_string(),])- .preopened_dir("benches/wasi", "/", DirPerms::READ, FilePerms::READ)+ .preopened_dir("benches/wasi", "/", FsPerms::ReadOnly).unwrap().build_p1()}diff --git a/crates/bench-api/src/lib.rs b/crates/bench-api/src/lib.rsindex 02482006af..2d3ee208b5 100644--- a/crates/bench-api/src/lib.rs+++ b/crates/bench-api/src/lib.rs@@ -145,7 +145,7 @@ use wasmtime::{};use wasmtime_cli_flags::CommonOptions;use wasmtime_wasi::cli::{InputFile, OutputFile};-use wasmtime_wasi::{DirPerms, FilePerms, I32Exit, WasiCtx, WasiCtxView, WasiView, p1::WasiP1Ctx};+use wasmtime_wasi::{FsPerms, I32Exit, WasiCtx, WasiCtxView, WasiView, p1::WasiP1Ctx};pub type ExitCode = c_int;pub const OK: ExitCode = 0;@@ -310,7 +310,7 @@ pub extern "C" fn wasm_bench_create(// Allow access to the working directory so that the benchmark can read// its input workload(s).- cx.preopened_dir(working_dir.clone(), ".", DirPerms::READ, FilePerms::READ)?;+ cx.preopened_dir(working_dir.clone(), ".", FsPerms::ReadOnly)?;// Pass this env var along so that the benchmark program can use smaller// input workload(s) if it has them and that has been requested.diff --git a/crates/c-api/include/wasi.h b/crates/c-api/include/wasi.hindex 2e87d90743..e770d38dbc 100644--- a/crates/c-api/include/wasi.h+++ b/crates/c-api/include/wasi.h@@ -210,43 +210,6 @@ WASI_API_EXTERN void wasi_config_set_stderr_custom(ptrdiff_t (*callback)(void *, const unsigned char *, size_t), void *data,void (*finalizer)(void *));-/**- * \brief The permissions granted for a directory when preopening it.- */-enum wasi_dir_perms_flags {- /**- * \brief This directory can be read, for example its entries can be iterated- */- WASMTIME_WASI_DIR_PERMS_READ = 1,-- /**- * \brief This directory can be written to, for example new files can be- * created within it.- */- WASMTIME_WASI_DIR_PERMS_WRITE = 2,-};--/**- * \brief The permissions granted for directories when preopening them,- * which is a bitmask with flag values from wasi_dir_perms_flags.- */-typedef size_t wasi_dir_perms;--/**- * \brief The permissions granted for files when preopening a directory.- */-enum wasi_file_perms_flags {- /**- * \brief Files can be read.- */- WASMTIME_WASI_FILE_PERMS_READ = 1,-- /**- * \brief Files can be written to.- */- WASMTIME_WASI_FILE_PERMS_WRITE = 2,-};-/*** \brief The max permissions granted a file within a preopened directory,* which is a bitmask with flag values from wasi_file_perms_flags.@@ -264,23 +227,15 @@ typedef size_t wasi_file_perms;* The `host_path` argument here is a path name on the host filesystem, and* `guest_path` is the name by which it will be known in wasm.*- * The `dir_perms` argument is the permissions that wasm will have to operate on- * `guest_path`. This can be used, for example, to provide readonly access to a- * directory. This argument is a bitmask with the following flag values:- * - WASMTIME_WASI_DIR_PERMS_READ- * - WASMTIME_WASI_DIR_PERMS_WRITE- *- * The `file_perms` argument is similar to `dir_perms` but corresponds to the- * maximum set of permissions that can be used for any file in this directory.- * This argument is a bitmask with the following flag values:- * - WASMTIME_WASI_FILE_PERMS_READ- * - WASMTIME_WASI_FILE_PERMS_WRITE+ * The `fs_mutable` argument is the permissions that wasm will have to operate+ * on `guest_path`. If true, operations that mutate the filesystem will be+ * permitted under that path. If false, only read operations will be permitted+ * on under that path.*/WASI_API_EXTERN bool wasi_config_preopen_dir(wasi_config_t *config,const char *host_path,const char *guest_path,- wasi_dir_perms dir_perms,- wasi_file_perms file_perms);+ bool fs_mutable);#undef owndiff --git a/crates/c-api/include/wasmtime/wasi.hh b/crates/c-api/include/wasmtime/wasi.hhindex 034554e3c1..7e1978381c 100644--- a/crates/c-api/include/wasmtime/wasi.hh+++ b/crates/c-api/include/wasmtime/wasi.hh@@ -91,9 +91,9 @@ class WasiConfig {/// Opens `path` to be opened as `guest_path` in the WASI pseudo-filesystem.[[nodiscard]] bool preopen_dir(const std::string &path,const std::string &guest_path,- size_t dir_perms, size_t file_perms) {+ bool fs_mutable) {return wasi_config_preopen_dir(ptr.get(), path.c_str(), guest_path.c_str(),- dir_perms, file_perms);+ fs_mutable);}/// Allows all network addresses accessible to the host.diff --git a/crates/c-api/src/wasi.rs b/crates/c-api/src/wasi.rsindex e5045ff581..abada403d2 100644--- a/crates/c-api/src/wasi.rs+++ b/crates/c-api/src/wasi.rs@@ -313,8 +313,7 @@ pub unsafe extern "C" fn wasi_config_preopen_dir(config: &mut wasi_config_t,path: *const c_char,guest_path: *const c_char,- dir_perms: usize,- file_perms: usize,+ fs_mutable: bool,) -> bool {let guest_path = match cstr_to_str(guest_path) {Some(p) => p,@@ -326,18 +325,14 @@ pub unsafe extern "C" fn wasi_config_preopen_dir(None => return false,};- let dir_perms = match wasmtime_wasi::DirPerms::from_bits(dir_perms) {- Some(p) => p,- None => return false,- };-- let file_perms = match wasmtime_wasi::FilePerms::from_bits(file_perms) {- Some(p) => p,- None => return false,+ let fs_perms = if fs_mutable {+ wasmtime_wasi::FsPerms::ReadWrite+ } else {+ wasmtime_wasi::FsPerms::ReadOnly};config.builder- .preopened_dir(host_path, guest_path, dir_perms, file_perms)+ .preopened_dir(host_path, guest_path, fs_perms).is_ok()}diff --git a/crates/c-api/tests/wasi.cc b/crates/c-api/tests/wasi.ccindex a4a346cda5..89264aab22 100644--- a/crates/c-api/tests/wasi.cc+++ b/crates/c-api/tests/wasi.cc@@ -19,7 +19,7 @@ TEST(WasiConfig, Smoke) {config.inherit_stderr();WasiConfig config2;- if (config2.preopen_dir("nonexistent", "nonexistent", 0, 0)) {+ if (config2.preopen_dir("nonexistent", "nonexistent", 0)) {Engine engine;Store store(engine);EXPECT_FALSE(store.context().set_wasi(std::move(config2)));diff --git a/crates/test-programs/src/bin/p1_file_rename_across_perms.rs b/crates/test-programs/src/bin/p1_file_rename_across_perms.rsindex d8b931c6b9..30531eefb0 100644--- a/crates/test-programs/src/bin/p1_file_rename_across_perms.rs+++ b/crates/test-programs/src/bin/p1_file_rename_across_perms.rs@@ -4,7 +4,6 @@ use std::env;use std::process;use test_programs::preview1::open_scratch_directory;-const RW_ALIAS_FILENAME: &str = "alias.txt";const RO_TEST_FILENAME: &str = "test.txt";const RO_EXPECTED_CONTENTS: &[u8] = b"read only test file\n";@@ -39,22 +38,11 @@ unsafe fn test_file_rename_across_perms(rw_dir_fd: wasip1::Fd, ro_dir_fd: wasip1// Check test preconditions.test_ro_file_has_expected_contents(ro_dir_fd);- // Create a hardlink inside the file ro dir so there are two files pointing to- // the read-only file.- match wasip1::path_link(ro_dir_fd, 0, RO_TEST_FILENAME, ro_dir_fd, RW_ALIAS_FILENAME) {- // The readonly dir isnt recreated fresh per test mode in the p2- // runner, so just allow this to fail with exists because its very- // tedious to restructure everything to fix this properly- Ok(()) | Err(wasip1::ERRNO_EXIST) => {}- _ => panic!("should be possible to create link inside ro file domain"),- }-- // Renaming that file into the file rw dir should fail with permissions- // error, otherwise it would permit opening the ro file as rw- let err = wasip1::path_rename(ro_dir_fd, RW_ALIAS_FILENAME, rw_dir_fd, RW_ALIAS_FILENAME);+ // Renaming the ro dir file into the rw dir should fail with permissions error+ let err = wasip1::path_rename(ro_dir_fd, RO_TEST_FILENAME, rw_dir_fd, RO_TEST_FILENAME);assert!(err.is_err(),- "path_rename should fail because link source readonly, dest is readwrite"+ "path_rename should fail because source dir is readonly, dest dir is readwrite");assert_eq!(err.err().unwrap(),diff --git a/crates/test-programs/src/bin/p2_file_rename_across_perms.rs b/crates/test-programs/src/bin/p2_file_rename_across_perms.rsindex 1ff8d7873b..3121c2e8af 100644--- a/crates/test-programs/src/bin/p2_file_rename_across_perms.rs+++ b/crates/test-programs/src/bin/p2_file_rename_across_perms.rs@@ -4,7 +4,6 @@ use test_programs::wasi::filesystem::types::{Descriptor, DescriptorFlags, ErrorCode, OpenFlags, PathFlags,};-const RW_ALIAS_FILENAME: &str = "alias.txt";const RO_TEST_FILENAME: &str = "test.txt";const RO_EXPECTED_CONTENTS: &[u8] = b"read only test file\n";@@ -31,31 +30,15 @@ unsafe fn test_ro_file_has_expected_contents(dir: &Descriptor) {);}-unsafe fn test_file_hardlink_across_perms(rw_dir: &Descriptor, ro_dir: &Descriptor) {+unsafe fn test_file_rename_across_perms(rw_dir: &Descriptor, ro_dir: &Descriptor) {// Check test preconditions.test_ro_file_has_expected_contents(ro_dir);- // Create a hardlink inside the file ro dir so there are two files pointing to- // the read-only file.- match ro_dir.link_at(- PathFlags::empty(),- RO_TEST_FILENAME,- ro_dir,- RW_ALIAS_FILENAME,- ) {- // The readonly dir isnt recreated fresh per test mode in the p2- // runner, so just allow this to fail with exists because its very- // tedious to restructure everything to fix this properly- Ok(()) | Err(ErrorCode::Exist) => {}- _ => panic!("should be possible to create link inside ro file domain"),- }-- // Renaming that file into the file rw dir should fail with permissions- // error, otherwise it would permit opening the ro file as rw- let err = ro_dir.rename_at(RW_ALIAS_FILENAME, rw_dir, RW_ALIAS_FILENAME);+ // Renaming the ro dir file into the rw dir should fail with permissions error+ let err = ro_dir.rename_at(RO_TEST_FILENAME, rw_dir, RO_TEST_FILENAME);assert!(err.is_err(),- "rename_at should fail because link source is file readonly, and dest is file readwrite"+ "rename_at should fail because source dir is readonly, dest dir is readwrite");assert_eq!(err.err().unwrap(),@@ -90,6 +73,6 @@ fn main() {// Run the tests.unsafe {- test_file_hardlink_across_perms(rw_dir, ro_dir);+ test_file_rename_across_perms(rw_dir, ro_dir);}}diff --git a/crates/test-programs/src/bin/p2_file_stream_not_permitted.rs b/crates/test-programs/src/bin/p2_file_stream_not_permitted.rsindex 88436f666d..d678140b79 100644--- a/crates/test-programs/src/bin/p2_file_stream_not_permitted.rs+++ b/crates/test-programs/src/bin/p2_file_stream_not_permitted.rs@@ -47,37 +47,4 @@ fn main() {drop(stream);drop(file);assert_eq!(contents, b"stream permission test\n");-- // --- writeonly preopen: read stream denied, write stream allowed ---- let (writeonly_dir, _) = preopens- .iter()- .find(|(_, path)| path == "writeonly")- .expect("find preopen named writeonly");-- let file = writeonly_dir- .open_at(- PathFlags::empty(),- "stream-write.txt",- OpenFlags::empty(),- DescriptorFlags::WRITE,- )- .expect("open for writing");-- let err = file- .read_via_stream(0)- .expect_err("read_via_stream without read permission");- assert_eq!(- err,- ErrorCode::NotPermitted,- "read_via_stream should return not-permitted, got {err:?}"- );-- let stream = file- .write_via_stream(0)- .expect("write_via_stream with write permission");- stream- .blocking_write_and_flush(b"ok")- .expect("write stream contents");- drop(stream);- drop(file);}diff --git a/crates/test-programs/src/bin/p3_file_rename_across_perms.rs b/crates/test-programs/src/bin/p3_file_rename_across_perms.rsindex a3d4aab096..8f4f13172f 100644--- a/crates/test-programs/src/bin/p3_file_rename_across_perms.rs+++ b/crates/test-programs/src/bin/p3_file_rename_across_perms.rs@@ -7,7 +7,6 @@ struct Component;p3::export!(Component);-const RW_ALIAS_FILENAME: &str = "alias.txt";const RO_TEST_FILENAME: &str = "test.txt";const RO_EXPECTED_CONTENTS: &[u8] = b"read only test file\n";@@ -39,25 +38,12 @@ async fn test_file_rename_across_perms(rw_dir: &Descriptor, ro_dir: &Descriptor)// Check test preconditions.test_ro_file_has_expected_contents(ro_dir).await;- // Create a hardlink inside the file ro dir so there are two files pointing to- // the read-only file.- ro_dir- .link_at(- PathFlags::empty(),- RO_TEST_FILENAME.to_owned(),- ro_dir,- RW_ALIAS_FILENAME.to_owned(),- )- .await- .expect("should be possible to create link inside ro file domain");-- // Renaming that file into the file rw dir should fail with permissions- // error, otherwise it would permit opening the ro file as rw+ // Renaming the ro dir file into the rw dir should fail with permissions errorlet err = ro_dir.rename_at(- RW_ALIAS_FILENAME.to_owned(),+ RO_TEST_FILENAME.to_owned(),rw_dir,- RW_ALIAS_FILENAME.to_owned(),+ RO_TEST_FILENAME.to_owned(),).await;assert!(diff --git a/crates/wasi-nn/tests/exec/wit.rs b/crates/wasi-nn/tests/exec/wit.rsindex 61ce65bfb6..319962f0df 100644--- a/crates/wasi-nn/tests/exec/wit.rs+++ b/crates/wasi-nn/tests/exec/wit.rs@@ -4,7 +4,7 @@ use std::path::Path;use wasmtime::component::{Component, Linker, ResourceTable};use wasmtime::{Config, Engine, Result, Store, format_err};use wasmtime_wasi::p2::bindings::sync::Command;-use wasmtime_wasi::{DirPerms, FilePerms, WasiCtx, WasiCtxView};+use wasmtime_wasi::{FsPerms, WasiCtx, WasiCtxView};use wasmtime_wasi_nn::wit::WasiNnView;use wasmtime_wasi_nn::{Backend, InMemoryRegistry, wit::WasiNnCtx};@@ -39,8 +39,7 @@ impl Ctx {builder.inherit_stdio().preopened_dir(preopen_dir,PREOPENED_DIR_NAME,- DirPerms::READ,- FilePerms::READ,+ FsPerms::ReadOnly,)?;let wasi = builder.build();diff --git a/crates/wasi-nn/tests/exec/witx.rs b/crates/wasi-nn/tests/exec/witx.rsindex 5d4fa3b00f..79951847eb 100644--- a/crates/wasi-nn/tests/exec/witx.rs+++ b/crates/wasi-nn/tests/exec/witx.rs@@ -4,7 +4,7 @@ use std::path::Path;use wasmtime::Result;use wasmtime::{Config, Engine, Linker, Module, Store};use wasmtime_wasi::p1::WasiP1Ctx;-use wasmtime_wasi::{DirPerms, FilePerms, WasiCtxBuilder};+use wasmtime_wasi::{FsPerms, WasiCtxBuilder};use wasmtime_wasi_nn::{Backend, InMemoryRegistry, witx::WasiNnCtx};/// Run a wasi-nn test program. This is modeled after@@ -36,8 +36,7 @@ impl Ctx {builder.inherit_stdio().preopened_dir(preopen_dir,PREOPENED_DIR_NAME,- DirPerms::READ,- FilePerms::READ,+ FsPerms::ReadOnly,)?;let wasi = builder.build_p1();diff --git a/crates/wasi/src/ctx.rs b/crates/wasi/src/ctx.rsindex 99c78ab334..13c3503830 100644--- a/crates/wasi/src/ctx.rs+++ b/crates/wasi/src/ctx.rs@@ -3,7 +3,7 @@ use crate::clocks::{HostMonotonicClock, HostWallClock, WasiClocksCtx};use crate::filesystem::{Dir, WasiFilesystemCtx};use crate::random::WasiRandomCtx;use crate::sockets::{SocketAddrCheck, SocketAddrUse, WasiSocketsCtx};-use crate::{DirPerms, FilePerms, OpenMode};+use crate::{FsPerms, OpenMode};use cap_primitives::ambient_authority;use rand::Rng;use std::future::Future;@@ -269,11 +269,8 @@ impl WasiCtxBuilder {/// * `guest_path` - the name of the preopened directory from WebAssembly's/// perspective. Note that this does not need to match the host's name for/// the directory.- /// * `dir_perms` - this is the permissions that wasm will have to operate on- /// `guest_path`. This can be used, for example, to provide readonly access to a- /// directory.- /// * `file_perms` - similar to `dir_perms` but corresponds to the maximum set- /// of permissions that can be used for any file in this directory.+ /// * `fs_perms` - permissions enforced by wasmtime-wasi on filesystem+ /// operations under a preopen.////// # Errors///@@ -283,17 +280,17 @@ impl WasiCtxBuilder {////// ```/// use wasmtime_wasi::WasiCtxBuilder;- /// use wasmtime_wasi::{DirPerms, FilePerms};+ /// use wasmtime_wasi::FsPerms;////// # fn main() {}/// # fn foo() -> wasmtime::Result<()> {/// let mut wasi = WasiCtxBuilder::new();////// // Make `./host-directory` available in the guest as `.`- /// wasi.preopened_dir("./host-directory", ".", DirPerms::all(), FilePerms::all());+ /// wasi.preopened_dir("./host-directory", ".", FsPerms::ReadWrite);////// // Make `./readonly` available in the guest as `./ro`- /// wasi.preopened_dir("./readonly", "./ro", DirPerms::READ, FilePerms::READ);+ /// wasi.preopened_dir("./readonly", "./ro", FsPerms::ReadOnly);/// # Ok(())/// # }/// ```@@ -301,22 +298,17 @@ impl WasiCtxBuilder {&mut self,host_path: impl AsRef<Path>,guest_path: impl AsRef<str>,- dir_perms: DirPerms,- file_perms: FilePerms,+ perms: FsPerms,) -> Result<&mut Self> {let dir = cap_primitives::fs::open_ambient_dir(host_path.as_ref(), ambient_authority())?;- let mut open_mode = OpenMode::empty();- if dir_perms.contains(DirPerms::READ) {- open_mode |= OpenMode::READ;- }- if dir_perms.contains(DirPerms::MUTATE) {- open_mode |= OpenMode::WRITE;- }+ let open_mode = match perms {+ FsPerms::ReadOnly => OpenMode::READ,+ FsPerms::ReadWrite => OpenMode::READ | OpenMode::WRITE,+ };self.filesystem.preopens.push((Dir::new(dir,- dir_perms,- file_perms,+ perms,open_mode,self.filesystem.allow_blocking_current_thread,),diff --git a/crates/wasi/src/filesystem.rs b/crates/wasi/src/filesystem.rsindex 74874ea549..a8e90bf989 100644--- a/crates/wasi/src/filesystem.rs+++ b/crates/wasi/src/filesystem.rs@@ -76,36 +76,46 @@ pub trait WasiFilesystemView: Send {fn filesystem(&mut self) -> WasiFilesystemCtxView<'_>;}-bitflags::bitflags! {- #[derive(Copy, Clone, Debug, PartialEq, Eq)]- pub struct FilePerms: usize {- const READ = 0b1;- const WRITE = 0b10;- }+/// Permission bits for operating on filesystem, specified per preopen,+/// as enforced by wasmtime-wasi.+///+/// Filesystems can deny all mutation operations (read-only) or permit+/// mutations (read-write).+///+/// Read-only permissions allow reading the contents+/// of any file or directory reachable under the preopen, as well as reading+/// any file metadata. Changing, appending, or truncating files is not+/// permitted. Creating or deleting files, directories, symbolic links, and+/// hard links are not permitted.+///+/// Read-write permissions include changing the contents of any reachable+/// file, creating and deleting files, directories, symbolic links, and+/// creating hard links, as well as mutating any file metadata.+///+/// These permissions are enforced by wasmtime-wasi. The host filesystem may+/// enforce additional restrictions not covered by these.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum FsPerms {+ // Only read operations are permitted - no mutation permitted+ ReadOnly,+ // All operations are permitted.+ ReadWrite,}-bitflags::bitflags! {- #[derive(Copy, Clone, Debug, PartialEq, Eq)]- pub struct OpenMode: usize {- const READ = 0b1;- const WRITE = 0b10;+impl FsPerms {+ /// Tests whether writes are not permitted, returning a boolean. Shorthand+ /// for matches!(perms, FsPerms::ReadOnly), used frequently in+ /// if-statements.+ pub fn write_not_permitted(&self) -> bool {+ matches!(self, Self::ReadOnly)}}bitflags::bitflags! {- /// Permission bits for operating on a directory.- ///- /// Directories can be limited to being readonly. This will restrict what- /// can be done with them, for example preventing creation of new files.#[derive(Copy, Clone, Debug, PartialEq, Eq)]- pub struct DirPerms: usize {- /// This directory can be read, for example its entries can be iterated- /// over and files can be opened.+ pub struct OpenMode: usize {const READ = 0b1;-- /// This directory can be mutated, for example by creating new files- /// within it.- const MUTATE = 0b10;+ const WRITE = 0b10;}}@@ -573,14 +583,14 @@ impl Descriptor {}match self {Self::File(f) => {- if !f.perms.contains(FilePerms::WRITE) {+ if f.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}f.run_blocking(move |f| f.set_times(times)).await?;Ok(())}Self::Dir(d) => {- if !d.perms.contains(DirPerms::MUTATE) {+ if d.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}d.run_blocking(move |d| d.set_times(times)).await?;@@ -664,9 +674,10 @@ pub struct File {/// `spawn_blocking`.pub file: Arc<std::fs::File>,/// Permissions to enforce on access to the file. These permissions are- /// specified by a user of the `crate::WasiCtxBuilder`, and are- /// enforced prior to any enforced by the underlying operating system.- pub perms: FilePerms,+ /// specified to the parent preopen by a user of the+ /// `crate::WasiCtxBuilder`, and are enforced prior to any enforced by the+ /// underlying operating system.+ pub perms: FsPerms,/// The mode the file was opened under: bits for reading, and writing./// Required to correctly report the DescriptorFlags, because/// cap-primitives doesn't presently provide a cross-platform equivalent@@ -679,7 +690,7 @@ pub struct File {impl File {pub fn new(file: std::fs::File,- perms: FilePerms,+ perms: FsPerms,open_mode: OpenMode,allow_blocking_current_thread: bool,) -> Self {@@ -754,7 +765,7 @@ impl File {}pub(crate) async fn set_size(&self, size: u64) -> Result<(), ErrorCode> {- if !self.perms.contains(FilePerms::WRITE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}self.run_blocking(move |f| f.set_len(size)).await?;@@ -772,15 +783,13 @@ pub struct Dir {////// Wrapped in an Arc because a copy is needed for `run_blocking`.pub dir: Arc<std::fs::File>,- /// Permissions to enforce on access to this directory. These permissions- /// are specified by a user of the `crate::WasiCtxBuilder`, and+ /// Permissions to enforce on access to the filesystem under this+ /// directory are specified by a user of the `crate::WasiCtxBuilder`, and/// are enforced prior to any enforced by the underlying operating system.////// These permissions are also enforced on any directories opened under/// this directory.- pub perms: DirPerms,- /// Permissions to enforce on any files opened under this directory.- pub file_perms: FilePerms,+ pub perms: FsPerms,/// The mode the directory was opened under: bits for reading, and writing./// Required to correctly report the DescriptorFlags, because/// cap-primitives doesn't presently provide a cross-platform equivalent@@ -793,15 +802,13 @@ pub struct Dir {impl Dir {pub fn new(dir: std::fs::File,- perms: DirPerms,- file_perms: FilePerms,+ perms: FsPerms,open_mode: OpenMode,allow_blocking_current_thread: bool,) -> Self {Dir {dir: Arc::new(dir),perms,- file_perms,open_mode,allow_blocking_current_thread,}@@ -841,7 +848,7 @@ impl Dir {}pub(crate) async fn create_directory_at(&self, path: String) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}self.run_blocking(move |d| {@@ -856,10 +863,6 @@ impl Dir {path_flags: PathFlags,path: String,) -> Result<DescriptorStat, ErrorCode> {- if !self.perms.contains(DirPerms::READ) {- return Err(ErrorCode::NotPermitted);- }-let follow = if path_flags.contains(PathFlags::SYMLINK_FOLLOW) {FollowSymlinks::Yes} else {@@ -878,7 +881,7 @@ impl Dir {atim: Option<SystemTime>,mtim: Option<SystemTime>,) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}let atim =@@ -904,16 +907,16 @@ impl Dir {new_dir: &Self,new_path: String,) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}- if !new_dir.perms.contains(DirPerms::MUTATE) {+ if new_dir.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}if old_path_flags.contains(PathFlags::SYMLINK_FOLLOW) {return Err(ErrorCode::Invalid);}- if self.perms != new_dir.perms || self.file_perms != new_dir.file_perms {+ if self.perms != new_dir.perms {return Err(ErrorCode::NotPermitted);}let new_dir_handle = Arc::clone(&new_dir.dir);@@ -932,19 +935,6 @@ impl Dir {flags: DescriptorFlags,allow_blocking_current_thread: bool,) -> Result<Descriptor, ErrorCode> {- if !self.perms.contains(DirPerms::READ) {- return Err(ErrorCode::NotPermitted);- }-- if !self.perms.contains(DirPerms::MUTATE) {- if oflags.contains(OpenFlags::CREATE) || oflags.contains(OpenFlags::TRUNCATE) {- return Err(ErrorCode::NotPermitted);- }- if flags.contains(DescriptorFlags::WRITE) {- return Err(ErrorCode::NotPermitted);- }- }-// Track whether we are creating file, for permission check:let mut create = false;// Track open mode, for permission check and recording in created descriptor:@@ -1014,11 +1004,10 @@ impl Dir {// Now enforce this WasiCtx's permissions before letting the OS have// its shot:- if !self.perms.contains(DirPerms::MUTATE) && create {- return Err(ErrorCode::NotPermitted);- }- if !self.file_perms.contains(FilePerms::WRITE) && open_mode.contains(OpenMode::WRITE) {- return Err(ErrorCode::NotPermitted);+ if self.perms.write_not_permitted() {+ if create || open_mode.contains(OpenMode::WRITE) {+ return Err(ErrorCode::NotPermitted);+ }}// Represents each possible outcome from the spawn_blocking operation.@@ -1055,14 +1044,13 @@ impl Dir {OpenResult::Dir(dir) => Ok(Descriptor::Dir(Dir::new(dir,self.perms,- self.file_perms,open_mode,allow_blocking_current_thread,))),OpenResult::File(file) => Ok(Descriptor::File(File::new(file,- self.file_perms,+ self.perms,open_mode,allow_blocking_current_thread,))),@@ -1072,9 +1060,6 @@ impl Dir {}pub(crate) async fn readlink_at(&self, path: String) -> Result<String, ErrorCode> {- if !self.perms.contains(DirPerms::READ) {- return Err(ErrorCode::NotPermitted);- }let link = self.run_blocking(move |d| cap_primitives::fs::read_link(d, path.as_ref())).await?;@@ -1084,7 +1069,7 @@ impl Dir {}pub(crate) async fn remove_directory_at(&self, path: String) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}self.run_blocking(move |d| cap_primitives::fs::remove_dir(d, path.as_ref()))@@ -1098,13 +1083,13 @@ impl Dir {new_dir: &Self,new_path: String,) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}- if !new_dir.perms.contains(DirPerms::MUTATE) {+ if new_dir.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}- if self.perms != new_dir.perms || self.file_perms != new_dir.file_perms {+ if self.perms != new_dir.perms {return Err(ErrorCode::NotPermitted);}let new_dir_handle = Arc::clone(&new_dir.dir);@@ -1120,7 +1105,7 @@ impl Dir {src_path: String,dest_path: String,) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}self.run_blocking(move |d| sys::symlink(src_path.as_ref(), d, dest_path.as_ref()))@@ -1129,7 +1114,7 @@ impl Dir {}pub(crate) async fn unlink_file_at(&self, path: String) -> Result<(), ErrorCode> {- if !self.perms.contains(DirPerms::MUTATE) {+ if self.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted);}self.run_blocking(move |d| sys::remove_file_or_symlink(d, path.as_ref()))diff --git a/crates/wasi/src/lib.rs b/crates/wasi/src/lib.rsindex 1d43a08fda..6dfd0b83d6 100644--- a/crates/wasi/src/lib.rs+++ b/crates/wasi/src/lib.rs@@ -53,7 +53,7 @@ mod view;pub use self::clocks::{HostMonotonicClock, HostWallClock};pub use self::ctx::{WasiCtx, WasiCtxBuilder};pub use self::error::{I32Exit, TrappableError};-pub use self::filesystem::{DirPerms, FilePerms, OpenMode};+pub use self::filesystem::{FsPerms, OpenMode};pub use self::random::{Deterministic, thread_rng};pub use self::view::{WasiCtxView, WasiView};#[doc(no_inline)]diff --git a/crates/wasi/src/p2/host/filesystem.rs b/crates/wasi/src/p2/host/filesystem.rsindex 3a668bb33b..3fc37a45ad 100644--- a/crates/wasi/src/p2/host/filesystem.rs+++ b/crates/wasi/src/p2/host/filesystem.rs@@ -7,7 +7,6 @@ use crate::p2::bindings::filesystem::types::{};use crate::p2::filesystem::{FileInputStream, FileOutputStream, ReaddirIterator};use crate::p2::{FsError, FsResult};-use crate::{DirPerms, FilePerms};use std::time::SystemTime;use wasmtime::component::Resource;use wasmtime_wasi_io::streams::{DynInputStream, DynOutputStream};@@ -108,9 +107,6 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {offset: types::Filesize,) -> FsResult<(Vec<u8>, bool)> {let f = self.table.get(&fd)?.file()?;- if !f.perms.contains(FilePerms::READ) {- return Err(ErrorCode::NotPermitted.into());- }let (mut buffer, r) = f.run_blocking(move |f| {@@ -142,7 +138,7 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {offset: types::Filesize,) -> FsResult<types::Filesize> {let f = self.table.get(&fd)?.file()?;- if !f.perms.contains(FilePerms::WRITE) {+ if f.perms.write_not_permitted() {return Err(ErrorCode::NotPermitted.into());}@@ -158,9 +154,6 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {fd: Resource<types::Descriptor>,) -> FsResult<Resource<types::DirectoryEntryStream>> {let d = self.table.get(&fd)?.dir()?;- if !d.perms.contains(DirPerms::READ) {- return Err(ErrorCode::NotPermitted.into());- }enum ReaddirError {Io(std::io::Error),@@ -377,10 +370,6 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {// Trap if fd lookup fails:let f = self.table.get(&fd)?.file()?;- if !f.perms.contains(FilePerms::READ) {- Err(types::ErrorCode::NotPermitted)?;- }-// Create a stream view for it.let reader: DynInputStream = Box::new(FileInputStream::new(f, offset));@@ -398,7 +387,7 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {// Trap if fd lookup fails:let f = self.table.get(&fd)?.file()?;- if !f.perms.contains(FilePerms::WRITE) {+ if f.perms.write_not_permitted() {Err(types::ErrorCode::NotPermitted)?;}@@ -419,7 +408,7 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {// Trap if fd lookup fails:let f = self.table.get(&fd)?.file()?;- if !f.perms.contains(FilePerms::WRITE) {+ if f.perms.write_not_permitted() {Err(types::ErrorCode::NotPermitted)?;}diff --git a/crates/wasi/src/p3/filesystem/host.rs b/crates/wasi/src/p3/filesystem/host.rsindex d36589f9c3..54437ce23f 100644--- a/crates/wasi/src/p3/filesystem/host.rs+++ b/crates/wasi/src/p3/filesystem/host.rs@@ -7,7 +7,6 @@ use crate::p3::bindings::filesystem::types::{};use crate::p3::filesystem::{FilesystemError, FilesystemResult, preopens};use crate::p3::{DEFAULT_BUFFER_CAPACITY, FallibleIteratorProducer};-use crate::{DirPerms, FilePerms};use bytes::BytesMut;use core::pin::Pin;use core::task::{Context, Poll, ready};@@ -523,15 +522,6 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {offset: Filesize,) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {let file = get_file(store.get().table, &fd)?;- if !file.perms.contains(FilePerms::READ) {- return Ok((- StreamReader::new(&mut store, iter::empty())?,- FutureReader::new(&mut store, async {- wasmtime::error::Ok(Err(ErrorCode::NotPermitted))- })?,- ));- }-let file = file.clone();let (result_tx, result_rx) = oneshot::channel();Ok((@@ -556,7 +546,7 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {let (result_tx, result_rx) = oneshot::channel();match get_file(store.get().table, &fd).and_then(|file| {- if !file.perms.contains(FilePerms::WRITE) {+ if file.perms.write_not_permitted() {Err(ErrorCode::NotPermitted.into())} else {Ok(file.clone())@@ -583,7 +573,7 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {let (result_tx, result_rx) = oneshot::channel();match get_file(store.get().table, &fd).and_then(|file| {- if !file.perms.contains(FilePerms::WRITE) {+ if file.perms.write_not_permitted() {Err(ErrorCode::NotPermitted.into())} else {Ok(file.clone())@@ -670,13 +660,7 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {FutureReader<Result<(), ErrorCode>>,)> {let (result_tx, result_rx) = oneshot::channel();- let stream = match get_dir(store.get().table, &fd).and_then(|dir| {- if !dir.perms.contains(DirPerms::READ) {- Err(ErrorCode::NotPermitted.into())- } else {- Ok(dir)- }- }) {+ let stream = match get_dir(store.get().table, &fd) {Ok(dir) => {let allow_blocking_current_thread = dir.allow_blocking_current_thread;let dir = Arc::clone(dir.as_dir());diff --git a/crates/wasi/tests/all/p1.rs b/crates/wasi/tests/all/p1.rsindex cd1f6d4e33..99bee44964 100644--- a/crates/wasi/tests/all/p1.rs+++ b/crates/wasi/tests/all/p1.rs@@ -300,7 +300,7 @@ async fn p1_file_truncation_readonly() {async fn run_with_readonly_testfile(component_path: &str) {use std::path::PathBuf;- use wasmtime_wasi::{DirPerms, FilePerms};+ use wasmtime_wasi::FsPerms;let prefix = format!("wasi_components_ro_");let tempdir = tempfile::Builder::new()@@ -314,13 +314,8 @@ async fn run_with_readonly_testfile(component_path: &str) {std::fs::write(&file, EXPECTED_CONTENTS).expect("write truncation test file");run(component_path, |b| {- b.preopened_dir(- tempdir.path(),- "readonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::READ,- )- .unwrap();+ b.preopened_dir(tempdir.path(), "readonly", FsPerms::ReadOnly)+ .unwrap();}).await.expect("run guest");diff --git a/crates/wasi/tests/all/p2/api.rs b/crates/wasi/tests/all/p2/api.rsindex 415ce250d6..4a59913daf 100644--- a/crates/wasi/tests/all/p2/api.rs+++ b/crates/wasi/tests/all/p2/api.rs@@ -7,8 +7,7 @@ use wasmtime::component::{Component, Linker, ResourceTable};use wasmtime_wasi::p2::add_to_linker_async;use wasmtime_wasi::p2::bindings::{Command, clocks::wall_clock, filesystem::types as filesystem};use wasmtime_wasi::{- DirPerms, FilePerms, HostMonotonicClock, HostWallClock, WasiCtx, WasiCtxBuilder, WasiCtxView,- WasiView,+ FsPerms, HostMonotonicClock, HostWallClock, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView,};struct CommandCtx {@@ -96,7 +95,7 @@ async fn p2_api_read_only() -> Result<()> {let table = ResourceTable::new();let wasi = WasiCtxBuilder::new()- .preopened_dir(dir.path(), "/", DirPerms::READ, FilePerms::READ)?+ .preopened_dir(dir.path(), "/", FsPerms::ReadOnly)?.build();let (mut store, command) =diff --git a/crates/wasi/tests/all/p2/async_.rs b/crates/wasi/tests/all/p2/async_.rsindex 0e2417e1b6..b170b2fd7b 100644--- a/crates/wasi/tests/all/p2/async_.rs+++ b/crates/wasi/tests/all/p2/async_.rs@@ -435,7 +435,7 @@ async fn p2_file_truncation_readonly() {async fn run_with_readonly_testfile(component_path: &str) {use std::path::PathBuf;- use wasmtime_wasi::{DirPerms, FilePerms};+ use wasmtime_wasi::FsPerms;let prefix = "wasi_components_ro_";let tempdir = tempfile::Builder::new()@@ -449,13 +449,8 @@ async fn run_with_readonly_testfile(component_path: &str) {std::fs::write(&file, EXPECTED_CONTENTS).expect("write read only test file");run(component_path, |b| {- b.preopened_dir(- tempdir.path(),- "readonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::READ,- )- .unwrap();+ b.preopened_dir(tempdir.path(), "readonly", FsPerms::ReadOnly)+ .unwrap();}).await.expect("run guest");@@ -487,38 +482,20 @@ async fn p2_file_stream_not_permitted() {}async fn file_stream_not_permitted(component_path: &str) {- use wasmtime_wasi::{DirPerms, FilePerms};+ use wasmtime_wasi::FsPerms;let readonly = tempfile::Builder::new().prefix("wasi_components_stream_np_ro_").tempdir().expect("create readonly tempdir");- let writeonly = tempfile::Builder::new()- .prefix("wasi_components_stream_np_wo_")- .tempdir()- .expect("create writeonly tempdir");const RO_CONTENTS: &[u8] = b"stream permission test\n";std::fs::write(readonly.path().join("stream-perms.txt"), RO_CONTENTS).expect("write readonly test file");- std::fs::write(writeonly.path().join("stream-write.txt"), b"")- .expect("create writeonly test file");run(component_path, |b| {- b.preopened_dir(- readonly.path(),- "readonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::READ,- )- .unwrap();- b.preopened_dir(- writeonly.path(),- "writeonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::WRITE,- )- .unwrap();+ b.preopened_dir(readonly.path(), "readonly", FsPerms::ReadOnly)+ .unwrap();}).await.expect("run p2_file_stream_not_permitted guest");diff --git a/crates/wasi/tests/all/p2/sync.rs b/crates/wasi/tests/all/p2/sync.rsindex 514c1b7ac3..343bc4d8c5 100644--- a/crates/wasi/tests/all/p2/sync.rs+++ b/crates/wasi/tests/all/p2/sync.rs@@ -405,7 +405,7 @@ fn p2_file_truncation_readonly() {fn run_with_readonly_testfile(component_path: &str) {use std::path::PathBuf;- use wasmtime_wasi::{DirPerms, FilePerms};+ use wasmtime_wasi::FsPerms;let prefix = "wasi_components_ro_";let tempdir = tempfile::Builder::new()@@ -419,13 +419,8 @@ fn run_with_readonly_testfile(component_path: &str) {std::fs::write(&file, EXPECTED_CONTENTS).expect("write read only test file");run(component_path, |b| {- b.preopened_dir(- tempdir.path(),- "readonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::READ,- )- .unwrap();+ b.preopened_dir(tempdir.path(), "readonly", FsPerms::ReadOnly)+ .unwrap();}).expect("run guest");@@ -456,38 +451,20 @@ fn p2_file_stream_not_permitted() {}fn file_stream_not_permitted(component_path: &str) {- use wasmtime_wasi::{DirPerms, FilePerms};+ use wasmtime_wasi::FsPerms;let readonly = tempfile::Builder::new().prefix("wasi_components_stream_np_ro_").tempdir().expect("create readonly tempdir");- let writeonly = tempfile::Builder::new()- .prefix("wasi_components_stream_np_wo_")- .tempdir()- .expect("create writeonly tempdir");const RO_CONTENTS: &[u8] = b"stream permission test\n";std::fs::write(readonly.path().join("stream-perms.txt"), RO_CONTENTS).expect("write readonly test file");- std::fs::write(writeonly.path().join("stream-write.txt"), b"")- .expect("create writeonly test file");run(component_path, |b| {- b.preopened_dir(- readonly.path(),- "readonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::READ,- )- .unwrap();- b.preopened_dir(- writeonly.path(),- "writeonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::WRITE,- )- .unwrap();+ b.preopened_dir(readonly.path(), "readonly", FsPerms::ReadOnly)+ .unwrap();}).expect("run p2_file_stream_not_permitted guest");}diff --git a/crates/wasi/tests/all/p3/mod.rs b/crates/wasi/tests/all/p3/mod.rsindex 18156e399b..a00dc7d64d 100644--- a/crates/wasi/tests/all/p3/mod.rs+++ b/crates/wasi/tests/all/p3/mod.rs@@ -4,7 +4,7 @@ use test_programs_artifacts::*;use wasmtime::component::{Component, Linker};use wasmtime::{Result, error::Context as _, format_err};use wasmtime_wasi::p3::bindings::Command;-use wasmtime_wasi::{DirPerms, FilePerms, WasiCtxBuilder};+use wasmtime_wasi::{FsPerms, WasiCtxBuilder};async fn run(path: &str) -> Result<()> {run_allow_blocking_current_thread(path, false).await@@ -203,12 +203,7 @@ async fn run_with_readonly_testfile(component_path: &str) -> wasmtime::Result<()run_with_builder(component_path, false, |builder| {builder- .preopened_dir(- tempdir.path(),- "readonly",- DirPerms::READ | DirPerms::MUTATE,- FilePerms::READ,- )+ .preopened_dir(tempdir.path(), "readonly", FsPerms::ReadOnly).unwrap();}).await?;diff --git a/crates/wasi/tests/all/store.rs b/crates/wasi/tests/all/store.rsindex f5bef3b1a3..afd06ebe42 100644--- a/crates/wasi/tests/all/store.rs+++ b/crates/wasi/tests/all/store.rs@@ -3,7 +3,7 @@ use wasmtime::Result;use wasmtime::component::ResourceTable;use wasmtime::{Engine, Store};use wasmtime_wasi::{- DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe,+ FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe,};pub struct Ctx<T> {@@ -52,7 +52,7 @@ impl<T> Ctx<T> {.allow_udp(true).allow_ip_name_lookup(true);println!("preopen: {workspace:?}");- builder.preopened_dir(workspace.path(), ".", DirPerms::all(), FilePerms::all())?;+ builder.preopened_dir(workspace.path(), ".", FsPerms::ReadWrite)?;for (var, val) in test_programs_artifacts::wasi_tests_environment() {builder.env(var, val);}diff --git a/src/common.rs b/src/common.rsindex a48ae9eb94..1500ea8a68 100644--- a/src/common.rs+++ b/src/common.rs@@ -350,12 +350,7 @@ impl RunCommon {}for (host, guest) in self.dirs.iter() {- builder.preopened_dir(- host,- guest,- wasmtime_wasi::DirPerms::all(),- wasmtime_wasi::FilePerms::all(),- )?;+ builder.preopened_dir(host, guest, wasmtime_wasi::FsPerms::ReadWrite)?;}if let Some(cwd) = &self.common.wasi.cwd {builder.initial_cwd(cwd);