Repository navigation
Conversation
…luating
JSC's GlobalDeclarationInstantiation consults JSGlobalObject::getOwnPropertySlot
directly (not through the method table), so createGlobalVarBinding and
canDeclareGlobalFunction never see properties that live on the contextified
sandbox. A program-level `var x` / `function x(){}` over an existing sandbox
property would add a fresh undefined symbol-table slot, and that slot then wins
every unqualified lookup for the rest of the context's lifetime while
`globalThis.x` still reads the sandbox value.
Before each evaluate, enumerate the sandbox's own string properties and
putDirect a placeholder with the same configurable/enumerable/writable
attributes onto the NodeVMGlobalObject for any name the global doesn't already
know about. JSGlobalObject::getOwnPropertySlot now finds them and
createGlobalVarBinding skips the symbol-table slot; canDeclareGlobalFunction
sees the real attributes so a function declaration over a non-configurable
non-writable sandbox property throws as the spec requires. Actual reads still
route through the method-table override, which consults the sandbox first, so
the placeholder value is never observed.
In NodeVMGlobalObject::put, once the sandbox accepts a write for a name that is
not also a global symbol-table slot, skip the forward to Base::put: the only
global-side copy is the (possibly read-only) placeholder, which is never read.
|
Status: fix is ready; all review threads resolved. Repro: CI build 72546: 284/286 jobs green. The two failing jobs are PR: #34074 |
WalkthroughChangesNode VM contexts now materialize sandbox-owned VM declaration handling
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 5:05 PM PT - Jul 13th, 2026
❌ @autofix-ci[bot], your commit 1935ced has 2 failures in
🧪 To try this PR locally: bunx bun-pr 34074That installs a local version of the PR into your bun-34074 --bun |
…ares The first cut mirrored every sandbox own property onto the context global before each evaluate. A script with no declarations would still leave placeholder properties behind, so a host-side `delete sandbox.x` between runs made the placeholder observable (`'x' in this` true, unqualified `x` resolving to undefined instead of ReferenceError). Drive the mirroring from the program's own variableDeclarations instead: fetch the UnlinkedProgramCodeBlock from the code cache (the evaluate that follows reuses it) and only materialise names that appear there and that the sandbox already owns. A script with no declarations touches nothing; a declared name that the sandbox also owns gets a direct-property placeholder with the sandbox's configurable/enumerable/writable bits so createGlobalVarBinding skips the symbol-table slot and canDeclareGlobalFunction sees real attributes. In put(), once the sandbox setter handles the write for an accessor property, stop forwarding to Base regardless of the accessor's enumerability: the only global-side copy is the (read-only) materialised placeholder, which Base::put would fail on.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/jsc/bindings/NodeVM.cpp`:
- Around line 1186-1188: Update the guard in the sandbox setter around
isDeclaredOnSandbox and getter.isAccessor() to also bypass Base::put for native
custom accessors, matching the declarations materialized by
materializeSandboxPropertiesForDeclarations. Preserve the existing behavior for
regular accessors and ensure custom-accessor writes short-circuit before
reaching the read-only placeholder.
- Around line 1482-1483: Update the call to
context->materializeSandboxPropertiesForDeclarations in NodeVM initialization to
pass context as the lexicalGlobalObject argument instead of globalObject,
ensuring sandbox property lookup and traps use the executing sandbox realm.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: dd677f5e-1f77-479c-91b0-5ee75599333a
📒 Files selected for processing (4)
src/jsc/bindings/NodeVM.cppsrc/jsc/bindings/NodeVM.hsrc/jsc/bindings/NodeVMScript.cpptest/js/node/vm/vm.test.ts
…he context realm for materialisation
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/jsc/bindings/NodeVM.cpp (1)
1097-1101: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftRefresh stale materialized descriptors after sandbox redefinition.
alreadyOnGlobalalso matches placeholders created by an earlier script. If the sandbox property is deleted and later recreated with different attributes, this branch skips rematerialization, so global declaration checks continue seeing the old descriptor. For example, an accessor or non-configurable property can be recreated as a writable data property (or vice versa), causing subsequentvar/functiondeclaration checks to use incorrect semantics.Track materialized placeholders separately and resynchronize/remove them when the sandbox descriptor changes; do not treat every existing global property as authoritative.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/jsc/bindings/NodeVM.cpp` around lines 1097 - 1101, Update the global-property handling around alreadyOnGlobal so it distinguishes materialized placeholders from authoritative global properties. When a sandbox property is deleted and recreated with different attributes, resynchronize or remove the stale placeholder before declaration checks; only skip rematerialization for unchanged authoritative properties, preserving correct var/function semantics for accessor, non-configurable, and writable data descriptors.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/jsc/bindings/NodeVM.cpp`:
- Around line 1097-1101: Update the global-property handling around
alreadyOnGlobal so it distinguishes materialized placeholders from authoritative
global properties. When a sandbox property is deleted and recreated with
different attributes, resynchronize or remove the stale placeholder before
declaration checks; only skip rematerialization for unchanged authoritative
properties, preserving correct var/function semantics for accessor,
non-configurable, and writable data descriptors.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: bbb35a72-57ef-496f-8ddc-4bdedf90fbb9
📒 Files selected for processing (1)
src/jsc/bindings/NodeVM.cpp
|
Re the outside-diff finding about stale placeholder attributes when a sandbox property is redefined between scripts: that is not a regression. The only observable case is const sandbox = { x: 1 };
vm.createContext(sandbox);
vm.runInContext("var x;", sandbox);
Object.defineProperty(sandbox, "x", { value: 42, writable: false, configurable: false });
vm.runInContext("function x(){}", sandbox);
// node: throws
// main: silent no-op (sandbox.x stays 42)
// this PR: silent no-op (sandbox.x stays 42)
|
…operty after var declares over it
The prototype-walking getPropertySlot used to populate the accessor check also finds inherited DontEnum accessors like Object.prototype.__proto__, so dropping the DontEnum gate made `this.__proto__ = X` inside a context return early and leave the vm global's [[Prototype]] unchanged. Gate the bypass on getter.slotBase() == sandbox so only an own accessor on the sandbox short-circuits; inherited ones fall through to Base::put as before.
There was a problem hiding this comment.
No new issues found in this pass. This touches deep JSC internals (ProgramExecutable/UnlinkedProgramCodeBlock code-cache access, direct-property placeholders on NodeVMGlobalObject to steer GlobalDeclarationInstantiation) and the put() accessor-bypass semantics, so a maintainer familiar with the vm bindings should sign off on the approach — especially given #33486/#34072 touch the same put() path.
Checked across review rounds and ruled out: stale placeholders after host-side delete (now declaration-driven, tested); __proto__ regression from dropping the DontEnum gate (now own-only via slotBase() == sandbox, tested); the RO+DD defineOwnProperty short-circuit vs placeholder value (Base::defineOwnProperty re-reads the descriptor via method table, tested); the Proxy-trap clearException() matches Node's trap-bypassing behaviour and is not a regression.
Extended reasoning...
Overview
Adds NodeVMGlobalObject::materializeSandboxPropertiesForDeclarations(), called before JSC::evaluate at both runInContext entry points. It fetches the program's UnlinkedProgramCodeBlock from the code cache, iterates variableDeclarations(), and for each name the sandbox owns but the base global does not, installs a direct property on the vm global mirroring the sandbox's attributes. This makes JSC's static JSGlobalObject::getOwnPropertySlot (used by createGlobalVarBinding/canDeclareGlobalFunction) observe those names, preventing the dead-undefined symbol-table slot. Also widens the put() accessor-bypass to isAccessor() || isCustom() while restricting it to own accessors via slotBase() == sandbox. 30 new tests across all four runIn* entry points; all 95 test-vm-*.js reported passing.
Security risks
node:vm is not a security boundary, but the change does affect how sandbox properties are surfaced on the vm global and how writes route through Base::put. The __proto__ handling was specifically examined (a real regression was caught and fixed in 978da1d). The clearException() after a Proxy trap throw is a deliberate Node-compat choice (V8's contextify Query bypasses traps entirely) and does not swallow anything Node would surface. No new user-controlled-input parsing.
Level of scrutiny
High. This is C++ JSC bindings code with subtle interactions between JSC's static vs method-table property lookup, the code cache, GlobalDeclarationInstantiation semantics, and property-attribute mirroring. The approach — pre-parsing via the code cache to enumerate declarations and installing attribute-only placeholders — is a novel architectural decision that works around JSC's static getOwnPropertySlot call, and a maintainer should confirm it is preferable to alternatives (e.g. patching the JSC call site). The put() change alters an existing guard whose original DontEnum gate had unclear intent.
Other factors
- Multiple review rounds already caught and fixed real regressions (stale placeholders,
__proto__inherited-accessor bypass), which suggests the interaction surface is genuinely tricky. - The author explicitly flagged two in-flight PRs (#33486, #34072) touching
NodeVMGlobalObject::put; whichever lands first the others need a rebase — coordination a human should handle. - One acknowledged corner deferred to a follow-up: sandbox property redefined to non-writable/non-configurable between scripts, then
function x(){}— silent no-op on both main and this PR (not a regression, but not Node-matching either). - The one CI failure (
test-worker-message-port-transfer-terminate.jsSIGABRT on x64-asan) appears unrelated to this diff.
|
#39588 reworks how a contextified global resolves against its sandbox and covers this case. On a build of that branch, the repro from this description prints |
Repro
Exposing read-only config on the sandbox (
Object.defineProperty(box, 'cfg', { value, writable: false })) is the canonical contextify pattern. On Bun the moment any guest code declaredvar cfg, every subsequent unqualified read in the context sawundefinedforever whileglobalThis.cfgstill held the real value. The same thing happened for writable data properties and getter-only accessors; a top-levelfunction cfg(){}over a non-writable non-configurable property was a silent no-op instead of throwing.Cause
JSC's
ProgramExecutable::initializeGlobalPropertiescallsJSGlobalObject::getOwnPropertySlotdirectly, not through the method table, socreateGlobalVarBinding/canDeclareGlobalFunctionnever seeNodeVMGlobalObject's override and never see the sandbox. For avar cfgdeclaration that check returns "not found", JSC adds a fresh symbol-table slot initialised toundefined, andabstractAccessthen resolves every unqualifiedcfgto that slot asGlobalVar, bypassing the method-table lookup that would have reached the sandbox.globalThis.cfggoes through the method table, so it kept working.Fix
Before each
JSC::evaluateon a contextified global, fetch the program'sUnlinkedProgramCodeBlockfrom the code cache (the evaluate that follows reuses it, so no extra parse) and, for each name in itsvariableDeclarations()that the sandbox already owns and the global does not, install a direct property on theNodeVMGlobalObjectwhose attributes mirror the sandbox's (value is a placeholder; accessors mirror as read-only).JSGlobalObject::getOwnPropertySlotnow reports those names, socreateGlobalVarBindingreturns early without adding a symbol-table slot andcanDeclareGlobalFunctionsees the real attributes (sofunction cfg(){}over a non-configurable non-writable property throwsTypeError, per spec).ProhibitsPropertyCachingonNodeVMGlobalObjectkeeps the link-time resolve type at uncachedGlobalProperty, and runtime reads still route through our method-table override which consults the sandbox first, so the placeholder value is never observed.Because the mirroring is driven by the program's own declarations, a script with no
var/functiondeclarations touches nothing; a host-sidedelete sandbox.xbetween runs leaves no phantom property behind, and the global-side binding for a declared name (which matches Node's behaviour) survives the sandbox delete.In
NodeVMGlobalObject::put, once the sandbox's setter has handled a write, stop forwarding toBase::putregardless of the accessor's enumerability: the only global-side copy for an accessor is the read-only materialised placeholder, whichBase::putwould fail on.Verification
30 new cases in
test/js/node/vm/vm.test.tsacrossrunInContext/runInNewContext/Script#runInContext/Script#runInNewContext, covering read-only data, getter-only accessor, writable data, non-enumerable, late-added, persistence across scripts, the function-declaration error, plus guards that a declaration-free script leaves no placeholder behind and that declared bindings survive host-side sandbox delete. 24 fail on 1.4.0 and all 30 pass with the fix. All 95test/js/node/test/parallel/test-vm-*.jspass.Related open PRs touching
NodeVMGlobalObject::putfor adjacent behaviours: #33486, #34072. None address this bug; whichever lands first the others will want a small rebase.[review] gate passed · iteration 1 · 4 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 5 passed · 0 rejected · iteration 1
evidence per changed file