Skip to content

node:vm: reject Object.freeze/seal/preventExtensions on a contextified global - #33077

Closed
robobun wants to merge 6 commits into
mainfrom
farm/62c29ebd/fix-vm-global-freeze
Closed

robobun wants to merge 6 commits into
mainfrom
farm/62c29ebd/fix-vm-global-freeze

Conversation

@robobun

@robobun robobun commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes #33075. Inside a contextified vm context, Object.freeze(globalThis) silently succeeded instead of throwing, and the freeze then corrupted the context so any later global write threw.

import vm from 'node:vm';
const context = vm.createContext();
vm.runInContext('Object.freeze(globalThis);', context);   // Node: TypeError: Cannot freeze
vm.runInContext('globalThis.__x = 1;', context);          // Bun: TypeError "undefined is not an object"

Cause: a contextified context exposes its global through a JSGlobalProxy that delegates property access to the sandbox. NodeVMGlobalObject overrode getOwnPropertySlot, put, defineOwnProperty, deleteProperty, and getOwnPropertyNames, but not preventExtensions. So JSC's default JSObject::preventExtensions ran, made the object non-extensible, and Object.freeze/seal/preventExtensions succeeded.

Fix (commit 1): override NodeVMGlobalObject::preventExtensions to return false for contextified contexts, matching V8's global proxy (which can never become non-extensible). JSC's ObjectConstructor then throws a TypeError for each entry point and the context stays usable. DONT_CONTEXTIFY contexts have a real global object, which Node lets you freeze, so those delegate to the base implementation.

Fix (commit 2): the first fix surfaced a latent bug. vm.runInNewContext(code, DONT_CONTEXTIFY) first contextifies via createContext (which returns the context's special sandbox), then hands that sandbox to Script.runInNewContext, which re-contextified it into a fresh contextified global. So globalThis was no longer the vanilla DONT_CONTEXTIFY global and Object.freeze(globalThis) started throwing. scriptRunInNewContext now detects the special sandbox and runs in its existing non-contextified context, matching runInContext and Node. The normal create-a-fresh-context path is unchanged, so contextCodeGeneration options still apply.

Note: the thrown message is JSC's ("Unable to prevent extension in Object.freeze") rather than Node's exact "Cannot freeze". The error type (TypeError) and behavior now match; preventExtensions doesn't know which Object.* entry point called it, so exact message parity would need separate plumbing.

How did you verify your code works?

New cases in test/js/node/vm/vm.test.ts:

  • Object.freeze/seal/preventExtensions(globalThis) each throw a TypeError in a contextified context
  • the context stays usable after a rejected freeze (a new global can still be set)
  • both runInContext and runInNewContext throw for a contextified global and allow freezing a DONT_CONTEXTIFY global, matching Node
# without the fix (released bun):  5 fail
# with the fix (bun bd):           vm.test.ts 213 pass / 0 fail

Also ran the full node:vm parallel compat suite (test/js/node/test/parallel/test-vm-*.js, 95 files) to green, including test-vm-context-dont-contextify.js and test-vm-codegen.js.

A contextified vm context exposes its global through a JSGlobalProxy that
delegates property access to the sandbox. JSC's default preventExtensions
made that global non-extensible, so Object.freeze/seal/preventExtensions on
the context's globalThis silently succeeded and then broke the
global-to-sandbox delegation (any later global write threw).

Override preventExtensions on NodeVMGlobalObject to fail for contextified
contexts, matching V8's global proxy, so Object.freeze(globalThis) throws a
TypeError and the context stays usable. DONT_CONTEXTIFY contexts keep a real,
freezable global.

Closes #33075
@robobun

robobun commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:55 PM PT - Jun 29th, 2026

❌ @robobun, your commit 1d6d867 has 4 failures in Build #66868 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33077

That installs a local version of the PR into your bun-33077 executable, so you can run:

bun-33077 --bun

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 10 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 414ebc36-00ca-4269-b80e-506f375c4e8e

📥 Commits

Reviewing files that changed from the base of the PR and between a22f31b and 1d6d867.

📒 Files selected for processing (2)
  • src/js/node/vm.ts
  • test/js/node/vm/vm.test.ts

Walkthrough

Adds a preventExtensions override for contextified VM globals, adds a runInNewContext fast-path for NodeVMSpecialSandbox, and updates VM tests for freeze/seal/preventExtensions behavior. Also updates two documentation pages.

Changes

VM context behavior

Layer / File(s) Summary
preventExtensions override
src/jsc/bindings/NodeVM.h, src/jsc/bindings/NodeVM.cpp
NodeVMGlobalObject declares and implements a static preventExtensions override that delegates to the base for non-contextified globals and returns false for contextified globals.
runInNewContext special sandbox fast-path
src/jsc/bindings/NodeVMScript.cpp
runInNewContext detects NodeVMSpecialSandbox and routes execution through its parentGlobal() with the sandbox object as the context.
preventExtensions VM tests
test/js/node/vm/vm.test.ts
Tests assert Object.freeze, Object.seal, and Object.preventExtensions throw TypeError on contextified globalThis, and cover the DONT_CONTEXTIFY cases for freeze and runInNewContext.

Documentation updates

Layer / File(s) Summary
guide and table formatting
docs/guides/util/base64.mdx, docs/runtime/web-apis.mdx
The Base64 warning adds a TypeScript example for btoa/atob, and the Web APIs page reflows its support table formatting.

Suggested reviewers

  • Jarred-Sumner
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The docs edits in Base64 and web-apis are unrelated to the vm bug fix and appear out of scope. Remove the unrelated documentation changes or split them into a separate PR focused on docs updates.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main vm behavior fix for rejecting freeze/seal/preventExtensions on contextified globals.
Description check ✅ Passed The description matches the template and includes both the change summary and verification details.
Linked Issues check ✅ Passed The changes address #33075 by making contextified vm globals reject Object.freeze and related operations with TypeError.

Comment @coderabbitai help to get the list of available commands.

@mintlify

mintlify Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
bun 🟢 Ready View Preview Jun 29, 2026, 2:00 PM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — small, focused method-table override following the same pattern as the neighboring overrides, with good test coverage.

Extended reasoning...

Overview

This PR adds a preventExtensions static override to NodeVMGlobalObject so that Object.freeze/seal/preventExtensions(globalThis) inside a contextified node:vm context fail with a TypeError (matching Node/V8) instead of silently making the proxy-backed global non-extensible and corrupting subsequent writes. The substantive change is ~12 lines across NodeVM.h/NodeVM.cpp plus 5 new test cases in vm.test.ts. The two docs/ diffs are pure autofix.ci whitespace reflow (table column realignment, code-block indentation) with no content changes.

Security risks

None. The change makes behavior strictly more conservative — it prevents an operation that previously left the vm global in a broken state. No new data flows, no auth/crypto/permissions surface. The uncheckedDowncast is safe because method-table dispatch guarantees the receiver type, and it's the exact pattern used by every neighboring override (put, defineOwnProperty, deleteProperty, etc.) in the same file.

Level of scrutiny

Low-to-moderate. This is a narrow Node.js-compat fix in the JSC bindings: one new method-table slot that returns false for contextified globals and delegates to Base::preventExtensions for DONT_CONTEXTIFY. CREATE_METHOD_TABLE(NodeVMGlobalObject) picks the static up automatically; no StructureFlags change is needed for preventExtensions. Returning false is the standard JSC contract — ObjectConstructor converts it to a TypeError, and Reflect.preventExtensions will correctly return false, both matching Node.

Other factors

  • Tests cover all three entry points, post-rejection usability, and the DONT_CONTEXTIFY carve-out. The cross-realm .name === "TypeError" assertion is the right approach.
  • The CI build-rust failures are infrastructure-related (this PR touches no Rust) and not caused by this change.
  • No CODEOWNERS apply to the touched files.
  • The bug-hunting system found no issues.

…Y global

vm.runInNewContext(code, DONT_CONTEXTIFY) first contextifies via createContext,
which returns the context's special sandbox, then hands that sandbox to
Script.runInNewContext. That path re-contextified the sandbox into a fresh
contextified global, so globalThis was no longer the vanilla DONT_CONTEXTIFY
global and Object.freeze(globalThis) threw instead of succeeding.

Detect the special sandbox and run in its existing non-contextified context,
matching runInContext and Node. The normal create-a-fresh-context path is
unchanged, so contextCodeGeneration options still apply.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn't find issues with the logic, but this touches native JSC bindings for node:vm sandbox semantics (and the latest CI run for bb83f23 isn't reflected in robobun's comment yet), so it's worth a human look before merging.

Extended reasoning...

Overview

This PR adds a preventExtensions override to NodeVMGlobalObject so that Object.freeze/seal/preventExtensions(globalThis) inside a contextified node:vm context returns false (causing JSC's ObjectConstructor to throw a TypeError) instead of silently making the proxy-backed global non-extensible and corrupting subsequent writes. DONT_CONTEXTIFY contexts delegate to the base implementation and remain freezable, matching Node. A follow-up commit (bb83f23) updates scriptRunInNewContext to detect when the context argument is already a NodeVMSpecialSandbox (which happens because the JS-side vm.runInNewContext calls createContext() before forwarding to the native script.runInNewContext) and reuse its parent global instead of re-contextifying it as a vanilla sandbox — without this, the new preventExtensions guard would incorrectly fire on DONT_CONTEXTIFY globals routed through runInNewContext. The two docs files are pure autofix whitespace reflow. New tests cover all three Object.* entry points, post-rejection extensibility, and both DONT_CONTEXTIFY paths.

Security risks

node:vm is sandboxing-adjacent. The change makes the contextified global more restrictive (refusing to become non-extensible), which is a hardening rather than a relaxation, and matches V8/Node semantics. The scriptRunInNewContext change reuses an existing NodeVMGlobalObject rather than creating a fresh one when handed a NodeVMSpecialSandbox; this mirrors what runInContext already does for the same input via getGlobalObjectFromContext. I don't see a new escape vector, but any change to vm global-object method-table hooks deserves a maintainer's eye.

Level of scrutiny

Medium-high. The diff is small and follows the established pattern of the other method-table overrides on NodeVMGlobalObject (put, defineOwnProperty, deleteProperty, getOwnPropertyNames), and CREATE_METHOD_TABLE will pick up the static preventExtensions automatically. Still, this is hand-written C++ in JSC bindings affecting global-object semantics across realms.

Other factors

  • robobun's CI comment reports test-vm-context-dont-contextify.js failing across all platforms for commit bc9257b0; commit bb83f23d was pushed afterward specifically to address that path (the NodeVMSpecialSandbox reuse), and the new vm.test.ts case "runInNewContext with DONT_CONTEXTIFY can still be frozen" exercises exactly that scenario. However, the updated CI results for bb83f23d aren't visible in the timeline yet, so green CI on the latest commit should be confirmed.
  • No CODEOWNERS entries cover these paths.

@robobun

robobun commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator Author

For reviewers: the two docs/*.mdx entries in this diff are from the repo's autofix.ci bot (commit bc9257b, authored by autofix-ci[bot]), which runs prettier --write docs on PRs and committed pre-existing formatting drift from main. They are unrelated to the fix here, which lives in src/jsc/bindings/NodeVM.cpp, src/jsc/bindings/NodeVM.h, src/jsc/bindings/NodeVMScript.cpp, and test/js/node/vm/vm.test.ts.

@robobun

robobun commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Update (build #66868): this run went broadly red across platforms, but the failing tests are all unrelated to node:vm: test/internal/oxlint-plugin-bun.test.ts, test/js/bun/test/parallel/test-docker-build-distroless.ts, test-http-localaddress-bind-error.js, test-set-http-max-http-headers.js, test-stdin-hang.js, test/regression/issue/tui-app-tty-pattern.test.ts, plus the same darwin artifact-download / alpine musl flakes. No vm test failed. bun run lint on src/js is clean locally (0 warnings/errors, 199 files) and vm.test.ts is 217/0, so this diff isn't implicated; the cross-platform breakage points to a CI-wide or main-base issue.

Comment thread src/jsc/bindings/NodeVMScript.cpp Resolved
vm.runInNewContext(code, context, options) contextifies via createContext
before running, and createContext reads options.codeGeneration, but
runInNewContext receives the setting under options.contextCodeGeneration.
Previously scriptRunInNewContext re-read the correct key on its fall-through
path, masking the mismatch. With the DONT_CONTEXTIFY special-sandbox reuse
fast-path, the already-built context is reused, so a dropped setting meant
eval/Function/wasm stayed enabled when the caller disabled them.

Alias contextCodeGeneration to codeGeneration before createContext (mirroring
Node's getContextOptions) so the reused context honors it.
Comment thread src/js/node/vm.ts Resolved
The previous commit aliased contextCodeGeneration to codeGeneration before
createContext validated it, so an invalid value reported the internal
`options.codeGeneration` name (which the caller never passed) instead of
`options.contextCodeGeneration`. Validate the value (and its strings/wasm
fields) under the user-facing name before aliasing, matching Node.
@robobun

robobun commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

Re-verified this against current main (b5afcac), since the same bug came up again (guest-side Object.freeze(globalThis) / Object.seal(globalThis) in a contextified context makes every builtin identifier resolve to undefined, because JSC's setIntegrityLevel redefines each global name with a value-less descriptor and NodeVMGlobalObject::defineOwnProperty mirrors that onto the sandbox as undefined).

  • The four fix commits (507f72b, bb83f23, f72cc84, 1d6d867) cherry-pick onto main cleanly. The autofix.ci docs commit is the only thing in this diff that would drop on a rebase.
  • With them applied on main: test/js/node/vm/vm.test.ts 225 pass / 0 fail (the 6 new cases fail on the released binary), and all 95 test/js/node/test/parallel/test-vm-*.js files pass.
  • After the fix, freeze/seal/preventExtensions(globalThis) throw a TypeError and the context keeps working (typeof Object is still "function", var declarations and throw new Error() work), which is Node's behavior apart from the message text.

Note for whoever lands this: #34623 removes NodeVMSpecialSandbox, so the NodeVMScript.cpp hunk from bb83f23 conflicts with it. The preventExtensions override itself is independent of that PR and stays correct under either model. The red CI here is from June 29 and the failures were unrelated to vm; a rebase would give it a fresh run.

@robobun

robobun commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator Author

#39588 reworks how a contextified global resolves against its sandbox and covers this case. It adds the preventExtensions override, and it runs Script.prototype.runInNewContext() in an existing context instead of wrapping a second global around it, which is what the second commit here did for DONT_CONTEXTIFY. On a build of that branch, Object.freeze, Object.seal and Object.preventExtensions of a contextified globalThis throw a TypeError, Reflect.preventExtensions returns false, the context stays usable, and a DONT_CONTEXTIFY global can still be frozen through both runInContext and runInNewContext, as in Node. Its "the global of a contextified context cannot be made non-extensible" test covers this, and the tests from this PR pass when applied on top of that branch. #33075 is fixed by #39588 as well. Closing in favor of #39588.

@robobun robobun closed this Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bun allows Object.freeze(globalThis) running runInContext from node:vm

1 participant