Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 88 additions & 59 deletions src/dotenv/env_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,84 +371,113 @@ impl<'a> Loader<'a> {
/// Returns true if the given hostname/host should bypass the proxy
/// according to the NO_PROXY / no_proxy environment variable.
pub fn is_no_proxy(&self, hostname: Option<&[u8]>, host: Option<&[u8]>) -> bool {
// NO_PROXY filter
// See the syntax at https://about.gitlab.com/blog/2021/01/27/we-need-to-talk-no-proxy/
let Some(hn) = hostname else { return false };

let Some(no_proxy_text) = self.get_lower_then_upper(b"no_proxy", b"NO_PROXY") else {
let Some(no_proxy_text) = self.get_no_proxy_text() else {
return false;
};
if Self::is_emptyish(no_proxy_text) {
return false;
no_proxy_matches(no_proxy_text, hostname, host)
}

/// Raw `no_proxy` / `NO_PROXY` value (None if unset or empty-ish).
pub fn get_no_proxy_text(&self) -> Option<&[u8]> {
let v = self.get_lower_then_upper(b"no_proxy", b"NO_PROXY")?;
if Self::is_emptyish(v) {
return None;
}
Some(v)
}

for no_proxy_item in no_proxy_text.split(|&b| b == b',') {
let mut no_proxy_entry = strings::trim(no_proxy_item, &strings::WHITESPACE_CHARS);
/// Raw `http_proxy` / `https_proxy` value (None if unset or empty-ish).
pub fn get_proxy_text(&self, is_http: bool) -> Option<&[u8]> {
let v = if is_http {
self.get_lower_then_upper(b"http_proxy", b"HTTP_PROXY")
} else {
self.get_lower_then_upper(b"https_proxy", b"HTTPS_PROXY")
}?;
if Self::is_emptyish(v) {
return None;
}
Some(v)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

/// Returns true if the given hostname/host should bypass the proxy according
/// to the supplied `no_proxy` list. Pure over its arguments so the HTTP
/// thread can re-evaluate per redirect hop from a captured copy of the env
/// value; see https://about.gitlab.com/blog/2021/01/27/we-need-to-talk-no-proxy/.
pub fn no_proxy_matches(
no_proxy_text: &[u8],
hostname: Option<&[u8]>,
host: Option<&[u8]>,
) -> bool {
let Some(hn) = hostname else { return false };
for no_proxy_item in no_proxy_text.split(|&b| b == b',') {
let mut no_proxy_entry = strings::trim(no_proxy_item, &strings::WHITESPACE_CHARS);
if no_proxy_entry.is_empty() {
continue;
}
if no_proxy_entry == b"*" {
return true;
}
// strips .
if strings::starts_with_char(no_proxy_entry, b'.') {
no_proxy_entry = &no_proxy_entry[1..];
if no_proxy_entry.is_empty() {
continue;
}
if no_proxy_entry == b"*" {
return true;
}
// strips .
if strings::starts_with_char(no_proxy_entry, b'.') {
no_proxy_entry = &no_proxy_entry[1..];
if no_proxy_entry.is_empty() {
continue;
}
}
}

// Determine if entry contains a port or is an IPv6 address
// IPv6 addresses contain multiple colons (e.g., "::1", "2001:db8::1")
// Bracketed IPv6 with port: "[::1]:8080"
// Host with port: "localhost:8080" (single colon)
let colon_count = no_proxy_entry.iter().filter(|&&b| b == b':').count();
let is_bracketed_ipv6 = strings::starts_with_char(no_proxy_entry, b'[');
let has_port = 'blk: {
if is_bracketed_ipv6 {
// Bracketed IPv6: check for "]:port" pattern
if strings::index_of(no_proxy_entry, b"]:").is_some() {
break 'blk true;
}
break 'blk false;
} else if colon_count == 1 {
// Single colon means host:port (not IPv6)
// Determine if entry contains a port or is an IPv6 address
// IPv6 addresses contain multiple colons (e.g., "::1", "2001:db8::1")
// Bracketed IPv6 with port: "[::1]:8080"
// Host with port: "localhost:8080" (single colon)
let colon_count = no_proxy_entry.iter().filter(|&&b| b == b':').count();
let is_bracketed_ipv6 = strings::starts_with_char(no_proxy_entry, b'[');
let has_port = 'blk: {
if is_bracketed_ipv6 {
// Bracketed IPv6: check for "]:port" pattern
if strings::index_of(no_proxy_entry, b"]:").is_some() {
break 'blk true;
}
// Multiple colons without brackets = bare IPv6 literal (no port)
break 'blk false;
};
} else if colon_count == 1 {
// Single colon means host:port (not IPv6)
break 'blk true;
}
// Multiple colons without brackets = bare IPv6 literal (no port)
break 'blk false;
};

if has_port {
// Entry has a port, do exact match against host:port
if let Some(h) = host {
if strings::eql_case_insensitive_ascii(h, no_proxy_entry, true) {
return true;
}
if has_port {
// Entry has a port, do exact match against host:port
if let Some(h) = host {
if strings::eql_case_insensitive_ascii(h, no_proxy_entry, true) {
return true;
}
} else {
// Entry is hostname/IPv6 only, match exact or dot-boundary suffix (case-insensitive)
let entry_len = no_proxy_entry.len();
if hn.len() == entry_len {
if strings::eql_case_insensitive_ascii(hn, no_proxy_entry, true) {
return true;
}
} else if hn.len() > entry_len
&& hn[hn.len() - entry_len - 1] == b'.'
&& strings::eql_case_insensitive_ascii(
&hn[hn.len() - entry_len..],
no_proxy_entry,
true,
)
{
}
} else {
// Entry is hostname/IPv6 only, match exact or dot-boundary suffix (case-insensitive)
let entry_len = no_proxy_entry.len();
if hn.len() == entry_len {
if strings::eql_case_insensitive_ascii(hn, no_proxy_entry, true) {
return true;
}
} else if hn.len() > entry_len
&& hn[hn.len() - entry_len - 1] == b'.'
&& strings::eql_case_insensitive_ascii(
&hn[hn.len() - entry_len..],
no_proxy_entry,
true,
)
{
return true;
}
}

false
}

false
}

impl<'a> Loader<'a> {
pub fn load_ccache_path(&mut self, fs: &bun_paths::fs::FileSystem) {
if DID_LOAD_CCACHE_PATH.load(Ordering::Relaxed) {
return;
Expand Down
2 changes: 1 addition & 1 deletion src/dotenv/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub mod env_loader;
pub use env_loader::{
DirEntryProbe, DotEnvBehavior, DotEnvFileSuffix, HAS_NO_CLEAR_SCREEN_CLI_FLAG, HashTable,
HashTableValue, INSTANCE, Kind, Loader, Map, Mode, NullDelimitedEnvMap, S3Credentials,
StdEnvMapWrapper, Value, instance, set_instance,
StdEnvMapWrapper, Value, instance, no_proxy_matches, set_instance,
};

/// `dotenv::map::{HashTable, Entry}` namespace expected by `install_jsc::ini_jsc` et al.
Expand Down
24 changes: 17 additions & 7 deletions src/http/AsyncHTTP.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ fn http_thread_timer_read() -> u64 {

/// Build the `Proxy-Authorization: Basic <b64(user[:pass])>` header value.
/// Returns `None` (and logs) if percent-decoding fails.
fn build_proxy_authorization(proxy: &URL<'_>) -> Option<Vec<u8>> {
pub(crate) fn build_proxy_authorization(proxy: &URL<'_>) -> Option<Vec<u8>> {
if proxy.username.is_empty() {
return None;
}
Expand Down Expand Up @@ -203,6 +203,7 @@ fn make_client<'a>(
if_modified_since: b"",
request_content_len_buf: [0u8; b"-4294967295".len()],
http_proxy,
proxy_settings: None,
proxy_headers,
proxy_authorization: None,
proxy_tunnel: None,
Expand Down Expand Up @@ -262,6 +263,7 @@ pub fn load_env(logger: &mut Log, env: &DotEnvLoader) {
#[derive(Default)]
pub struct Options<'a> {
pub http_proxy: Option<URL<'a>>,
pub proxy_settings: Option<Box<crate::ProxySettings>>,
pub proxy_headers: Option<Headers>,
pub hostname: Option<&'a [u8]>,
pub signals: Option<Signals>,
Expand Down Expand Up @@ -535,12 +537,11 @@ impl<'a> AsyncHTTP<'a> {
this.client.tls_props = Some(val);
}
this.client.compress = options.compress;
this.client.proxy_settings = options.proxy_settings;

if let Some(proxy) = &this.http_proxy {
if let Some(auth) = build_proxy_authorization(proxy) {
this.client.proxy_authorization = Some(auth);
}
}
// `client.proxy_authorization` stays `None` on the JS-thread original;
// `on_start` derives it on the HTTP-thread clone so redirects can
// reassign it without double-freeing the `ptr::read`-shared Vec.
this
}

Expand Down Expand Up @@ -763,7 +764,7 @@ impl<'a> AsyncHTTP<'a> {
// (`start_queued_task`), so any owned field that was already
// populated at that point — `request_headers`,
// `client.header_entries`, `client.proxy_headers`,
// `client.proxy_authorization`, `client.tls_props`,
// `client.proxy_settings`, `client.tls_props`,
// `client.unix_socket_path` — is *shared* with the original
// and must NOT be dropped here; the original drops them when
// its `Box<AsyncHTTP>` is reclaimed. Only the state the clone
Expand Down Expand Up @@ -800,6 +801,7 @@ impl<'a> AsyncHTTP<'a> {
drop(core::mem::take(&mut client.redirect));
drop(core::mem::take(&mut client.prev_redirect));
drop(core::mem::take(&mut client.compressed_request_body));
drop(core::mem::take(&mut client.proxy_authorization));
Comment thread
robobun marked this conversation as resolved.
Resolved
if let Some(tunnel) = client.proxy_tunnel.take() {
// SAFETY: tunnel was created by ProxyTunnel::start
// (heap::alloc) and is refcounted; detach the socket
Expand Down Expand Up @@ -901,6 +903,14 @@ impl<'a> AsyncHTTP<'a> {
AsyncHTTP::on_async_http_callback_raw,
);

// Clone-owned: derived here (post-`ptr::read`) so
// `reevaluate_proxy_for_redirect` can freely drop/replace it. The
// original's copy stays `None`.
debug_assert!(self.client.proxy_authorization.is_none());
if let Some(proxy) = &self.client.http_proxy {
self.client.proxy_authorization = build_proxy_authorization(proxy);
}

self.elapsed = http_thread_timer_read();

// `response_buffer` was set in `init()` to a caller-owned MutableString
Expand Down
1 change: 1 addition & 0 deletions src/http/HTTPThread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,7 @@ impl HttpThread {
drop(core::mem::take(&mut client.redirect));
drop(core::mem::take(&mut client.prev_redirect));
drop(core::mem::take(&mut client.compressed_request_body));
drop(core::mem::take(&mut client.proxy_authorization));
if let Some(tunnel) = client.proxy_tunnel.take() {
(*tunnel.as_ptr()).detach_socket();
tunnel.deref();
Expand Down
80 changes: 80 additions & 0 deletions src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,52 @@ use bun_core::ZigStringSlice;
use bun_url::URL;
use core::ptr::NonNull;

/// Owned copies of the proxy environment captured at request creation so the
/// HTTP thread can re-resolve `HTTPClient::http_proxy` per redirect hop.
/// curl / Node's undici `EnvHttpProxyAgent` both re-run the no_proxy match
/// and the http/https proxy choice against each redirected URL.
pub struct ProxySettings {
http_proxy: Box<[u8]>,
https_proxy: Box<[u8]>,
no_proxy: Box<[u8]>,
}

impl ProxySettings {
/// Returns `None` when neither proxy is set: no re-evaluation is needed.
pub fn new(
http_proxy: Option<&[u8]>,
https_proxy: Option<&[u8]>,
no_proxy: Option<&[u8]>,
) -> Option<Box<Self>> {
let http_proxy = http_proxy.unwrap_or(b"");
let https_proxy = https_proxy.unwrap_or(b"");
if http_proxy.is_empty() && https_proxy.is_empty() {
return None;
}
Some(Box::new(Self {
http_proxy: http_proxy.into(),
https_proxy: https_proxy.into(),
no_proxy: no_proxy.unwrap_or(b"").into(),
}))
}

/// Proxy href to use for `url`, or `None` for a direct connection.
pub fn resolve(&self, url: &URL<'_>) -> Option<&[u8]> {
let href: &[u8] = if url.is_http() {
&self.http_proxy
} else {
&self.https_proxy
};
if href.is_empty() {
return None;
}
if bun_dotenv::no_proxy_matches(&self.no_proxy, Some(url.hostname), Some(url.host)) {
return None;
}
Some(href)
}
}

// TODO: reduce the size of this struct
// Many of these fields can be moved to a packed struct and use less space
//
Expand Down Expand Up @@ -639,6 +685,10 @@ pub struct HTTPClient<'a> {
pub request_content_len_buf: [u8; b"-4294967295".len()],

pub http_proxy: Option<URL<'a>>,
/// Captured proxy env (http_proxy / https_proxy / no_proxy) so redirects
/// can re-resolve `http_proxy` against each hop's URL on the HTTP thread.
/// `None` means the initial `http_proxy` is used for every hop.
pub proxy_settings: Option<Box<ProxySettings>>,
pub proxy_headers: Option<Headers>,
pub proxy_authorization: Option<Vec<u8>>,
/// Set while this request is tunneling through an HTTP proxy (CONNECT).
Expand Down Expand Up @@ -2505,13 +2555,42 @@ impl<'a> HTTPClient<'a> {
self.flags.proxy_tunneling = false;
self.close_proxy_tunnel(false);
self.flags.protocol = Protocol::Http1_1;
self.reevaluate_proxy_for_redirect();

self.start(
HTTPRequestBody::Bytes(request_body),
body_out::as_mut(body_out_str),
);
}

/// Re-resolve `http_proxy` against the post-redirect `self.url`. The
/// decision was made once on the JS thread at request creation; without
/// this, a redirect into a `no_proxy`-exempt host would still be sent via
/// the proxy, and a redirect out of one would bypass it.
fn reevaluate_proxy_for_redirect(&mut self) {
let Some(settings) = self.proxy_settings.as_deref() else {
return;
};
let new_href = settings.resolve(&self.url);
let current = self.http_proxy.as_ref().map(|p| p.href).unwrap_or(b"");
if new_href.unwrap_or(b"") == current {
return;
}
match new_href {
None => {
self.http_proxy = None;
self.proxy_authorization = None;
}
Some(href) => {
// SAFETY: self-borrow. `href` points into `self.proxy_settings`'s
// boxed storage, which lives as long as `self` (>= `'a`).
let proxy: URL<'a> = unsafe { URL::parse(href).erase_lifetime() };
self.proxy_authorization = async_http::build_proxy_authorization(&proxy);
self.http_proxy = Some(proxy);
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}

/// **Not thread safe while request is in-flight**
pub fn is_https(&self) -> bool {
if let Some(proxy) = &self.http_proxy {
Expand Down Expand Up @@ -4302,6 +4381,7 @@ impl<'a> HTTPClient<'a> {
self.state.reset();
self.flags.proxy_tunneling = false;
self.flags.protocol = Protocol::Http1_1;
self.reevaluate_proxy_for_redirect();
// SAFETY: body_out_str points at the caller-owned MutableString.
self.start(
HTTPRequestBody::Bytes(request_body),
Expand Down
Loading
Loading