From 2f15dfbbe287266921916f4431e93f09880ac4ce Mon Sep 17 00:00:00 2001 From: Syrus Akbary Date: Mon, 16 Nov 2026 19:32:33 -0800 Subject: [PATCH 1/3] Add an embedder WebAssembly policy for guest environments Guest environments allocate V8 array buffers in the guest's linear memory, where they count against the context's memory budget. V8's WebAssembly memories and compiled code come from V8's page allocator instead, outside every limit the provider enforces. Let the embedder decide whether guests get WebAssembly at all. * `NapiCtxBuilder::webassembly(WasmPolicy)`. `EnabledUnmetered`, the default, keeps today's behavior. `Restricted` removes the `WebAssembly` global from the env's own realm and from every realm made in it, and V8 refuses wasm code generation in all of the isolate's contexts, also ones the provider did not create. The enum is non-exhaustive so a metered variant can follow. * The policy is stored per context, copied into every store's env (WASIX worker threads included) and passed to the bridge, which calls the provider-private `snapi_private_create_env`. It is not an env-create option: that descriptor is also the guest's wasm32 ABI, so guests can neither set nor observe it. Unknown values are refused after the guest heap is released. `unofficial_napi_create_env` keeps its signature and behavior. * Every provider isolate gets an AllowWasmCodeGenerationCallback. It refuses all wasm in a restricted agent and otherwise honors each realm's `allow_code_gen_wasm` (vm's `codeGeneration.wasm`), which was accepted and ignored until now. * asm.js: V8 15.2 removed asm.js translation to wasm, so asm.js runs as ordinary JavaScript under every policy and cannot bypass the callback. A static_assert refuses older V8. * The host-JS backend runs guest JS with the host's own WebAssembly and cannot remove it, so it refuses to create a restricted env. * `napi_wasmer --restricted-webassembly`. Tests: native test_21 cases for both policies, realms with and without wasm code generation, a context the provider did not make, and an unknown policy; WASIX guests for the restricted and default policies, per-context policies in one process, and asm.js under both; unit tests for the policy reaching every store env and the refused policy releasing the guest-heap context. Co-Authored-By: Claude Opus 5.5 --- docs/cli.md | 12 ++ docs/realms.md | 20 +-- include/unofficial_napi.h | 6 +- src/bin/napi_wasmer.rs | 10 +- src/ctx.rs | 113 ++++++++++++++++- src/env.rs | 4 + src/guest/napi.rs | 13 +- src/guest/napi_js.rs | 13 +- src/guest_heap.rs | 22 ++++ src/lib.rs | 2 +- src/napi_bridge_init.cc | 29 ++++- src/snapi.rs | 5 + src/snapi_js.rs | 16 ++- tests/concurrent_envs.rs | 6 +- tests/programs/test_js_asmjs_plain.c | 67 ++++++++++ tests/programs/test_js_wasm_enabled.c | 114 +++++++++++++++++ tests/programs/test_js_wasm_restricted.c | 92 ++++++++++++++ tests/runners/test_21_general.cc | 149 +++++++++++++++++++++++ tests/v8_host_control.rs | 74 ++++++++++- v8/src/internal/napi_v8_agent.h | 3 + v8/src/internal/napi_v8_env.h | 2 + v8/src/internal/napi_wasm_policy.h | 62 ++++++++++ v8/src/internal/unofficial_napi_bridge.h | 5 + v8/src/unofficial_napi.cc | 35 +++++- v8/src/unofficial_napi_contextify.cc | 22 +++- 25 files changed, 864 insertions(+), 32 deletions(-) create mode 100644 tests/programs/test_js_asmjs_plain.c create mode 100644 tests/programs/test_js_wasm_enabled.c create mode 100644 tests/programs/test_js_wasm_restricted.c create mode 100644 v8/src/internal/napi_wasm_policy.h diff --git a/docs/cli.md b/docs/cli.md index 05876c6312..7c57cdffd5 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -35,3 +35,15 @@ CLI module caches are separated into `cranelift` and `llvm` subdirectories under `WASMER_NAPI_CACHE_DIR` (by default, the temporary directory's `wasmer-napi-cache`). Use a fresh cache root when comparing different Wasmer source revisions, and warm each guest before measuring steady-state throughput. + +## WebAssembly in the guest + +Guest JavaScript has V8's `WebAssembly` by default (`WasmPolicy::EnabledUnmetered`): +wasm memories and compiled code are not charged to any N-API limit. Pass +`--restricted-webassembly` to take it away (`WasmPolicy::Restricted`). The +`WebAssembly` global is then absent from the guest's realms, and V8 refuses to +compile wasm in all of them: + +```sh +./target/release/napi_wasmer --restricted-webassembly guest.wasm +``` diff --git a/docs/realms.md b/docs/realms.md index b93b7d1f3a..de7b7a6f22 100644 --- a/docs/realms.md +++ b/docs/realms.md @@ -79,12 +79,15 @@ napi_status unofficial_napi_compile_function(napi_env env, unofficial_napi_realm | `host_defined_option_id` | yes | yes | no | | `allow_code_gen_strings` | yes | no | no | | `own_microtask_queue` | yes | no | no | - | `allow_code_gen_wasm` | no | no | no | + | `allow_code_gen_wasm` | yes | no | no | | `name`, `origin` | no | no | no | With `allow_code_gen_strings` false, V8 makes `eval` and the `Function` - constructors throw an `EvalError` in the realm. WebAssembly code - generation stays allowed on V8 (QuickJS has no WebAssembly). + constructors throw an `EvalError` in the realm. With `allow_code_gen_wasm` + false, compiling WebAssembly there throws a `WebAssembly.CompileError` + (QuickJS has no WebAssembly). An env whose embedder chose + `WasmPolicy::Restricted` has no `WebAssembly` global in any realm and + refuses wasm code generation in all of them, whatever the option says. - **`get_realm`** returns NULL for any object that isn't a realm's global or sandbox, the env's own global included. - **`enter_realm` / `leave_realm`:** @@ -370,12 +373,11 @@ between the engines: last copy, and a script it starts in the realm copies the sandbox in again, over the running script's global writes to the same names. - host-JS evaluates against the sandbox with `with`. -- **Code generation per realm.** No provider enforces - `allow_code_gen_wasm`. V8 would need an isolate-wide - `AllowWasmCodeGenerationCallback` that reads a per-realm flag, as Node - does. There is also no call to change a realm's code-generation policy - after it is created, which a browser needs because CSP arrives with the - response. +- **Code generation per realm.** Only V8 enforces `allow_code_gen_wasm`, + through an isolate-wide `AllowWasmCodeGenerationCallback` that reads it + from the realm's record, as Node does. There is no call to change a + realm's code-generation policy after it is created, which a browser needs + because CSP arrives with the response. ## History diff --git a/include/unofficial_napi.h b/include/unofficial_napi.h index ebb8ce887c..cc7431a740 100644 --- a/include/unofficial_napi.h +++ b/include/unofficial_napi.h @@ -376,8 +376,10 @@ enum { UNOFFICIAL_NAPI_REALM_OPTIONS_VERSION = 1 }; // - `allow_code_gen_strings`: V8 only. When false, eval and the Function // constructors throw an EvalError in the realm. // - `own_microtask_queue`: V8 only. -// - `allow_code_gen_wasm`, `name` and `origin`: no provider. WebAssembly code -// generation stays allowed wherever the engine has WebAssembly. +// - `allow_code_gen_wasm`: V8 only. When false, compiling WebAssembly in the +// realm throws a WebAssembly.CompileError. An env whose embedder restricted +// WebAssembly refuses it in every realm, whatever this option says. +// - `name` and `origin`: no provider. typedef struct { uint32_t size; uint32_t version; diff --git a/src/bin/napi_wasmer.rs b/src/bin/napi_wasmer.rs index d8e926c28f..96bef51058 100644 --- a/src/bin/napi_wasmer.rs +++ b/src/bin/napi_wasmer.rs @@ -1,7 +1,7 @@ use anyhow::{Context, Result, anyhow, bail}; use std::path::{Path, PathBuf}; use wasmer_napi::{ - NapiCtx, + NapiCtx, WasmPolicy, cli::{GuestMount, run_wasix_main_with_ctx}, }; @@ -282,7 +282,7 @@ fn main() -> Result<()> { Some(path) => PathBuf::from(path), None => { bail!( - "usage: napi_wasmer [--builtin-js-dir ] [--app-dir ] [--mount :] [--env =] [--cwd ] [--program-name ] [--] [guest-args...]" + "usage: napi_wasmer [--builtin-js-dir ] [--app-dir ] [--mount :] [--env =] [--cwd ] [--program-name ] [--restricted-webassembly] [--] [guest-args...]" ); } }; @@ -298,6 +298,7 @@ fn main() -> Result<()> { .to_string(); let mut guest_args = Vec::new(); let mut forwarding_guest_args = false; + let mut webassembly = WasmPolicy::EnabledUnmetered; while let Some(arg) = argv.next() { if forwarding_guest_args { @@ -306,6 +307,9 @@ fn main() -> Result<()> { } match arg.as_str() { "--" => forwarding_guest_args = true, + // Takes V8's WebAssembly away from the guest (see + // `WasmPolicy::Restricted`). + "--restricted-webassembly" => webassembly = WasmPolicy::Restricted, "--app-dir" => { let host_dir = argv .next() @@ -383,7 +387,7 @@ fn main() -> Result<()> { maybe_remap_first_guest_arg_to_app_mount(&mut guest_args, &mut extra_mounts)?; maybe_add_builtin_mounts(&mut extra_mounts, builtin_js_dir)?; - let ctx = NapiCtx::default(); + let ctx = NapiCtx::builder().webassembly(webassembly).build(); let exit_code = run_wasix_main_with_ctx( &ctx, &wasm_path, diff --git a/src/ctx.rs b/src/ctx.rs index ec7623ca98..a49fbe000f 100644 --- a/src/ctx.rs +++ b/src/ctx.rs @@ -32,10 +32,60 @@ impl NapiLimits { } } +/// Whether JavaScript in guest environments can use V8's `WebAssembly`. +/// +/// Guest environments allocate V8 array buffers in the guest's linear memory, +/// where they count against the context's memory budget. V8 does not allocate +/// WebAssembly memories and compiled wasm code that way: they come from V8's +/// page allocator, outside the guest heap and outside every limit this crate +/// enforces. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum WasmPolicy { + /// No `WebAssembly` in guest environments. The global is absent from an + /// environment's own realm and from every realm made in it (`vm` + /// contexts), and V8 refuses to compile wasm in all of them, also in + /// realms V8 makes on its own, such as `ShadowRealm`s. asm.js still runs, + /// as ordinary JavaScript: V8 no longer translates it to wasm. + /// + /// The host-JavaScript backend runs guest JavaScript with the host's own + /// `WebAssembly` and cannot remove it, so environment creation fails + /// there under this policy. + Restricted, + /// V8's `WebAssembly` as the engine ships it, **without resource + /// accounting** (the default). + /// + /// Guest JavaScript can make V8 reserve address space for wasm memories + /// (by default 4 GiB for each 32-bit memory without a declared maximum) + /// and commit memory as they grow, compile and commit executable wasm + /// code, also on V8 background threads, and use compiler working memory + /// that grows with the module size. None of it is charged to + /// [`NapiLimits::total_memory_bytes`], to a [`NapiMemoryAccountant`] or to + /// any other limit of the context; only process-wide V8 flags bound it. + /// It also exposes V8's wasm compilers to guest code. + /// + /// Realms follow their own `allow_code_gen_wasm` option (`vm`'s + /// `codeGeneration.wasm`). + #[default] + EnabledUnmetered, +} + +impl WasmPolicy { + /// The value passed to the native bridge; `NapiWebAssemblyPolicy` in + /// `v8/src/internal/napi_wasm_policy.h`. + pub(crate) const fn bridge_code(self) -> u32 { + match self { + Self::Restricted => 0, + Self::EnabledUnmetered => 1, + } + } +} + #[derive(Default)] pub struct NapiCtxBuilder { limits: NapiLimits, accountant: Option>, + webassembly: WasmPolicy, } #[derive(Clone, Debug)] @@ -121,6 +171,7 @@ impl NapiRuntimeControl { #[derive(Debug)] struct NapiCtxInner { limits: NapiLimits, + webassembly: WasmPolicy, active_sessions: AtomicUsize, /// One shared accountant per app, `Arc`-shared into the engine's budgeted /// tunables (guest wasm linear memory) and, in later phases, the V8 heap, @@ -183,6 +234,15 @@ impl NapiCtxBuilder { self } + /// Whether guest JavaScript can use V8's `WebAssembly` (default: + /// [`WasmPolicy::EnabledUnmetered`], which no limit of this context + /// covers). Applies to every environment a guest creates through this + /// context, including those of its WASIX worker threads. + pub fn webassembly(mut self, policy: WasmPolicy) -> Self { + self.webassembly = policy; + self + } + pub fn build(self) -> NapiCtx { let budget = match self.accountant { Some(accountant) => ResourceBudget::with_accountant(accountant), @@ -194,6 +254,7 @@ impl NapiCtxBuilder { NapiCtx { inner: Arc::new(NapiCtxInner { limits: self.limits, + webassembly: self.webassembly, active_sessions: AtomicUsize::new(0), budget, envs: Arc::new(Mutex::new(crate::env::EnvRegistry::default())), @@ -218,6 +279,11 @@ impl NapiCtx { &self.inner.limits } + /// The WebAssembly policy of this context's guest environments. + pub fn webassembly_policy(&self) -> WasmPolicy { + self.inner.webassembly + } + pub fn active_sessions(&self) -> usize { self.inner.active_sessions.load(Ordering::Acquire) } @@ -401,12 +467,13 @@ impl NapiSession { fn add_imports(&self, store: &mut StoreMut<'_>, import_object: &mut Imports) -> Result<()> { register_env_imports(store, import_object); - let napi_env = NapiEnv::new( + let mut napi_env = NapiEnv::new( Arc::clone(&self.inner.ctx.budget), self.inner.ctx.limits.max_envs, Arc::clone(&self.inner.ctx.envs), Arc::clone(&self.inner.ctx.host_stopped), ); + napi_env.webassembly = self.inner.ctx.webassembly; let func_env = FunctionEnv::new(store, napi_env); { let mut guard = self @@ -657,6 +724,50 @@ mod tests { .expect("configure instance A"); } + #[test] + fn webassembly_policy_reaches_every_store_env() { + assert_eq!( + super::WasmPolicy::default(), + super::WasmPolicy::EnabledUnmetered + ); + // NapiWebAssemblyPolicy in v8/src/internal/napi_wasm_policy.h. + assert_eq!(super::WasmPolicy::Restricted.bridge_code(), 0); + assert_eq!(super::WasmPolicy::EnabledUnmetered.bridge_code(), 1); + + let mut store = Store::default(); + let module = compile_wat( + &store, + r#"(module + (import "napi" "napi_get_undefined" (func (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 512)) + )"#, + ); + for policy in [ + super::WasmPolicy::Restricted, + super::WasmPolicy::EnabledUnmetered, + ] { + let ctx = NapiCtx::builder().webassembly(policy).build(); + assert_eq!(ctx.webassembly_policy(), policy); + let hooks = ctx.runtime_hooks(); + // Each store (a guest's and each of its WASIX threads') gets the + // context's policy. + for _ in 0..2 { + let (_imports, state) = hooks + .additional_imports(&module, &mut store.as_store_mut()) + .expect("imports register"); + let session = state.session.expect("an N-API module has a session"); + let func_env = session + .inner + .func_env + .lock() + .unwrap() + .clone() + .expect("imports made the function env"); + assert_eq!(func_env.as_ref(&store).webassembly, policy); + } + } + } + #[test] fn configure_instance_rejects_missing_state() { let mut store = Store::default(); diff --git a/src/env.rs b/src/env.rs index a747f7e241..11127e4b4d 100644 --- a/src/env.rs +++ b/src/env.rs @@ -117,6 +117,9 @@ pub(crate) struct NapiEnv { pub(crate) budget: Arc, /// Per-app cap on live V8 isolates (`None` = unlimited). pub(crate) max_envs: Option, + /// The embedder's policy for V8 `WebAssembly` in the envs this store + /// creates. + pub(crate) webassembly: crate::WasmPolicy, env_registry: Arc>, host_stopped: Arc, /// Heap charge per live V8 env, keyed by guest env id, so teardown releases @@ -205,6 +208,7 @@ impl NapiEnv { Self { budget, max_envs, + webassembly: crate::WasmPolicy::default(), env_registry, host_stopped, env_heap_charges: HashMap::new(), diff --git a/src/guest/napi.rs b/src/guest/napi.rs index 9679eebdce..61e4c85ee7 100644 --- a/src/guest/napi.rs +++ b/src/guest/napi.rs @@ -37,6 +37,7 @@ fn guest_napi_wasm_init_env(mut env: FunctionEnvMut) -> i32 { }; let guest_heap_ctx = guest_heap_alloc_ctx(&env); + let webassembly_policy = env.data().webassembly.bridge_code(); let mut snapi_env_state: SnapiEnv = std::ptr::null_mut(); let status = if reservation.clamped { unsafe { @@ -49,11 +50,19 @@ fn guest_napi_wasm_init_env(mut env: FunctionEnvMut) -> i32 { reservation.code_range, 0, guest_heap_ctx, + webassembly_policy, &mut snapi_env_state, ) } } else { - unsafe { snapi_bridge_unofficial_create_env(8, guest_heap_ctx, &mut snapi_env_state) } + unsafe { + snapi_bridge_unofficial_create_env( + 8, + guest_heap_ctx, + webassembly_policy, + &mut snapi_env_state, + ) + } }; if status != 0 || snapi_env_state.is_null() { env.data().abort_isolate(&reservation); @@ -250,6 +259,7 @@ fn guest_unofficial_napi_create_env( }; let guest_heap_ctx = guest_heap_alloc_ctx(&env); + let webassembly_policy = env.data().webassembly.bridge_code(); let mut snapi_env_state: SnapiEnv = std::ptr::null_mut(); let status = unsafe { snapi_bridge_unofficial_create_env_with_options( @@ -261,6 +271,7 @@ fn guest_unofficial_napi_create_env( reservation.code_range, stack_limit, guest_heap_ctx, + webassembly_policy, &mut snapi_env_state, ) }; diff --git a/src/guest/napi_js.rs b/src/guest/napi_js.rs index 5129905497..f7667e7a3c 100644 --- a/src/guest/napi_js.rs +++ b/src/guest/napi_js.rs @@ -44,9 +44,16 @@ fn guest_napi_wasm_init_env(mut env: FunctionEnvMut) -> i32 { return env_id as i32; } + let webassembly_policy = env.data().webassembly.bridge_code(); let mut snapi_env_state: SnapiEnv = std::ptr::null_mut(); - let status = - unsafe { snapi_bridge_unofficial_create_env(8, std::ptr::null(), &mut snapi_env_state) }; + let status = unsafe { + snapi_bridge_unofficial_create_env( + 8, + std::ptr::null(), + webassembly_policy, + &mut snapi_env_state, + ) + }; if status != 0 || snapi_env_state.is_null() { return 0; } @@ -522,6 +529,7 @@ fn guest_unofficial_napi_create_env( (0, 0, 0, 0, 0, 0) }; + let webassembly_policy = env.data().webassembly.bridge_code(); let mut snapi_env_state: SnapiEnv = std::ptr::null_mut(); let status = unsafe { snapi_bridge_unofficial_create_env_with_options( @@ -533,6 +541,7 @@ fn guest_unofficial_napi_create_env( code_range_size_in_bytes, stack_limit, std::ptr::null(), + webassembly_policy, &mut snapi_env_state, ) }; diff --git a/src/guest_heap.rs b/src/guest_heap.rs index 81ec71c378..35cb51936b 100644 --- a/src/guest_heap.rs +++ b/src/guest_heap.rs @@ -823,6 +823,28 @@ mod tests { (memory, heap) } + /// The bridge owns a guest-heap context once it is handed over, so a + /// policy it refuses must still release it, exactly once, and create no + /// environment. + #[test] + fn unknown_webassembly_policy_is_refused_and_releases_the_heap_ctx() { + let mut store = Store::default(); + let (_memory, heap) = shared_heap(&mut store, ResourceBudget::unlimited()); + let weak_before = Arc::weak_count(&heap); + let ctx = heap.make_alloc_ctx(); + assert_eq!(Arc::weak_count(&heap), weak_before + 1); + + let unknown_policy = crate::WasmPolicy::EnabledUnmetered.bridge_code() + 1; + let mut env: crate::snapi::SnapiEnv = std::ptr::null_mut(); + // napi_invalid_arg, refused before the process-wide runtime is used. + let status = unsafe { + crate::snapi::snapi_bridge_unofficial_create_env(8, ctx, unknown_policy, &mut env) + }; + assert_eq!(status, 1); + assert!(env.is_null()); + assert_eq!(Arc::weak_count(&heap), weak_before); + } + #[test] fn chunk_node_budget_scales_with_chunk_size() { // What this pins: `OffsetAllocator::new` sizes every chunk for 128Ki diff --git a/src/lib.rs b/src/lib.rs index 1ef187fddb..f6a04e7eb3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,7 +26,7 @@ pub use budget::{ }; pub use ctx::{ NapiCtx, NapiCtxBuilder, NapiInstantiationState, NapiLimits, NapiRuntimeControl, - NapiRuntimeHooks, NapiSession, + NapiRuntimeHooks, NapiSession, WasmPolicy, }; use enum_iterator::Sequence; pub(crate) use env::NapiEnv; diff --git a/src/napi_bridge_init.cc b/src/napi_bridge_init.cc index df5730ca66..ea554fc69c 100644 --- a/src/napi_bridge_init.cc +++ b/src/napi_bridge_init.cc @@ -28,8 +28,22 @@ #include "unofficial_napi.h" #include "edge_v8_platform.h" #include "internal/napi_v8_env.h" +#include "internal/napi_wasm_policy.h" #include "internal/unofficial_napi_bridge.h" +// Provider-private (v8/src/unofficial_napi.cc): unofficial_napi_create_env +// with the embedder's WebAssembly policy. Never imported by guests. +extern "C" napi_status NAPI_CDECL snapi_private_create_env( + int32_t module_api_version, + const unofficial_napi_env_create_options* options, + uint32_t webassembly_policy, + napi_env* env_out, + unofficial_napi_env_owner* owner_out); + +// The Rust side encodes `WasmPolicy` with these values (src/ctx.rs). +static_assert(static_cast(NapiWebAssemblyPolicy::kRestricted) == 0); +static_assert(static_cast(NapiWebAssemblyPolicy::kAllowUnmetered) == 1); + namespace { // Only shared registry/message ownership lives under this lock. Never enter @@ -3351,8 +3365,11 @@ extern "C" int snapi_bridge_create_function(SnapiEnvState* env_state, const char return napi_ok; } +// `webassembly_policy` is a NapiWebAssemblyPolicy. The guest-heap context is +// the provider's from here on, also when the policy is refused. extern "C" int snapi_bridge_unofficial_create_env(int32_t module_api_version, const void* guest_heap_ctx, + uint32_t webassembly_policy, SnapiEnvState** env_out) { napi_env env = nullptr; unofficial_napi_env_owner owner = nullptr; @@ -3363,9 +3380,11 @@ extern "C" int snapi_bridge_unofficial_create_env(int32_t module_api_version, options.version = UNOFFICIAL_NAPI_ENV_CREATE_OPTIONS_VERSION; options.guest_heap = reinterpret_cast( const_cast(guest_heap_ctx)); - s = unofficial_napi_create_env(module_api_version, &options, &env, &owner); + s = snapi_private_create_env(module_api_version, &options, + webassembly_policy, &env, &owner); } else { - s = unofficial_napi_create_env(module_api_version, nullptr, &env, &owner); + s = snapi_private_create_env(module_api_version, nullptr, + webassembly_policy, &env, &owner); } if (s != napi_ok) return s; @@ -3396,6 +3415,7 @@ extern "C" int snapi_bridge_unofficial_create_env_with_options( uint32_t code_range_size_in_bytes, uint32_t /*stack_limit*/, const void* guest_heap_ctx, + uint32_t webassembly_policy, SnapiEnvState** env_out) { unofficial_napi_env_create_options options{}; const bool has_options = @@ -3421,8 +3441,9 @@ extern "C" int snapi_bridge_unofficial_create_env_with_options( const_cast(guest_heap_ctx)); napi_env env = nullptr; unofficial_napi_env_owner owner = nullptr; - napi_status s = unofficial_napi_create_env( - module_api_version, has_options ? &options : nullptr, &env, &owner); + napi_status s = snapi_private_create_env( + module_api_version, has_options ? &options : nullptr, webassembly_policy, + &env, &owner); if (s != napi_ok) return s; SnapiEnvState* state = NewAgentWithPrincipalEnv(env, owner); diff --git a/src/snapi.rs b/src/snapi.rs index 04f1f9e129..adeba28d1c 100644 --- a/src/snapi.rs +++ b/src/snapi.rs @@ -62,11 +62,15 @@ unsafe extern "C" { engine_flags: *const c_char, engine_flags_length: u32, ) -> i32; + /// `webassembly_policy` is [`crate::WasmPolicy::bridge_code`]. The bridge + /// owns `guest_heap_ctx` from here on, also when it refuses the call. pub fn snapi_bridge_unofficial_create_env( module_api_version: i32, guest_heap_ctx: *const core::ffi::c_void, + webassembly_policy: u32, env_out: *mut SnapiEnv, ) -> i32; + /// `webassembly_policy` is [`crate::WasmPolicy::bridge_code`]. pub fn snapi_bridge_unofficial_create_env_with_options( module_api_version: i32, total_memory: u64, @@ -76,6 +80,7 @@ unsafe extern "C" { code_range_size_in_bytes: u32, stack_limit: u32, guest_heap_ctx: *const core::ffi::c_void, + webassembly_policy: u32, env_out: *mut SnapiEnv, ) -> i32; pub fn snapi_bridge_unofficial_release_env(env: SnapiEnv) -> i32; diff --git a/src/snapi_js.rs b/src/snapi_js.rs index db789a3c19..e8fc78f606 100644 --- a/src/snapi_js.rs +++ b/src/snapi_js.rs @@ -2851,6 +2851,7 @@ pub unsafe extern "C" fn snapi_bridge_init() -> i32 { pub unsafe extern "C" fn snapi_bridge_unofficial_create_env( _version: i32, _guest_heap_ctx: *const c_void, + webassembly_policy: u32, out: *mut SnapiEnv, ) -> i32 { let runtime_configured = RUNTIME_ENGINE_FLAGS @@ -2859,6 +2860,18 @@ pub unsafe extern "C" fn snapi_bridge_unofficial_create_env( if out.is_null() || !runtime_configured { return NAPI_INVALID_ARG; } + // Guest JavaScript runs in a host realm here, with the host's own + // WebAssembly, which this backend cannot take away: refuse a restricted + // env rather than create one that is not restricted. + if webassembly_policy == crate::WasmPolicy::Restricted.bridge_code() { + wasmer_napi_console_error( + "the host-JS N-API backend cannot restrict WebAssembly (WasmPolicy::Restricted)", + ); + return NAPI_GENERIC_FAILURE; + } + if webassembly_policy != crate::WasmPolicy::EnabledUnmetered.bridge_code() { + return NAPI_INVALID_ARG; + } if !wasmer_napi_can_create_global_context() { wasmer_napi_console_error( "Native Worker realm lease already consumed; start a fresh Worker", @@ -2881,9 +2894,10 @@ pub unsafe extern "C" fn snapi_bridge_unofficial_create_env_with_options( _code: u32, _stack: u32, guest_heap_ctx: *const c_void, + webassembly_policy: u32, out: *mut SnapiEnv, ) -> i32 { - unsafe { snapi_bridge_unofficial_create_env(version, guest_heap_ctx, out) } + unsafe { snapi_bridge_unofficial_create_env(version, guest_heap_ctx, webassembly_policy, out) } } #[unsafe(no_mangle)] diff --git a/tests/concurrent_envs.rs b/tests/concurrent_envs.rs index 7bb2f68688..b927ef4757 100644 --- a/tests/concurrent_envs.rs +++ b/tests/concurrent_envs.rs @@ -339,9 +339,11 @@ fn a_message_has_exactly_one_consumer() { unsafe extern "C" { fn snapi_bridge_unofficial_configure_runtime(flags: *const c_char, length: u32) -> i32; + /// `webassembly_policy` 1 is `WasmPolicy::EnabledUnmetered`. fn snapi_bridge_unofficial_create_env( module_api_version: i32, guest_heap_ctx: *const c_void, + webassembly_policy: u32, env_out: *mut *mut c_void, ) -> i32; fn snapi_bridge_unofficial_release_env(env: *mut c_void) -> i32; @@ -376,7 +378,7 @@ fn bridge_call_throughput() { thread::spawn(move || unsafe { let mut env: *mut c_void = std::ptr::null_mut(); assert_eq!( - snapi_bridge_unofficial_create_env(8, std::ptr::null(), &mut env), + snapi_bridge_unofficial_create_env(8, std::ptr::null(), 1, &mut env), 0 ); let mut id = 0u32; @@ -463,7 +465,7 @@ fn foreign_threads_may_only_terminate_an_env() { ); let mut env: *mut c_void = std::ptr::null_mut(); assert_eq!( - snapi_bridge_unofficial_create_env(8, std::ptr::null(), &mut env), + snapi_bridge_unofficial_create_env(8, std::ptr::null(), 1, &mut env), 0 ); let mut global = 0u32; diff --git a/tests/programs/test_js_asmjs_plain.c b/tests/programs/test_js_asmjs_plain.c new file mode 100644 index 0000000000..944d38cfaa --- /dev/null +++ b/tests/programs/test_js_asmjs_plain.c @@ -0,0 +1,67 @@ +#include +#include + +#include "napi_test_helpers.h" + +// V8 before 15.2 translated validated asm.js modules to WebAssembly and +// compiled them with its wasm pipeline, without asking the embedder's wasm +// code-generation callback. V8 15.2 removed that translation, which +// WasmPolicy::Restricted relies on (v8/src/internal/napi_wasm_policy.h). An +// asm.js module must therefore run as ordinary JavaScript under every policy. +// +// The probe tells the two apart by inspecting the asm.js function's stack frame +// from a foreign function it calls: in sloppy-mode JavaScript, +// CallSite.getFunction() returns the very function object that is running; a +// frame of translated asm.js code is a wasm frame and never yields it. +static const char kScript[] = + "(function () {\n" + " var observed = 'no frame';\n" + " function probe() {\n" + " var saved = Error.prepareStackTrace;\n" + " Error.prepareStackTrace = function (_error, frames) { return frames; };\n" + " var frames = new Error().stack;\n" + " Error.prepareStackTrace = saved;\n" + " for (var i = 0; i < frames.length; i++) {\n" + " if (frames[i].getFunctionName() === 'asmAdd') {\n" + " observed = frames[i].getFunction();\n" + " break;\n" + " }\n" + " }\n" + " }\n" + " function AsmModule(stdlib, foreign) {\n" + " 'use asm';\n" + " var probe = foreign.probe;\n" + " function asmAdd(a, b) {\n" + " a = a | 0;\n" + " b = b | 0;\n" + " probe();\n" + " return (a + b) | 0;\n" + " }\n" + " return { asmAdd: asmAdd };\n" + " }\n" + " var exports = AsmModule(globalThis, { probe: probe });\n" + " var sum = exports.asmAdd(40, 2);\n" + " if (sum !== 42) return 'wrong result ' + sum;\n" + " if (observed === exports.asmAdd) return 'plain';\n" + " return 'translated (frame function: ' + typeof observed + ')';\n" + "})()"; + +int main(void) { + napi_env env = napi_wasm_init_env(); + CHECK_OR_FAIL(env != NULL, "napi_wasm_init_env returned NULL"); + + napi_value source; + NAPI_CALL(env, napi_create_string_utf8(env, kScript, NAPI_AUTO_LENGTH, &source)); + napi_value result; + NAPI_CALL(env, napi_run_script(env, source, &result)); + + char text[128] = {0}; + size_t length = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, result, text, sizeof(text), &length)); + if (strcmp(text, "plain") != 0) { + printf("FAIL: asm.js module did not run as plain JavaScript: %s\n", text); + return 1; + } + puts("ASMJS_RUNS_AS_PLAIN_JS_OK"); + return 0; +} diff --git a/tests/programs/test_js_wasm_enabled.c b/tests/programs/test_js_wasm_enabled.c new file mode 100644 index 0000000000..bbacc4375f --- /dev/null +++ b/tests/programs/test_js_wasm_enabled.c @@ -0,0 +1,114 @@ +#include +#include +#include + +#include "napi_test_helpers.h" +#include "node_api.h" +#include "unofficial_napi.h" + +// Runs under WasmPolicy::EnabledUnmetered, the default: V8's WebAssembly +// works in the env's own realm and in realms that allow wasm code generation, +// and a realm made with allow_code_gen_wasm = false (vm's +// codeGeneration.wasm) refuses to compile. + +// (module (func (export "add") (param i32 i32) (result i32) +// local.get 0 local.get 1 i32.add)) +#define ADD_MODULE_BYTES \ + "new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, " \ + "0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, " \ + "0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, 0x01, " \ + "0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b])" + +static const char kRunModule[] = + "(function () {\n" + " if (typeof WebAssembly !== 'object') return 'WebAssembly is ' +" + " typeof WebAssembly;\n" + " var bytes = " ADD_MODULE_BYTES ";\n" + " if (!WebAssembly.validate(bytes)) return 'module did not validate';\n" + " try {\n" + " var instance = new WebAssembly.Instance(new WebAssembly.Module(bytes));\n" + " var sum = instance.exports.add(40, 2);\n" + " if (sum !== 42) return 'wrong result ' + sum;\n" + " var memory = new WebAssembly.Memory({ initial: 1, maximum: 2 });\n" + " if (memory.buffer.byteLength !== 65536) return 'wrong memory size';\n" + " if (memory.grow(1) !== 1) return 'memory did not grow';\n" + " } catch (e) {\n" + " return e instanceof WebAssembly.CompileError ? 'refused' : String(e);\n" + " }\n" + " return 'ok';\n" + "})()"; + +// Runs `source` in `realm`, or in the env's own realm when it is NULL. +static napi_status RunIn(napi_env env, + unofficial_napi_realm realm, + const char* source, + napi_value* result) { + napi_value text = NULL; + napi_value filename = NULL; + napi_status status = napi_create_string_utf8(env, source, NAPI_AUTO_LENGTH, &text); + if (status != napi_ok) return status; + status = napi_create_string_utf8(env, "wasm_enabled.js", NAPI_AUTO_LENGTH, &filename); + if (status != napi_ok) return status; + const unofficial_napi_js_source script = unofficial_napi_js_source_from_text(text); + return unofficial_napi_run_script( + env, realm, &script, filename, 0, 0, -1, true, false, false, NULL, result); +} + +static bool IsText(napi_env env, napi_value value, const char* expected, const char* what) { + char text[256] = {0}; + size_t length = 0; + if (napi_get_value_string_utf8(env, value, text, sizeof(text), &length) != napi_ok) { + printf("FAIL: %s did not return a string\n", what); + return false; + } + if (strcmp(text, expected) != 0) { + printf("FAIL: %s: expected '%s', got '%s'\n", what, expected, text); + return false; + } + return true; +} + +// Makes a realm with or without wasm code generation, with a sandbox (as +// vm.createContext(sandbox) does) or a fresh global. +static napi_status MakeRealm(napi_env env, + bool with_sandbox, + bool allow_code_gen_wasm, + unofficial_napi_realm* realm_out) { + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + options.allow_code_gen_wasm = allow_code_gen_wasm; + if (with_sandbox) { + napi_value sandbox = NULL; + napi_status status = napi_create_object(env, &sandbox); + if (status != napi_ok) return status; + options.sandbox_or_null = sandbox; + } + return unofficial_napi_create_realm(env, &options, realm_out, NULL); +} + +int main(void) { + napi_env env = napi_wasm_init_env(); + CHECK_OR_FAIL(env != NULL, "napi_wasm_init_env returned NULL"); + napi_value result = NULL; + + NAPI_CALL(env, RunIn(env, NULL, kRunModule, &result)); + CHECK_OR_FAIL(IsText(env, result, "ok", "env realm"), + "V8 WebAssembly is not usable in the env's own realm"); + + for (int with_sandbox = 0; with_sandbox <= 1; with_sandbox++) { + unofficial_napi_realm allowed = NULL; + NAPI_CALL(env, MakeRealm(env, with_sandbox, true, &allowed)); + NAPI_CALL(env, RunIn(env, allowed, kRunModule, &result)); + CHECK_OR_FAIL(IsText(env, result, "ok", "realm allowing wasm code generation"), + "V8 WebAssembly is not usable in a realm that allows it"); + + unofficial_napi_realm refused = NULL; + NAPI_CALL(env, MakeRealm(env, with_sandbox, false, &refused)); + NAPI_CALL(env, RunIn(env, refused, kRunModule, &result)); + CHECK_OR_FAIL(IsText(env, result, "refused", "realm refusing wasm code generation"), + "a realm compiled wasm although allow_code_gen_wasm is false"); + } + + puts("JS_WASM_ENABLED_OK"); + return 0; +} diff --git a/tests/programs/test_js_wasm_restricted.c b/tests/programs/test_js_wasm_restricted.c new file mode 100644 index 0000000000..a25fb22635 --- /dev/null +++ b/tests/programs/test_js_wasm_restricted.c @@ -0,0 +1,92 @@ +#include +#include +#include + +#include "napi_test_helpers.h" +#include "node_api.h" +#include "unofficial_napi.h" + +// Runs under WasmPolicy::Restricted: no realm of the env has V8's +// WebAssembly, also realms that ask for wasm code generation. + +// Runs `source` in `realm`, or in the env's own realm when it is NULL. +static napi_status RunIn(napi_env env, + unofficial_napi_realm realm, + const char* source, + napi_value* result) { + napi_value text = NULL; + napi_value filename = NULL; + napi_status status = napi_create_string_utf8(env, source, NAPI_AUTO_LENGTH, &text); + if (status != napi_ok) return status; + status = napi_create_string_utf8(env, "wasm_restricted.js", NAPI_AUTO_LENGTH, &filename); + if (status != napi_ok) return status; + const unofficial_napi_js_source script = unofficial_napi_js_source_from_text(text); + return unofficial_napi_run_script( + env, realm, &script, filename, 0, 0, -1, true, false, false, NULL, result); +} + +static bool IsText(napi_env env, napi_value value, const char* expected, const char* what) { + char text[256] = {0}; + size_t length = 0; + if (napi_get_value_string_utf8(env, value, text, sizeof(text), &length) != napi_ok) { + printf("FAIL: %s did not return a string\n", what); + return false; + } + if (strcmp(text, expected) != 0) { + printf("FAIL: %s: expected '%s', got '%s'\n", what, expected, text); + return false; + } + return true; +} + +// Every own global whose name starts with "WebAssembly", joined. +static const char kWasmGlobals[] = + "Object.getOwnPropertyNames(globalThis)" + ".filter(function (name) { return /^WebAssembly/.test(name); }).join()"; + +// A ShadowRealm gets a fresh global from V8, not from the provider. V8 does +// not ship ShadowRealm; this fails when it does, so that path is handled then. +static const char kShadowRealm[] = + "typeof ShadowRealm === 'undefined' ? 'undefined' : " + "new ShadowRealm().evaluate('typeof WebAssembly')"; + +int main(void) { + napi_env env = napi_wasm_init_env(); + CHECK_OR_FAIL(env != NULL, "napi_wasm_init_env returned NULL"); + napi_value result = NULL; + + NAPI_CALL(env, RunIn(env, NULL, "typeof WebAssembly", &result)); + CHECK_OR_FAIL(IsText(env, result, "undefined", "env realm"), + "the env's own realm has WebAssembly"); + NAPI_CALL(env, RunIn(env, NULL, kWasmGlobals, &result)); + CHECK_OR_FAIL(IsText(env, result, "", "env realm globals"), + "the env's own realm has a WebAssembly global"); + NAPI_CALL(env, RunIn(env, NULL, kShadowRealm, &result)); + CHECK_OR_FAIL(IsText(env, result, "undefined", "ShadowRealm"), + "a ShadowRealm has WebAssembly"); + + // A realm with a fresh global that allows wasm code generation. + unofficial_napi_realm realm = NULL; + NAPI_CALL(env, unofficial_napi_create_realm(env, NULL, &realm, NULL)); + CHECK_OR_FAIL(realm != NULL, "create_realm did not return a realm"); + NAPI_CALL(env, RunIn(env, realm, "typeof WebAssembly", &result)); + CHECK_OR_FAIL(IsText(env, result, "undefined", "fresh realm"), + "a realm made with default options has WebAssembly"); + + // A sandbox realm, as vm.createContext(sandbox) makes. + napi_value sandbox = NULL; + NAPI_CALL(env, napi_create_object(env, &sandbox)); + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + options.sandbox_or_null = sandbox; + options.allow_code_gen_wasm = true; + unofficial_napi_realm sandbox_realm = NULL; + NAPI_CALL(env, unofficial_napi_create_realm(env, &options, &sandbox_realm, NULL)); + CHECK_OR_FAIL(sandbox_realm != NULL, "create_realm did not return the sandbox realm"); + NAPI_CALL(env, RunIn(env, sandbox_realm, "typeof WebAssembly", &result)); + CHECK_OR_FAIL(IsText(env, result, "undefined", "sandbox realm"), + "a sandbox realm has WebAssembly"); + + puts("JS_WASM_RESTRICTED_OK"); + return 0; +} diff --git a/tests/runners/test_21_general.cc b/tests/runners/test_21_general.cc index 6db26c6d1b..cb5c9ff4c1 100644 --- a/tests/runners/test_21_general.cc +++ b/tests/runners/test_21_general.cc @@ -25,6 +25,19 @@ extern "C" void napi_host_guest_heap_release(void* ctx) { g_last_released_guest_heap_ctx = ctx; } +#if defined(NAPI_TEST_ENGINE_V8) +#include + +// Provider-private env creation with the embedder's WebAssembly policy +// (NapiWebAssemblyPolicy: 0 restricted, 1 unmetered). +extern "C" napi_status snapi_private_create_env( + int32_t module_api_version, + const unofficial_napi_env_create_options* options, + uint32_t webassembly_policy, + napi_env* env_out, + unofficial_napi_env_owner* owner_out); +#endif + class Test21General : public FixtureTestBase {}; namespace { @@ -142,6 +155,142 @@ TEST_F(Test21General, FullEnvironmentOptionsTransferGuestHeapOwnershipBeforeOutp EXPECT_EQ(g_last_released_guest_heap_ctx, options.guest_heap); } +#if defined(NAPI_TEST_ENGINE_V8) +namespace { + +constexpr uint32_t kWebAssemblyRestricted = 0; +constexpr uint32_t kWebAssemblyAllowUnmetered = 1; + +// Compiles (module (func (export "add") (param i32 i32) (result i32) +// local.get 0 local.get 1 i32.add)) with the JS API, which asks the isolate's +// AllowWasmCodeGenerationCallback. (V8's C++ WasmModuleObject::Compile does +// not: it serves ESM integration, and only native embedder code reaches it.) +constexpr char kCompileAddModule[] = + "new WebAssembly.Module(new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, " + "0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, " + "0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, " + "0x00, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, " + "0x0b])) instanceof WebAssembly.Module"; + +std::string RunToString(napi_env env, const char* script) { + napi_value source = nullptr; + napi_value result = nullptr; + if (napi_create_string_utf8(env, script, NAPI_AUTO_LENGTH, &source) != napi_ok || + napi_run_script(env, source, &result) != napi_ok) { + return "