diff --git a/src/jsc/JSPropertyIterator.rs b/src/jsc/JSPropertyIterator.rs index 77fb7017e9bf..5053b60f0086 100644 --- a/src/jsc/JSPropertyIterator.rs +++ b/src/jsc/JSPropertyIterator.rs @@ -7,9 +7,10 @@ use crate::{JSGlobalObject, JSObject, JSValue, JsResult}; /// Runtime flag set passed to [`JSPropertyIterator::init`]. /// /// `Default` is `own_properties_only = true`, -/// `observable = true`, `only_non_index_properties = false`. +/// `observable = true`, `only_non_index_properties = false`, +/// `include_symbols = false`. // Runtime flags (not const generics) because the branches gate per-property work, not a -// hot inner loop, and the monomorphization fan-out would be 32 instantiations. Profile +// hot inner loop, and the monomorphization fan-out would be 64 instantiations. Profile // if hot. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct JSPropertyIteratorOptions { @@ -18,10 +19,14 @@ pub struct JSPropertyIteratorOptions { pub own_properties_only: bool, pub observable: bool, pub only_non_index_properties: bool, + /// Also yield Symbol-keyed properties. The yielded name is the symbol's + /// description, not a property key, so this is only for callers that + /// count or display properties. Off by default, like `Object.keys`. + pub include_symbols: bool, } impl JSPropertyIteratorOptions { - /// Shorthand for the most common call-site shape; the remaining three + /// Shorthand for the most common call-site shape; the remaining /// options take the [`Default`] values. pub const fn new(skip_empty_name: bool, include_value: bool) -> Self { Self { @@ -30,6 +35,7 @@ impl JSPropertyIteratorOptions { own_properties_only: true, observable: true, only_non_index_properties: false, + include_symbols: false, } } } @@ -43,11 +49,12 @@ impl Default for JSPropertyIteratorOptions { own_properties_only: true, observable: true, only_non_index_properties: false, + include_symbols: false, } } } -/// Two-field shorthand of [`JSPropertyIteratorOptions`]; the remaining three options +/// Two-field shorthand of [`JSPropertyIteratorOptions`]; the remaining options /// take the default values via the `From` conversion. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct PropertyIteratorOptions { @@ -142,6 +149,7 @@ impl<'a> JSPropertyIterator<'a> { &mut len, options.own_properties_only, options.only_non_index_properties, + options.include_symbols, )?; if cfg!(debug_assertions) { if len > 0 { @@ -250,6 +258,7 @@ impl JSPropertyIteratorImpl { count: &mut usize, own_properties_only: bool, only_non_index_properties: bool, + include_symbols: bool, ) -> JsResult>> { // may return null without an exception let raw = from_js_host_call_generic(global_object, || { @@ -259,6 +268,7 @@ impl JSPropertyIteratorImpl { count, own_properties_only, only_non_index_properties, + include_symbols, ) })?; Ok(NonNull::new(raw)) @@ -311,6 +321,7 @@ unsafe extern "C" { count: &mut usize, own_properties_only: bool, only_non_index_properties: bool, + include_symbols: bool, ) -> *mut JSPropertyIteratorImpl; safe fn Bun__JSPropertyIterator__getNameAndValue( iter: &mut JSPropertyIteratorImpl, diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index 962044c4b021..638bb670a4bf 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -6445,6 +6445,7 @@ impl VirtualMachine { own_properties_only: true, observable: false, only_non_index_properties: true, + include_symbols: true, }, )?; let longest_name = iterator.get_longest_property_name().min(10); diff --git a/src/jsc/bindings/JSPropertyIterator.cpp b/src/jsc/bindings/JSPropertyIterator.cpp index 6e032bdccb83..7df4acb78ac4 100644 --- a/src/jsc/bindings/JSPropertyIterator.cpp +++ b/src/jsc/bindings/JSPropertyIterator.cpp @@ -36,7 +36,7 @@ class JSPropertyIterator { WTF_DEPRECATED_MAKE_FAST_ALLOCATED(JSPropertyIterator); }; -extern "C" JSPropertyIterator* Bun__JSPropertyIterator__create(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue encodedValue, size_t* count, bool own_properties_only, bool only_non_index_properties) +extern "C" JSPropertyIterator* Bun__JSPropertyIterator__create(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue encodedValue, size_t* count, bool own_properties_only, bool only_non_index_properties, bool include_symbols) { auto& vm = JSC::getVM(globalObject); JSC::JSValue value = JSValue::decode(encodedValue); @@ -45,7 +45,11 @@ extern "C" JSPropertyIterator* Bun__JSPropertyIterator__create(JSC::JSGlobalObje ASSERT(count); auto scope = DECLARE_THROW_SCOPE(vm); - JSC::PropertyNameArrayBuilder array(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); + // The iterator yields every name as a string. A Symbol key has no string + // name: its impl() is the description, so `Symbol.for("s")` would come + // out as the key "s". Only callers that merely count or display + // properties opt in to symbols. + JSC::PropertyNameArrayBuilder array(vm, include_symbols ? PropertyNameMode::StringsAndSymbols : PropertyNameMode::Strings, PrivateSymbolMode::Exclude); if (object->hasNonReifiedStaticProperties()) [[unlikely]] { object->reifyAllStaticProperties(globalObject); diff --git a/src/runtime/api/JSTranspiler.rs b/src/runtime/api/JSTranspiler.rs index d128f2c4b7b3..e5c1d8c2df70 100644 --- a/src/runtime/api/JSTranspiler.rs +++ b/src/runtime/api/JSTranspiler.rs @@ -148,6 +148,7 @@ const PROP_ITER_OPTS: JSPropertyIteratorOptions = JSPropertyIteratorOptions { own_properties_only: true, observable: true, only_non_index_properties: false, + include_symbols: false, }; impl Config { diff --git a/src/runtime/test_runner/expect.rs b/src/runtime/test_runner/expect.rs index 671c51e4a574..9fc598cd66e0 100644 --- a/src/runtime/test_runner/expect.rs +++ b/src/runtime/test_runner/expect.rs @@ -1333,6 +1333,7 @@ impl Expect { own_properties_only: false, observable: true, only_non_index_properties: false, + include_symbols: false, }, )?; diff --git a/src/runtime/test_runner/expect/toBeEmpty.rs b/src/runtime/test_runner/expect/toBeEmpty.rs index 4ad772162e76..a1067d3ad76c 100644 --- a/src/runtime/test_runner/expect/toBeEmpty.rs +++ b/src/runtime/test_runner/expect/toBeEmpty.rs @@ -54,6 +54,9 @@ pub(crate) fn to_be_empty( skip_empty_name: false, own_properties_only: false, include_value: true, + // jest-extended compares against `{}` with an equality + // that sees enumerable Symbol keys, so count them too. + include_symbols: true, // FIXME: can we do this? ..Default::default() }, diff --git a/test/bundler/transpiler/macro-test.test.ts b/test/bundler/transpiler/macro-test.test.ts index 0d8dca08b5b2..965008868621 100644 --- a/test/bundler/transpiler/macro-test.test.ts +++ b/test/bundler/transpiler/macro-test.test.ts @@ -12,6 +12,7 @@ import defaultMacro, { identity as identity1, identity as identity2, ireturnapromise, + symbolKeys, } from "./macro.ts" assert { type: "macro" }; import * as macros from "./macro.ts" assert { type: "macro" }; @@ -38,6 +39,14 @@ test("type coercion", () => { expect(identity(true)).toBe(true); }); +// A Symbol key has no source form. The inlined object keeps the string keys +// only, like JSON.stringify, instead of a string key named by the description. +test("object with Symbol keys", () => { + const value = symbolKeys(); + expect(value).toEqual({ v: 2 }); + expect(Reflect.ownKeys(value)).toEqual(["v"]); +}); + test("escaping", () => { expect(identity("\\")).toBe("\\"); expect(identity("\f")).toBe("\f"); diff --git a/test/bundler/transpiler/macro.ts b/test/bundler/transpiler/macro.ts index 9da8d72c5a10..c21c8768262f 100644 --- a/test/bundler/transpiler/macro.ts +++ b/test/bundler/transpiler/macro.ts @@ -23,3 +23,7 @@ export async function ireturnapromise() { setTimeout(() => resolve("aaa"), 100); return promise; } + +export function symbolKeys() { + return { v: 2, [Symbol.for("s")]: 1, [Symbol("d")]: 3, [Symbol()]: 4 }; +} diff --git a/test/js/bun/spawn/spawn-env.test.ts b/test/js/bun/spawn/spawn-env.test.ts index 79e7ae8a9f38..d8b60c349775 100644 --- a/test/js/bun/spawn/spawn-env.test.ts +++ b/test/js/bun/spawn/spawn-env.test.ts @@ -1,6 +1,6 @@ import { spawn } from "bun"; -import { test } from "bun:test"; -import { bunExe } from "harness"; +import { expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; test("spawn env", async () => { const env = {}; @@ -22,3 +22,17 @@ test("spawn env", async () => { } catch (e) {} } }); + +// A Symbol key is not an environment variable name. It used to reach the +// child as a variable named by the symbol description. +test("spawn env skips Symbol keys", async () => { + await using proc = spawn({ + cmd: [bunExe(), "-e", "console.log(JSON.stringify([process.env.SYMKEY ?? null, process.env.PLAIN]))"], + env: { ...bunEnv, PLAIN: "1", [Symbol("SYMKEY")]: "leaked" }, + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe('[null,"1"]\n'); + expect(exitCode).toBe(0); +}); diff --git a/test/js/bun/yaml/yaml.test.ts b/test/js/bun/yaml/yaml.test.ts index 80b6410b3171..d3a8ac84eda5 100644 --- a/test/js/bun/yaml/yaml.test.ts +++ b/test/js/bun/yaml/yaml.test.ts @@ -4302,8 +4302,8 @@ refs: normalKey: "normal value", symbolValue: sym, }; - // Symbol keys are not enumerable, symbol values are undefined - expect(YAML.stringify(obj, null, 2)).toBe("normalKey: normal value\ntest: symbol key value"); + // Symbol keys are skipped (like JSON.stringify), symbol values are undefined + expect(YAML.stringify(obj, null, 2)).toBe("normalKey: normal value"); }); test("handles WeakMap and WeakSet", () => { diff --git a/test/js/node/http2/node-http2.test.js b/test/js/node/http2/node-http2.test.js index 2ed62caf61f6..f73bebcc9863 100644 --- a/test/js/node/http2/node-http2.test.js +++ b/test/js/node/http2/node-http2.test.js @@ -1799,6 +1799,39 @@ it("sensitive headers should work", async () => { } }); +// The never-index list lives under a Symbol key of the headers object. The +// native header walk must skip Symbol keys. It used to send them as headers +// named by the symbol description ("nodejs.http2.sensitiveheaders: cookie"). +it("Symbol keys of the headers object are not sent as headers", async () => { + const server = http2.createServer((req, res) => { + res.end(JSON.stringify(Object.keys(req.headers).filter(name => !name.startsWith(":")))); + }); + let client; + try { + const { promise, resolve, reject } = Promise.withResolvers(); + server.listen(0, () => { + client = http2.connect(`http://localhost:${server.address().port}`); + client.on("error", reject); + const req = client.request({ + ":path": "/", + cookie: "a=b", + [http2.sensitiveHeaders]: ["cookie"], + [Symbol("local")]: "v", + }); + let body = ""; + req.setEncoding("utf8"); + req.on("data", chunk => (body += chunk)); + req.on("end", () => resolve(body)); + req.on("error", reject); + req.end(); + }); + expect(JSON.parse(await promise)).toEqual(["cookie"]); + } finally { + server.close(); + client?.close?.(); + } +}); + it("http2 session.goaway() validates input types", async done => { const { mustCall } = createCallCheckCtx(done); const server = http2.createServer((req, res) => {