Repository navigation
Conversation
|
Reproduced with the raw-TCP repro in the PR body: bodyless Close echoed as CI on build #80259 (final): 195 jobs passed with no websocket-client failures; the only hard failure is |
|
Warning Review limit reached
Next review available in: 20 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughChangesThe WebSocket client now supports bodyless Close frames, preserves received status codes when echoing, and derives JavaScript close codes through optional payload handling. New TCP-level tests cover legal codes, bodyless closes, and Close frames split across reads. WebSocket close handling
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 3:11 AM PT - Jul 25th, 2026
❌ @robobun, your commit e6255cc has 1 failures in
Add 🧪 To try this PR locally: bunx bun-pr 35529That installs a local version of the PR into your bun-35529 --bun |
||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
|
Not a duplicate of #33457. They share the
#33457's |
75a4c3e to
2b32f3f
Compare
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟣
src/http_jsc/websocket_client.rs:900-907— Pre-existing (not introduced by this PR), noting since it's the same "close code not echoed verbatim" class:recv_close'sbody_remain == 1andbody_remain == 0checks aren't guarded by!self.control_frame_started.get(), unlikerecv_ping_or_pong. Oncebuffer_control_payloadhas run once and returnedNone,body_remainis repurposed to "bytes buffered so far", so if a Close frame's 2-byte header arrives alone in one TCP read and the code bytes arrive in the next, re-entry hits the bodyless branch (echoes bodyless, JS sees 1005) and the server's actual code is discarded; header+1 payload byte re-enters intoInvalidControlFrame. Guarding both checks with!self.control_frame_started.get()would fix it — happy to do as a follow-up.Extended reasoning...
What this is
recv_close()decides how to handle a received Close frame by inspectingcursor.body_remain:fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step { if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD { return self.recv_failed(ErrorCode::InvalidControlFrame); } if cursor.body_remain == 0 { self.close_received.set(true); self.send_close(); return Step::Terminated; } let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else { return Step::NeedMoreData; }; ... }
These two guards assume
body_remainstill means "declared payload length from the frame header". Butbuffer_control_payload()'s doc comment states: "Whilecontrol_frame_started,cursor.body_remaincounts bytes buffered so far, not bytes left." Oncebuffer_control_payloadhas run once and returnedNone(partial read), it has setcontrol_frame_started = trueand repurposedbody_remain.handle_data_loop's epilogue then persists that repurposed value intoself.receive_body_remain, and the nexthandle_datacall restores it intocursor.body_remainbefore re-enteringrecv_close.recv_ping_or_ponghandles this correctly — its size check is gated on!self.control_frame_started.get().recv_closeis not.Step-by-step trigger
Server sends a Close frame with code 1000, but the TCP stack delivers it as two reads: first the 2-byte header
[0x88, 0x02]alone, then the 2-byte code[0x03, 0xE8].Read 1 (
data = [0x88, 0x02]):recv_frame_headerconsumes both bytes, setsstate = Close,body_remain = 2, returnsContinuewithcursor.dataempty.recv_close:body_remain = 2→ falls through tobuffer_control_payload.buffer_control_payload:control_frame_startedis false → setsping_len = 2,body_remain = 0,control_frame_started = true.cursor.datais empty so nothing is copied.payload_len (2) > body_remain (0)→ returnsNone.recv_closereturnsNeedMoreData. Loop epilogue persistsreceive_body_remain = 0,receive_state = Close.
Read 2 (
data = [0x03, 0xE8]):
5.handle_data_looprestorescursor.body_remain = 0,cursor.state = Close.
6.recv_close:body_remain == 0→ takes the bodyless branch →self.send_close()echoes a bodyless Close and dispatches 1005 to JS.The server's actual code (1000) is discarded and its bytes are never consumed.
Variant: if exactly 1 payload byte arrives with the header (
[0x88, 0x02, 0x03]),buffer_control_payloadcopies 1 byte andbody_remainpersists as 1. On re-entryrecv_closeseesbody_remain == 1→recv_failed(InvalidControlFrame)→ abrupt close (JS sees 1002, not the server's code).Why nothing prevents it
control_frame_startedis aCell<bool>onself, so it survives acrosshandle_datacalls.handle_data_loopunconditionally persistscursor.body_remainonNeedMoreData. The only defense would be gating the== 0/== 1checks on!self.control_frame_started.get()— whichrecv_ping_or_pongdoes for its> MAX_CONTROL_PAYLOADcheck, butrecv_closedoes not.The existing test
websocket-close-fragmented.test.tsdoesn't cover this: it sends the header plus 12 payload bytes together in the first segment (code + 10-byte reason), so on re-entrybody_remain = 12and both checks are bypassed.Impact and relationship to this PR
This is pre-existing; the PR neither introduces nor worsens it. Before this PR, the
body_remain == 0misroute calledsend_close()which echoed 1000 on the wire and dispatched 1005 to JS; after this PR it echoes bodyless and still dispatches 1005 — JS-visible behavior is identical, and the wire echo is arguably less wrong now (bodyless is at least a legal echo shape). Thebody_remain == 1misroute is byte-identical before and after.It's flagged here only because the PR touches
recv_close/send_closedirectly and the failure mode — "server's close code is not echoed verbatim" — is exactly the class the PR title claims to address, so a follow-up in the same area seems worthwhile. The trigger is narrow (a 4-byte Close frame split at the exact header boundary by the TCP stack), so it shouldn't block this PR.Fix
Mirror
recv_ping_or_pong:fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step { if !self.control_frame_started.get() { if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD { return self.recv_failed(ErrorCode::InvalidControlFrame); } if cursor.body_remain == 0 { self.close_received.set(true); self.send_close(); return Step::Terminated; } } let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else { ... }; ... }
|
Addressed all three review points in 816d13c:
Fail-before on stock bun: 4 fail (EMPTY, 1001, and the two split-read cases). With the fix: 33/33 pass. |
816d13c to
a3aa9c5
Compare
…35534) Adds a self-contained GitHub Action that scans `claude`-labeled PRs for multi-line comment blocks added under `src/` and leaves a review line comment on each one asking for it to be deleted (and the thread resolved once done). ### Behavior - Triggers on `pull_request_target` (`opened` / `synchronize` / `reopened` / `labeled`), gated on `github.repository == 'oven-sh/bun'` and the `claude` label being present. The `labeled` trigger covers the normal case where `auto-label-claude-prs.yml` applies the label after open. - Fetches PR files via `pulls.listFiles` and parses the unified diff in `actions/github-script`. No repo checkout. - A group is **2+ consecutive added lines** that are pure comment lines (`//`, `///`, `//!`, `/* ... */`, `* ` continuation) in `.rs` / `.c` / `.cpp` / `.h` / `.ts` / `.js` and friends. Groups containing `SAFETY:` are skipped. - Posts one standalone review line comment per consecutive group via `pulls.createReviewComment` (no review summary). - Each comment carries `<!-- comment-cop:<path>:<sha12> -->` keyed on the group's content hash, so reruns (new pushes, relabels) skip groups that already have a marker. - On each run, any existing comment-cop thread whose flagged block is no longer present in the diff is auto-resolved via `resolveReviewThread`. ### Verification Dry-ran the parser against the five most recent open `claude` PRs via `gh api repos/oven-sh/bun/pulls/<n>/files`: ``` #35531 src/runtime/webcore/Blob.rs:5245-5246 #35529 src/http_jsc/websocket_client.rs:907-910 #35528 src/runtime/webcore/FileSink.rs:917-920 #35526 src/http_jsc/websocket_client.rs:2179-2182 #35532 (clean) ``` Cross-checked `#35531` line numbers against the fetched head ref; `Blob.rs:5245` is the first line of the flagged block. `actionlint` and prettier both pass. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · build/CI scripts only; test-proof not applicable <!-- robobun:evidence:end -->
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟣
src/http_jsc/websocket_client.rs:892-902— Pre-existing (not introduced by this PR), but since you're inrecv_close: its twocursor.body_remainguards are evaluated on every entry, yet afterbuffer_control_payloadsetscontrol_frame_started,body_remainhas been repurposed from "declared payload length" to "bytes buffered so far". If a server's Close frame with a code arrives split so the first TCP read delivers only the 2-byte header (or header + 1 payload byte), the persistedbody_remainis 0 (or 1) and the next entry short-circuits tosend_close()(JS sees 1005) orrecv_failed(InvalidControlFrame)(JS sees 1002) instead of resumingbuffer_control_payloadto read the real code. Fix: gate both checks on!self.control_frame_started.get(), mirroringrecv_ping_or_pong.Extended reasoning...
What the bug is
recv_closeopens with two guards that inspectcursor.body_remain:fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step { if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD { return self.recv_failed(ErrorCode::InvalidControlFrame); } if cursor.body_remain == 0 { self.close_received.set(true); self.send_close(); return Step::Terminated; } let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else { return Step::NeedMoreData; }; ...
These guards assume
body_remainis the declared payload length from the frame header. That's true on first entry. Butbuffer_control_payload— per its own doc comment — repurposesbody_remainwhilecontrol_frame_startedis set: "While control_frame_started, cursor.body_remain counts bytes buffered so far, not bytes left." On its first call it stashes the declared length intoping_len, setsbody_remain = 0, setscontrol_frame_started = true, then accumulates bytes. When the payload spans TCP reads it returnsNone,recv_closereturnsNeedMoreData, and the loop epilogue persists the accumulator value intoself.receive_body_remain. On the next read,recv_closere-runs both guards against the accumulator, not the declared length.The sibling
recv_ping_or_pongguards its equivalent check with exactly this condition:if !self.control_frame_started.get() && cursor.body_remain > MAX_CONTROL_PAYLOAD {
recv_closedoes not, so it mis-validates on re-entry.Step-by-step proof (header-only first read)
Server sends Close code 3000, no reason: bytes
[0x88, 0x02, 0x0B, 0xB8]. TCP delivers[0x88, 0x02]in the first read and[0x0B, 0xB8]in the second.First read
[0x88, 0x02]:handle_data_loopinitscursor{state=NeedHeader, body_remain=0}.recv_frame_headerconsumes both bytes →state=Close,body_remain=2,data=[], returnsContinue(itsdata.is_empty()early-return only fires forstate==NeedBody).- Loop iterates →
recv_close.body_remain=2passes both guards.buffer_control_payload:control_frame_startedis false → setsping_len=2,body_remain=0,control_frame_started=true;datais empty so nothing is copied;payload_len(2) > body_remain(0)→ returnsNone.recv_closereturnsNeedMoreData. - Loop epilogue (
terminated=false) persistsreceive_state=Close,receive_body_remain=0.close_receivedis not set (only set afterbuffer_control_payloadreturnsSome, or in thebody_remain==0branch which didn't fire).
Second read
[0x0B, 0xB8]:
5.handle_datachecksclose_received→ false → proceeds.handle_data_loopinitscursor{state=Close, body_remain=0}.
6.recv_closere-entry: first guardbody_remain==1→ false; second guardbody_remain==0→ true →self.send_close()+Step::Terminated.Result: the client echoes a bodyless Close and JS sees
CloseEvent.code == 1005. Correct behavior would resumebuffer_control_payload(sincecontrol_frame_startedis still true onself), copy the two payload bytes, reach thepayload_len >= 2branch, and dispatch code 3000.Step-by-step proof (header + 1 payload byte in first read)
First read
[0x88, 0x02, 0x0B]: step 3 copies 1 byte →body_remain=1,payload_len(2) > body_remain(1)→None→ persistedreceive_body_remain=1. Second read[0xB8]:recv_closere-entry hits the first guardbody_remain==1→recv_failed(InvalidControlFrame)→ JS sees 1002 withwasClean=falseand the socket is RST'd viaterminate → fail → cancel(Failure).Why existing tests don't catch it
websocket-close-fragmented.test.tssplits the Close frame after 12 payload bytes are already buffered (header + code + 10 reason bytes), so the persisted accumulator is never 0 or 1. This PR's new tests write each frame in onesock.write(), andwebsocket-client-short-read.test.tsdoesn't cover a Close split at the header/payload boundary.Impact
When a server's Close frame with a status code lands with a TCP read boundary at exactly byte 2 or byte 3 of the frame, the client reports the wrong
CloseEvent.code(1005 or 1002 instead of the received code), and in the byte-3 case treats a valid frame as a protocol error and RSTs. This is timing-dependent and rare over loopback, but reachable on real networks — a 4-byte Close frame following a ≥MSS burst can straddle a segment boundary.Relation to this PR
Pre-existing. The guards are untouched; the PR only wraps the
send_close_with_bodyargs at line 895 inSome()and changes whatsend_close()puts on the wire. The PR slightly changes the wire symptom of thebody_remain==0sub-case (bodyless echo instead of1000), but the JS-visible wrong code (1005) and the root cause — validating the accumulator as if it were the declared length — are identical before and after. The PR neither introduces nor worsens the reachability. Flagging only because the author is in this exact function; not blocking.Fix
Gate both checks on
!self.control_frame_started.get(), matchingrecv_ping_or_pong:fn recv_close(&self, cursor: &mut RecvCursor<'_>) -> Step { if !self.control_frame_started.get() { if cursor.body_remain == 1 || cursor.body_remain > MAX_CONTROL_PAYLOAD { return self.recv_failed(ErrorCode::InvalidControlFrame); } if cursor.body_remain == 0 { self.close_received.set(true); self.send_close(); return Step::Terminated; } } let Some((payload, payload_len)) = self.buffer_control_payload(cursor) else { return Step::NeedMoreData; }; ...
|
Already addressed in a3aa9c5 (the review ran against a pre-rebase snapshot): |
There was a problem hiding this comment.
LGTM — both prior review comments are addressed and the split-read fix now mirrors recv_ping_or_pong.
What was reviewed:
- Traced the two split-read cases (header-only and header+1-byte) through
recv_close→buffer_control_payloadre-entry with the new!control_frame_startedgate — both now reachsend_close_with_body(Some(code), None, …)with the correct code. - Checked the bodyless echo path:
Mask::fill_in_placestill writes the 4-byte mask key intoframe[2..6]before early-returning on the empty payload, so the 6-byte masked frame (0x88 0x80 <mask>) stays RFC-5.3-compliant. - Confirmed
gotEcho.rejectonsock.on('close')afterresolveis a no-op, so the happy path isn't broken by the added rejection wiring.
Extended reasoning...
Overview
Three related fixes to the WebSocket client's server-initiated Close handling in src/http_jsc/websocket_client.rs:
send_close_with_bodynow takescode: Option<u16>soNoneemits a genuine bodyless Close frame (payload length 0, mask key still present).send_close()passesNoneinstead of1000, so a received bodyless Close is echoed bodyless rather than as an explicit1000.received_close_codes→received_close_code(u16) -> u16: the1001 → 1000wire-echo rewrite is removed, so1001echoes verbatim. With that gone, the wire echo and JS dispatch are always identical, so the tuple collapsed to a scalar (my earlier review comment).recv_close'sbody_remain == 0 / == 1 / > 125guards are now gated on!control_frame_started, matchingrecv_ping_or_pong. Oncebuffer_control_payloadhas started,body_remainis repurposed to "bytes buffered so far", so re-entry with 0 or 1 buffered bytes was misfiring the bodyless / invalid branches.
The test file gains a new describe.concurrent block with a raw TCP server that unmasks the client's echo and asserts both the wire code and CloseEvent.code for 7 codes plus 2 split-read variants. gotEcho now rejects on socket error/close (my earlier review comment) so a regression that RSTs surfaces as an assertion failure instead of a timeout.
Security risks
None. This is RFC 6455 §5.5.1 wire-echo correctness. No new untrusted-input parsing was added; the existing received_close_code validation (which maps illegal codes to 1002) is unchanged. The bodyless-frame path writes a fixed 6-byte masked frame with no user-controlled length.
Level of scrutiny
Moderate. The Close-echo path is user-observable on the wire but not a hot path, and two of the three fixes (bodyless echo, 1001 rewrite) change only the wire echo — CloseEvent.code was already correct. The third (split-read gating) is a straightforward mirror of the existing recv_ping_or_pong pattern in the same file. I traced both split-read scenarios byte-by-byte through buffer_control_payload's re-entry semantics to confirm the fix.
Other factors
- All prior review feedback (2 inline comments) is addressed and threads are resolved.
- Strong test coverage: 9 new cases in the target file, verified fail-before (4 fail on stock bun) / pass-after per the PR description, plus the existing
websocket.test.js -t close,websocket-client.test.ts,websocket-close-fragmented.test.ts,websocket-pong-fragmented.test.ts, andwebsocket-client-short-read.test.tsreported passing unchanged. - The 10ms
setTimeoutbetween segment writes is below the 50ms threshold and matches the established split-read pattern inwebsocket-close-fragmented/websocket-client-short-read(called out in the helper's comment). - The known overlap with #33457 (user-initiated
ws.close()bodyless path) is acknowledged in the PR description with a rebase plan; the sharedOption<u16>refactor is the only conflict surface.
When the server sends a Close frame, the client's echo must mirror what was received (RFC 6455 5.5.1). Two cases were being rewritten: * a bodyless Close (no status code) was answered with an explicit 1000, so the peer could no longer tell "no status" from a deliberate normal closure (1005 is the reserved off-wire marker for exactly this case) * a received 1001 (going away) was answered with 1000 Both now echo verbatim (bodyless -> bodyless, 1001 -> 1001), matching Node/undici. The JS-visible CloseEvent.code was already correct (1005 and 1001 respectively) and is unchanged. send_close_with_body() now takes Option<u16> for the wire code so it can emit a bodyless frame; received_close_codes() drops the 1001->1000 special case.
…length checks on first entry, reject gotEcho on socket close - received_close_codes -> received_close_code returning a single u16; the (echo, dispatch) tuple was vestigial once the 1001 rewrite was removed - recv_close: body_remain == 0/1/>125 checks now gated on !control_frame_started, matching recv_ping_or_pong. Once buffer_control_payload has run, body_remain is repurposed to 'bytes buffered so far', so a Close whose header arrives in one read and code in the next no longer misroutes into the bodyless branch. - test helper: gotEcho rejects on socket error/close so a missing echo fails the assertion instead of the harness timeout; two split-read cases cover the recv_close re-entry fix.
a3aa9c5 to
fae8525
Compare
There was a problem hiding this comment.
Both earlier nits are addressed (tuple collapsed to received_close_code() -> u16; gotEcho now rejects on socket error/close). No further findings, but this touches the native WebSocket receive state machine so it's worth a human look before merge.
What was reviewed:
- Traced the split-read fix through
buffer_control_payload'sbody_remainrepurposing for both header-alone and header+1-byte cases — the!control_frame_startedgate matchesrecv_ping_or_pongand the persistedbody_remainvalues (0 and 1) are correctly skipped on re-entry. - Verified the bodyless-echo path:
payload_len = 0, mask key still written byMask::fill_in_placebefore the empty-buf early return,frame_len = 6. - Checked all three
send_close_with_bodycall sites for theOption<u16>signature;dispatch_code.or(code).unwrap_or(1005)produces the right JS-visible code on each. - The four comment-cop flags are RFC-section citations / invariant docs, not workaround justifications.
Extended reasoning...
Overview
Two files: src/http_jsc/websocket_client.rs (~50 lines net) and test/js/web/websocket/websocket-close-code.test.ts (+119 lines). The Rust change fixes three cases where the client's Close-frame echo diverged from what the server sent: bodyless→1000, 1001→1000, and a split-read bug in recv_close where the length guards ran against body_remain after buffer_control_payload had repurposed it as a bytes-buffered counter. send_close_with_body's wire code becomes Option<u16> so it can emit a true bodyless frame; received_close_codes collapses to a single-u16 received_close_code now that echo and dispatch never differ.
Security risks
None identified. All inputs are already bounds-checked upstream (MAX_CONTROL_PAYLOAD, the body_remain > 125 guard still runs on first entry). The bodyless path writes a 6-byte frame with a generated mask key and zero-length payload; no new user-controlled length reaches an allocation or index.
Level of scrutiny
Moderate. This is native protocol-state-machine code on a hot user-facing path. The change is small, mirrors the existing recv_ping_or_pong gating pattern, and ships with a raw-TCP test that unmasks the client's echo and asserts both wire and JS codes across seven values plus two split-read shapes. The PR body shows fail-before/pass-after under both debug+ASAN and release. Still, the body_remain dual-meaning is subtle enough that a maintainer glance is warranted.
Other factors
My two prior review comments (vestigial tuple, unrejectable gotEcho promise) were both addressed in fae8525. The four comment-cop bot flags on lines 879/910/1157/2131 target RFC §5.5.1/§7.1.5/§7.4 citations and an invariant note — these are the durable non-obvious content REVIEW.md asks for, not workaround justifications. The PR overlaps #33457's Option<u16> refactor of send_close_with_body (different bug, user-initiated vs. server-echo path); whichever lands second needs a small rebase there.
The recv_close guard comment restated buffer_control_payload's doc comment (and recv_ping_or_pong has the same guard with no comment); the rest are trimmed to keep the RFC refs and parameter contracts without prose that restates the code.
There was a problem hiding this comment.
LGTM — both prior review points (vestigial tuple, unreachable gotEcho reject path) are addressed and the split-read fix mirrors recv_ping_or_pong's existing !control_frame_started gate.
What was reviewed:
send_close_with_body(None, ...)produces a correctly-masked 6-byte bodyless frame (payload_len = 0, mask key still written byfill_in_placebefore its empty-buf early return);dispatch_code.or(code).unwrap_or(1005)preserves JS-visible codes for all three call sites.recv_closere-entry semantics: on first entrybody_remainis the declared length (0/1/>125 checks apply); afterbuffer_control_payloadit becomes bytes-buffered-so-far and is persisted viareceive_body_remain, so gating oncontrol_frame_startedis the correct discriminator — same asrecv_ping_or_pong.- Test's
sock.on('close', reject)fires afterresolve(wireCode)in the happy path — harmless since the promise is already settled. - The two remaining comment-cop flags (3-line doc comments carrying RFC §refs) are false positives, not workaround justifications.
Extended reasoning...
Overview
Fixes three related bugs in the WebSocket client's Close-frame echo path (src/http_jsc/websocket_client.rs): bodyless server Close was echoed as explicit 1000; received 1001 was rewritten to 1000; and a Close frame whose header and payload arrived in separate TCP reads mis-fired the length guards because body_remain is repurposed to "bytes buffered so far" once buffer_control_payload starts. The fix makes send_close_with_body's wire code an Option<u16> (None → bodyless), collapses received_close_codes to a single u16 (the 1001 rewrite was the only divergence), and gates recv_close's length checks on !control_frame_started — the exact pattern recv_ping_or_pong already uses. New tests in websocket-close-code.test.ts assert both the on-wire echo (via a raw TCP server that unmasks the client's frame) and CloseEvent.code for EMPTY/1000/1001/1002/1003/3000/4999 plus two split-read variants.
Security risks
None. This is outbound Close-frame framing on the client side; no new parsing of untrusted input beyond what recv_close already did. The > MAX_CONTROL_PAYLOAD guard still runs on first entry (before control_frame_started is set), and on re-entry body_remain is bounded by ping_len ≤ 125 so gating the check is safe.
Level of scrutiny
Medium — protocol framing code, but the change is narrow and mechanical. The Option<u16> refactor touches one function with three call sites, all traced. The !control_frame_started gate copies the sibling recv_ping_or_pong verbatim. Fail-before/pass-after is demonstrated on both debug+ASAN and release in the PR evidence.
Other factors
Both of my earlier inline comments were addressed in fae8525: the vestigial (u16, u16) tuple is now a single u16, and the test helper rejects gotEcho on socket error/close so a missing echo fails the assertion instead of the harness timeout. The remaining unresolved comment-cop bot flags target 2–3 line doc comments carrying RFC 6455 section references — these are exactly the "durable non-obvious content" REVIEW.md asks for, not workaround justifications, and robobun's reply correctly notes they're at or below the length of the comments they replace on main. The overlap with #33457 (user-initiated ws.close() no-args path) is called out in the description; the shared Option<u16> refactor will need a small rebase for whichever lands second.
…35534) Adds a self-contained GitHub Action that scans `claude`-labeled PRs for multi-line comment blocks added under `src/` and leaves a review line comment on each one asking for it to be deleted (and the thread resolved once done). ### Behavior - Triggers on `pull_request_target` (`opened` / `synchronize` / `reopened` / `labeled`), gated on `github.repository == 'oven-sh/bun'` and the `claude` label being present. The `labeled` trigger covers the normal case where `auto-label-claude-prs.yml` applies the label after open. - Fetches PR files via `pulls.listFiles` and parses the unified diff in `actions/github-script`. No repo checkout. - A group is **2+ consecutive added lines** that are pure comment lines (`//`, `///`, `//!`, `/* ... */`, `* ` continuation) in `.rs` / `.c` / `.cpp` / `.h` / `.ts` / `.js` and friends. Groups containing `SAFETY:` are skipped. - Posts one standalone review line comment per consecutive group via `pulls.createReviewComment` (no review summary). - Each comment carries `<!-- comment-cop:<path>:<sha12> -->` keyed on the group's content hash, so reruns (new pushes, relabels) skip groups that already have a marker. - On each run, any existing comment-cop thread whose flagged block is no longer present in the diff is auto-resolved via `resolveReviewThread`. ### Verification Dry-ran the parser against the five most recent open `claude` PRs via `gh api repos/oven-sh/bun/pulls/<n>/files`: ``` #35531 src/runtime/webcore/Blob.rs:5245-5246 #35529 src/http_jsc/websocket_client.rs:907-910 #35528 src/runtime/webcore/FileSink.rs:917-920 #35526 src/http_jsc/websocket_client.rs:2179-2182 #35532 (clean) ``` Cross-checked `#35531` line numbers against the fetched head ref; `Blob.rs:5245` is the first line of the flagged block. `actionlint` and prettier both pass. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 0 · build/CI scripts only; test-proof not applicable <!-- robobun:evidence:end -->
|
The |
…oss reads (#42511) ### Problem - A server Close frame can span two TCP reads. If the first read ends after the 2-byte header, the `close` event reports `1005 ""`, not the real `4000 "bye"`. If it ends one byte later, the client fails with `1002 "Protocol error - invalid control frame"`. - `recv_close` (`src/http_jsc/websocket_client.rs:841`) tests `cursor.body_remain == 0` (empty Close) and `== 1` (illegal payload) on every entry. Once `buffer_control_payload` starts a frame, `cursor.body_remain` counts the bytes buffered so far, not the declared length. On the second read, 0 or 1 buffered bytes trip those tests. ### Fix - `recv_close` runs its length checks only when `!control_frame_started`, the first entry for a frame. `recv_ping_or_pong` already has this guard, so Ping and Pong splits are not affected. - Correct because the declared length is checked once, while `cursor.body_remain` still holds it. - #35529 carries the same guard next to two changes to the echoed close code. This PR splits the guard out so that it can land alone. - Verified: a new block in `test/js/web/websocket/websocket-close-fragmented.test.ts` cuts a 7-byte Close frame at every position. Stock bun fails cuts 2 and 3. The other close, ping and `ws` suites pass (list in Notes). ### Background - A Close frame is a control frame: a 2-byte header, then an optional payload of a 2-byte status code and a UTF-8 reason. A 1-byte payload is illegal. - `CloseEvent.code` is `1005` when the Close frame has no payload. - `buffer_control_payload` collects a control payload that spans reads. It parks the declared length in `ping_len` and sets `control_frame_started` until the payload is complete. <details><summary>Notes</summary> Standalone repro (public APIs only). The server writes the first `cut` bytes of a 7-byte Close frame (code 4000, reason "bye"), waits 5 ms, then writes the rest. ```js import net from "node:net"; import { createHash } from "node:crypto"; const close = Buffer.from([0x88, 0x05, 0x0f, 0xa0, 0x62, 0x79, 0x65]); for (const cut of [7, 1, 2, 3, 4, 5, 6]) { const srv = net.createServer(s => { s.setNoDelay(true); s.once("data", d => { const key = /sec-websocket-key: *(.+)\r\n/i.exec(d.toString())[1]; s.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64") + "\r\n\r\n"); setTimeout(() => { s.write(close.subarray(0, cut)); setTimeout(() => { if (cut < 7) s.write(close.subarray(cut)); setTimeout(() => s.end(), 30); }, 5); }, 5); }); s.on("error", () => {}); }).listen(0, "127.0.0.1"); await new Promise(r => srv.once("listening", r)); const ws = new WebSocket("ws://127.0.0.1:" + srv.address().port); const ev = await new Promise(r => { ws.onclose = r; }); console.log(`close frame split at byte ${cut}/7 -> code=${ev.code} reason=${JSON.stringify(ev.reason)} wasClean=${ev.wasClean}`); srv.close(); } ``` Before (1.4.3-canary.1+6a92015fc, also reported on 1.4.0, 1.4.1 and 1.4.2): ``` close frame split at byte 7/7 -> code=4000 reason="bye" wasClean=true close frame split at byte 1/7 -> code=4000 reason="bye" wasClean=true close frame split at byte 2/7 -> code=1005 reason="" wasClean=true close frame split at byte 3/7 -> code=1002 reason="Protocol error - invalid control frame" wasClean=false close frame split at byte 4/7 -> code=4000 reason="bye" wasClean=true close frame split at byte 5/7 -> code=4000 reason="bye" wasClean=true close frame split at byte 6/7 -> code=4000 reason="bye" wasClean=true ``` After (this branch, debug build): all seven lines print `code=4000 reason="bye" wasClean=true`. Node v26.3.0 prints the same seven lines. Trace of the two cuts that fail: - Cut 2. Read 1 is the header. `recv_close` sees `body_remain == 5`, `buffer_control_payload` parks 5 in `ping_len`, sets `body_remain = 0` and waits. Read 2 enters `recv_close` with `body_remain == 0`, takes the empty-Close branch and calls `send_close()`, which reports 1005. - Cut 3. Read 1 is the header plus one payload byte. `buffer_control_payload` copies that byte and leaves `body_remain == 1`. Read 2 enters `recv_close` with `body_remain == 1` and fails with `InvalidControlFrame`. The `ws` package shim sits on the same native client, so it gets the same fix. Test design. The test uses no timers. The server writes an empty Ping and the first part of the Close frame in one write. It writes the rest only after it receives the Pong. The Pong proves that the client already read the first part, so the two parts cannot arrive in one read. Each case also checks that the client echoes `4000 "bye"` on the wire. On stock bun the new block gives the same result in 25 of 25 runs: cuts 2 and 3 fail, cuts 1, 4, 5 and 6 pass. Suites run with the debug build, all pass: - `test/js/web/websocket/websocket-close-fragmented.test.ts` (7) - `test/js/web/websocket/websocket-close-code.test.ts` (24) - `test/js/web/websocket/websocket-pong-fragmented.test.ts` (4) - `test/js/web/websocket/websocket-client-short-read.test.ts` (4) - `test/js/web/websocket/websocket-close-async-dispatch.test.ts` (5) - `test/js/web/websocket/websocket-close-connecting.test.ts` (4) - `test/js/web/websocket/websocket-client.test.ts` (37) - `test/js/web/websocket/websocket-buffered-amount.test.ts` (7) - `test/js/web/websocket/websocket-permessage-deflate.test.ts` (10, 1 skip) - `test/js/web/websocket/websocket.test.js -t close` (23) - `test/js/first_party/ws/ws.test.ts` (65) </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 2 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 2 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/web/websocket/websocket-close-fragmented.test.ts bun test v1.4.3 (6a92015) test/js/web/websocket/websocket-close-fragmented.test.ts: (pass) WebSocket > fragmented close frame [71.02ms] 211 | const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>(); 212 | const ws = new WebSocket(`ws://${server.hostname}:${server.port}`); 213 | ws.onclose = ev => closed.resolve({ code: ev.code, reason: ev.reason, wasClean: ev.wasClean }); 214 | 215 | try { 216 | expect(await closed.promise).toEqual({ code: 4000, reason: "bye", wasClean: true }); ^ error: expect(received).toEqual(expected) { - "code": 4000, - "reason": "bye", + "code": 1005, + "reason": "", "wasClean": true, } - Expected - 2 + Received + 2 at <anonymous> (/workspace/bun/test/js/web/websocket/websocket-close-fragmented.test.ts:216:36) 211 | const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>(); 212 | const ws ... (truncated) release without fix: 2 FAILED bun test v1.4.3-canary.1 (6a92015) test/js/web/websocket/websocket-close-fragmented.test.ts: (pass) WebSocket > fragmented close frame [11.55ms] 211 | const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>(); 212 | const ws = new WebSocket(`ws://${server.hostname}:${server.port}`); 213 | ws.onclose = ev => closed.resolve({ code: ev.code, reason: ev.reason, wasClean: ev.wasClean }); 214 | 215 | try { 216 | expect(await closed.promise).toEqual({ code: 4000, reason: "bye", wasClean: true }); ^ error: expect(received).toEqual(expected) { - "code": 4000, - "reason": "bye", + "code": 1005, + "reason": "", "wasClean": true, } - Expected - 2 + Received + 2 at <anonymous> (/workspace/bun/test/js/web/websocket/websocket-close-fragmented.test.ts:216:36) 211 | const closed = Promise.withResolvers<{ code: number; reason: string; wasClean: boolean }>(); 212 | const ws = new WebSocket(`ws://${server.hostname}:${server.port}`); 213 | ws.onclose = ev => closed.resolve({ code: ev.code, reason: ev.reason, wasClean: ev.wasClean }); 214 | 215 | ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/web/websocket/websocket-close-fragmented.test.ts bun test v1.4.3 (6a92015) test/js/web/websocket/websocket-close-fragmented.test.ts: (pass) WebSocket > fragmented close frame [77.15ms] (pass) WebSocket close frame split across two reads > after byte 1 of 7 [76.69ms] (pass) WebSocket close frame split across two reads > after byte 2 of 7 [56.71ms] (pass) WebSocket close frame split across two reads > after byte 3 of 7 [53.98ms] (pass) WebSocket close frame split across two reads > after byte 4 of 7 [52.51ms] (pass) WebSocket close frame split across two reads > after byte 5 of 7 [51.13ms] (pass) WebSocket close frame split across two reads > after byte 6 of 7 [5.78ms] 7 pass 0 fail 14 expect() calls Ran 7 tests across 1 file. [2.88s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) target linux-x64-gnu build type Release build dir ./build/release revision 4b652ed features baseline 23 deps, 131 codegen, 1172 objects in 768ms ninja: Entering directory `/workspace/bun/build/release' [1/1244] install /workspace/bun bun install v1.4.3-canary.1 (6a92015) Checked 22 installs across 61 packages (no changes) [8.00ms] [2/1244] install /workspace/bun/packages/bun-error bun install v1.4.3-canary.1 (6a92015) Checked 1 install across 2 packages (no changes) [5.00ms] [3/1244] install /workspace/bun/src/node-fallbacks bun install v1.4.3-canary.1 (6a92015) Checked 111 installs across 104 packages (no changes) [14.00ms] [4/1244] gen ErrorCode+*.h [5/1244] gen node-fallbacks/react-refresh.js Bundled 1 module in 5ms react-refresh.js 4.81 KB (entry point) [6/1244] fetch tinycc [tinycc] up to date [7/1243] fetch zlib [zlib] up to date [8/1243] gen bindgenv2 [9/1243] fetch libjpeg-turbo [libjpeg-turbo] up to date [10/1216] gen .bind.ts → GeneratedBindings.cpp [11/1216] gen bake.{client,server,error}.js -> bake.client.js, bake.server ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/http_jsc/websocket_client.rs | 16 ++-- .../websocket/websocket-close-fragmented.test.ts | 96 ++++++++++++++++++++++ 2 files changed, 105 insertions(+), 7 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/http_jsc/websocket_client.rs 2 1 9 test/js/web/websocket/websocket-close-fragmented.test.ts 1 1 8 ``` </details> <!-- robobun:evidence:end -->
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-25, 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. |
Problem
When the client
WebSocketreceives a server-initiated Close frame, RFC 6455 section 5.5.1 says the echo it sends back "typically echoes the status code it received". Bun rewrote the echo in three cases:1000, so the peer could no longer tell "no status" from a deliberate normal closure. This is exactly what the reserved off-wire code1005exists to represent; putting1000on the wire hides it.1001("going away") was answered with1000.1005) or, if exactly one code byte arrived with the header, failed asInvalidControlFrame.Every other legal code already echoed verbatim. Node/undici echo bodyless → bodyless and
1001→1001.The JS-visible
CloseEvent.codewas already correct for the first two cases (1005for bodyless,1001for1001); only the wire echo was wrong. The split-read case was wrong on both the wire and in JS.Repro
Cause
src/http_jsc/websocket_client.rs:send_close()(the bodyless-Close echo path) calledsend_close_with_body(1000, Some(1005), &[]), andsend_close_with_bodyhad no way to emit a bodyless frame: it always wrote the 2-byte code.received_close_codes()special-cased1001:let echo = if dispatch == 1001 { 1000 } else { dispatch }.recv_close()checkedbody_remain == 0/== 1on every entry. Oncebuffer_control_payloadhas started buffering a partial payload it repurposesbody_remainto "bytes buffered so far", so on re-entry a Close whose header arrived alone (buffered = 0) hit the bodyless branch and one whose header arrived with a single code byte (buffered = 1) hit theInvalidControlFramebranch.recv_ping_or_pongalready gated its size check on!control_frame_started;recv_closedid not.Fix
send_close_with_bodynow takescode: Option<u16>.Noneemits a bodyless Close frame (payload length 0, mask key still present). The JS dispatch code falls back to1005when bothcodeanddispatch_codeareNone.send_close()passesNonefor the wire code.received_close_codes()is replaced byreceived_close_code() -> u16: with the1001 -> 1000rewrite gone, the wire echo and JS dispatch are always the same value.recv_close()gates its length checks on!control_frame_started, matchingrecv_ping_or_pong.The JS
ws.close(code, reason)entrypoint passesSome(code)and is unchanged in behaviour.Verification
New describe block in
test/js/web/websocket/websocket-close-code.test.tsruns a raw TCP server that sends a Close frame (optionally split across writes) and unmasks the client's echo, asserting both the wire code andCloseEvent.codeforEMPTY,1000,1001,1002,1003,3000,4999, and two split-read variants.websocket.test.js -t close(22 tests),websocket-client.test.ts(34 tests),websocket-close-fragmented.test.ts,websocket-pong-fragmented.test.ts, andwebsocket-client-short-read.test.tspass unchanged.Not a duplicate of #33457: that PR fixes the user-initiated
ws.close()(no arguments) path to send a bodyless frame; this one fixes the server-initiated echo path. They share theOption<u16>refactor ofsend_close_with_bodyso whichever lands second will need a small rebase there.[review] gate passed · iteration 2 · 2 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 2 rejected · iteration 2
evidence per changed file