Skip to content

console: format Date from internal [[DateValue]], not JSON.stringify - #35287

Closed
robobun wants to merge 3 commits into
mainfrom
farm/2d6ec4c3/console-date-internal-value
Closed

robobun wants to merge 3 commits into
mainfrom
farm/2d6ec4c3/console-date-internal-value

Conversation

@robobun

@robobun robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

What

console.log / Bun.inspect formatted Date values by calling JSON.stringify(value) and trimming the surrounding quotes. JSON.stringify dispatches through the value's own toJSON → toISOString, so any Date carrying an own/subclass hook ran user code inside the formatter.

Repro

const a = new Date(0);
a.toISOString = () => { throw new Error("iso-boom") };
console.log(a);            // bun: throws iso-boom OUT of console.log; node: 1970-01-01T00:00:00.000Z

const c = new Date(0);
c.toJSON = () => "SPOOFED";
console.log(c);            // bun prints: SPOOFED

const d = new Date(0);
d.toJSON = () => ({ nested: { fake: 1 } });
console.log(d);            // bun prints corrupted: "nested":{"fake":1}  (quote-trim slices a non-string)

const e = new Date(0);
e.toJSON = () => { throw new Error("mid") };
console.log(["before", e, "after"]);   // bun: prints `[ "before",` then throws mid-print

Node reads the internal date value and never calls user toJSON/toISOString. Bun's own ported util.inspect(date) is also correct; only the native console arm dispatches.

Realistic trigger: any Date carrying an own/subclass toJSON/toISOString (ORM wrappers, moment-style subclasses, Object.assign(new Date(), {toJSON})). Logging it kills the logging call.

Fix

Switch both formatters (ConsoleObject.rs and the test runner's pretty_format.rs) to value.to_iso_string(), which reads DateInstance::internalNumber() via Bun::toISOString and never executes JS. None (NaN time value) yields Invalid Date as before. This also drops the json_stringify → fixed-buffer render → quote-trim dance.

Verification

$ USE_SYSTEM_BUN=1 bun test test/js/bun/util/inspect.test.js -t "Date ignores own toJSON"
(fail) Date ignores own toJSON/toISOString when formatting
  error: expect(received).not.toThrow()
  Error message: "iso-boom"

$ bun bd test test/js/bun/util/inspect.test.js -t "Date ignores own toJSON"
(pass) Date ignores own toJSON/toISOString when formatting
(pass) console.log of Date with throwing toJSON does not throw

[review] gate passed · iteration 1 · 3 files touched

fails on main (without fix)
ASAN without fix: 2 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/util/inspect.test.js
bun test v1.4.0 (1b04c4f4c)

test/js/bun/util/inspect.test.js:
(pass) prototype [306.22ms]
(pass) getters [5.28ms]
(pass) setters [3.49ms]
(pass) getter/setters [2.12ms]
(pass) Timeout [4.76ms]
(pass) when prototype defines the same property, don't print the same property twice [2.15ms]
(pass) Blob inspect [8.55ms]
(pass) utf16 property name [64.75ms]
(pass) latin1 [4.08ms]
(pass) Request object [2.60ms]
(pass) MessageEvent [1.86ms]
(pass) MessageEvent with no data set [1.79ms]
(pass) MessageEvent with deleted data [2.46ms]
(pass) TypedArray prints [96.64ms]
(pass) BigIntArray [31.49ms]
(pass) Float32Array 42.68000030517578 [4.12ms]
(pass) Float32Array 42.68 [3.93ms]
(pass) Float64Array 42.68000030517578 [1.34ms]
(pass) Float64Array 42.68 [1.53ms]
(pass) jsx with two elements [26.83ms]
(pass) jsx with anon component [2.43ms]
(pass) jsx with fragment [4.39ms]
(pass) inspect [75.03ms]
(pass) latin1 supplemental > latin1 (input) "äbc" [ "äbc" ] [1.79ms]
(pass) latin1 supplemental > latin1 (input) "cbä" 
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (1b04c4f4c)

test/js/bun/util/inspect.test.js:
(pass) prototype [3.94ms]
(pass) getters [0.10ms]
(pass) setters [0.04ms]
(pass) getter/setters [0.02ms]
(pass) Timeout [0.10ms]
(pass) when prototype defines the same property, don't print the same property twice [0.04ms]
(pass) Blob inspect [0.31ms]
(pass) utf16 property name [1.15ms]
(pass) latin1 [0.05ms]
(pass) Request object [0.05ms]
(pass) MessageEvent [0.03ms]
(pass) MessageEvent with no data set [0.02ms]
(pass) MessageEvent with deleted data [0.03ms]
(pass) TypedArray prints [0.96ms]
(pass) BigIntArray [0.31ms]
(pass) Float32Array 42.68000030517578 [0.07ms]
(pass) Float32Array 42.68 [0.05ms]
(pass) Float64Array 42.68000030517578 [0.03ms]
(pass) Float64Array 42.68
(pass) jsx with two elements [0.57ms]
(pass) jsx with anon component [0.03ms]
(pass) jsx with fragment [0.07ms]
(pass) inspect [0.72ms]
(pass) latin1 supplemental > latin1 (input) "äbc" [ "äbc" ] [0.03ms]
(pass) latin1 supplemental > latin1 (input) "cbä" [ "cbä" ]
(pass) latin1 supplemental > latin1 (input) "cäb" [ "cäb" ]
(pass) latin1 supplemental > latin1 (input) "äbc äbc" [ "äbc äbc" ]
(pass) latin1 supplemental >
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/util/inspect.test.js
bun test v1.4.0 (1b04c4f4c)

test/js/bun/util/inspect.test.js:
(pass) prototype [292.28ms]
(pass) getters [5.04ms]
(pass) setters [3.41ms]
(pass) getter/setters [2.06ms]
(pass) Timeout [5.20ms]
(pass) when prototype defines the same property, don't print the same property twice [2.18ms]
(pass) Blob inspect [8.45ms]
(pass) utf16 property name [59.86ms]
(pass) latin1 [3.89ms]
(pass) Request object [2.37ms]
(pass) MessageEvent [1.79ms]
(pass) MessageEvent with no data set [1.95ms]
(pass) MessageEvent with deleted data [2.43ms]
(pass) TypedArray prints [90.46ms]
(pass) BigIntArray [31.82ms]
(pass) Float32Array 42.68000030517578 [4.08ms]
(pass) Float32Array 42.68 [4.07ms]
(pass) Float64Array 42.68000030517578 [1.32ms]
(pass) Float64Array 42.68 [1.49ms]
(pass) jsx with two elements [26.58ms]
(pass) jsx with anon component [2.49ms]
(pass) jsx with fragment [4.37ms]
(pass) inspect [65.36ms]
(pass) latin1 supplemental > latin1 (input) "äbc" [ "äbc" ] [1.59ms]
(pass) latin1 supplemental > latin1 (input) "cbä" 
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 690ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/5] gen generated_host_exports.rs
generated_host_exports.rs: 91 exports (host=3, lazy=10, generic=78, rust=0); 237 extern-C blocks audited
[1/5] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_jsc v0.0.0 (/workspace/bun/src/jsc)
�[1m�[92m   Compiling�[0m bun_ast_jsc v0.0.0 (/workspace/bun/src/ast_jsc)
�[1m�[92m   Compiling�[0m bun_js_parser_jsc v0.0.0 (/workspace/bun/src/js_parser_jsc)
�[1m�[92m   Compiling�[0m bun_patch_jsc v0.0.0 (/workspace/bun/src/patch_jsc)
�[1m�[92m   Compiling�[0m bun_semver_jsc v0.0.0 (/workspace/bun/src/semver_jsc)
�[1m�[92m   Compiling�[0m bun_sys_jsc v0.0.0 (/workspace/bun/src/sys_jsc)
�[1m�[92m   Compiling�[0m bun_bundler_jsc v0.0.0 (/workspace/bun/src/bundler_jsc)
�[1m�[92m   Compiling�[0m bun_http_jsc v0.0.0 (/workspace/bun/src/http_jsc)
�[1m�[92m   Compiling�[0m bun_sql_jsc v0.0.0 (/workspace/bun/src/sql_jsc)
�[1m�[92m   
... (truncated)
diff hotspot
src/jsc/ConsoleObject.rs                 | 36 +++++++---------
 src/runtime/test_runner/pretty_format.rs | 36 +++++++---------
 test/js/bun/util/inspect.test.js         | 71 ++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 43 deletions(-)

gate history · 2 passed · 0 rejected · iteration 1

evidence per changed file
file                                      reads  edits  tests
src/jsc/ConsoleObject.rs                      2      2      0
src/runtime/test_runner/pretty_format.rs      1      2      0
test/js/bun/util/inspect.test.js              3      3      0

console.log / Bun.inspect formatted Date values by calling
JSON.stringify(value) and trimming the quotes. JSON.stringify dispatches
through the value's own toJSON -> toISOString, so any Date carrying an
own or subclass hook (ORM wrappers, Object.assign(new Date(), {toJSON}))
ran user code inside the formatter:

  - a throwing toISOString/toJSON threw out of console.log
  - a non-callable toISOString threw a TypeError
  - a spoofing toJSON controlled the printed text
  - a toJSON returning an object produced corrupted output after the
    quote-trim sliced a non-string
  - a throw mid-array left partial output on stdout

Node and bun's own util.inspect read the internal date value and never
call these hooks.

Switch both formatters (ConsoleObject.rs and the test runner's
pretty_format.rs) to value.to_iso_string(), which reads
DateInstance::internalNumber() via Bun::toISOString and never executes
JS. NaN yields 'Invalid Date' as before.
@robobun

robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: Diff is ready. New tests fail on the released binary and pass on the debug build. All review threads resolved; two LGTM bot reviews.

Reproduced with: USE_SYSTEM_BUN=1 bun test test/js/bun/util/inspect.test.js -t 'Date ignores own toJSON'

CI runs #78715 and #78730 show failures only in unrelated lanes (no-orphans.test.ts perl timeout on darwin, test-https-server-connections-checking-leak.js file-watcher EAGAIN panic on debian aarch64, plus install/TLS/fs-promises flakes). None touch inspect.test.js, console-log.test.ts, or the two edited formatters. Both [new] failures reported to main-break triage. Needs a maintainer to merge.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

Date formatting in console and test-runner output now uses the Date’s internal timestamp through to_iso_string, ignoring overridden serialization methods while preserving invalid-date and non-Date JSON behavior. Tests cover direct, array, subclass, and subprocess logging scenarios.

Date formatting behavior

Layer / File(s) Summary
Direct internal Date formatting
src/jsc/ConsoleObject.rs, src/runtime/test_runner/pretty_format.rs
Date output bypasses json_stringify, formats from the internal date value, handles Invalid Date, and retains general JSON stringification for non-Date values.
Override regression coverage
test/js/bun/util/inspect.test.js
Tests verify formatting with throwing, non-function, overridden, and subclass Date serialization methods, including arrays and subprocess logging.

Possibly related PRs

  • oven-sh/bun#34936: Also changes console formatting to bypass user-defined JSON serialization behavior.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: Date formatting now uses the internal [[DateValue]] instead of JSON.stringify.
Description check ✅ Passed It covers the PR purpose, examples of the bug, the fix, and verification steps, even though the headings don't exactly match the template.

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

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

Actionable comments posted: 1

🤖 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 `@test/js/bun/util/inspect.test.js`:
- Around line 556-561: Update the subprocess assertions around Promise.all to
compare one combined result object containing stdout, stderr, and exitCode.
Preserve the existing newline normalization for stdout and expected values while
replacing the separate expect calls with the suite’s combined-object assertion
pattern.
🪄 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: 9b3faf13-a577-430a-a8aa-d66ead40ee7c

📥 Commits

Reviewing files that changed from the base of the PR and between 892b1da and c511be8.

📒 Files selected for processing (3)
  • src/jsc/ConsoleObject.rs
  • src/runtime/test_runner/pretty_format.rs
  • test/js/bun/util/inspect.test.js

Comment thread test/js/bun/util/inspect.test.js Resolved
@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Fix console.log calling toJSON on objects #35045 - Also fixes console.log/Bun.inspect invoking user-overridable toJSON on objects during formatting, changing the same JSAsJSONType code path in ConsoleObject.rs

🤖 Generated with Claude Code

@robobun

robobun commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author

Not a duplicate of #35045. That PR changes the JSAsJSONType arm (TagPayload::ToJSON → TagPayload::Object) in the tag dispatcher. This PR changes the JSDate arm's print_json body to read DateInstance::internalNumber() instead of calling JSON.stringify. Different JSTypes, different code paths; neither patch touches the other's lines.

@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 — replaces the json_stringify → quote-trim path for JSDate with the existing to_iso_string() helper, which reads DateInstance::internalNumber() directly and never dispatches to user JS.

What was reviewed:

  • Verified JSC__JSValue__toISOString (bindings.cpp:5794) does a dynamicDowncast<DateInstance> + internalNumber() and returns -1 for non-Date/NaN → unwrap_or(b"Invalid Date") preserves the existing Invalid Date output.
  • Buffer widened 36→64 to match the C++ char[64] signature (also used by TOMLObject.rs); expanded-year form fits.
  • Non-Date Tag::JSON path is unchanged — json_stringify just moved below the early return; add_for_new_line now gets the actual printed length in the Date branch.
  • Both sibling formatters (ConsoleObject.rs, pretty_format.rs) fixed identically; tests cover throwing/spoofing/non-function hooks, subclass, NaN, mid-array, and the subprocess console.log path.
Extended reasoning...

Overview

Two Rust formatters (src/jsc/ConsoleObject.rs and src/runtime/test_runner/pretty_format.rs) had a Tag::JSON arm that special-cased JSType::JSDate by calling json_stringify, rendering into a 36-byte buffer, and stripping the surrounding quotes. Because JSON.stringify on a Date dispatches through user-visible toJSON/toISOString, an own or subclass hook could throw out of console.log or spoof/corrupt the output. The fix replaces that with the pre-existing JSValue::to_iso_string helper, which calls JSC__JSValue__toISOString → Bun::toISOString — pure C++ over DateInstance::internalNumber() and vm.dateCache. The non-Date Tag::JSON fallthrough (json_stringify + print) is preserved verbatim, just relocated after the early return. Tests are added to test/js/bun/util/inspect.test.js alongside the existing new Date(..) coverage.

Security risks

None introduced; if anything the change reduces surface by no longer executing arbitrary user JS from inside the console formatter. to_iso_string writes into a caller-owned [u8; 64] and returns a bounded slice; the C++ side's max output (~28 bytes for expanded-year ISO) is well under 64.

Level of scrutiny

Low-medium. This is a targeted output-formatting fix in a well-understood path, reusing an existing helper already exercised by TOMLObject.rs and BunProcess.cpp. No new FFI, no allocation/ownership changes, no control-flow beyond an early return that was already there. The only behavioral delta for the non-Date arm is that json_stringify now runs after the Date check instead of before — semantically identical since the Date branch returned early anyway.

Other factors

  • Both parallel formatters were updated (satisfies "fix the whole class").
  • Existing new Date(..) test continues to cover valid ISO output and Invalid Date; new tests add the hostile-override matrix (throwing, non-function, spoofing string, spoofing object, subclass, NaN) plus a spawned subprocess exercising the real console.log writer.
  • CodeRabbit's combined-object-assertion nit was applied in a24ca95 and the thread is resolved; no other outstanding comments.
  • add_for_new_line in the Date branch now receives the printed length rather than the quoted JSON length — a minor accuracy improvement, not a regression.

@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 — targeted fix that swaps the JSON.stringify → quote-trim dance for the existing to_iso_string helper, so Date formatting no longer invokes user JS.

What was reviewed:

  • Verified JSC__JSValue__toISOString reads DateInstance::internalNumber() via dynamicDowncast and never enters JS; None/NaN → Invalid Date preserved.
  • Both parallel formatters (ConsoleObject.rs, pretty_format.rs) updated symmetrically; non-Date Tag::JSON path is unchanged (just moved after the early return).
  • Buffer size matches the Rust signature's required [u8; 64]; add_for_new_line now gets the actual output length instead of the JSON string's.
  • Tests cover throwing/spoofing/non-function toJSON/toISOString, subclass, NaN, mid-array, and a subprocess console.log case; combined-object assertion applied per review feedback.
Extended reasoning...

Overview

The PR replaces the JSDate arm in both native formatters (src/jsc/ConsoleObject.rs and src/runtime/test_runner/pretty_format.rs). Previously, both called value.json_stringify(...) — which dispatches through the value's own toJSON → toISOString — then rendered the result into a 36-byte stack buffer and stripped the surrounding quotes. Now they call value.to_iso_string(global, &mut [0u8; 64]), which wraps JSC__JSValue__toISOString in bindings.cpp: that helper does a dynamicDowncast<DateInstance>, reads internalNumber(), and formats via Bun::toISOString (a copy of JSC's own DatePrototype ISO formatter). No JS is entered. None maps to b"Invalid Date", matching the old ConsoleObject.rs behavior and fixing pretty_format.rs (which previously would quote-trim null into ul for NaN dates). The non-Date json_stringify fallback is preserved unchanged, just relocated after the Date early-return.

Security risks

None. This removes a path where user-controlled toJSON/toISOString could execute inside the formatter, which is strictly a robustness improvement — console.log can no longer throw or be spoofed by a hostile Date. No new attack surface is introduced.

Level of scrutiny

Low-to-medium. The change is small (~40 lines of native code across two mirrored sites), uses an existing, already-exercised in-tree helper (to_iso_string / Bun::toISOString, also used by process.report), and the buffer size exactly matches the Rust signature's &mut [u8; 64]. The test-runner formatter is lower-stakes (diff output). Node compat is the reference behavior here, and Node's util.inspect reads the internal slot the same way.

Other factors

  • Test coverage is thorough for this class: throwing toISOString, non-callable toISOString, string-returning toJSON, object-returning toJSON (the old quote-trim corruption case), throwing toJSON mid-array, NaN date with spoofed toJSON, and a Date subclass. A subprocess test verifies console.log itself doesn't throw. Existing new Date(..) tests (including Invalid Date) still pass, confirming no regression on the happy path.
  • The PR's gate evidence shows the new tests fail on the unfixed ASAN build and pass with the fix.
  • CodeRabbit's one comment (combined-object subprocess assertion) was applied in a24ca95 and marked resolved.
  • The duplicate-PR bot flagged #35045; robobun correctly explained they touch different arms (JSAsJSONType vs JSDate) and don't conflict.

@robobun

robobun commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author
Updated 10:59 AM PT - Jul 23rd, 2026

❌ @robobun, your commit 1b04c4f has 1 failures in Build #78730 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 35287

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

bun-35287 --bun

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-23, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

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.

2 participants