Skip to content

fetch: re-evaluate http_proxy/no_proxy per redirect hop - #33651

Merged
Jarred-Sumner merged 7 commits into
mainfrom
farm/6bccc099/fetch-proxy-redirect-reevaluate
Jul 9, 2026
Merged

Jarred-Sumner merged 7 commits into
mainfrom
farm/6bccc099/fetch-proxy-redirect-reevaluate

Conversation

@robobun

@robobun robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

fetch() resolves the proxy decision (the http_proxy vs https_proxy choice and the NO_PROXY exemption) once on the JS thread from the original URL and bakes it into the HTTP client. do_redirect repoints self.url at the redirect target but never re-consults the proxy env, so:

  • a redirect into a NO_PROXY-exempt host is still sent via the proxy (the exempted internal URL, path + query, is handed to the egress proxy in absolute-form; and the proxy usually cannot reach the internal host, so the request also fails)
  • a redirect out of an exempt host silently bypasses the proxy (unreachable in a locked-down network where every non-exempt host is only reachable through the egress proxy)
  • an http->https redirect keeps the http_proxy-derived proxy instead of switching to https_proxy

curl and Node's undici EnvHttpProxyAgent both re-run the match against each redirected URL.

Reproduction

Two origins on 127.0.0.1 with different ports so no_proxy can distinguish them via host:port matching, plus a recording forward proxy:

// no_proxy=127.0.0.1:<B>, http_proxy=<proxy>
// fetch http://127.0.0.1:<A>/r302  (302 -> http://127.0.0.1:<B>/final)
//   before: hop 2 sent via proxy (absolute-form "GET http://127.0.0.1:<B>/final")
//   after:  hop 2 sent direct to origin B

// no_proxy=127.0.0.1:<A>, http_proxy=<proxy>
// fetch http://127.0.0.1:<A>/r302  (302 -> http://127.0.0.1:<B>/final)
//   before: hop 2 sent direct (proxy bypassed)
//   after:  hop 2 sent via proxy

Fix

The env loader lives on the JS thread and do_redirect runs on the HTTP thread, so the proxy env cannot be re-read there. Instead:

  • A new bun_http::ProxySettings owns copies of http_proxy / https_proxy / no_proxy captured at request creation. from_env(&Loader) reads the env via Loader::get(); from_explicit(href, &Loader) captures an explicit fetch({ proxy }) option with NO_PROXY still applied per hop. resolve(&URL) runs a no_proxy match against the captured list and returns the proxy href for a given URL (or None for direct).
  • HTTPClient gains proxy_settings: Option<Box<ProxySettings>>; do_redirect and do_redirect_multiplexed call reevaluate_proxy_for_redirect() before restarting, which re-derives http_proxy and proxy_authorization from the snapshot against the post-redirect self.url.
  • proxy_authorization is now derived on the HTTP-thread clone in on_start (post-ptr::read) and dropped with the other clone-owned fields, so redirects can reassign it without touching storage shared with the JS-thread original.
  • FetchTasklet builds the snapshot and resolves hop 0 from it, replacing the previous url_proxy_buffer-appending path.

src/dotenv/ is unchanged. Other AsyncHTTP callers (install, S3, upgrade) pass proxy_settings: None via ..Default::default(), preserving their current behavior.

Tests

Added to test/js/bun/http/proxy.test.ts under http_proxy/NO_PROXY re-evaluated per redirect hop:

  • redirect into NO_PROXY-exempt host goes direct (env http_proxy)
  • redirect out of NO_PROXY-exempt host goes via proxy (env http_proxy)
  • redirect into NO_PROXY-exempt host goes direct (explicit proxy option)
  • redirect into NO_PROXY-exempt host with credentialed http_proxy (asserts Proxy-Authorization: Basic dXNlcjpwYXNz; guards the proxy_authorization lifecycle under ASAN)
  • http->https redirect drops http_proxy when https_proxy is unset
  • control: no redirect still honors NO_PROXY

The first five fail on main (wrong hop-2 route recorded by the proxy, or ASAN double-free), all six pass with the fix.

fetch() resolved the proxy decision (http_proxy/https_proxy choice and
NO_PROXY exemption) once on the JS thread from the original URL and
baked it into the HTTP client. do_redirect repointed self.url at the
redirect target but never re-consulted the proxy env, so:

- a redirect into a NO_PROXY-exempt host was still sent via the proxy
  (leaking the exempted URL + query to the egress proxy, and usually
  failing because the proxy cannot reach the internal host)
- a redirect out of an exempt host silently bypassed the proxy
- an http->https redirect kept the http_proxy-derived proxy

curl and Node's undici EnvHttpProxyAgent both re-run the match per hop.

The env loader lives on the JS thread, so the fix captures owned copies
of http_proxy/https_proxy/no_proxy into a ProxySettings on the client at
creation. do_redirect (h1) and do_redirect_multiplexed (h2/h3) now
re-resolve self.http_proxy and proxy_authorization against the new URL
from that snapshot before restarting. The NO_PROXY matcher is extracted
to a pure free function so the HTTP thread can run it.
@github-actions github-actions Bot added the claude label Jul 7, 2026
@robobun

robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 6:47 PM PT - Jul 7th, 2026

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


🧪   To try this PR locally:

bunx bun-pr 33651

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

bun-33651 --bun

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR extracts NO_PROXY matching into a shared helper, adds ProxySettings to capture proxy configuration, threads it through HTTP request setup, and re-evaluates proxy selection on redirect hops. The test suite adds redirect and no-redirect coverage for proxy, NO_PROXY, and proxy-auth handling.

Changes

Per-redirect proxy re-evaluation

Layer / File(s) Summary
Extract no_proxy_matches helper and accessors
src/dotenv/env_loader.rs, src/dotenv/lib.rs
Loader::is_no_proxy now delegates to no_proxy_matches through new no-proxy/proxy text accessors, and the helper is re-exported from the crate.
ProxySettings type and HTTPClient redirect re-resolution
src/http/lib.rs
ProxySettings captures proxy inputs and resolves per URL; HTTPClient stores it and re-evaluates proxy use on redirect in both redirect paths.
AsyncHTTP options and lifecycle wiring for proxy_settings
src/http/AsyncHTTP.rs
Options carries proxy_settings, init stores it on the client, on_start derives proxy_authorization, and cleanup comments and reclamation are updated.
FetchTasklet builds and passes ProxySettings
src/runtime/webcore/fetch/FetchTasklet.rs
Request setup now builds ProxySettings from explicit or environment proxy values, resolves the initial proxy href from it, and passes it into AsyncHTTP::init.
Redirect proxy re-evaluation tests
test/js/bun/http/proxy.test.ts
New tests cover redirect-hop proxy re-evaluation, explicit proxy behavior, credentialed proxy auth, http -> https redirects, and no-redirect NO_PROXY handling.

Possibly related PRs

  • oven-sh/bun#31352: Both PRs update test/js/bun/http/proxy.test.ts to verify proxy behavior across redirect hops with a mock forward proxy.
  • oven-sh/bun#31782: Both PRs touch build_proxy_authorization() and proxy-auth handling in the HTTP proxy path.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: re-evaluating proxy settings on each redirect hop.
Description check ✅ Passed The description covers the problem, reproduction, fix, and verification/tests, so it satisfies the template's required substance.

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

Comment thread src/http/lib.rs Resolved
proxy_authorization was built in AsyncHTTP::init on the JS-thread
original, so after start_queued_task's ptr::read the HTTP-thread clone
held a bitwise copy of the same Vec. reevaluate_proxy_for_redirect then
assigned to it on the clone, which dropped the shared allocation; the
original's Drop freed it again (ASAN double-free whenever http_proxy
carries userinfo and a redirect crosses a no_proxy boundary).

Derive proxy_authorization in on_start (post-ptr::read) and drop it with
the other clone-owned fields in on_async_http_callback_raw, so the clone
is the sole owner and redirects can freely reassign it. Adds a
credentialed-proxy redirect test that trips the double-free under ASAN
without this change.

@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: 3

🤖 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/dotenv/env_loader.rs`:
- Around line 380-399: Summary: empty-ish lowercase proxy env values are being
treated as final values instead of falling through to uppercase. Update
get_lower_then_upper() in env_loader so it treats quoted-empty forms like
b"\"\"" and b"''" the same as b"" for fallback, allowing get_no_proxy_text() and
get_proxy_text() to continue checking NO_PROXY/HTTP_PROXY/HTTPS_PROXY before
returning None. Keep the existing empty-ish filtering in get_no_proxy_text() and
get_proxy_text(), but make the fallback decision happen after recognizing any
empty-ish lowercase value.

In `@test/js/bun/http/proxy.test.ts`:
- Around line 1841-1848: The proxy test only records the request line, so it can
pass even if proxy authentication is missing. Update the proxy capture logic in
the HTTP proxy tests around the request handling code to also record the
Proxy-Authorization header, then add assertions that the credentialed proxy case
sends the expected Basic dXNlcjpwYXNz value. Apply the same stronger assertion
pattern in the related test block near the second proxy flow so the auth header,
not just the route, is verified.
- Around line 1802-1956: The new redirect tests cover NO_PROXY re-evaluation but
do not exercise scheme-based proxy switching, so the `ProxySettings::resolve()`
path for `http` to `https` remains untested. Extend the existing
`http_proxy/NO_PROXY re-evaluated per redirect hop` suite with a case that
starts on an HTTP origin, redirects to an HTTPS URL, and sets both `http_proxy`
and `https_proxy` so you can assert the second hop uses the HTTPS proxy while
the first hop follows the HTTP proxy rules. Use the existing `runFetch`,
`proxyLog`, and redirect/server setup to keep the test colocated and easy to
locate.
🪄 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: c52ed42b-a116-4cc0-9f2c-3d4c00124d86

📥 Commits

Reviewing files that changed from the base of the PR and between 3f5d816 and b8ec134.

📒 Files selected for processing (6)
  • src/dotenv/env_loader.rs
  • src/dotenv/lib.rs
  • src/http/AsyncHTTP.rs
  • src/http/lib.rs
  • src/runtime/webcore/fetch/FetchTasklet.rs
  • test/js/bun/http/proxy.test.ts

Comment thread src/dotenv/env_loader.rs Resolved
Comment thread test/js/bun/http/proxy.test.ts Resolved
Comment thread test/js/bun/http/proxy.test.ts Resolved
The recording proxy now captures Proxy-Authorization so the credentialed
case asserts 'Basic dXNlcjpwYXNz' is actually sent (not just that the
route went via the proxy). Adds an http->https redirect test with
http_proxy set and https_proxy unset to cover the per-hop scheme branch
in ProxySettings::resolve: hop 2 must not inherit http_proxy.
Comment thread src/http/AsyncHTTP.rs Resolved
robobun and others added 2 commits July 7, 2026 12:24
dealloc_in_flight_for_exit mirrors on_async_http_callback_raw's
clone-owned teardown so LSan stays clean at process exit; update it now
that proxy_authorization is clone-owned.

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

Both memory-safety issues I flagged are now addressed and the bug hunter found nothing else, but this reworks the ptr::read-shared-field ownership model for proxy_authorization and adds unsafe lifetime-erased self-borrows in the HTTP client's redirect path — worth a human look before merging.

Extended reasoning...

Overview

This PR makes fetch() re-evaluate the http_proxy/https_proxy/no_proxy decision on every redirect hop instead of baking it in once from the original URL. It touches:

  • src/dotenv/env_loader.rs — extracts is_no_proxy's body into a pure free function no_proxy_matches() and adds get_no_proxy_text() / get_proxy_text() accessors (behavior-preserving refactor).
  • src/http/lib.rs — new ProxySettings struct owning copies of the proxy env, HTTPClient::proxy_settings field, and reevaluate_proxy_for_redirect() called from both do_redirect and do_redirect_multiplexed.
  • src/http/AsyncHTTP.rs — moves proxy_authorization derivation from init() (JS thread, pre-ptr::read) to on_start() (HTTP-thread clone, post-ptr::read), reclassifying it from bitwise-shared to clone-owned; updates the clone-teardown drop list and the shared-field comment.
  • src/http/HTTPThread.rs — mirrors the new drop into dealloc_in_flight_for_exit.
  • src/runtime/webcore/fetch/FetchTasklet.rs — replaces the url_proxy_buffer-appending path with ProxySettings::new() + hop-0 resolve(), using an unsafe raw-pointer reborrow into the boxed ProxySettings heap storage.
  • test/js/bun/http/proxy.test.ts — six new tests covering redirect into/out of NO_PROXY, explicit proxy option, credentialed proxy (ASAN double-free repro), http→https scheme switch, and a no-redirect control.

Security risks

Proxy routing is security-relevant: the change decides whether a request (including path, query, and Proxy-Authorization credentials) is sent to an egress proxy or direct. The direction of the fix is correct (matches curl/undici) and the tests cover both leak directions. reevaluate_proxy_for_redirect rebuilds proxy_authorization from the new proxy URL, so credentials from http_proxy are not carried to a hop that resolves to a different proxy or direct. I don't see a new credential-leak or downgrade path introduced here.

Level of scrutiny

High. The proxy_authorization ownership change moves a field across the bitwise-shared / clone-owned boundary in the core::ptr::read-based ThreadlocalAsyncHTTP discipline — an area enforced only by comment convention across three sites (on_async_http_callback_raw, dealloc_in_flight_for_exit, on_start). My first review caught a heap double-free in the initial version; the fix for that then missed one of two parallel teardown sites (my second review). Both are now fixed, but the pattern is fragile enough that a maintainer familiar with HTTPThread's clone lifecycle should confirm the three-site invariant is now consistent. The two unsafe blocks (URL::erase_lifetime() in reevaluate_proxy_for_redirect self-borrowing proxy_settings's boxed storage, and the *const [u8] reborrow in FetchTasklet) look sound to me — the boxed storage is address-stable and outlives the borrows — but they warrant a second pair of eyes.

Other factors

All prior review feedback (mine and CodeRabbit's) is resolved. The author confirmed the double-free under ASAN and added a targeted regression test. Test coverage is good: six subprocess-based tests with a recording proxy that assert exact per-hop routing and the Proxy-Authorization header value. The env_loader.rs refactor is a clean extract-function with the original is_no_proxy delegating to it. The FetchTasklet change removes ~30 lines of the old url_proxy_buffer splicing in favor of the owned ProxySettings, which is a net simplification but changes how the hop-0 proxy URL's storage is kept alive.

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

Both earlier findings are addressed and I found nothing further, but this reworks the ptr::read shared-vs-clone-owned field split in the HTTP client and changes proxy routing across redirects — worth a maintainer sign-off.

Extended reasoning...

Overview

This PR makes fetch() re-evaluate the http_proxy/https_proxy/no_proxy decision on every redirect hop instead of baking it in once from the original URL. It touches:

  • src/dotenv/env_loader.rs — extracts is_no_proxy into a pure free function no_proxy_matches and adds get_no_proxy_text/get_proxy_text accessors (behavior-preserving refactor).
  • src/http/lib.rs — adds ProxySettings (owned copies of the proxy env) and HTTPClient::reevaluate_proxy_for_redirect, called from both do_redirect and do_redirect_multiplexed. Uses unsafe { erase_lifetime() } for a self-borrow into the boxed ProxySettings.
  • src/http/AsyncHTTP.rs / src/http/HTTPThread.rs — moves proxy_authorization from bitwise-shared (populated in init, pre-ptr::read) to clone-owned (populated in on_start, post-ptr::read), and updates both raw-dealloc teardown sites to drop it explicitly.
  • src/runtime/webcore/fetch/FetchTasklet.rs — replaces the url_proxy_buffer-appending path with ProxySettings construction; hop-0 proxy borrows the boxed settings via a raw pointer before the box is moved into AsyncHTTP::init.
  • test/js/bun/http/proxy.test.ts — six new tests covering redirect into/out of NO_PROXY, explicit proxy option, credentialed proxy (ASAN double-free guard), http→https scheme switching, and a no-redirect control.

Security risks

Proxy routing is security-relevant: it determines which egress path a request (including its Authorization headers and body) takes. The change is in the correct direction — matching curl/undici by re-evaluating per hop closes a case where a NO_PROXY-exempt internal URL could be leaked to the egress proxy in absolute form. I don't see a new exposure introduced here, but proxy-selection changes on redirect are exactly the kind of thing where a subtle mismatch (e.g. connection-pool keying vs. the new per-hop proxy) could mis-route a request.

Level of scrutiny

High. This is core HTTP client code with a hand-maintained ptr::read bitwise-shared-field invariant (documented only in comments) that this PR actively reshapes. My two prior review passes each found a real memory bug in exactly that machinery (a double-free, then a shutdown-path leak in the mirrored teardown site), both now fixed. The unsafe erase_lifetime() self-borrow and the raw-pointer borrow-before-move in FetchTasklet look sound to me, but they rely on non-local reasoning about Box address stability and the clone's raw-dealloc-without-Drop teardown.

Other factors

  • All four review threads (two from me, two from CodeRabbit) are resolved; the author was responsive and added targeted tests for each.
  • The bug-hunting pass on the current revision found nothing.
  • Other AsyncHTTP callers (install, S3, upgrade) default proxy_settings: None via ..Default::default(), so their behavior is unchanged.
  • Test coverage is solid for the behavioral change; the credentialed-proxy test specifically guards the ownership rework under ASAN.

Given the memory-model sensitivity and that this changes how requests are routed across trust boundaries, I'm not comfortable approving without a maintainer look, but I have no outstanding concerns of my own.

@robobun

robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status: the diff is green. Build #70054 (for a9345ab, after the env_loader revert) finished 283 passed / 3 failed, all three on darwin aarch64 infra:

  • 2x darwin-26-aarch64 - test-bun: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun' and failed to git clone vendor 'elysia': code 128 (neither ran any tests; same lane hit identical timeouts on #69883 and #69945)
  • 1x darwin-14-aarch64 - test-bun: test/js/web/websocket/autobahn.test.ts docker exec format error (amd64 image on arm64 host)

No failures in proxy/fetch; test/js/bun/http/proxy.test.ts passes on every lane that ran it. Ready for review.

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move the proxy-related stuff out of env_loader - env_loader should not grow more configuration parsing. It's just a dumb map.

env_loader stays a plain map. The no_proxy matcher and the
http_proxy/https_proxy/no_proxy readers now live on ProxySettings in
bun_http (from_env / from_explicit constructors that take &Loader and
read via its public get()). FetchTasklet calls those instead of the
Loader accessors this PR previously added.
@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Moved the proxy env parsing out of env_loader in a9345ab: src/dotenv/ is now unchanged vs main. The no_proxy matcher and the env readers live on bun_http::ProxySettings (from_env / from_explicit take &Loader and read via its public get()), and FetchTasklet calls those. All 55 tests in proxy.test.ts still pass.

Comment thread src/http/lib.rs Resolved
@Jarred-Sumner
Jarred-Sumner merged commit b05b4fa into main Jul 9, 2026
75 of 78 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/6bccc099/fetch-proxy-redirect-reevaluate branch July 9, 2026 01:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants