Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
112 changes: 107 additions & 5 deletions src/core/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,19 @@ pub(crate) async fn fetch_public_download_with_range(
.await
}

fn remaining_before_deadline(
deadline: Option<tokio::time::Instant>,
) -> anyhow::Result<Option<Duration>> {
let Some(deadline) = deadline else {
return Ok(None);
};
let remaining = deadline
.checked_duration_since(tokio::time::Instant::now())
.filter(|duration| !duration.is_zero())
.ok_or_else(|| anyhow::anyhow!("Download exceeded overall timeout across redirects"))?;
Ok(Some(remaining))
}

async fn fetch_public_download_with_options(
raw: &str,
user_agent: &str,
Expand All @@ -185,8 +198,10 @@ async fn fetch_public_download_with_options(
binary_transfer: bool,
fresh: bool,
) -> anyhow::Result<reqwest::Response> {
let deadline = total_timeout.map(|timeout| tokio::time::Instant::now() + timeout);
let mut url = Url::parse(raw).map_err(|_| anyhow::anyhow!("Invalid download URL"))?;
for hop in 0..=MAX_REDIRECTS {
let remaining = remaining_before_deadline(deadline)?;
validate_download_url(url.as_str())?;
anyhow::ensure!(
url.username().is_empty() && url.password().is_none(),
Expand All @@ -199,8 +214,11 @@ async fn fetch_public_download_with_options(
let port = url
.port_or_known_default()
.ok_or_else(|| anyhow::anyhow!("Download URL has no port"))?;
let lookup_timeout = remaining.map_or(DOWNLOAD_CONNECT_TIMEOUT, |budget| {
budget.min(DOWNLOAD_CONNECT_TIMEOUT)
});
let addresses: Vec<_> = tokio::time::timeout(
DOWNLOAD_CONNECT_TIMEOUT,
lookup_timeout,
tokio::net::lookup_host((host.as_str(), port)),
)
.await??
Expand All @@ -209,16 +227,23 @@ async fn fetch_public_download_with_options(
&& is_loopback_host(url.host_str())
&& crate::core::paths::test_mode();
validate_resolved_addresses(&addresses, loopback_fixture)?;
let remaining = remaining_before_deadline(deadline)?;
let connect_timeout = remaining.map_or(DOWNLOAD_CONNECT_TIMEOUT, |budget| {
budget.min(DOWNLOAD_CONNECT_TIMEOUT)
});
let read_timeout = remaining.map_or(DOWNLOAD_READ_TIMEOUT, |budget| {
budget.min(DOWNLOAD_READ_TIMEOUT)
});
let mut builder = Client::builder()
.no_proxy()
.redirect(redirect::Policy::none())
.connect_timeout(DOWNLOAD_CONNECT_TIMEOUT)
.read_timeout(DOWNLOAD_READ_TIMEOUT)
.connect_timeout(connect_timeout)
.read_timeout(read_timeout)
.resolve_to_addrs(&host, &addresses);
if binary_transfer {
builder = builder.no_gzip().no_brotli().no_zstd();
}
if let Some(timeout) = total_timeout {
if let Some(timeout) = remaining {
builder = builder.timeout(timeout);
}
let client = builder.build()?;
Expand All @@ -236,7 +261,14 @@ async fn fetch_public_download_with_options(
.header(reqwest::header::RANGE, format!("bytes={offset}-"))
.header(reqwest::header::IF_RANGE, validator.clone());
}
let response = request.send().await.map_err(reqwest::Error::without_url)?;
let response = if let Some(timeout) = remaining {
tokio::time::timeout(timeout, request.send())
.await
.map_err(|_| anyhow::anyhow!("Download exceeded overall timeout across redirects"))?
.map_err(reqwest::Error::without_url)?
} else {
request.send().await.map_err(reqwest::Error::without_url)?
};
if !response.status().is_redirection() {
return Ok(response);
}
Expand Down Expand Up @@ -1427,4 +1459,74 @@ mod metadata_limit_tests {
async fn actual_download_client_refuses_a_redirect_to_a_private_listener() {
assert_private_redirect_is_refused(download_client()).await;
}

#[test]
#[expect(unsafe_code)] // Process-wide environment is changed only in the isolated child.
fn fetch_public_download_with_timeout_enforces_overall_deadline_across_redirects()
-> anyhow::Result<()> {
const NAME: &str = "core::http::metadata_limit_tests::fetch_public_download_with_timeout_enforces_overall_deadline_across_redirects";
if crate::core::testing::run_isolated_test(NAME) {
return Ok(());
}
// SAFETY: isolated single-test child process with no concurrent env readers.
unsafe {
std::env::set_var("OMG_TEST_MODE", "1");
}
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?;
let (done_tx, mut done_rx) = tokio::sync::oneshot::channel::<()>();
let server = tokio::spawn(async move {
let mut hop = 0_u32;
loop {
let mut stream = tokio::select! {
_ = &mut done_rx => break,
accepted = listener.accept() => accepted.expect("accept hop").0,
};
let mut buf = [0_u8; 1024];
let _ = stream.read(&mut buf).await;
tokio::time::sleep(Duration::from_millis(120)).await;
hop += 1;
let body = format!(
"HTTP/1.1 302 Found\r\nLocation: http://{address}/hop-{hop}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let _ = stream.write_all(body.as_bytes()).await;
}
});

let started = tokio::time::Instant::now();
let result = fetch_public_download_with_timeout(
&format!("http://{address}/hop-0"),
"omg-redirect-deadline-test",
Some(Duration::from_millis(200)),
)
.await;
let elapsed = started.elapsed();
let _ = done_tx.send(());
let _ = server.await;

let error = result
.expect_err("slow redirect chain must fail once overall deadline expires");
let is_deadline_error = error
.to_string()
.contains("overall timeout across redirects")
|| error.chain().any(|cause| {
cause
.downcast_ref::<reqwest::Error>()
.is_some_and(reqwest::Error::is_timeout)
});
assert!(is_deadline_error, "unexpected error: {error:#}");
assert!(
elapsed < Duration::from_millis(450),
"overall deadline should not reset per hop (elapsed={elapsed:?})"
);
Ok(())
})
}
}
8 changes: 5 additions & 3 deletions src/runtimes/bun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};

#[cfg(test)]
use super::common::extract_zip;
use super::common::{
GITHUB_USER_AGENT, GithubRelease, activate_version, begin_download, begin_staged_install,
complete_staged_install, download_with_progress, extract_zip, normalize_version,
parse_sha256_digest, print_already_installed, print_installed, print_using, version_cmp,
complete_staged_install, download_with_progress, normalize_version, parse_sha256_digest,
print_already_installed, print_installed, print_using, version_cmp,
};
use crate::{cli::style, core::http::download_client};

Expand Down Expand Up @@ -122,7 +124,7 @@ impl BunManager {
let publisher =
super::security::record_download("bun", version, &version_dir, download_path, url)?;
let staging = begin_staged_install(&self.versions_dir)?;
extract_zip(download_path, staging.path(), 1).await?;
let staging = super::common::extract_zip_staged(download_path, staging, None, 1).await?;
self.publish_install(&staging, version)?;
publisher.commit();
Ok(())
Expand Down
Loading
Loading