Skip to content

websocket: close() with no code sends an empty close payload - #33457

Closed
robobun wants to merge 2 commits into
mainfrom
farm/405b72ad/websocket-close-no-status
Closed

robobun wants to merge 2 commits into
mainfrom
farm/405b72ad/websocket-close-no-status

Conversation

@robobun

@robobun robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

WebSocket#close() with no arguments put a 1000 status code on the wire, so the peer could not tell close() apart from close(1000). RFC 6455 7.1.5 reserves 1005 ("no status received") precisely for that distinction, and server logic keyed on it saw Bun clients requesting a normal closure they never asked for.

Repro

A raw TCP server that completes the handshake and prints the client's close frame:

const ws = new WebSocket(`ws://127.0.0.1:${srv.port}/`);
ws.onopen = () => ws.close(); // no code, no reason
bun           : client close frame: payload len=2 code=1000
ws / browsers : payload len=0  -> the peer reports 1005

Cause

WebSocket::close() (src/jsc/bindings/webcore/WebSocket.cpp) collapsed an absent code to 1000 before handing it to the frame builder:

int code = optionalCode ? optionalCode.value() : static_cast<int>(1000);

The native client then always framed a 2-byte status code, so a bodyless close frame was unreachable from JS.

Fix

Pass 1005 down instead. It is reserved and never legal on the wire (isValidCloseCodeForSending already rejects it from user input), which is how WebKit marks "no code was specified". send_close_with_body now takes an Option<u16> and frames a zero-byte payload when there is no code; JS sees 1005 in the CloseEvent, matching step 3 of the WHATWG close() algorithm ("If neither code nor reason is present, the WebSocket Close message must not have a body"), ws, undici and WebKit.

A reason keeps the body: RFC 6455 5.5.1 puts the reason after the status code, so close(undefined, "bye") still sends 1000 in front of it. An explicitly passed "" is present under WebIDL and keeps the body too; only an omitted reason (a null String from the binding) leaves it out.

Bun's own uWS server already skips 1005/1006 in formatClosePayload, so only the client fabricated a code.

Verification

test/js/web/websocket/websocket-close-code.test.ts asserts the bytes on the wire and the CloseEvent for close(), close(1000), close(undefined, "bye") and close(undefined, ""), plus a Bun.serve round trip showing the server's close handler now reports 1005. Two existing assertions on the old behavior are updated (websocket-client.test.ts, ws.test.ts), where ws.close() now reports 1005 exactly as npm ws does.

ws.test.ts also runs its echo server under node now, the way websocket-client.test.ts already does with the same fixture. That block spawns a server process per test against a 1s budget, which a debug build spends on startup alone, so all 30 of its tests timed out under bun bd test; under node they pass.

fail before / pass after
without the fix:
(fail) close() with no code reports 1005 to the server and to JS
(fail) close() with no code sends a close frame with no payload
(fail) WebSocket > close() > (no arguments)        [websocket-client.test.ts]
(fail) WebSocket > close() > (no arguments)        [ws.test.ts]

$ bun bd test websocket-close-code.test.ts websocket-client.test.ts ws.test.ts
 103 pass, 0 fail

WebSocket::close() turned an absent code into 1000 before handing it to
the frame builder, so a peer could not tell close() apart from
close(1000): it saw a normal-closure request the caller never made.

Hand 1005 ("no status received", reserved and never legal on the wire)
to the native client instead and have it frame a close payload of zero
bytes. The peer then reports 1005, as does the local CloseEvent, per
RFC 6455 7.1.5 and step 3 of the WHATWG close() algorithm. A reason
without a code still sends 1000, since the wire format puts the status
code in front of the reason.

Bun's own uWS server already skips 1005/1006 in formatClosePayload, so
only the client fabricated a code.
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4e5be232-29cb-403a-bf0d-0b0d80d665b8

📥 Commits

Reviewing files that changed from the base of the PR and between 48ff9eb and cbfa886.

📒 Files selected for processing (5)
  • src/http_jsc/websocket_client.rs
  • src/jsc/bindings/webcore/WebSocket.cpp
  • test/js/first_party/ws/ws.test.ts
  • test/js/web/websocket/websocket-client.test.ts
  • test/js/web/websocket/websocket-close-code.test.ts

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

@robobun

robobun commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Comment thread src/jsc/bindings/webcore/WebSocket.cpp Resolved
A reason passed as "" is present under WebIDL, so the Close frame keeps
its body and the status code in front of it. Only an omitted reason, a
null String from the binding, leaves the payload out. Pins the
close(undefined, "") case with a test.

Run ws.test.ts's echo server under node, as websocket-client.test.ts
already does with the same fixture: the block spawns a server per test
on a 1s budget, which a debug build spends on startup alone.
@robobun

robobun commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status on the red CI, since none of it is this diff.

Build 68918 (current head cbfa886f) has finished: 196 test-bun jobs passed, across every platform including x64-asan. Not one websocket test failed anywhere. The 14 red lanes break down as:

  • 13 lanes: the same three test/js/bun/cookie/cookie-map.test.ts tests (delete with prefixed cookie names > ...), identical everywhere. These are red on main's current tip, which is also this PR's merge base: build 68832 on 48ff9eb2 ("cookie: update remaining cookie-map Expires assertions to IMF-fixdate") fails the same three, and they reproduce on a clean checkout with no changes applied.
  • 1 lane (darwin 26 aarch64): infrastructure, not a test.
    Error: buildkite-agent artifact download timed out after 120s for step
    'darwin-aarch64-build-bun'. Refusing to continue with a partial download
    

A handful of jobs also expired waiting for an agent (freebsd/windows build-cpp, binary-size), which blocked their downstream steps.

Since 48ff9eb2 is main's tip there is nothing newer to rebase onto, and retriggering would reproduce the cookie failures deterministically, so I have left the build alone. Happy to rebase the moment those tests are green on main.

This diff touches WebSocket close framing only. The three test files it changes run 103 pass / 0 fail on a debug build:

$ bun bd test websocket-close-code.test.ts websocket-client.test.ts ws.test.ts
 103 pass, 0 fail

@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 — thanks for switching to reason.isNull() and adding the close(undefined, "") test.

Extended reasoning...

Overview

This PR fixes WebSocket#close() with no arguments to send a bodyless Close frame (so the peer reports 1005 "no status received") instead of fabricating code 1000 on the wire. It touches:

  • src/jsc/bindings/webcore/WebSocket.cpp: pass closeCodeNotSpecified (1005) as a sentinel when no code and no reason are given, keyed on reason.isNull().
  • src/http_jsc/websocket_client.rs: send_close_with_body now takes Option<u16> and frames a zero-byte payload when None; the extern-C close entrypoint maps 1005 → None. All three internal callers updated.
  • New wire-level tests in websocket-close-code.test.ts asserting the exact frame bytes for close(), close(1000), close(undefined, "bye"), and close(undefined, ""), plus a Bun.serve round-trip; two existing 1000→1005 assertions updated in websocket-client.test.ts and ws.test.ts.

Follow-up since my last review

I previously left one nit suggesting reason.isEmpty() → reason.isNull() to distinguish close() from close(undefined, ""). Commit cbfa886 addresses it exactly and adds a test locking in that close(undefined, "") sends 1000 with an empty reason. Nothing else changed.

Security risks

None. This only affects the 2-byte status code (or its absence) in an outbound Close frame; no new untrusted-input parsing, no auth/crypto/permissions surface. 1005 is already rejected by isValidCloseCodeForSending so user code cannot smuggle it as a wire value.

Level of scrutiny

Medium: it changes observable wire behavior in the WebSocket client, but the change is a spec-conformance fix that aligns Bun with browsers, npm ws, undici, and WebKit. The Rust refactor is mechanical — payload_len correctly collapses to 0 when code is None, the header/mask/frame_len derive from it, and dispatch_code.or(code).unwrap_or(CLOSE_CODE_NOT_SPECIFIED) preserves the previous JS-visible semantics for every existing caller while yielding 1005 for the new bodyless path.

Other factors

  • The bug-hunting system found no issues.
  • CI failure is cookie-map.test.ts, unrelated to this diff.
  • The ws.test.ts nodeExe() ?? bunExe() swap for the echo server mirrors the existing pattern in websocket-client.test.ts and is a test-speed tweak, not a behavior change.
  • Test coverage is thorough at the byte level and verified fail-before/pass-after.

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

@robobun robobun closed this Sep 13, 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.

1 participant