Repository navigation
fetch: re-evaluate http_proxy/no_proxy per redirect hop - #33651
Conversation
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.
|
Updated 6:47 PM PT - Jul 7th, 2026
❌ @robobun, your commit a9345ab has 1 failures in
🧪 To try this PR locally: bunx bun-pr 33651That installs a local version of the PR into your bun-33651 --bun |
WalkthroughThis PR extracts NO_PROXY matching into a shared helper, adds ChangesPer-redirect proxy re-evaluation
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
src/dotenv/env_loader.rssrc/dotenv/lib.rssrc/http/AsyncHTTP.rssrc/http/lib.rssrc/runtime/webcore/fetch/FetchTasklet.rstest/js/bun/http/proxy.test.ts
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.
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.
There was a problem hiding this comment.
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— extractsis_no_proxy's body into a pure free functionno_proxy_matches()and addsget_no_proxy_text()/get_proxy_text()accessors (behavior-preserving refactor).src/http/lib.rs— newProxySettingsstruct owning copies of the proxy env,HTTPClient::proxy_settingsfield, andreevaluate_proxy_for_redirect()called from bothdo_redirectanddo_redirect_multiplexed.src/http/AsyncHTTP.rs— movesproxy_authorizationderivation frominit()(JS thread, pre-ptr::read) toon_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 intodealloc_in_flight_for_exit.src/runtime/webcore/fetch/FetchTasklet.rs— replaces theurl_proxy_buffer-appending path withProxySettings::new()+ hop-0resolve(), using anunsaferaw-pointer reborrow into the boxedProxySettingsheap storage.test/js/bun/http/proxy.test.ts— six new tests covering redirect into/out of NO_PROXY, explicitproxyoption, 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.
There was a problem hiding this comment.
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— extractsis_no_proxyinto a pure free functionno_proxy_matchesand addsget_no_proxy_text/get_proxy_textaccessors (behavior-preserving refactor).src/http/lib.rs— addsProxySettings(owned copies of the proxy env) andHTTPClient::reevaluate_proxy_for_redirect, called from bothdo_redirectanddo_redirect_multiplexed. Usesunsafe { erase_lifetime() }for a self-borrow into the boxedProxySettings.src/http/AsyncHTTP.rs/src/http/HTTPThread.rs— movesproxy_authorizationfrom bitwise-shared (populated ininit, pre-ptr::read) to clone-owned (populated inon_start, post-ptr::read), and updates both raw-dealloc teardown sites to drop it explicitly.src/runtime/webcore/fetch/FetchTasklet.rs— replaces theurl_proxy_buffer-appending path withProxySettingsconstruction; hop-0 proxy borrows the boxed settings via a raw pointer before the box is moved intoAsyncHTTP::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
AsyncHTTPcallers (install, S3, upgrade) defaultproxy_settings: Nonevia..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.
|
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:
No failures in proxy/fetch; |
Jarred-Sumner
left a comment
There was a problem hiding this comment.
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.
|
Moved the proxy env parsing out of |
Problem
fetch()resolves the proxy decision (thehttp_proxyvshttps_proxychoice and theNO_PROXYexemption) once on the JS thread from the original URL and bakes it into the HTTP client.do_redirectrepointsself.urlat the redirect target but never re-consults the proxy env, so: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)http->httpsredirect keeps thehttp_proxy-derived proxy instead of switching tohttps_proxycurl and Node's undici
EnvHttpProxyAgentboth re-run the match against each redirected URL.Reproduction
Two origins on
127.0.0.1with different ports sono_proxycan distinguish them viahost:portmatching, plus a recording forward proxy:Fix
The env loader lives on the JS thread and
do_redirectruns on the HTTP thread, so the proxy env cannot be re-read there. Instead:bun_http::ProxySettingsowns copies ofhttp_proxy/https_proxy/no_proxycaptured at request creation.from_env(&Loader)reads the env viaLoader::get();from_explicit(href, &Loader)captures an explicitfetch({ proxy })option withNO_PROXYstill applied per hop.resolve(&URL)runs ano_proxymatch against the captured list and returns the proxy href for a given URL (orNonefor direct).HTTPClientgainsproxy_settings: Option<Box<ProxySettings>>;do_redirectanddo_redirect_multiplexedcallreevaluate_proxy_for_redirect()before restarting, which re-deriveshttp_proxyandproxy_authorizationfrom the snapshot against the post-redirectself.url.proxy_authorizationis now derived on the HTTP-thread clone inon_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.FetchTaskletbuilds the snapshot and resolves hop 0 from it, replacing the previousurl_proxy_buffer-appending path.src/dotenv/is unchanged. OtherAsyncHTTPcallers (install, S3, upgrade) passproxy_settings: Nonevia..Default::default(), preserving their current behavior.Tests
Added to
test/js/bun/http/proxy.test.tsunderhttp_proxy/NO_PROXY re-evaluated per redirect hop:NO_PROXY-exempt host goes direct (envhttp_proxy)NO_PROXY-exempt host goes via proxy (envhttp_proxy)NO_PROXY-exempt host goes direct (explicitproxyoption)NO_PROXY-exempt host with credentialedhttp_proxy(assertsProxy-Authorization: Basic dXNlcjpwYXNz; guards theproxy_authorizationlifecycle under ASAN)http->httpsredirect dropshttp_proxywhenhttps_proxyis unsetNO_PROXYThe first five fail on main (wrong hop-2 route recorded by the proxy, or ASAN double-free), all six pass with the fix.