Skip to content

fetch: run checkServerIdentity before writing the request - #31325

Merged
Jarred-Sumner merged 10 commits into
mainfrom
claude/hardening-fix-r4-38-request-transmitted-before-custom-server-identity
May 26, 2026
Merged

Jarred-Sumner merged 10 commits into
mainfrom
claude/hardening-fix-r4-38-request-transmitted-before-custom-server-identity

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

When fetch() is given a tls.checkServerIdentity callback, the connection is now parked after the TLS handshake and the request (headers and body) is only written once the callback has approved the peer certificate. The callback runs on the first certificate-carrying progress update — once per redirect hop, before that hop's request goes out — instead of only after response metadata arrives. For an HTTPS proxy, the proxy's own certificate is verified natively against the proxy hostname instead of being handed to the user callback.

Adds tests covering: a rejecting callback resulting in zero plaintext bytes reaching the server (direct TLS and CONNECT-tunneled), an approving callback still round-tripping the request/response, and per-hop callback invocation across a cross-origin redirect.

When a JS checkServerIdentity callback is supplied, park the connection
after the TLS handshake and only write the request once the callback has
approved the peer certificate. The callback now runs on the first
certificate-carrying progress update (once per redirect hop) instead of
after response metadata arrives, and the proxy's own certificate for an
HTTPS proxy is checked natively against the proxy hostname rather than
being passed to the callback.
@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Jarred-Sumner, we couldn't start this review because you've used your available PR reviews for now.

Your plan includes 5 reviews of capacity. Refill in 33 minutes and 18 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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4457b466-0a67-4056-a263-3ae2064215dc

📥 Commits

Reviewing files that changed from the base of the PR and between e0c4571 and 6dc52b9.

📒 Files selected for processing (2)
  • test/js/bun/http/proxy.test.ts
  • test/js/web/fetch/fetch.tls.test.ts

Walkthrough

This PR parks connections during JS checkServerIdentity, queues resume messages on the HTTP thread, blocks/resumes application I/O accordingly, and adds tests to verify accept/reject behaviors and proxy/mTLS interactions.

Changes

Certificate check parking and resumption

Layer / File(s) Summary
Connection parking state
src/http/InternalState.rs
InternalStateFlags gains is_waiting_for_cert_check to track connections awaiting JS certificate approval, with lifecycle documentation for socket data handling rules during the parked state.
HTTP thread resume queue infrastructure
src/http/HTTPThread.rs
HttpThread adds queued_cert_check_resumes queue and lock, CertCheckResumeMessage type carrying async_http_id, initialization in new(), drain_queued_cert_check_resumes() to process queue entries and route to the correct socket context, and schedule_cert_check_resume() to enqueue and wake the thread.
HTTPClient request/response I/O gating
src/http/lib.rs, src/http/ProxyTunnel.rs
check_server_identity parks connections by setting is_waiting_for_cert_check when invoking the JS cert-check path; on_writable blocks write attempts while parked; on_data treats any received application data as invalid and fails; h2/h3 offers are disabled when JS cert errors are pending; resume_after_cert_check clears the flag and re-enters on_writable. ProxyTunnel::on_data rejects decrypted data while parked.
FetchTasklet JavaScript certificate verification
src/runtime/webcore/fetch/FetchTasklet.rs
on_progress_update executes user checkServerIdentity when certificate_info is available, rejects promise on verification failure and schedules HTTP-thread shutdown, and schedules HTTP-thread resume on approval; VM-teardown path now shuts down parked connections to free slots.
Integration and regression tests
test/js/bun/http/proxy.test.ts, test/js/web/fetch/fetch.tls.test.ts, test/regression/issue/26125.test.ts
Proxy HTTPS and fetch TLS tests verify checkServerIdentity is invoked with correct hostnames, that rejecting verification blocks request transmission (zero plaintext bytes sent), that approving verification permits request transmission, and that an mTLS test server waits for client data before responding.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly reflects the main change: parked connections that only write requests after checkServerIdentity approval completes.
Description check ✅ Passed The description comprehensively covers the change including the before/after behavior, redirect handling, proxy certificate handling, and test coverage.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@robobun

robobun commented May 24, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 2:20 AM PT - May 25th, 2026

❌ @Jarred-Sumner, your commit 6dc52b9 has 1 failures in Build #57870 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 31325

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

bun-31325 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 3 issues this PR may fix:

  1. Bun fetch + HTTPS-over-CONNECT-proxy: raw upstream HTTP/1.1 leaks into response.body #30381 - Directly involves the HTTPS-over-CONNECT proxy tunnel path that this PR rewrites; both touch ProxyTunnel and the CONNECT handshake/upgrade sequence
  2. Bug: tls.checkServerIdentity rejecting valid IPv6 hostnames in bracket #30668 - Directly about tls.checkServerIdentity in fetch() — the exact callback this PR overhauls — where the wrong hostname string is passed to the callback
  3. node:https: ERR_TLS_CERT_ALTNAME_INVALID when manual Host header contains a port #26333 - The cert altname validation failure is caused by a port-bearing hostname; this PR reworks how hostnames are delivered to checkServerIdentity

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #30381
Fixes #30668
Fixes #26333

🤖 Generated with Claude Code

@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 `@src/http/lib.rs`:
- Around line 1509-1515: The pre-send approval enforced by the new park gate is
not applied to HTTP/2 and HTTP/3 transmission paths, so when checkServerIdentity
is enabled h2/h3 sessions (created via the force_http2 path or alt-svc session
objects and reused by pooled keep-alive sockets) can send frames before JS
approval; modify the h2/h3 session creation and transmit paths to consult the
same park/approval guard used for HTTP/1.1 (the checkServerIdentity gating
mechanism) and block any send/initial frames until the approval flag is
set—specifically, update the h2/h3 session bootstrap and any functions that
reuse TLS sessions (alt-svc session objects / pooled keep-alive socket code) to
await the park gate or a shared pre_send_approved flag before transmitting.
🪄 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: e2c6ae61-6fd2-43a7-b6d0-80740f130abe

📥 Commits

Reviewing files that changed from the base of the PR and between 49c97de and e21c1fc.

📒 Files selected for processing (7)
  • src/http/HTTPThread.rs
  • src/http/InternalState.rs
  • src/http/ProxyTunnel.rs
  • src/http/lib.rs
  • src/runtime/webcore/fetch/FetchTasklet.rs
  • test/js/bun/http/proxy.test.ts
  • test/js/web/fetch/fetch.tls.test.ts

Comment thread src/http/lib.rs Resolved

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

I didn't find any correctness bugs, but this reworks TLS certificate verification timing and cross-thread park/resume coordination in the HTTP client — security-sensitive enough that it warrants a human reviewer (and CI is currently red on several build-rust targets).

Extended reasoning...

Overview

This PR changes fetch() so that when a user supplies tls.checkServerIdentity, the HTTP-thread connection is parked after the TLS handshake and the request (line, headers, body) is withheld until the JS-thread callback approves the peer certificate. It adds a new cross-thread message queue (queued_cert_check_resumes) to HttpThread, a new is_waiting_for_cert_check state flag, gates in on_writable/on_data/ProxyTunnel::on_data, a resume_after_cert_check entry point, and reorders FetchTasklet::on_progress_update so the certificate check runs before the metadata-less early return. It also changes HTTPS-proxy behavior so the proxy's own certificate is no longer handed to the user callback. ~300 lines of Rust across HTTPThread.rs, InternalState.rs, ProxyTunnel.rs, lib.rs, and FetchTasklet.rs, plus four new integration tests.

Security risks

This is squarely security-sensitive: the whole point is to prevent credentials/body bytes from reaching a TLS peer whose certificate the user's pinning callback hasn't approved. Subtle ordering bugs (e.g. a path that writes before the flag is set, or a resume racing a same-tick abort) would silently leak request data. The PR also intentionally changes which certificate the user callback sees when an HTTPS proxy is in play, and explicitly documents residual gaps on the experimental h2/h3 paths — a design tradeoff a maintainer should sign off on.

Level of scrutiny

High. TLS verification, cross-thread lock-guarded queues, raw-pointer reentrant callback paths in ProxyTunnel, and a behavioral change to an existing public API (checkServerIdentity now fires per-hop, before send, and never for the proxy cert). The reordering in FetchTasklet::on_progress_update interacts with the #27275 coalesced-failure path and the VM-teardown path in non-obvious ways.

Other factors

  • robobun reports build failures on aarch64 / aarch64-musl / x64-android for this commit.
  • CodeRabbit flagged the documented h2/h3 bypass; whether to leave that as a known-gap or harden it now is a maintainer call.
  • Good test coverage for the h1 direct and CONNECT-tunneled paths (zero-bytes-on-reject, round-trip-on-approve, per-hop on redirect), but the change updates an existing test's expected output (verifiedHostnames now includes both hops), which is a user-visible behavior change worth confirming.

Comment thread src/http/lib.rs Resolved
…e paths

- Schedule socket shutdown on the defensive fallthrough in check_server_identity
  so every false return releases the parked connection
- Fail protocol "http2" + checkServerIdentity up front in start_, mirroring the
  existing http3 guard, instead of after a wasted TLS handshake
- Make the 26125 mock server wait for the request before responding
- Make the proxy test's tunnel teardown propagate on abortive client close and
  track target connections at the TCP layer
Comment thread src/http/lib.rs Resolved

@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 `@src/http/lib.rs`:
- Around line 1509-1517: Requests that carry a JS callback (signaled via
signals::Field::CertErrors / checkServerIdentity) must not reuse pooled TLS
sockets that skipped the handshake; update the keep-alive reuse logic so such
requests are opted out: either modify the socket pool key generation to include
the callback/cert-check policy (so pools are segregated) or add a short-circuit
in the reuse path that start_/can_offer_h2/can_try_h3_alt_svc/force_http3
consult before returning a pooled socket and refuse reuse when CertErrors is
present. Ensure the change prevents selecting a pooled connection that was
prevalidated under a different callback policy.
🪄 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: a6dad6d5-b337-4bd2-b5a8-024197239202

📥 Commits

Reviewing files that changed from the base of the PR and between e21c1fc and bee1970.

📒 Files selected for processing (4)
  • src/http/lib.rs
  • src/runtime/webcore/fetch/FetchTasklet.rs
  • test/js/bun/http/proxy.test.ts
  • test/regression/issue/26125.test.ts

Comment thread src/http/lib.rs Resolved
Comment thread test/js/web/fetch/fetch.tls.test.ts Resolved

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

All my earlier feedback has been addressed and I didn't find anything new this round, but this changes when request bytes are released to a TLS peer relative to user-supplied certificate verification — security-sensitive enough that a human should sign off on the overall design.

Extended reasoning...

Overview

This PR changes fetch()'s tls.checkServerIdentity semantics so the JS callback runs before any HTTP application data is written to the peer, instead of after response metadata arrives. It introduces a cross-thread park/resume protocol: the HTTP thread sets is_waiting_for_cert_check after the TLS handshake, posts the certificate to the JS thread, and gates on_writable/on_data until the JS thread schedules either a resume (schedule_cert_check_resume) or a shutdown. Touches src/http/{HTTPThread,InternalState,ProxyTunnel,lib}.rs, FetchTasklet.rs, plus three test files. Requests carrying the callback are pinned to HTTP/1.1 (h2/h3 paths don't honor the park gate); the HTTPS-proxy's own certificate now uses native SAN verification rather than the user callback.

Security risks

This is squarely security-sensitive: it governs whether request headers/body (including Authorization, cookies, request bodies) reach a peer whose certificate the user's pinning callback has not yet approved. The invariant — zero plaintext bytes to an unverified peer when a JS callback is registered — is enforced at on_writable (skip write while parked), on_data/ProxyTunnel::on_data (fail on unexpected data while parked), can_offer_h2/can_try_h3_alt_svc/start_ (pin to h1), and the resume queue is drained after shutdowns so a same-tick abort wins. The new tests assert zero decrypted bytes reach the server on rejection (direct and CONNECT-tunneled). I flagged and the author addressed: h2/h3 bypass, the one false-return path that didn't tear down the parked socket, the force_http2 timing asymmetry, and the Windows secureConnection race in the test. The pre-existing keep-alive behavior (a callback-bearing request can reuse a pooled socket whose cert was only native-SAN-checked) matches Node's https.Agent semantics and is now accurately documented rather than changed.

Level of scrutiny

High. This is a behavioral change to TLS certificate verification timing in the production HTTP client, with new cross-thread state (a fourth queued-message type on HttpThread, a new InternalStateFlags bit, reordered control flow in FetchTasklet::on_progress_update). The state machine has several edges (redirect hops re-park via InternalState::reset, VM-teardown releases parked sockets, coalesced certificate+failure updates fall through to reject, proxy-tunnel inner-TLS records keep flowing while parked). Each of these is handled and commented, but the surface area is large enough that a human reviewer familiar with the HTTP-thread/JS-thread protocol should confirm the design.

Other factors

Five rounds of bot review (CodeRabbit + my prior runs) have all been addressed; every inline thread is resolved. Test coverage is good (rejection → zero bytes, approval → round-trip, per-hop redirect, proxy tunnel). robobun still shows fetch.tls.test.ts failing on the three Windows targets for commit 895791a (the commit that applied the raw-connection fix); the author reports 21/21 locally, so that may be a flake or a separate issue — worth confirming CI is green on the latest commit before merge, but it's already visible to the author via robobun so I'm not re-raising it inline.

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

No issues found on this revision — all prior review feedback has been addressed. Deferring to human review given this reworks TLS certificate-verification gating (security-sensitive) with new cross-thread park/resume coordination in the HTTP client state machine.

Extended reasoning...

Overview

This PR changes fetch() so that when a tls.checkServerIdentity callback is supplied, the HTTP-thread connection is parked after the TLS handshake and the request (headers + body) is withheld until the JS-thread callback approves the peer certificate. It adds a new is_waiting_for_cert_check state flag, a new cross-thread queued_cert_check_resumes message queue on HttpThread, gates in on_writable/on_data (and the ProxyTunnel decrypted-data path), pins callback-bearing requests to HTTP/1.1 (h2/h3 opt-out), reorders FetchTasklet::on_progress_update so the cert check runs before the metadata-less early return, and adds VM-teardown handling for parked sockets. ~400 lines across 8 files plus four new tests.

Security risks

This is the security-critical surface of the change: TLS peer-certificate verification gating. The invariant being enforced — no application bytes reach a peer the user's callback hasn't approved — is exactly what prevents credential/body leakage to a MITM. The implementation depends on several subtle ordering properties: drain_queued_cert_check_resumes running after drain_queued_shutdowns so a same-tick abort wins; the on_data park guard sitting below the proxy-tunnel dispatch so inner-TLS records still reach the SSLWrapper; the abort-tracker lookup correctly routing both SocketTls and SocketTcp (HTTPS-behind-plaintext-proxy) entries. The HTTPS-proxy-own-certificate carve-out (native SAN check instead of JS callback) is also a semantic change. All of these look correct to me and are well-commented, but they are the kind of thing a human maintainer should sign off on.

Level of scrutiny

High. This is production-critical networking code in the core fetch() path, and it directly governs whether request data is transmitted to an unverified TLS peer. It introduces new cross-thread coordination (JS ↔ HTTP thread) with lock-guarded queues and ordering invariants. Per the approval guidelines, both "touches security-sensitive code" and "complex/touches critical code paths" apply.

Other factors

The PR has been through five rounds of automated review; the author addressed every finding (h2/h3 bypass, the unreachable-fallthrough parked-socket leak, the force_http2 asymmetry, the Windows test race, and two comment-accuracy nits). All inline threads are resolved. The new tests directly assert the security invariant (zero plaintext bytes reach the server on rejection, both direct-TLS and CONNECT-tunneled) and the per-hop redirect behavior. CI status on the latest commit (930183b) was still building when last checked. No new issues were found on this revision, but the nature of the change warrants a human reviewer's approval rather than bot auto-approval.

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator Author

Fix the conflicts.

…r4-38-request-transmitted-before-custom-server-identity

# Conflicts:
#	test/js/bun/http/proxy.test.ts
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator Author

Merged main and resolved the conflict in test/js/bun/http/proxy.test.ts — kept main's reworked proxy helper plus its new redirect test and both of this PR's checkServerIdentity tunnel tests; proxy, fetch.tls, and 26125 test files pass locally. Merge commit: 6dc52b9.

@Jarred-Sumner
Jarred-Sumner merged commit 0974d03 into main May 26, 2026
77 of 78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the claude/hardening-fix-r4-38-request-transmitted-before-custom-server-identity branch May 26, 2026 00:06
springmin pushed a commit to springmin/bun that referenced this pull request May 26, 2026
* oven/main (10 new commits):
  Optimize TextEncoder.encode: restore SIMD ASCII fast paths lost in the Rust port (oven-sh#31385)
  js_parser: sanitize auto-generated default export name for digit-named modules (oven-sh#31403)
  fetch: run checkServerIdentity before writing the request (oven-sh#31325)
  ffi: avoid copying the threadsafe callback wrapper on the calling thread (oven-sh#31332)
  install: gate the exit-callback cache teardown to the main thread (oven-sh#31376)
  fix(node:module): don't register native helpers as their own constructors (oven-sh#31393)
  css: escape custom pseudo-class/element names when printing (oven-sh#31404)
  Deepen the lots-of-for-loop fixture so the transpiler stack-overflow tests throw on Windows (oven-sh#31382)
  Hardening: input validation and bounds tightening across 36 subsystems (round 4) (oven-sh#31339)
  Speed up FormData multipart serialization (oven-sh#31379)

Auto-merged: src/install/PackageManager.rs, src/runtime/cli/upgrade_command.rs, src/runtime/webcore/Blob.rs, src/sys/lib.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants