Repository navigation
Add an embedder WebAssembly policy for guest environments - #160
Conversation
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 <noreply@anthropic.com>
syrusakbary
left a comment
There was a problem hiding this comment.
The 21 native V8 tests and three WASIX smoke tests passed locally. The message-policy finding is from source inspection.
| scope->agent->webassembly_restricted = restrict_webassembly; | ||
| // Installed under every policy: it refuses all wasm code of a restricted | ||
| // isolate and otherwise honors each realm's allow_code_gen_wasm. | ||
| isolate->SetAllowWasmCodeGenerationCallback(NapiV8AllowWasmCodeGeneration); |
There was a problem hiding this comment.
[P1] Enforce the WebAssembly policy on incoming messages
Cross-environment message deserialization can restore compiled Wasm modules and growable shared Wasm memory from an enabled sender into a restricted environment. V8 restores those objects without consulting the code-generation callback. Check the receiving environment’s policy before accepting Wasm payloads in DeserializeTransferredClone.
There was a problem hiding this comment.
Fixed in 6e4df7f. V8 has no API that tells which shared buffer backs a WebAssembly.Memory, so each message now records whether its sender allows WebAssembly. DeserializeTransferredClone in a restricted env refuses any wasm module, and refuses shared memory from a sender that allows WebAssembly, before V8 reads the message. The error is recorded as N-API's pending exception. Envs of one context share their policy, so messages between them are unaffected. New native test: Test21General.RestrictedEnvironmentsRefuseWebAssemblyMessages covers modules, shared memories and shared buffers in both directions.
| /// Runs `program` under `policy` and checks that it printed `marker` and | ||
| /// exited cleanly. | ||
| fn assert_guest_passes(program: &str, policy: WasmPolicy, marker: &str) { | ||
| let wasm = build_wasix_test(program); |
There was a problem hiding this comment.
[P2] Prevent concurrent builds of the same WASIX fixture
The per-context test and the individual policy tests build the same guest fixtures in parallel. The compiler rewrites the shared output in place, so one test can read a partial file after its own build has returned. Paired cold builds produced zero-byte and partial files. Build each fixture once per test process or publish the output atomically.
There was a problem hiding this comment.
Fixed in 6e4df7f, in two places. build_wasix_test in tests/common/mod.rs builds each fixture once per test process, holding a lock across the build. build-test-wasix.sh now compiles into a per-process temp file and renames it into place. Cold-built three times with the policy tests in parallel, and ran two concurrent builds of one fixture: both succeeded, and the module was complete.
| compile wasm in all of them: | ||
|
|
||
| ```sh | ||
| ./target/release/napi_wasmer --restricted-webassembly guest.wasm |
There was a problem hiding this comment.
[P3] Put the Wasm file first in the CLI example
The CLI consumes the first argument as the input path. I verified that the documented command exits while trying to open --restricted-webassembly as a file. napi_wasmer guest.wasm --restricted-webassembly works.
There was a problem hiding this comment.
Fixed in 6e4df7f: the example is now napi_wasmer guest.wasm --restricted-webassembly, and the doc says options follow the module path.
* A restricted env refuses messages that carry WebAssembly. V8 restores a compiled WebAssembly.Module, and a shared WebAssembly.Memory over a shared buffer, without asking the code-generation callback, and no V8 API tells which shared buffer backs a memory. Each message now records whether its sender allows WebAssembly. A restricted receiver refuses any wasm module, and the shared memory of such a sender, before V8 reads the message, and reports it as N-API's pending exception. Envs of one context share their policy, so messages between them are unaffected. Native test_21 covers modules, shared memories and shared buffers between restricted and unrestricted envs. * WASIX fixtures are built once per test process, under a lock, and build-test-wasix.sh renames a finished module into place, so parallel tests and concurrent builds never read a partial file. * docs/cli.md puts the module path before --restricted-webassembly, as the CLI requires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| (!wasm_modules.empty() || | ||
| (sender_allows_webassembly && !shared_array_buffers.empty()))) { | ||
| // Recorded as N-API's pending exception, without entering JS. | ||
| napi_v8_set_last_exception( |
There was a problem hiding this comment.
[P3] Preserve termination when rejecting a message
If a policy rejection occurs while the receiver is terminating, this call can replace its pending termination marker with an ordinary error. Canceling termination only clears marked exceptions, so the policy error can remain pending after the environment resumes. In unofficial_napi_message_take, check NAPI_V8_RETURN_IF_TERMINATING(env) after taking ownership of the message and before deserializing it.
There was a problem hiding this comment.
Fixed in 1ca68c4: unofficial_napi_message_take now runs NAPI_V8_RETURN_IF_TERMINATING(env) after taking ownership of the message and before deserializing. New native test Test21General.RefusedMessageKeepsTheTermination terminates a restricted env, has it refuse a module message, cancels the termination, and checks that nothing is left pending. It fails without the check. The full native suite passes (416 tests).
unofficial_napi_message_take now returns early while its env is terminating, after taking ownership of the message. A refused WebAssembly message (or a deserializer error) would otherwise replace the termination with an ordinary error, which stays pending after the termination is cancelled. test_21 covers it; it fails without the check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Part of moving Wasmer Edge onto napi
main(the "WebAssembly policy and metering" block of #84). This PR is the policy half. The metering half needs the per-instance V8 lane and follows separately.Why
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. Today every guest gets WebAssembly, and an embedder cannot take it away.
What changes
NapiCtxBuilder::webassembly(WasmPolicy)EnabledUnmetered(default): today's behavior.Restricted: noWebAssemblyglobal in the env's own realm or in any realm made in it (vmcontexts with or without a sandbox), and V8 refuses wasm code generation in every context of the isolate, including contexts the provider did not create.#[non_exhaustive], soEnabledMeteredcan be added later.NapiCtx, copied into every store's env (WASIX worker threads included) and passed to the bridge, which calls the provider-privatesnapi_private_create_env. It is not an env-create option because that struct is also the guest's wasm32 ABI, so guests cannot set or observe it. An unknown value is refused after the guest heap is released.unofficial_napi_create_envkeeps its signature and behavior.AllowWasmCodeGenerationCallbackon every provider isolate. It refuses all wasm in a restricted agent. Otherwise it honors the realm'sallow_code_gen_wasm(vm'scodeGeneration.wasm), which was accepted and ignored until now. That second part changes behavior under the default policy.--no-validate-asmbecause asm.js translation bypassed the callback. V8 15.2 removed asm.js translation, so on 15.9 asm.js always runs as plain JavaScript and cannot reach wasm code generation under any policy. Astatic_assertrefuses V8 older than 15.2 rather than reopen that path.WebAssembly, which this backend cannot remove, so it refuses to create aRestrictedenv instead of silently ignoring the policy.napi_wasmer --restricted-webassembly(documented indocs/cli.md).docs/realms.mdandinclude/unofficial_napi.hnow say V8 honorsallow_code_gen_wasm.The enforcement is agent-based rather than #84's per-context embedder slot:
mainalready maps each isolate to itsnapi_agent__, and each realm to a record that now carriesallow_code_gen_wasm.Not in this PR (metering half of the block)
WasmPolicy::EnabledMetered,WasmLimits),try_charge_softandNapiLimitExceeded. In feat(napi): consolidate managed Edge V8 and metered WebAssembly #84 these charge the V8 lane bound to the current thread, so they need the lane first.WasmEngineLimits/configure_wasm_engine. feat(napi): consolidate managed Edge V8 and metered WebAssembly #84 designed them around the lane and the process code budget, so they move with metering.edge-napi-webassembly-metered.Testing
On macOS arm64 against prebuilt V8 15.9.111.1:
main). Newtest_21cases cover both policies, realms that allow or refuse wasm code generation, a context the provider did not make (it keeps V8's ownWebAssemblyglobal, so only the callback can refuse), and an unknown policy releasing the guest heap exactly once.cargo test --lib: 66 passed, including the policy reaching every store env and a refused policy releasing the guest-heap context.concurrent_envs,concurrent_stores,foreground_task_waker,guest_callbacks,guest_c_strings,guest_memory,guest_memory_pressureandguest_lazy_propertiesall pass.v8_host_control: the restricted policy across all realms, the default policy honoringallow_code_gen_wasm, the policy staying per context within one process, and asm.js running as plain JS under both policies.tests/programs/manifest.jsonguests pass through the CLI under both the default policy and--restricted-webassembly.wasm32-unknown-unknown --features js.Two suites that CI does not run fail on
mainwithout this change, and the same way here:v8_host_control::isolate_reservations_are_released_when_the_guest_exits(an isolate stays charged after the guest exits) and the native half ofmanifest_tests(run_script_test's two-env check, plus a stale V8 version intests/build-test-native.sh). They are being fixed separately.🤖 Generated with Claude Code