Skip to content

node:vm: make the contextified sandbox the store for guest-created globals - #33486

Closed
robobun wants to merge 3 commits into
mainfrom
farm/fdb17f15/vm-contextify-sandbox-delete
Closed

robobun wants to merge 3 commits into
mainfrom
farm/fdb17f15/vm-contextify-sandbox-delete

Conversation

@robobun

@robobun robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Superseded by #39588, which fixes this with the same approach as part of a full contextify port and closes #33075. Kept open only as a possible stopgap until #39588's WebKit dependency lands. See the status comment.

Repro

A global the guest creates, and the host then deletes from the sandbox object, stays visible inside the context:

import * as vm from "node:vm";

const box = {};
vm.createContext(box);
vm.runInContext("globalThis.a = 1; var b = 2;", box);

console.log("host delete a:", delete box.a, "| host still sees a:", "a" in box);
console.log(
  "inside:", vm.runInContext("[typeof a, 'a' in globalThis].join(',')", box),
  "| ownNames:", vm.runInContext("Object.getOwnPropertyNames(globalThis).filter(n => n == 'a' || n == 'b').join(',')", box),
);
node v26.3.0:  inside: undefined,false | ownNames: b
bun 1.4.0:     inside: number,true     | ownNames: b,a     <- the host-deleted global is still there

That breaks the common pattern of reusing one context and resetting it between runs by deleting the keys the guest added (for (const k of Object.keys(box)) delete box[k]): under bun the guest keeps seeing every stale global from the previous run.

Cause

Both of the method-table hooks that write a property onto a contextified global store it on the sandbox and mirror it onto the JSC global object. The host's delete box.a removes only the sandbox copy, so the global copy keeps answering lookups.

V8's contextify callbacks report the operation handled, so the sandbox is the only store. The one exception is a property the global object already declares (a var/function binding, a builtin), whose global copy does stay in sync.

put — the gate that was supposed to decide this never fired:

bool isDeclaredOnGlobalObject = slot.type() == JSC::PutPropertySlot::NewProperty;

slot.type() is Uncachable on entry to put, before anything has written through the slot, so this was always false and the mirroring was unconditional.

defineOwnProperty — mirrors too, and only looked harmless. JSObject::defineOwnNonIndexProperty re-reads the current descriptor through methodTable()->getOwnPropertySlot, which consults the sandbox first and finds the value written one line earlier, so validateAndApplyPropertyDescriptor sees current.equalTo(descriptor) and returns early. The mirror was suppressed by accident, and the suppression breaks down as soon as the global has a binding of its own:

vm.runInContext("var v = 1; Object.defineProperty(globalThis, 'v', { value: 2, configurable: true });", box);
// node v26.3.0: succeeds
// bun on main:  TypeError: Attempting to change configurable attribute of unconfigurable property

The var leaves a non-configurable symbol-table entry on the global; the guest asks for configurable: true.

Fix

put computes isDeclaredOnGlobalObject with a real own-property lookup on the global object, bypassing this class' sandbox interception (the same qualified-static-call idiom defineOwnProperty already used, and it sees symbol-table var/function bindings as well as regular properties). When the property isn't declared there, the sandbox is the only store, so a host-side delete removes it from the context too.

defineOwnProperty defines on the sandbox and stops. The accessor branch and the already-on-the-sandbox branch were doing exactly that already, so the tail collapses into the one remaining call. The ReadOnly && DontDelete bail stays; node returns "not intercepted" there too.

put also checked value.isSymbol() where node checks the key: if (!is_declared && property->IsSymbol()). Fixed to propertyName.isSymbol(), which corrects two more divergences (a symbol-keyed assignment was landing on the sandbox, and a symbol value assigned to a string key was not).

Verification

A behaviour matrix run against node v26.3.0 and bun, covering every direction the store can take. bun bd output is now byte-identical to node on all twelve rows; before the fix, rows 1, 2, 3, 9 and 12 diverged.

# case node v26.3.0 bun before bun after
1 guest-assign then host delete undefined number undefined
2 implicit global, host delete undefined number undefined
3 host-preset then guest-assign, host delete undefined number undefined
4 var, host delete number number number
5 function decl, host delete function function function
6 overwrite builtin Object number number number
7 assign inherited toString function function function
8 sandbox accessor set 5|7 5|7 5|7
9 reset loop, then read undefined,number number,number undefined,number
10 guest-assign, host re-set, read 9 9 9
11 strict undeclared assign ReferenceError ReferenceError ReferenceError
12 symbol-keyed assign, read on sandbox undefined 1 undefined

Fifteen tests added to test/js/node/vm/vm.test.ts. Eight fail with src/jsc/bindings/NodeVM.cpp reverted to main; the other seven are negative-contract tests that must pass both ways (var/function bindings survive, builtin overwrites stay mirrored, sandbox accessors still fire, strict-mode stores still reach the sandbox, and the three defineProperty cases that previously only worked by accident).

Test runs
bun bd test test/js/node/vm/vm.test.ts
 291 pass, 0 fail

for f in test/js/node/test/parallel/test-vm-*; do bun-debug "$f"; done
 97 pass, 0 fail

Rebase onto current main

Main gained twelve node:vm commits since this branch was cut. One conflicted: #36709 (322f3abf9d) fixed a debug assertion in defineOwnProperty by giving the sandbox probe its own PropertySlot instead of reusing the one already filled by the global-object lookup. This PR deletes that probe entirely (the function now defines on the sandbox and stops), so the second lookup #36709 was guarding no longer exists and the fix is subsumed. Resolution: take this branch's collapsed version. #36709's regression test (Object.defineProperty on the context global when the sandbox is an uncacheable dictionary holding an accessor) still passes on the merged result, and the fail-before count is unchanged on the new base (8 of the 15 new tests fail with src/jsc/bindings/NodeVM.cpp reverted to main), so none of the intervening commits fixed this independently.

Notes for review

Inline caches. put's early return leaves slot.base() pointing at the sandbox rather than the global object, which is already the case on the pre-existing accessor early-return a few lines above. No inline cache can pick it up: NodeVMGlobalObject's StructureFlags carry ProhibitsPropertyCaching, so tryCachePutBy bails after CommonSlowPaths::originalStructureBeforePut unwraps the JSGlobalProxy to the target, and tryCachePutToScopeGlobal bails independently on slot.base() != scope. A test hammers one assignment site 2000 times and then checks the sandbox is still the store.

Still divergent from node, pre-existing and untouched:

  • No indexed-property interceptor for vm globals (globalThis[0] = 1 lands on the global, not the sandbox).
  • Node's read_only early-return in the setter is unimplemented.
  • A var cannot be shadowed by the sandbox for a free-variable read. JSC's createGlobalVarBinding<Global> calls addSymbolTableEntry, so a var is a scope slot rather than a property, and op_get_from_scope resolves it to GlobalVar and reads the slot directly without consulting getOwnPropertySlot. V8 uses a property cell, which its interceptor does see. So after var v = 1; box.v = 2, v reads 1 in bun and 2 in node, while globalThis.v reads 2 in both. Reachable on main with no defineProperty involved, and not fixable without changing how JSC creates global var bindings for contextified globals.
  • Above a V8 IC-warmup threshold (~100 iterations on one store site, also under --jitless), node itself leaves a stale copy on the global and exhibits the original bug. Bun is consistent at every iteration count.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

This review includes 2 billable files. This on-demand review is free during your promotion.

Your included review limit has been reached. Run @coderabbitai review --use-credits to review the latest changes using usage credits.

  • Run review — free
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f5c6f8a9-c951-46fc-9462-46ced97af389

📥 Commits

Reviewing files that changed from the base of the PR and between 6dfa8f4 and 259483b.

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

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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

@github-actions github-actions Bot added the claude label Jul 6, 2026
@robobun

robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: superseded by #39588

#39588 (dylan-conway) rewrites every NodeVMGlobalObject override as a port of node_contextify.cc, on top of a new JSC scope interceptor (oven-sh/WebKit#471). It fixes the bug this PR fixes with the same gate (a store reaches the global object only when the global itself owns the name), and dylan confirmed it against this PR's cases: "#33486 — fixed", with tests added, including the reset-between-runs pattern from the original report. It also covers the defineProperty and symbol-key parts here, plus the divergences this PR listed as out of scope (var shadowing, indexed keys, Proxy traps, preventExtensions, DONT_CONTEXTIFY), and it closes the tracking issue #33075.

Nothing here is needed once #39588 lands. The one thing this PR has that #39588 does not is that it applies to today's WebKit: #39588 depends on an unmerged WebKit change and currently has conflicts with main. If a stopgap is wanted in the meantime, this diff is green and self-contained (291 pass in vm.test.ts, 97/97 test-vm-*, 8 of its 15 tests fail without it). Otherwise it can be closed in favour of #39588. Maintainer's call; no further pushes from this side.

What this PR found, for the record
  • Root cause: both put and defineOwnProperty mirrored guest writes onto the JSC global object as well as the sandbox, so a host-side delete box.a removed only one copy. put's guard read slot.type() == NewProperty, which is Uncachable on entry and never matched. defineOwnProperty's mirror was suppressed only by accident (the global's [[DefineOwnProperty]] re-reads the current descriptor through the sandbox interception and bails on equalTo), and broke into a TypeError when the global held a var binding.
  • Node is not self-consistent on this bug: above a V8 IC-warmup threshold it leaves a copy on the global and reproduces the original symptom itself. dylan reached the same conclusion independently on node:vm: put the sandbox in front of global variables the way Node's contextify does #39588; both PRs give the interpreter answer in every tier.
  • Pre-existing, unrelated to either PR: the cookie-map failure seen on an earlier CI run was a stale assertion on main, since fixed by cookie: update remaining cookie-map Expires assertions to IMF-fixdate #33425.

Review writeups: JIT / strict-mode / symbol · the defineOwnProperty sibling · var hoisting · cross-check against #39588.

@robobun

robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:08 AM PT - Aug 19th, 2026

✅ @robobun, your commit 259483b0afc27fab27db7974da82fa1cc7bbdb42 passed in Build #101135! 🎉


🧪   To try this PR locally:

bunx bun-pr 33486

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

bun-33486 --bun

@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 any bugs, but this changes property-store semantics in NodeVMGlobalObject::put (JSC bindings) — worth a human look to confirm the mirroring gate and the value.isSymbol() → propertyName.isSymbol() swap don't regress anything the test matrix doesn't cover.

Extended reasoning...

Overview

This PR modifies NodeVMGlobalObject::put in src/jsc/bindings/NodeVM.cpp to change when a guest-side global assignment is mirrored onto the underlying JSC global object versus stored only on the sandbox. It replaces a dead slot.type() == NewProperty check with a real own-property lookup on the base global (via a qualified JSC::JSGlobalObject::getOwnPropertySlot call), adds an early-return that skips the mirror when the property isn't declared on the global, and swaps value.isSymbol() → propertyName.isSymbol(). Nine tests are added to test/js/node/vm/vm.test.ts.

Security risks

None apparent. node:vm is not a security boundary, and this change narrows (rather than widens) where writes land. The extra getOwnPropertySlot lookup runs against the base JSGlobalObject method table, not user-controllable traps.

Level of scrutiny

High. This is the C++ put hook for every global property write inside a contextified vm — a hot, semantics-defining path in the JSC integration. The change is well-reasoned and mirrors V8 contextify's PropertySetterCallback, and the PR description addresses inline-cache safety (ProhibitsPropertyCaching). But the interaction between the new early-return, PutPropertySlot state, strict-mode contextual stores, and var/function symbol-table bindings is subtle enough that someone familiar with this file should confirm the reasoning.

Other factors

The verification matrix and negative-contract tests are thorough, and the qualified-static-call idiom matches what defineOwnProperty in the same file already does. The value.isSymbol() → propertyName.isSymbol() fix is a real behavior change (symbol-keyed writes now bypass the sandbox entirely) that deserves an explicit sign-off. No CODEOWNERS cover this path and there are no prior review comments.

@robobun

robobun commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Good call on all three. Two of them weren't covered by the original matrix, so I went and closed the gaps; pushed as 3b65536cd9.

The mirroring gate under JIT warmup

The interesting one. A store site hot enough to warm its inline cache could in principle start writing a second copy onto the global behind the sandbox's back. It doesn't in bun, and asserting it turned up something worth recording: node has the original bug too, above an IC-warmup threshold.

// 500 stores, each from a fresh script (no IC warmup on any one store site)
for (let i = 0; i < 500; i++) vm.runInContext(`globalThis.hot = ${i};`, box);
delete box.hot;
vm.runInContext("typeof hot", box);   // node: undefined   bun: undefined

// the same 500 stores, from one hot loop (one store site, IC warms up)
vm.runInContext(`for (let i = 0; i < 500; i++) globalThis.hot = i;`, box);
delete box.hot;
vm.runInContext("typeof hot", box);   // node: number      bun: undefined

Node flips at roughly 100 iterations, and it flips under --jitless too, so it's the ignition-level store IC rather than a tier-up artifact. The copy V8 leaves on the global object is stale and normally shadowed by the interceptor, so it is only observable once the host deletes the sandbox entry, which is exactly the bug this PR is about. Bun post-fix is consistent at every iteration count, which is what the contextify model promises.

Bun can't regress into this: NodeVMGlobalObject's StructureFlags carry ProhibitsPropertyCaching, so Structure::prototypeQueriesAreCacheable() is false, which makes tryCachePutBy bail after CommonSlowPaths::originalStructureBeforePut unwraps the JSGlobalProxy to the target, and tryCachePutToScopeGlobal bails independently on slot.base() != scope. Now covered by a test that hammers the site 2000 times, then deletes from the sandbox and re-homes the property from the host.

Strict-mode contextual stores

isDeclared does flip value for names declared on the global but not on the sandbox, and it feeds the slot.isStrictMode() && !isDeclared && isContextualStore branch. In practice nothing observable changes, because isContextualStore is false for every store that can reach that branch in JSC: op_put_to_scope passes the scope as the slot's thisValue, and globalThis.x = passes the global proxy, which the function normalizes to false a few lines up. Pinned down with a test covering a builtin, a declared var, and a host-provided property under "use strict" — it passes on the unfixed build too, which is the point.

For the record, isDeclared is also what node feeds its own equivalent branch (is_declared_on_global_proxy || is_declared_on_sandbox), so the new value is the one node uses.

The symbol swap

It's a real behavior change, and it's the behavior node has. Node checks the key, not the value:

if (!is_declared && property->IsSymbol()) return Intercepted::kNo;

Both halves of the swap were observable divergences:

vm.runInContext("globalThis[Symbol.for('s')] = 1", box);   // key is a symbol
typeof box[Symbol.for('s')]   // node: undefined   bun before: number    bun after: undefined

vm.runInContext("globalThis.x = Symbol('q')", box);        // value is a symbol
typeof box.x                  // node: symbol      bun before: undefined bun after: symbol

Reads inside the context are unaffected either way, since getOwnPropertySlot falls back to the global object when the sandbox misses. Covered by two tests, both of which fail on the unfixed build.

Where that leaves the test file

11 tests in the new block. 7 fail with src/jsc/bindings/NodeVM.cpp reverted to main; the other 4 are negative-contract tests that must pass both ways (var/function bindings survive, builtin overwrites stay mirrored, sandbox accessors still fire, strict-mode stores still reach the sandbox).

bun bd test test/js/node/vm/vm.test.ts              217 pass, 0 fail
for f in test/js/node/test/parallel/test-vm-*       97 pass, 0 fail

Agreed that a human should sign off on the semantics; the put hook is load-bearing for every global write inside a contextified vm.

Comment thread src/jsc/bindings/NodeVM.cpp Resolved
@robobun

robobun commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch on the sibling, though not for the reason given. Fixed in b33b5cc6b5.

The stated repro doesn't reproduce

vm.runInContext("Object.defineProperty(globalThis,'a',{value:1,writable:true,enumerable:true,configurable:true});", box);
delete box.a;
vm.runInContext("typeof a", box);   // node: undefined   bun, before this PR: undefined

Base::defineOwnProperty is reached (I instrumented it to be sure), but it no-ops. JSObject::defineOwnNonIndexProperty re-reads the current descriptor through methodTable()->getOwnPropertySlot, which is NodeVMGlobalObject::getOwnPropertySlot, which consults the sandbox first. The sandbox was written one line earlier, so validateAndApplyPropertyDescriptor sees current.equalTo(descriptor) and returns early without touching the global. The mirror was suppressed by accident.

That also means the "poisoning" follow-on doesn't happen: nothing is seeded on the global, so put()'s new gate isn't defeated.

(The // TODO nodejs/node#52634 note the reasoning leans on isn't in this repo — grep -rn 52634 src/ is empty.)

But the structural point was right, and it is observable

Leaning on that accidental suppression is exactly as fragile as it sounds. It breaks down the moment the global object has a binding of its own, because then current comes from the global, not the sandbox:

vm.runInContext("var v = 1; Object.defineProperty(globalThis,'v',{value:2,writable:true,enumerable:true,configurable:true});", box);
// node v26.3.0: succeeds
// bun on main:  TypeError: Attempting to change configurable attribute of unconfigurable property

The var leaves a non-configurable symbol-table entry on the global, and the guest asks for configurable: true. Pre-existing on main, independent of this PR's put() change; I verified both.

Fix

Define on the sandbox and stop, matching V8's contextify PropertyDefinerCallback, which reports the operation handled and never lets V8 define on the global. The accessor branch and the already-on-the-sandbox branch were already doing exactly that, so the whole tail collapses into the one remaining call and isDeclaredOnSandbox / did go away. The ReadOnly && DontDelete bail stays: node returns "not intercepted" there too.

Four tests added. Object.defineProperty + var fails on the unfixed build; the other three lock in the behaviour that previously only worked by accident (fresh data property, redefining a builtin, accessor not flattened onto the global).

One residual divergence, pre-existing and out of scope

Fixing the TypeError exposes a layer underneath, which I want to flag rather than bury:

vm.runInContext("var v = 1;", box);
box.v = 2;                        // host overwrites the sandbox's copy
vm.runInContext("v", box);           // node: 2   bun: 1
vm.runInContext("globalThis.v", box);   // node: 2   bun: 2

JSC's createGlobalVarBinding<Global> calls addSymbolTableEntry, so a var is a scope slot, not a property. op_get_from_scope resolves it to GlobalVar and reads the slot directly, never consulting getOwnPropertySlot, so the sandbox cannot shadow it for a free-variable read. V8 uses a property cell, which the interceptor does see. Reachable on main with no defineProperty involved, identical before and after this PR, and not fixable without changing how JSC creates global var bindings for contextified globals.

Where the diff stands

src/jsc/bindings/NodeVM.cpp: put() and defineOwnProperty(), the two method-table hooks that were mirroring onto the global object.

bun bd test test/js/node/vm/vm.test.ts          221 pass, 0 fail
for f in test/js/node/test/parallel/test-vm-*    97 pass, 0 fail

15 tests in the new block, 8 of which fail with src/jsc/bindings/NodeVM.cpp reverted to main. Every probe script I have now matches node v26.3.0 byte for byte, except the documented V8 IC-warmup artifact.

@robobun robobun changed the title node:vm: reflect host-side sandbox deletes into the contextified global node:vm: make the contextified sandbox the store for guest-created globals Jul 6, 2026

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

Thanks — b33b5cc addresses the defineOwnProperty mirroring I flagged, with tests for the fresh-property, var-collision, builtin, and accessor cases. No further issues found, but since put and defineOwnProperty together now change where every global write in a contextified vm lands (and defineOwnProperty goes sandbox-only even for names already on the global), a human should confirm the semantics before merge.

Extended reasoning...

Overview

This PR changes two method-table overrides on NodeVMGlobalObject in src/jsc/bindings/NodeVM.cpp:

  • put(): replaces the always-false slot.type() == NewProperty gate with a real JSC::JSGlobalObject::getOwnPropertySlot lookup, adds an early return so plain assignments to undeclared names stay sandbox-only, and fixes value.isSymbol() → propertyName.isSymbol().
  • defineOwnProperty() (new commit b33b5cc, in response to my prior review): drops the fall-through to Base::defineOwnProperty entirely; after the read-only+non-configurable guard, all defines go to the sandbox only. This is more aggressive than the fix I suggested (it never mirrors, even when isDeclaredOnGlobalProxy is true), which the commit message justifies via the var-collision case and Node v26's PropertyDefinerCallback returning Intercepted::kYes unconditionally.

15 new tests in test/js/node/vm/vm.test.ts cover both paths, including negative-contract tests for var/function bindings, builtins, accessors, strict mode, and a JIT-warmup probe.

Security risks

node:vm is a soft sandbox but not a security boundary. The change moves where global writes land (sandbox vs JSC global), which affects isolation semantics between host and guest. No new unchecked casts, no new allocation, exception scopes look correct (RETURN_IF_EXCEPTION after the new getOwnPropertySlot call). I don't see auth/crypto/injection surface here.

Level of scrutiny

High. NodeVMGlobalObject::put runs on every global assignment inside every contextified vm, and defineOwnProperty on every Object.defineProperty(globalThis, ...) and any [[DefineOwnProperty]] path JSC routes there. The author (robobun) explicitly noted "a human should sign off on the semantics." The defineOwnProperty simplification also removes a getPropertySlot on the sandbox and the accessor-descriptor branch — worth a maintainer confirming JSC doesn't route hoisted var/function declarations through this hook in a way that now diverges.

Other factors

  • My prior inline comment on defineOwnProperty was addressed by b33b5cc with 4 dedicated tests.
  • The bug-hunting system found no issues on the current revision.
  • CI on the previous commit (3b65536) had an unrelated cookie-map.test.ts failure; CI status on b33b5cc is not yet visible in the timeline.
  • Test coverage is thorough (positive + negative-contract + JIT-tier probe), and the Node parallel test suite reportedly passes.

@robobun

robobun commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

worth a maintainer confirming JSC doesn't route hoisted var/function declarations through this hook

Checked, from both ends. JSC does not route them through defineOwnProperty.

ProgramExecutable::initializeGlobalProperties hoists via createGlobalVarBinding<BindingCreationContext::Global> and createGlobalFunctionBinding<BindingCreationContext::Global>, and in the Global context both land on addSymbolTableEntry (JSGlobalObject.cpp, JSGlobalObjectInlines.h), which takes a scope offset and writes through symbolTable() directly. No method-table dispatch, so neither defineOwnProperty nor put sees the hoist.

Confirmed empirically too: nothing appears on the sandbox at hoist time, in either engine.

const box = {};
vm.createContext(box);
try { vm.runInContext("var b = (function(){ throw new Error('x') })();", box); } catch {}
Object.getOwnPropertyNames(box);   // node: []   bun: []

The sandbox copy of a var is created later, by the assignment, through put — which is why put must keep mirroring onto the global when isDeclaredOnGlobalObject is true (the hoist already put a symbol-table entry there) while defineOwnProperty never needs to. That asymmetry is the whole reason the two hooks don't get the same treatment, and it's pinned by the var and function declarations survive deletion of their sandbox copy test.

defineOwnProperty goes sandbox-only even for names already on the global

Deliberate, and it's what node does. Every case I could construct where the global already has the name agrees:

case node v26.3.0 bun after
defineProperty over builtin Object, then host-delete function (global untouched) function
defineProperty over a var, then host-delete succeeds, global keeps 1 same
defineProperty over a host-preset prop, then host-delete undefined undefined

The ReadOnly && DontDelete guard is the one case that still falls through to Base::defineOwnProperty, matching node returning "not intercepted" there.


CI

Both red lanes on b33b5cc6 are unrelated to this diff.

cookie-map.test.ts is broken on main, not by this PR. 028f210723 ("Fix Bun.Cookie Expires to emit an IMF-fixdate", #32926) changed the serialized format to Thu, 01 Jan 1970 00:00:00 GMT but left three assertions in test/js/bun/cookie/cookie-map.test.ts expecting the old Fri, 1 Jan 1970 00:00:00 -0000 (which isn't even a real date, Jan 1 1970 was a Thursday). Those assertions predate the format change. Verified by reverting src/jsc/bindings/NodeVM.cpp to main and rebuilding: still 3 fail, so the diff has nothing to do with it. The file contains zero references to node:vm.

:windows: 2019 x64 - test-bun ran all 595 files with 0 fail on every one, then exited 2 at the harness level. The twelve vm files in that shard (test-vm-global-setter, test-vm-global-contextual-store, test-vm-strict-mode, test-vm-cross-context, …) are green, and those exercise put directly.

Not retriggering: the cookie failure is deterministic, so a re-roll can't clear it.

This branch, latest commit:

bun bd test test/js/node/vm/vm.test.ts          221 pass, 0 fail
for f in test/js/node/test/parallel/test-vm-*    97 pass, 0 fail

@robobun

robobun commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator Author

Checked against #39588 on a build of its branch: this still applies. The put there also stores an undeclared property on the global object, so after delete box.a from the host the repro in this description still prints number,true inside the context (Node prints undefined,false), and 5 of the tests from this PR fail on that branch (the four host-side delete cases and the hot assignment site). The defineProperty over a var and the symbol-key parts are covered by #39588. Once #39588 lands, the remaining fix needs to be redone on top of its put.

@robobun
robobun force-pushed the farm/fdb17f15/vm-contextify-sandbox-delete branch from 37e0a8d to dae6431 Compare August 19, 2026 07:45
Comment thread src/jsc/bindings/NodeVM.cpp Resolved
Comment thread src/jsc/bindings/NodeVM.cpp Resolved
Comment thread src/jsc/bindings/NodeVM.cpp Resolved
NodeVMGlobalObject::put mirrored every guest assignment onto the JSC global
object as well as the sandbox, so deleting the sandbox copy from the host left
the global copy behind and the guest kept seeing the property.

Only let the store fall through to the global object when the property is
already declared there (a var/function binding, or a builtin), matching V8's
contextify PropertySetterCallback. isDeclaredOnGlobalObject now does a real
own-property lookup instead of reading slot.type(), which is Uncachable on
entry and so never matched.

Also check propertyName.isSymbol() rather than value.isSymbol(), mirroring
node's `if (!is_declared && property->IsSymbol())`.
A store site hot enough to reach the JIT tiers must not start writing a second
copy onto the context's global object: the inline caches are disabled for the
contextified global, but assert it rather than assume it.

The strict-mode branch reads isDeclared, which now accounts for bindings on the
global object, so pin down that stores to a builtin, a declared var, and a
host-provided property all still reach the sandbox.
NodeVMGlobalObject::defineOwnProperty defined the property on the sandbox and
then called Base::defineOwnProperty as well, the same mirroring put() did.

It only looked harmless because the mirror almost always no-ops: the global's
[[DefineOwnProperty]] re-reads the current descriptor through this class'
getOwnPropertySlot, which consults the sandbox first and finds the value that
was just written there, so validateAndApplyPropertyDescriptor sees an identical
descriptor and returns early.

That suppression breaks down when the global already has a binding of its own.
Redefining a `var` is rejected, because the global's symbol-table entry is
non-configurable and the guest asks for a configurable property:

  var v = 1;
  Object.defineProperty(globalThis, 'v', { value: 2, configurable: true });
  // node: succeeds     bun: TypeError

Define on the sandbox and stop there, matching V8's contextify
PropertyDefinerCallback. The accessor and already-on-the-sandbox branches did
exactly that already, so they collapse into the single remaining call.
@robobun
robobun force-pushed the farm/fdb17f15/vm-contextify-sandbox-delete branch from dae6431 to 259483b Compare August 19, 2026 07:49

@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 re-reviewed after the defineOwnProperty follow-up and the rebase onto current main; the automated pass found no bugs. My earlier concern about the sibling hook is addressed (and the collapsed tail subsumes #36709's PropertySlot fix, whose regression test still passes). Given this changes where every global write inside a contextified vm lands — and the open note about redoing part of it on top of #39588 once that merges — a human read on the semantics is still worthwhile.

What was reviewed:

  • put(): the new qualified JSGlobalObject::getOwnPropertySlot lookup replacing the never-true slot.type() == NewProperty gate, and the propertyName.isSymbol() fix — checked exception-scope placement and that ProhibitsPropertyCaching keeps the early-return's slot.base() from being IC'd.
  • defineOwnProperty(): the collapsed sandbox-only tail — confirmed the removed isDeclaredOnSandbox probe is what #36709 was guarding, so no reintroduced assert path.
  • Tests: 15 new cases cover the host-delete, hot-site, strict-mode, symbol, var/function, builtin-overwrite, and defineProperty variants; 8 fail-before verified per the description.
Extended reasoning...

Overview

The PR changes two method-table overrides on NodeVMGlobalObject in src/jsc/bindings/NodeVM.cpp (put and defineOwnProperty) so that guest-created globals in a node:vm context are stored only on the contextified sandbox object rather than mirrored onto the JSC global. This makes host-side delete sandbox.key actually remove the binding from the context, matching Node v26. Fifteen tests are added to test/js/node/vm/vm.test.ts, eight of which fail on the unfixed build.

Security risks

node:vm is not a security boundary, but the change does affect where writes land inside a contextified global. The direction of the change (fewer writes onto the real JSC global object, more confined to the sandbox) is if anything a reduction in cross-realm surface. No new user-controlled data reaches native APIs; the added lookup is a qualified static call into JSGlobalObject::getOwnPropertySlot on thisObject itself, guarded by RETURN_IF_EXCEPTION. I don't see auth/crypto/permissions implications.

Level of scrutiny

High. This is a semantic change to the storage model for every global assignment inside a vm context, implemented by editing JSC method-table hooks. The PR body itself documents subtle interactions (inline caches, ProhibitsPropertyCaching, symbol-table var bindings vs property cells, the accidental suppression in defineOwnProperty via validateAndApplyPropertyDescriptor) and lists three pre-existing divergences left for follow-up. The author's own status comment says it wants a human read, and there is an open note that once #39588 lands the remaining fix needs to be redone on top of its put. That is exactly the kind of design/merge-ordering call a maintainer should make.

Other factors

  • My prior inline concern (the defineOwnProperty sibling still mirroring) was investigated and addressed in a follow-up commit; the thread is resolved and covered by four of the new tests.
  • The rebase note explains the conflict with #36709 and that its regression test still passes on the merged result — I confirmed the removed sandbox probe is what that PR's separate PropertySlot was guarding, so the collapsed tail subsumes it.
  • Exception-scope hygiene looks correct: the throw scope was hoisted above the new getOwnPropertySlot call and RETURN_IF_EXCEPTION follows it; the removed code's RETURN_IF_EXCEPTION/RELEASE_AND_RETURN pairs are replaced by a single tail RELEASE_AND_RETURN.
  • Test coverage is thorough (12-row behavior matrix vs Node v26.3.0, hot-site JIT test, strict-mode negative-contract tests, symbol key/value both directions, defineProperty over var/builtin/accessor). The 97 test-vm-* parallel tests also pass per the description.
  • Comment-cop threads were addressed (comments trimmed to one line each in 259483b).

@robobun

robobun commented Aug 19, 2026

Copy link
Copy Markdown
Collaborator Author

The #39588 ordering question is resolved: it supersedes this PR rather than building on it. dylan confirmed on that thread that #39588 fixes this case with the same gate and added tests for it, and it also covers everything this PR listed as out of scope. Details in the status comment at the top.

This PR stays open only as a possible stopgap, since #39588 depends on an unmerged WebKit change. Whether to land it in the meantime or close it is a maintainer's call; nothing further will be pushed here.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-19.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 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