Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/jsc/JSPropertyIterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -30,6 +35,7 @@ impl JSPropertyIteratorOptions {
own_properties_only: true,
observable: true,
only_non_index_properties: false,
include_symbols: false,
}
}
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -250,6 +258,7 @@ impl JSPropertyIteratorImpl {
count: &mut usize,
own_properties_only: bool,
only_non_index_properties: bool,
include_symbols: bool,
) -> JsResult<Option<NonNull<JSPropertyIteratorImpl>>> {
// may return null without an exception
let raw = from_js_host_call_generic(global_object, || {
Expand All @@ -259,6 +268,7 @@ impl JSPropertyIteratorImpl {
count,
own_properties_only,
only_non_index_properties,
include_symbols,
)
})?;
Ok(NonNull::new(raw))
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 6 additions & 2 deletions src/jsc/bindings/JSPropertyIterator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down
1 change: 1 addition & 0 deletions src/runtime/api/JSTranspiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions src/runtime/test_runner/expect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1333,6 +1333,7 @@ impl Expect {
own_properties_only: false,
observable: true,
only_non_index_properties: false,
include_symbols: false,
},
)?;

Expand Down
3 changes: 3 additions & 0 deletions src/runtime/test_runner/expect/toBeEmpty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
},
Expand Down
9 changes: 9 additions & 0 deletions test/bundler/transpiler/macro-test.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };
Expand All @@ -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");
Expand Down
4 changes: 4 additions & 0 deletions test/bundler/transpiler/macro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
18 changes: 16 additions & 2 deletions test/js/bun/spawn/spawn-env.test.ts
Original file line number Diff line number Diff line change
@@ -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 = {};
Expand All @@ -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);
});
4 changes: 2 additions & 2 deletions test/js/bun/yaml/yaml.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
33 changes: 33 additions & 0 deletions test/js/node/http2/node-http2.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
Loading