Skip to content

Add an embedder WebAssembly policy for guest environments - #160

Merged
syrusakbary merged 3 commits into
mainfrom
feat/wasm-policy
Nov 17, 2026
Merged

syrusakbary merged 3 commits into
mainfrom
feat/wasm-policy

Conversation

@syrusakbary

Copy link
Copy Markdown
Member

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: no WebAssembly global in the env's own realm or in any realm made in it (vm contexts with or without a sandbox), and V8 refuses wasm code generation in every context of the isolate, including contexts the provider did not create.
    • The enum is #[non_exhaustive], so EnabledMetered can be added later.
  • Plumbing. The policy is stored per NapiCtx, 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 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_env keeps its signature and behavior.
  • AllowWasmCodeGenerationCallback on every provider isolate. It refuses all wasm in a restricted agent. Otherwise it honors the realm's allow_code_gen_wasm (vm's codeGeneration.wasm), which was accepted and ignored until now. That second part changes behavior under the default policy.
  • asm.js. feat(napi): consolidate managed Edge V8 and metered WebAssembly #84 passed --no-validate-asm because 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. A static_assert refuses V8 older than 15.2 rather than reopen that path.
  • Host-JS backend. Guest JS runs there with the host's own WebAssembly, which this backend cannot remove, so it refuses to create a Restricted env instead of silently ignoring the policy.
  • CLI. napi_wasmer --restricted-webassembly (documented in docs/cli.md). docs/realms.md and include/unofficial_napi.h now say V8 honors allow_code_gen_wasm.

The enforcement is agent-based rather than #84's per-context embedder slot: main already maps each isolate to its napi_agent__, and each realm to a record that now carries allow_code_gen_wasm.

Not in this PR (metering half of the block)

Testing

On macOS arm64 against prebuilt V8 15.9.111.1:

  • Native ctest: 414 passed, 0 failed (1 skipped, as on main). New test_21 cases cover both policies, realms that allow or refuse wasm code generation, a context the provider did not make (it keeps V8's own WebAssembly global, 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.
  • CI cargo suites: concurrent_envs, concurrent_stores, foreground_task_waker, guest_callbacks, guest_c_strings, guest_memory, guest_memory_pressure and guest_lazy_properties all pass.
  • New WASIX guests in v8_host_control: the restricted policy across all realms, the default policy honoring allow_code_gen_wasm, the policy staying per context within one process, and asm.js running as plain JS under both policies.
  • All 40 tests/programs/manifest.json guests pass through the CLI under both the default policy and --restricted-webassembly.
  • The host-JS backend type-checks for wasm32-unknown-unknown --features js.

Two suites that CI does not run fail on main without 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 of manifest_tests (run_script_test's two-env check, plus a stale V8 version in tests/build-test-native.sh). They are being fixed separately.

🤖 Generated with Claude Code

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 syrusakbary left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 21 native V8 tests and three WASIX smoke tests passed locally. The message-policy finding is from source inspection.

Comment thread v8/src/unofficial_napi.cc
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);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/v8_host_control.rs
/// 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);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/cli.md Outdated
compile wasm in all of them:

```sh
./target/release/napi_wasmer --restricted-webassembly guest.wasm

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Comment thread v8/src/unofficial_napi.cc
(!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(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant