Repository navigation
node:http2: reassemble HEADERS+CONTINUATION before HPACK decoding - #31323
Jarred-Sumner merged 7 commits into
Conversation
Buffer header block fragments per stream and run the HPACK decoder once over the concatenated block when END_HEADERS arrives, instead of decoding each fragment independently. A decode failure on a complete block is now a connection error (COMPRESSION_ERROR), interleaving any other frame into an unfinished header block is a connection error (PROTOCOL_ERROR), and the buffered compressed block is capped at maxHeaderListSize. The per-stream header list size/count limits now finish consuming the block before rejecting it so the connection-scoped dynamic table stays consistent. Also spread the request() options object before encoding the header block (matching Node) so a user-supplied option getter that re-entrantly calls request() cannot reorder header blocks on the wire relative to the order they were encoded.
|
Updated 12:45 PM PT - May 24th, 2026
❌ @Jarred-Sumner, your commit 2dcbe92 has 2 failures in
🧪 To try this PR locally: bunx bun-pr 31323That installs a local version of the PR into your bun-31323 --bun |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
Warning Review limit reached
Your plan currently allows 2 reviews/hour. Refill in 16 minutes and 53 seconds. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more review capacity refills, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughThis PR implements HEADERS/CONTINUATION buffering and connection-level ordering enforcement, refactors HPACK decoding to treat full-block errors as connection-level faults and defer stream finalization until decode completes, and adds an early shallow-clone of JS request options. Four tests validate these edge cases. ChangesHTTP/2 Frame Assembly, Ordering, and HPACK Error Handling
JS Option Evaluation
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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 `@src/runtime/api/bun/h2_frame_parser.rs`:
- Around line 3276-3290: The handler currently returns the stream
(self.streams.get().get(&stream_id).copied()) after sending a terminal GOAWAY
for compression or abuse errors, which lets callers continue success flows;
update the COMPRESSION_ERROR and ENHANCE_YOUR_CALM branches (the blocks that
call self.send_go_away(...) with ErrorCode::COMPRESSION_ERROR and
ENHANCE_YOUR_CALM) to return a terminal None instead of the stream value (i.e.,
return Ok(None) / None consistent with the function's return type) so callers do
not run success-path cleanup like onStreamEnd after a terminal error.
🪄 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: bae16baa-97fb-452d-a455-b0072ca0b69d
📒 Files selected for processing (3)
src/js/node/http2.tssrc/runtime/api/bun/h2_frame_parser.rstest/js/node/http2/node-http2.test.js
…d preserve HEADERS flags across CONTINUATION reassembly
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime/api/bun/h2_frame_parser.rs (1)
4054-4069:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReset header-block reassembly state on the oversized-block terminal paths.
Line 4225 marks the stream as waiting for more headers, and the Line 4054 path keeps the parser in continuation mode, but both
ENHANCE_YOUR_CALMreturns exit without clearing that state. If more bytes from the same socket are already buffered, the parser can still accept laterCONTINUATIONfragments for a block that was already rejected, or emit a second misleadingPROTOCOL_ERRORon the next frame.Suggested fix
if stream.pending_header_block.len() + payload.len() > self.local_settings.get().max_header_list_size as usize { + stream.pending_header_block.clear(); + stream.pending_header_flags = 0; + stream.is_waiting_more_headers = false; + self.expecting_continuation.set(0); // The compressed block already exceeds the header list limit // (HPACK never expands a header list when encoding it, so the // decoded size check would reject it too). Reject the whole // connection rather than leaving the stream waiting on more // fragments for an emptied buffer. @@ let fragment = &payload[offset..end]; if fragment.len() > self.local_settings.get().max_header_list_size as usize { + stream.pending_header_block.clear(); + stream.pending_header_flags = 0; + stream.is_waiting_more_headers = false; // The compressed block already exceeds the header list // limit (HPACK never expands a header list when encoding // it, so the decoded size check would reject it too). // Reject the whole connection rather than leaving a // partially buffered block behind.Also applies to: 4224-4252
🤖 Prompt for 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. In `@src/runtime/api/bun/h2_frame_parser.rs` around lines 4054 - 4069, The oversized-header-block early-return path leaves header reassembly state set and continuation mode enabled; before returning after calling send_go_away (and likewise on the other terminal path around the waiting-for-more-headers return), clear the stream's reassembly state by emptying stream.pending_header_block and reset any continuation-tracking state on the parser/stream (e.g., the waiting_for_continuation flag or continuation_stream field) so the parser will not accept later CONTINUATION fragments for the rejected block.
🤖 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.
Outside diff comments:
In `@src/runtime/api/bun/h2_frame_parser.rs`:
- Around line 4054-4069: The oversized-header-block early-return path leaves
header reassembly state set and continuation mode enabled; before returning
after calling send_go_away (and likewise on the other terminal path around the
waiting-for-more-headers return), clear the stream's reassembly state by
emptying stream.pending_header_block and reset any continuation-tracking state
on the parser/stream (e.g., the waiting_for_continuation flag or
continuation_stream field) so the parser will not accept later CONTINUATION
fragments for the rejected block.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: aadca2c7-cfa7-4c8e-ab52-911eac4f174b
📒 Files selected for processing (1)
src/runtime/api/bun/h2_frame_parser.rs
… reassembly Don't create stream state or fire onStreamStart for a HEADERS frame that arrives while a header block is still being reassembled, and return None from the :status pseudo-header rejection path so callers skip post-decode stream finalization.
There was a problem hiding this comment.
All three issues I raised have been addressed and the bug hunter found nothing new on 7933fe3, but this is a non-trivial rework of the HTTP/2 frame-dispatch / HPACK-decode state machine handling untrusted peer input, so it's worth a human pass before merge.
Extended reasoning...
Overview
This PR reworks how Bun's node:http2 frame parser handles HEADERS+CONTINUATION sequences: it adds connection-level expecting_continuation state and per-stream pending_header_block/pending_header_flags buffers, defers HPACK decoding and END_STREAM finalization until END_HEADERS arrives, converts mid-block decode failures into COMPRESSION_ERROR GOAWAYs, rejects interleaved frames as PROTOCOL_ERROR, caps the buffered compressed block at maxHeaderListSize, and changes the header-list-limit check to finish consuming the block before rejecting so the connection-scoped dynamic table stays consistent. It also extracts finish_headers_end_stream, short-circuits new-stream allocation in lookup_inbound_stream during reassembly, spreads the options object in ClientHttp2Session.request(), and adds four raw-frame tests.
Security risks
The changed code is the inbound HTTP/2 frame dispatcher and HPACK decoder — it runs directly on bytes from an untrusted peer on both client and server. The relevant risks are DoS via unbounded buffering, HPACK dynamic-table desync across streams, post-teardown state mutation, and event-ordering hazards from re-entrant JS dispatches. The PR explicitly bounds the reassembly buffer, takes ownership of the buffer before dispatching to JS, and (after the follow-up commits) returns Ok(None) from all terminal paths so callers don't run success-path finalization after a GOAWAY. I don't see an exploitable issue in the final revision, but the surface area is exactly the kind that benefits from a second set of eyes.
Level of scrutiny
High. ~250 lines of Rust changes to a network-protocol state machine that already went through three rounds of follow-up fixes on this PR (terminal-path return values, HEADERS-vs-CONTINUATION flag preservation, and stream-allocation ordering relative to the new guard). All three are now addressed and resolved in the thread, and the bug hunter found nothing new on the latest commit, but the iteration count itself argues for a human review.
Other factors
- CI on the previous commit (3e06876) reported a macOS aarch64 build-cpp failure; I can't tell from the timeline whether 7933fe3 is green.
- Good targeted test coverage was added for the four new behaviors, and the existing CONTINUATION suite is reported passing.
- The
request()options-spread change is small and matches Node, but is a separate behavioral change bundled into the same PR.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/runtime/api/bun/h2_frame_parser.rs (2)
4043-4056:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReset header-reassembly state before returning ENHANCE_YOUR_CALM.
Both oversize-buffer branches send a terminal GOAWAY, but they leave
stream.is_waiting_more_headersand the pending-header state live, and the CONTINUATION branch also leavesexpecting_continuationarmed. Becauseread()keeps draining the current input slice after this return, later bytes in the same batch can still be appended to or decoded as the abandoned header block.💡 Minimal fix
if stream.pending_header_block.len() + payload.len() > self.local_settings.get().max_header_list_size as usize { + stream.is_waiting_more_headers = false; + stream.pending_header_block.clear(); + stream.pending_header_flags = 0; + self.expecting_continuation.set(0); self.send_go_away( frame.stream_identifier, ErrorCode::ENHANCE_YOUR_CALM, b"ENHANCE_YOUR_CALM", self.last_stream_id.get(), @@ if stream.is_waiting_more_headers { let fragment = &payload[offset..end]; if fragment.len() > self.local_settings.get().max_header_list_size as usize { + stream.is_waiting_more_headers = false; + stream.pending_header_block.clear(); + stream.pending_header_flags = 0; + self.expecting_continuation.set(0); self.send_go_away( frame.stream_identifier, ErrorCode::ENHANCE_YOUR_CALM, b"ENHANCE_YOUR_CALM", self.last_stream_id.get(),Also applies to: 4211-4231
🤖 Prompt for 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. In `@src/runtime/api/bun/h2_frame_parser.rs` around lines 4043 - 4056, The oversize-header branches call send_go_away (see the call in h2_frame_parser where ErrorCode::ENHANCE_YOUR_CALM is sent) but fail to reset the header-reassembly state; before returning Ok(end) clear stream.pending_header_block, set stream.is_waiting_more_headers = false and clear/disable expecting_continuation (and any related header state like pending header name/length counters) so the abandoned block cannot be extended or decoded later; apply the same reset to the similar branch around the 4211-4231 region that sends ENHANCE_YOUR_CALM.
4696-4711:⚠️ Potential issue | 🟠 Major | ⚡ Quick winClear the in-flight frame when the continuation-order guard aborts.
This branch returns before any payload bytes are consumed, but
current_frameandremaining_lengthstay set. The nextread_bytes()call will re-enter with that stale header and can keep emitting GOAWAYs while treating unrelated bytes as the rejected frame.💡 Minimal fix
if expecting != 0 && (header.type_ != FrameType::HTTP_FRAME_CONTINUATION as u8 || header.stream_identifier != expecting) { + self.current_frame.set(None); + self.remaining_length.set(0); + self.expecting_continuation.set(0); self.send_go_away( header.stream_identifier, ErrorCode::PROTOCOL_ERROR, b"Expected CONTINUATION frame", self.last_stream_id.get(),🤖 Prompt for 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. In `@src/runtime/api/bun/h2_frame_parser.rs` around lines 4696 - 4711, When the continuation-order guard in the branch that calls send_go_away aborts, clear the in-flight frame state so stale header info doesn't persist: before returning, reset the parser's current_frame and remaining_length (e.g., set self.current_frame to None and self.remaining_length to zero) so subsequent read_bytes() calls don't reuse the rejected header; keep the existing send_go_away call and return afterwards.
🤖 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.
Outside diff comments:
In `@src/runtime/api/bun/h2_frame_parser.rs`:
- Around line 4043-4056: The oversize-header branches call send_go_away (see the
call in h2_frame_parser where ErrorCode::ENHANCE_YOUR_CALM is sent) but fail to
reset the header-reassembly state; before returning Ok(end) clear
stream.pending_header_block, set stream.is_waiting_more_headers = false and
clear/disable expecting_continuation (and any related header state like pending
header name/length counters) so the abandoned block cannot be extended or
decoded later; apply the same reset to the similar branch around the 4211-4231
region that sends ENHANCE_YOUR_CALM.
- Around line 4696-4711: When the continuation-order guard in the branch that
calls send_go_away aborts, clear the in-flight frame state so stale header info
doesn't persist: before returning, reset the parser's current_frame and
remaining_length (e.g., set self.current_frame to None and self.remaining_length
to zero) so subsequent read_bytes() calls don't reuse the rejected header; keep
the existing send_go_away call and return afterwards.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: d5b29613-1017-466a-b11e-4f133db1362a
📒 Files selected for processing (2)
src/js/node/http2.tssrc/runtime/api/bun/h2_frame_parser.rs
There was a problem hiding this comment.
All earlier review feedback is addressed and I have nothing further to flag, but this reworks the HTTP/2 frame parser's HPACK reassembly and stream state machine enough that it's worth a human pass before merging.
Extended reasoning...
Overview
This PR changes how Bun's node:http2 frame parser handles HEADERS+CONTINUATION sequences: fragments are now buffered per-stream and HPACK-decoded as a single block when END_HEADERS arrives, instead of being decoded fragment-by-fragment. Supporting changes include a connection-level expecting_continuation guard that rejects interleaved frames (RFC 9113 §4.3), a DoS cap on the buffered compressed block, deferral of END_STREAM finalization until the block is complete, COMPRESSION_ERROR on full-block decode failure, and a refactor of the max-header-list-size/count rejection so the dynamic table is fully consumed before rejecting. There's also a small JS-side change to shallow-clone options in ClientHttp2Session.request(). Four raw-frame regression tests are added.
Security risks
This is network-facing protocol parser code. The PR adds hardening (compressed-block size cap, interleaved-frame rejection, COMPRESSION_ERROR on bad HPACK) rather than removing it, and the new buffering is bounded by maxHeaderListSize. I don't see new injection, auth, or data-exposure surface, but state-machine and error-path changes in an HTTP/2 parser are exactly the kind of thing where subtle ordering bugs become DoS or desync vectors — five such issues were found and fixed during review.
Level of scrutiny
High. h2_frame_parser.rs is production-critical and the diff touches the stream state machine, HPACK decode loop, frame dispatch ordering, and error/teardown paths. Over the course of review, one CodeRabbit finding and four of my own were confirmed and fixed (terminal-path Ok(None) returns, CONTINUATION flags vs HEADERS flags, pre-dispatch stream allocation on the server, the missed :status terminal path, and the CLOSED-state guard in finish_headers_end_stream). All are now resolved in the current diff and the bug hunter found nothing further, but the volume of follow-ups is itself a signal that this change benefits from a human reviewer's sign-off.
Other factors
CI shows only an unrelated spawn-pipe-leak flake on Windows aarch64. The author reports node-http2-continuation 9/9 and node-http2.test.js 268 passing. The new tests cover the four headline behaviors. Given the scope and the iteration history, deferring rather than auto-approving.
* oven/main (20 new commits): webcore: free Blob's owned content type on drop (oven-sh#31358) Support cross-compiling macOS binaries from Linux (oven-sh#31303) test: forward keep-alive requests in proxy.test.ts's mock proxy (oven-sh#31352) Port Bun.stringWidth to C++ with explicit SIMD (oven-sh#31351) Fix quadratic hang reporting duplicate-binding parse errors in the transpiler (oven-sh#31341) shell: don't abort when a glob's directory prefix doesn't exist (oven-sh#31367) Error instead of crashing on deeply nested statements in the transpiler (oven-sh#31333) Fix JSX transform panic when a bare `key` prop precedes `key` with a value (oven-sh#31350) Cap ANSI markdown indentation so deeply nested lists render in linear time (oven-sh#31366) css: bound selector-list expansion when compiling nesting for older targets (oven-sh#31277) node:http2: reassemble HEADERS+CONTINUATION before HPACK decoding (oven-sh#31323) Fix `await using` expression printing `using` as `await` (oven-sh#31324) Parenthesize `async` when it starts a for-of loop initializer (oven-sh#31326) Print Infinity and negative numeric property keys as computed properties (oven-sh#31328) css: keep required grouping parens in @container conditions when minifying (oven-sh#31330) Fix panic on anonymous export default class with an auto-accessor field (oven-sh#31331) node:http2: send GOAWAY frames on stream 0 (oven-sh#31353) parser: fix Scope mismatch while visiting panic from decorators on dropped class members (oven-sh#31340) webcrypto: reject oversized BufferSource inputs instead of aborting (oven-sh#31356) Error instead of crashing on deeply nested TypeScript types in the transpiler (oven-sh#31361) Resolved conflicts: - scripts/build.ts: kept both OHOS and macOS-cross argv entries - scripts/build/config.ts: kept both OHOS and macOS-cross config fields - scripts/build/deps/webkit.ts: kept OHOS fno-pic exclusion, adopted upstream -flto=thin
The getter fires during the JS-side options spread (since #31323), not while a native *Stream is held. Make the comment say so.
The node:http2 frame parser decoded each HEADERS and CONTINUATION fragment independently and silently truncated the header list when an HPACK instruction straddled a fragment boundary, which also left the connection-scoped dynamic table out of sync. Fragments are now buffered per stream and decoded once when END_HEADERS arrives; a decode failure on a complete block tears down the connection with COMPRESSION_ERROR, any non-CONTINUATION frame interleaved into an unfinished header block is a PROTOCOL_ERROR, and the buffered compressed block is capped at maxHeaderListSize. The header list size/count limits now finish consuming the block before rejecting it so the dynamic table stays consistent.
request()now also spreads its options object before the header block is encoded (matching Node), so a user-supplied option getter that re-entrantly callsrequest()can no longer reorder header blocks on the wire relative to the order they were encoded.Adds four raw-frame tests to test/js/node/http2/node-http2.test.js covering reassembly of a block split mid-instruction, decode failure of a complete block, an interleaved frame during reassembly, and an oversized compressed block. The existing CONTINUATION suite (150/300-header send and receive, large trailers, padding sweep) passes unchanged.