diff --git a/src/core/http.rs b/src/core/http.rs index 065bd4ffb..e14a5ba66 100644 --- a/src/core/http.rs +++ b/src/core/http.rs @@ -177,6 +177,19 @@ pub(crate) async fn fetch_public_download_with_range( .await } +fn remaining_before_deadline( + deadline: Option, +) -> anyhow::Result> { + 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, @@ -185,8 +198,10 @@ async fn fetch_public_download_with_options( binary_transfer: bool, fresh: bool, ) -> anyhow::Result { + 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(), @@ -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?? @@ -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()?; @@ -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); } @@ -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::() + .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(()) + }) + } } diff --git a/src/runtimes/bun.rs b/src/runtimes/bun.rs index 4955caff7..fcbfbc621 100644 --- a/src/runtimes/bun.rs +++ b/src/runtimes/bun.rs @@ -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}; @@ -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(()) diff --git a/src/runtimes/common.rs b/src/runtimes/common.rs index cb530eb49..f05a3ce43 100644 --- a/src/runtimes/common.rs +++ b/src/runtimes/common.rs @@ -437,6 +437,9 @@ const DOWNLOAD_HEARTBEAT_PERIOD: std::time::Duration = std::time::Duration::from /// 256 KiB per 30s (~8.5 KiB/s) catches degraded CDN trickles while leaving /// small downloads unaffected. const DOWNLOAD_LOW_SPEED_MIN_BYTES: u64 = 256 * 1024; +/// Overall wall-clock budget for a single runtime artifact download across +/// all attempts, redirects, and retries so a slow trickle cannot hang forever. +const DOWNLOAD_OVERALL_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(20); /// Stream a runtime artifact body into a same-filesystem temporary file with /// bounded retry for transient mid-stream failures and low-speed stalls. @@ -453,22 +456,48 @@ where F: FnMut(Option) -> Fut, Fut: std::future::Future>, { - stream_runtime_download_to_temp_with_low_speed::( + stream_runtime_download_to_temp_with_limits::( host, request, dest, DOWNLOAD_HEARTBEAT_PERIOD, DOWNLOAD_LOW_SPEED_MIN_BYTES, + DOWNLOAD_OVERALL_TIMEOUT, ) .await } +#[cfg(test)] async fn stream_runtime_download_to_temp_with_low_speed( + host: &str, + request: F, + dest: &Path, + heartbeat_period: std::time::Duration, + low_speed_min_bytes: u64, +) -> Result<(tempfile::TempPath, String)> +where + D: Digest + Default, + F: FnMut(Option) -> Fut, + Fut: std::future::Future>, +{ + stream_runtime_download_to_temp_with_limits::( + host, + request, + dest, + heartbeat_period, + low_speed_min_bytes, + DOWNLOAD_OVERALL_TIMEOUT, + ) + .await +} + +async fn stream_runtime_download_to_temp_with_limits( host: &str, mut request: F, dest: &Path, heartbeat_period: std::time::Duration, low_speed_min_bytes: u64, + overall_timeout: std::time::Duration, ) -> Result<(tempfile::TempPath, String)> where D: Digest + Default, @@ -478,6 +507,19 @@ where use futures::StreamExt; use tokio::io::{AsyncSeekExt, AsyncWriteExt}; + let overall_deadline = tokio::time::Instant::now() + overall_timeout; + let remaining_budget = || -> Result { + overall_deadline + .checked_duration_since(tokio::time::Instant::now()) + .filter(|duration| !duration.is_zero()) + .ok_or_else(|| { + anyhow::anyhow!( + "Runtime download from {host} exceeded the {}s overall deadline", + overall_timeout.as_secs() + ) + }) + }; + let parent = dest.parent().unwrap_or_else(|| Path::new(".")); tokio::fs::create_dir_all(parent) .await @@ -499,6 +541,7 @@ where let mut resume: Option = None; for attempt in 0..MAX_DOWNLOAD_ATTEMPTS { + let attempt_budget = remaining_budget()?; let requested = resume.clone(); let started = tokio::time::Instant::now(); tracing::info!( @@ -506,9 +549,16 @@ where host, "Runtime download request started" ); - let response = match request(requested.clone()).await { - Ok(response) => response, - Err(error) => { + let response = match tokio::time::timeout(attempt_budget, request(requested.clone())).await + { + Ok(Ok(response)) => response, + Err(_) => { + anyhow::bail!( + "Runtime download from {host} exceeded the {}s overall deadline", + overall_timeout.as_secs() + ); + } + Ok(Err(error)) => { if attempt + 1 < MAX_DOWNLOAD_ATTEMPTS && is_retryable_connect_error(&error) { // Local Debian sweep lane (run-mfY0GF) failed the Go row with // "Failed to connect to go.dev: deadline has elapsed" while the @@ -664,6 +714,12 @@ where loop { let item = tokio::select! { item = stream.next() => item, + () = tokio::time::sleep_until(overall_deadline) => { + anyhow::bail!( + "Runtime download from {host} exceeded the {}s overall deadline", + overall_timeout.as_secs() + ); + } _ = heartbeat.tick() => { let window_bytes = received_this_attempt.saturating_sub(last_heartbeat_bytes); last_heartbeat_bytes = received_this_attempt; @@ -671,7 +727,6 @@ where let remaining_exceeds_floor = total_size == 0 || total_size.saturating_sub(downloaded) > low_speed_min_bytes; if low_speed_min_bytes > 0 - && attempt + 1 < MAX_DOWNLOAD_ATTEMPTS && remaining_exceeds_floor && window_bytes < low_speed_min_bytes { @@ -709,6 +764,17 @@ where if stalled { drop(stream); + if attempt + 1 >= MAX_DOWNLOAD_ATTEMPTS { + anyhow::bail!( + "Runtime download from {host} stalled below minimum throughput ({low_speed_min_bytes} bytes per {}s)", + heartbeat_period.as_secs() + ); + } + let backoff = crate::core::http::retry_backoff( + std::time::Duration::from_millis(100), + u32::try_from(attempt).unwrap_or(u32::MAX), + ); + let _ = remaining_budget()?; resume = representation.as_ref().and_then(|(total, validator)| { (downloaded > 0 && downloaded < *total).then(|| ResumeRequest { offset: downloaded, @@ -725,11 +791,7 @@ where retained_bytes, "Runtime download stalled below minimum throughput; retrying bounded download" ); - tokio::time::sleep(crate::core::http::retry_backoff( - std::time::Duration::from_millis(100), - u32::try_from(attempt).unwrap_or(u32::MAX), - )) - .await; + tokio::time::sleep(backoff.min(remaining_budget()?)).await; continue; } @@ -1068,6 +1130,32 @@ fn extract_tar_entries( /// Synchronously extract selected entries from a .tar.gz component archive /// with a bounded decompression budget. /// +struct ExtractTaskGuard(Option); + +impl ExtractTaskGuard { + fn start(archive_path: &Path) -> Self { + Self(Some(extract_task(archive_path))) + } + + fn task(&self) -> &ProgressTask { + self.0.as_ref().expect("extract task guard active") + } + + fn finish_done(&mut self) { + if let Some(task) = self.0.take() { + task.finish(Outcome::Done); + } + } +} + +impl Drop for ExtractTaskGuard { + fn drop(&mut self) { + if let Some(task) = self.0.take() { + task.finish(Outcome::Failed); + } + } +} + /// Also backs whole-runtime extraction: [`extract_tar_gz`] calls this with the /// default strip selector and [`MAX_DECOMPRESSED_BYTES`]. pub(crate) fn extract_component_tar_gz( @@ -1076,6 +1164,7 @@ pub(crate) fn extract_component_tar_gz( budget: u64, select: TarEntrySelector<'_>, ) -> Result<()> { + let mut task_guard = ExtractTaskGuard::start(archive_path); let file = File::open(archive_path) .with_context(|| format!("Failed to open archive: {}", archive_path.display()))?; @@ -1083,18 +1172,17 @@ pub(crate) fn extract_component_tar_gz( let bounded = BudgetedReader::new(decoder, budget); let mut archive = tar::Archive::new(bounded); - let task = extract_task(archive_path); - fs::create_dir_all(dest_dir)?; - extract_tar_entries(&mut archive, dest_dir, select, &task)?; + extract_tar_entries(&mut archive, dest_dir, select, task_guard.task())?; std::io::copy(&mut archive.into_inner(), &mut std::io::sink()) .context("Failed to finalize gzip archive")?; - task.finish(Outcome::Done); + task_guard.finish_done(); Ok(()) } /// Extract a .tar.gz archive with progress +#[cfg(test)] pub(crate) async fn extract_tar_gz( archive_path: &Path, dest_dir: &Path, @@ -1111,6 +1199,7 @@ pub(crate) async fn extract_tar_gz( /// Extract through the same bounded archive owner with an explicit expansion limit. /// Callers selecting a larger limit must authenticate the archive first. +#[cfg(test)] pub(crate) async fn extract_tar_gz_with_budget( archive_path: &Path, dest_dir: &Path, @@ -1124,10 +1213,43 @@ pub(crate) async fn extract_tar_gz_with_budget( let select = |path: &Path| -> Result> { stripped_archive_path(path, strip_components) }; - let task = extract_task(&archive_path); - let result = extract_component_tar_gz(&archive_path, &dest_dir, max_bytes, &select); - task.finish(Outcome::Done); - result + extract_component_tar_gz(&archive_path, &dest_dir, max_bytes, &select) + }) + .await? +} + +/// Extract a .tar.gz archive into an owned staging directory, transferring +/// ownership of `staging` into `spawn_blocking` so cancelling the async task +/// cannot remove the directory while extraction is still writing to it. +pub(crate) async fn extract_tar_gz_staged( + archive_path: &Path, + staging: tempfile::TempDir, + strip_components: usize, +) -> Result { + extract_tar_gz_staged_with_budget( + archive_path, + staging, + strip_components, + MAX_DECOMPRESSED_BYTES, + ) + .await +} + +/// Owned-staging counterpart to [`extract_tar_gz_with_budget`]. +pub(crate) async fn extract_tar_gz_staged_with_budget( + archive_path: &Path, + staging: tempfile::TempDir, + strip_components: usize, + max_bytes: u64, +) -> Result { + let archive_path = archive_path.to_path_buf(); + + tokio::task::spawn_blocking(move || { + let select = |path: &Path| -> Result> { + stripped_archive_path(path, strip_components) + }; + extract_component_tar_gz(&archive_path, staging.path(), max_bytes, &select)?; + Ok(staging) }) .await? } @@ -1178,11 +1300,11 @@ pub(crate) fn extract_component_tar_xz( budget: u64, select: TarEntrySelector<'_>, ) -> Result<()> { + let mut task_guard = ExtractTaskGuard::start(archive_path); let file = File::open(archive_path) .with_context(|| format!("Failed to open archive: {}", archive_path.display()))?; - let task = extract_task(archive_path); - task.set_message("Decompressing XZ..."); + task_guard.task().set_message("Decompressing XZ..."); fs::create_dir_all(dest_dir)?; let output = tempfile::tempfile_in(dest_dir).with_context(|| { @@ -1208,13 +1330,14 @@ pub(crate) fn extract_component_tar_xz( output.seek(SeekFrom::Start(0))?; let mut archive = tar::Archive::new(output); - extract_tar_entries(&mut archive, dest_dir, select, &task)?; + extract_tar_entries(&mut archive, dest_dir, select, task_guard.task())?; - task.finish(Outcome::Done); + task_guard.finish_done(); Ok(()) } /// Extract a .tar.xz archive with progress (pure Rust) +#[cfg(test)] pub(crate) async fn extract_tar_xz( archive_path: &Path, dest_dir: &Path, @@ -1227,105 +1350,136 @@ pub(crate) async fn extract_tar_xz( let select = |path: &Path| -> Result> { stripped_archive_path(path, strip_components) }; - let task = extract_task(&archive_path); - task.set_message("Decompressing XZ..."); - let result = - extract_component_tar_xz(&archive_path, &dest_dir, MAX_DECOMPRESSED_BYTES, &select); - task.finish(Outcome::Done); - result + extract_component_tar_xz(&archive_path, &dest_dir, MAX_DECOMPRESSED_BYTES, &select) }) .await? } -/// Extract a .zip archive with progress -pub(crate) async fn extract_zip( +/// Extract a .tar.xz archive into an owned staging directory, transferring +/// ownership of `staging` into `spawn_blocking` so cancelling the async task +/// cannot remove the directory while extraction is still writing to it. +pub(crate) async fn extract_tar_xz_staged( archive_path: &Path, - dest_dir: &Path, + staging: tempfile::TempDir, strip_components: usize, -) -> Result<()> { +) -> Result { let archive_path = archive_path.to_path_buf(); - let dest_dir = dest_dir.to_path_buf(); tokio::task::spawn_blocking(move || { - let file = File::open(&archive_path) - .with_context(|| format!("Failed to open archive: {}", archive_path.display()))?; + let select = |path: &Path| -> Result> { + stripped_archive_path(path, strip_components) + }; + extract_component_tar_xz( + &archive_path, + staging.path(), + MAX_DECOMPRESSED_BYTES, + &select, + )?; + Ok(staging) + }) + .await? +} - let mut archive = zip::ZipArchive::new(file).context("Failed to read ZIP archive")?; +fn extract_zip_sync(archive_path: &Path, dest_dir: &Path, strip_components: usize) -> Result<()> { + let mut task_guard = ExtractTaskGuard::start(archive_path); + let file = File::open(archive_path) + .with_context(|| format!("Failed to open archive: {}", archive_path.display()))?; - struct ExtractTaskGuard(Option); - impl Drop for ExtractTaskGuard { - fn drop(&mut self) { - if let Some(task) = self.0.take() { - task.finish(Outcome::Failed); - } - } + let mut archive = zip::ZipArchive::new(file).context("Failed to read ZIP archive")?; + task_guard.task().set_message("Extracting..."); + + fs::create_dir_all(dest_dir)?; + let mut remaining_budget = MAX_DECOMPRESSED_BYTES; + + let mut entry_budget = ArchiveEntryBudget::default(); + anyhow::ensure!( + archive.len() <= MAX_ARCHIVE_ENTRIES, + "Archive contains too many entries" + ); + for i in 0..archive.len() { + let mut file = archive.by_index(i)?; + let entry_name = file.name()?; + let path = file + .enclosed_name() + .ok_or_else(|| anyhow::anyhow!("Unsafe path in runtime ZIP archive: {entry_name}"))?; + entry_budget.charge(&path)?; + let Some(stripped) = stripped_archive_path(&path, strip_components)? else { + continue; + }; + if file.is_symlink() { + anyhow::bail!( + "Unsupported symlink entry in runtime ZIP archive: {}", + path.display() + ); } - let mut task_guard = ExtractTaskGuard(Some(extract_task(&archive_path))); - let task = task_guard.0.as_ref().expect("task guard initialized"); - task.set_message("Extracting..."); - fs::create_dir_all(&dest_dir)?; - let mut remaining_budget = MAX_DECOMPRESSED_BYTES; + let dest_path = dest_dir.join(&stripped); + task_guard + .task() + .set_message(&format!("Extracting: {}", stripped.display())); - let mut entry_budget = ArchiveEntryBudget::default(); - anyhow::ensure!( - archive.len() <= MAX_ARCHIVE_ENTRIES, - "Archive contains too many entries" - ); - for i in 0..archive.len() { - let mut file = archive.by_index(i)?; - let entry_name = file.name()?; - let path = file.enclosed_name().ok_or_else(|| { - anyhow::anyhow!("Unsafe path in runtime ZIP archive: {entry_name}") - })?; - entry_budget.charge(&path)?; - let Some(stripped) = stripped_archive_path(&path, strip_components)? else { - continue; - }; - if file.is_symlink() { - anyhow::bail!( - "Unsupported symlink entry in runtime ZIP archive: {}", - path.display() - ); + if file.is_dir() { + fs::create_dir_all(&dest_path)?; + } else { + fs::create_dir_all(dest_path.parent().unwrap_or(dest_dir))?; + anyhow::ensure!( + file.size() <= remaining_budget, + "decompressed ZIP data exceeds the maximum supported size of {MAX_DECOMPRESSED_BYTES} bytes" + ); + let mut outfile = File::create(&dest_path)?; + copy_with_budget(&mut file, &mut outfile, &mut remaining_budget) + .context("Runtime ZIP exceeded decompression budget")?; + + // Preserve ordinary permission bits on Unix; never restore + // setuid, setgid, or sticky bits from an untrusted archive. + #[cfg(unix)] + if let Some(mode) = file.unix_mode() { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dest_path, fs::Permissions::from_mode(mode & 0o777))?; } + } + } - let dest_path = dest_dir.join(&stripped); - task.set_message(&format!("Extracting: {}", stripped.display())); + task_guard.finish_done(); + Ok(()) +} - if file.is_dir() { - fs::create_dir_all(&dest_path)?; - } else { - if let Some(parent) = dest_path.parent() { - fs::create_dir_all(parent)?; - } - anyhow::ensure!( - file.size() <= remaining_budget, - "decompressed ZIP data exceeds the maximum supported size of {MAX_DECOMPRESSED_BYTES} bytes" - ); - let mut outfile = File::create(&dest_path)?; - if let Err(error) = copy_with_budget(&mut file, &mut outfile, &mut remaining_budget) - { - drop(outfile); - let _ = fs::remove_file(&dest_path); - return Err(error).context("Runtime ZIP exceeded decompression budget"); - } +/// Extract a .zip archive with progress +#[cfg(test)] +pub(crate) async fn extract_zip( + archive_path: &Path, + dest_dir: &Path, + strip_components: usize, +) -> Result<()> { + let archive_path = archive_path.to_path_buf(); + let dest_dir = dest_dir.to_path_buf(); - // Preserve ordinary permission bits on Unix; never restore - // setuid, setgid, or sticky bits from an untrusted archive. - #[cfg(unix)] - if let Some(mode) = file.unix_mode() { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&dest_path, fs::Permissions::from_mode(mode & 0o777))?; - } - } - } + tokio::task::spawn_blocking(move || { + extract_zip_sync(&archive_path, &dest_dir, strip_components) + }) + .await? +} - task_guard - .0 - .take() - .expect("task guard active") - .finish(Outcome::Done); - Ok(()) +/// Extract a .zip archive into an owned staging directory (or a relative +/// subdirectory within it), transferring ownership of `staging` into +/// `spawn_blocking` so cancelling the async task cannot remove the directory +/// while extraction is still writing to it. +pub(crate) async fn extract_zip_staged( + archive_path: &Path, + staging: tempfile::TempDir, + subdir: Option<&Path>, + strip_components: usize, +) -> Result { + let archive_path = archive_path.to_path_buf(); + let subdir = subdir.map(Path::to_path_buf); + + tokio::task::spawn_blocking(move || { + let dest_dir = match subdir { + Some(rel) => staging.path().join(rel), + None => staging.path().to_path_buf(), + }; + extract_zip_sync(&archive_path, &dest_dir, strip_components)?; + Ok(staging) }) .await? } @@ -5861,4 +6015,158 @@ mod entry_budget_tests { assert!(extract_zip(&sym_zip, &dest, 0).await.is_err()); Ok(()) } + + #[tokio::test] + async fn extract_tar_gz_staged_transfers_ownership_and_cleans_up_on_cancel() -> Result<()> { + let versions = tempfile::tempdir()?; + let archive_path = versions.path().join("sample.tar.gz"); + { + let file = File::create(&archive_path)?; + let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::fast()); + let mut tar = tar::Builder::new(encoder); + let payload = b"hello staged runtime"; + let mut header = tar::Header::new_gnu(); + header.set_size(payload.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + tar.append_data(&mut header, "pkg/bin/tool", &payload[..])?; + tar.into_inner()?.finish()?; + } + + // Normal path returns the owned staging directory intact. + let staging = begin_staged_install(versions.path())?; + let staging = extract_tar_gz_staged(&archive_path, staging, 1).await?; + assert_eq!( + fs::read(staging.path().join("bin/tool"))?, + b"hello staged runtime" + ); + drop(staging); + + // Owned-staging zip extraction supports both root and relative subdir targets. + let zip_path = versions.path().join("sample.zip"); + { + let mut archive = zip::ZipWriter::new(File::create(&zip_path)?); + let opts = zip::write::SimpleFileOptions::default(); + archive.start_file("tool", opts)?; + archive.write_all(b"zip-tool")?; + archive.finish()?; + } + let staging = begin_staged_install(versions.path())?; + let staging = extract_zip_staged(&zip_path, staging, None, 0).await?; + assert_eq!(fs::read(staging.path().join("tool"))?, b"zip-tool"); + drop(staging); + let staging = begin_staged_install(versions.path())?; + let staging = extract_zip_staged(&zip_path, staging, Some(Path::new("bin")), 0).await?; + assert_eq!(fs::read(staging.path().join("bin/tool"))?, b"zip-tool"); + drop(staging); + + // Cancelled future transfers TempDir ownership to spawn_blocking so + // cleanup happens cleanly after the blocking task exits with no orphan. + let staging = begin_staged_install(versions.path())?; + let staged_path = staging.path().to_path_buf(); + let _ = tokio::time::timeout( + std::time::Duration::from_nanos(1), + extract_tar_gz_staged(&archive_path, staging, 1), + ) + .await; + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(!staged_path.exists()); + Ok(()) + } + + #[tokio::test] + async fn stream_runtime_download_enforces_overall_deadline_on_trickle() -> Result<()> { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + let dir = tempfile::tempdir()?; + let dest = dir.path().join("slow.tar.xz"); + + let pending_request = |_resume| std::future::pending::>(); + let zero_err = stream_runtime_download_to_temp_with_limits::( + "127.0.0.1", + pending_request, + &dest, + std::time::Duration::from_secs(30), + 0, + std::time::Duration::ZERO, + ) + .await + .expect_err("zero overall budget must fail immediately"); + assert!(zero_err.to_string().contains("overall deadline")); + + let connect_err = stream_runtime_download_to_temp_with_limits::( + "127.0.0.1", + pending_request, + &dest, + std::time::Duration::from_secs(30), + 0, + std::time::Duration::from_millis(20), + ) + .await + .expect_err("slow connect must fail on overall deadline"); + assert!(connect_err.to_string().contains("overall deadline")); + + 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 { + loop { + let mut stream = tokio::select! { + _ = &mut done_rx => break, + accepted = listener.accept() => accepted.expect("accept trickle client").0, + }; + let mut buf = [0_u8; 1024]; + let _ = stream.read(&mut buf).await; + let headers = + "HTTP/1.1 200 OK\r\nContent-Length: 4096\r\nConnection: close\r\n\r\n"; + let _ = stream.write_all(headers.as_bytes()).await; + for _ in 0..8 { + let _ = stream.write_all(&[b'x'; 16]).await; + tokio::time::sleep(std::time::Duration::from_millis(30)).await; + } + } + }); + + let client = reqwest::Client::new(); + let url = format!("http://{address}/slow.tar.xz"); + let error = stream_runtime_download_to_temp_with_limits::( + "127.0.0.1", + |_resume| { + let client = client.clone(); + let url = url.clone(); + async move { client.get(url).send().await.map_err(Into::into) } + }, + &dest, + std::time::Duration::from_secs(30), + 0, + std::time::Duration::from_millis(200), + ) + .await + .expect_err("trickling artifact must fail once overall deadline expires"); + assert!(error.to_string().contains("overall deadline")); + + let stall_err = stream_runtime_download_to_temp_with_limits::( + "127.0.0.1", + |_resume| { + let client = client.clone(); + let url = url.clone(); + async move { client.get(url).send().await.map_err(Into::into) } + }, + &dest, + std::time::Duration::from_millis(25), + 2048, + std::time::Duration::from_secs(10), + ) + .await + .expect_err("sustained low-speed trickle must fail on final attempt"); + let _ = done_tx.send(()); + let _ = server.await; + assert!( + stall_err + .to_string() + .contains("stalled below minimum throughput") + ); + Ok(()) + } } diff --git a/src/runtimes/deno.rs b/src/runtimes/deno.rs index c423f0e4e..ba1effd91 100644 --- a/src/runtimes/deno.rs +++ b/src/runtimes/deno.rs @@ -10,9 +10,9 @@ use std::path::{Path, PathBuf}; use super::common::{ GITHUB_USER_AGENT, GithubAsset, GithubRelease, activate_version, begin_download, - begin_staged_install, complete_staged_install, download_with_progress, extract_zip, - fetch_github_releases, normalize_version, parse_sha256_digest, print_already_installed, - print_installed, print_using, require_regular_file, validate_download_filename, version_cmp, + begin_staged_install, complete_staged_install, download_with_progress, fetch_github_releases, + normalize_version, parse_sha256_digest, print_already_installed, print_installed, print_using, + require_regular_file, validate_download_filename, version_cmp, }; use crate::{cli::style, core::http::download_client}; @@ -143,8 +143,9 @@ impl DenoManager { let staging = begin_staged_install(&self.versions_dir)?; // Vendor ZIPs carry `deno` at the archive root, so strip 0 lands it // at `/bin/deno` and any future sibling tools beside it. - let staging_bin = staging.path().join("bin"); - extract_zip(download_path, &staging_bin, 0).await?; + let staging = + super::common::extract_zip_staged(download_path, staging, Some(Path::new("bin")), 0) + .await?; // Publish only a complete vendor tree: the native command must be a // real regular file before the version directory can exist at all. require_regular_file(&staging.path().join("bin").join("deno"))?; diff --git a/src/runtimes/dotnet.rs b/src/runtimes/dotnet.rs index cd35ac19d..c60809563 100644 --- a/src/runtimes/dotnet.rs +++ b/src/runtimes/dotnet.rs @@ -15,8 +15,8 @@ use std::path::{Path, PathBuf}; use super::common::{ activate_version, begin_staged_install, complete_staged_install, download_with_progress_sha512, - extract_tar_gz, normalize_version, parse_sha512_digest, print_already_installed, - print_installed, print_using, remove_file_best_effort, + normalize_version, parse_sha512_digest, print_already_installed, print_installed, print_using, + remove_file_best_effort, }; use crate::core::http::BoundedResponseExt; use crate::{cli::style, core::http::download_client}; @@ -176,7 +176,7 @@ impl DotnetManager { super::security::record_exact_release(&version_dir, &version, &version, components)?; let staging = begin_staged_install(&self.versions_dir)?; // SDK tarballs extract flat (no top-level directory). - extract_tar_gz(&download_path, staging.path(), 0).await?; + let staging = super::common::extract_tar_gz_staged(&download_path, staging, 0).await?; let binary = staging.path().join("dotnet"); require_staged_dotnet(&binary)?; make_staged_executable(&binary)?; diff --git a/src/runtimes/erlang.rs b/src/runtimes/erlang.rs index 96a0daa38..1fddd7991 100644 --- a/src/runtimes/erlang.rs +++ b/src/runtimes/erlang.rs @@ -26,9 +26,9 @@ use std::path::{Path, PathBuf}; use super::common::{ activate_version_with_linked_binary, begin_staged_install, complete_staged_install, - download_with_progress, extract_tar_gz, is_valid_version_dir, normalize_version, - parse_sha256_digest, print_already_installed, print_installed, print_using, - remove_file_best_effort, uninstall_version, validate_download_filename, + download_with_progress, is_valid_version_dir, normalize_version, parse_sha256_digest, + print_already_installed, print_installed, print_using, remove_file_best_effort, + uninstall_version, validate_download_filename, }; use crate::core::http::BoundedResponseExt; use crate::{cli::style, core::http::download_client}; @@ -424,7 +424,7 @@ impl ErlangManager { let publisher = super::security::record_download("erlang", version, &version_dir, download_path, url)?; let staging = begin_staged_install(&self.versions_dir)?; - extract_tar_gz(download_path, staging.path(), 1).await?; + let staging = super::common::extract_tar_gz_staged(download_path, staging, 1).await?; if std::env::consts::OS == "linux" { require_staged_install_script(&staging.path().join("Install"))?; } @@ -442,7 +442,7 @@ impl ErlangManager { if std::env::consts::OS == "linux" { admission.before_execution(&version_dir)?; println!("{} Running OTP Install script...", style::informative("→")); - if let Err(error) = run_install_script(&version_dir) { + if let Err(error) = run_install_script(&version_dir).await { cleanup_broken_install(&version_dir); return Err(error); } @@ -453,7 +453,7 @@ impl ErlangManager { .prepare_staged("erlang", version, &version_dir, &version_dir)?; after_setup.before_execution(&version_dir)?; println!("{} Verifying installation...", style::informative("→")); - if let Err(error) = smoke_erl(&version_dir) { + if let Err(error) = smoke_erl(&version_dir).await { cleanup_broken_install(&version_dir); return Err(error.context( "The prebuilt Erlang/OTP binary does not run here (likely glibc \ @@ -517,7 +517,7 @@ fn require_staged_install_script(script: &Path) -> Result<()> { /// Run OTP's `Install -minimal ` in the published directory. The script /// travels as argv (never interpolated) and runs under `sh` so a missing /// executable bit on the script itself cannot break the install. -fn run_install_script(version_dir: &Path) -> Result<()> { +async fn run_install_script(version_dir: &Path) -> Result<()> { let mut command = std::process::Command::new("sh"); super::common::harden_untrusted_runtime_command(&mut command, version_dir); command @@ -525,27 +525,29 @@ fn run_install_script(version_dir: &Path) -> Result<()> { .arg("-minimal") .arg(version_dir) .current_dir(version_dir); - super::tool_artifacts::run_with_timeout( + super::tool_artifacts::run_with_timeout_async( command, "OTP Install script", std::time::Duration::from_mins(2), - )?; + ) + .await?; Ok(()) } /// Smoke-test the installed runtime: `erl` must start and halt cleanly. /// This is also the glibc-compatibility probe (same check the asdf /// installer runs before falling back to a source build). -fn smoke_erl(version_dir: &Path) -> Result<()> { +async fn smoke_erl(version_dir: &Path) -> Result<()> { let erl = version_dir.join("bin/erl"); let mut command = std::process::Command::new(&erl); super::common::harden_untrusted_runtime_command(&mut command, version_dir); command.args(["-noshell", "-eval", "halt()."]); - super::tool_artifacts::run_with_timeout( + super::tool_artifacts::run_with_timeout_async( command, "Erlang/OTP smoke test", std::time::Duration::from_secs(30), - )?; + ) + .await?; Ok(()) } diff --git a/src/runtimes/github_tool.rs b/src/runtimes/github_tool.rs index 5d21d783f..1314b0473 100644 --- a/src/runtimes/github_tool.rs +++ b/src/runtimes/github_tool.rs @@ -14,10 +14,9 @@ use std::path::{Path, PathBuf}; use super::common::{ GITHUB_USER_AGENT, GithubAsset, GithubRelease, activate_version_with_linked_binary, - begin_staged_install, complete_staged_install, download_with_progress, extract_tar_gz, - extract_tar_xz, extract_zip, fetch_github_releases, normalize_version, parse_sha256_digest, - print_already_installed, print_installed, print_using, remove_file_best_effort, - require_regular_file, validate_download_filename, + begin_staged_install, complete_staged_install, download_with_progress, fetch_github_releases, + normalize_version, parse_sha256_digest, print_already_installed, print_installed, print_using, + remove_file_best_effort, require_regular_file, validate_download_filename, }; use super::tool_registry::RegistryTool; use crate::{ @@ -584,8 +583,7 @@ impl GenericToolManager { let version_dir = self.versions_dir.join(version); println!("{} Extracting (pure Rust)...", style::informative("→")); let staging = begin_staged_install(&self.versions_dir)?; - self.populate_staging(download_path, kind, staging.path()) - .await?; + let staging = self.populate_staging(download_path, kind, staging).await?; let publisher = super::security::record_download( self.spec.name, version, @@ -610,53 +608,48 @@ impl GenericToolManager { &self, download_path: &Path, kind: ArchiveKind, - staging: &Path, - ) -> Result<()> { - if kind == ArchiveKind::BareBinary { - let bin_dir = staging.join("bin"); - fs::create_dir_all(&bin_dir)?; - let dest = bin_dir.join(self.spec.binary); - fs::copy(download_path, &dest).with_context(|| { - format!("Failed to stage downloaded binary: {}", dest.display()) - })?; - make_executable(&dest)?; - return Ok(()); - } - self.extract_and_link(download_path, kind, staging).await - } - - /// Extract once and link the discovered binary into `staging/bin`. - async fn extract_and_link( - &self, - download_path: &Path, - kind: ArchiveKind, - staging: &Path, - ) -> Result<()> { - match kind { - ArchiveKind::TarGz => extract_tar_gz(download_path, staging, 0).await, - ArchiveKind::Zip => extract_zip(download_path, staging, 0).await, - ArchiveKind::TarXz => extract_tar_xz(download_path, staging, 0).await, - ArchiveKind::BareBinary => Ok(()), - }?; - let found = self.find_binary(staging).with_context(|| { + staging: tempfile::TempDir, + ) -> Result { + let staging = match kind { + ArchiveKind::BareBinary => { + let bin_dir = staging.path().join("bin"); + fs::create_dir_all(&bin_dir)?; + let dest = bin_dir.join(self.spec.binary); + fs::copy(download_path, &dest).with_context(|| { + format!("Failed to stage downloaded binary: {}", dest.display()) + })?; + make_executable(&dest)?; + return Ok(staging); + } + ArchiveKind::TarGz => { + super::common::extract_tar_gz_staged(download_path, staging, 0).await? + } + ArchiveKind::Zip => { + super::common::extract_zip_staged(download_path, staging, None, 0).await? + } + ArchiveKind::TarXz => { + super::common::extract_tar_xz_staged(download_path, staging, 0).await? + } + }; + let found = self.find_binary(staging.path()).with_context(|| { format!( "Installed {} archive but found no `{}` binary inside", self.spec.name, self.spec.binary ) })?; make_executable(&found)?; - let bin_dir = staging.join("bin"); + let bin_dir = staging.path().join("bin"); // The binary already lives exactly at `bin/`: nothing to do. if found.parent() == Some(bin_dir.as_path()) && found.file_name().and_then(|name| name.to_str()) == Some(self.spec.binary) { - return Ok(()); + return Ok(staging); } fs::create_dir_all(&bin_dir)?; let link = bin_dir.join(self.spec.binary); if link.exists() { require_regular_file(&link)?; - return Ok(()); + return Ok(staging); } let target = pathdiff_relative(&found, &bin_dir); #[cfg(unix)] @@ -671,7 +664,7 @@ impl GenericToolManager { let _ = target; anyhow::bail!("Registry tool installs are unsupported on this platform"); } - Ok(()) + Ok(staging) } /// Find the primary binary below `staging` (shallowest match wins). @@ -1242,19 +1235,54 @@ mod tests { archive.start_file("lib/elixir/ebin/module.beam", options)?; archive.write_all(b"library")?; archive.finish()?; - let staging = dir.path().join("staging"); - fs::create_dir(&staging)?; + let staging = tempfile::tempdir_in(dir.path())?; let mut manager = GenericToolManager::for_name("elixir").expect("registered"); manager.versions_dir = dir.path().join("versions"); assert!(manager.list_installed()?.is_empty()); - manager - .populate_staging(&archive_path, ArchiveKind::Zip, &staging) + let staging = manager + .populate_staging(&archive_path, ArchiveKind::Zip, staging) .await?; - assert!(staging.join("bin/elixir").is_file()); + assert!(staging.path().join("bin/elixir").is_file()); assert_eq!( - fs::read(staging.join("lib/elixir/ebin/module.beam"))?, + fs::read(staging.path().join("lib/elixir/ebin/module.beam"))?, b"library" ); + + let bare = dir.path().join("elixir-bare"); + fs::write(&bare, b"#!/bin/sh\nexit 0\n")?; + let bare_staging = manager + .populate_staging( + &bare, + ArchiveKind::BareBinary, + tempfile::tempdir_in(dir.path())?, + ) + .await?; + assert!(bare_staging.path().join("bin/elixir").is_file()); + + let xz_path = dir.path().join("elixir.tar.xz"); + { + let mut tar_bytes = Vec::new(); + { + let mut tar = tar::Builder::new(&mut tar_bytes); + let payload = b"#!/bin/sh\nexit 0\n"; + let mut header = tar::Header::new_gnu(); + header.set_size(payload.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + tar.append_data(&mut header, "bin/elixir", &payload[..])?; + tar.finish()?; + } + let mut xz_file = std::fs::File::create(&xz_path)?; + lzma_rs::xz_compress(&mut tar_bytes.as_slice(), &mut xz_file)?; + } + let xz_staging = manager + .populate_staging( + &xz_path, + ArchiveKind::TarXz, + tempfile::tempdir_in(dir.path())?, + ) + .await?; + assert!(xz_staging.path().join("bin/elixir").is_file()); Ok(()) } @@ -1523,4 +1551,48 @@ mod tests { .expect_err("missing tool binary must be rejected"); assert!(!missing_err.to_string().is_empty()); } + + #[tokio::test] + async fn stage_archive_handles_bare_binary_and_existing_bin_target() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let manager = GenericToolManager::for_name("ripgrep").expect("ripgrep spec"); + + let bare_staging = tempfile::tempdir_in(dir.path())?; + let bare_download = dir.path().join("rg"); + fs::write(&bare_download, b"#!/bin/sh\n")?; + let staged_bare = manager + .populate_staging(&bare_download, ArchiveKind::BareBinary, bare_staging) + .await?; + assert!(staged_bare.path().exists()); + let missing_err = manager + .populate_staging( + &dir.path().join("missing-rg"), + ArchiveKind::BareBinary, + tempfile::tempdir_in(dir.path())?, + ) + .await + .expect_err("missing bare binary must fail"); + assert!( + missing_err + .to_string() + .contains("Failed to stage downloaded binary") + ); + + let zip_path = dir.path().join("rg.zip"); + let zip_file = fs::File::create(&zip_path)?; + let mut zip = zip::ZipWriter::new(zip_file); + let opts = zip::write::SimpleFileOptions::default(); + zip.start_file("a/rg", opts)?; + std::io::Write::write_all(&mut zip, b"#!/bin/sh\n")?; + zip.finish()?; + + let pre_staging = tempfile::tempdir_in(dir.path())?; + fs::create_dir_all(pre_staging.path().join("bin"))?; + fs::write(pre_staging.path().join("bin/rg"), b"#!/bin/sh\n")?; + let staged_existing = manager + .populate_staging(&zip_path, ArchiveKind::Zip, pre_staging) + .await?; + assert!(staged_existing.path().join("bin/rg").is_file()); + Ok(()) + } } diff --git a/src/runtimes/go.rs b/src/runtimes/go.rs index 0c4c677dd..4e85e8716 100644 --- a/src/runtimes/go.rs +++ b/src/runtimes/go.rs @@ -16,10 +16,12 @@ use std::{ use anyhow::{Context, Result}; use serde::Deserialize; +#[cfg(test)] +use super::common::extract_tar_gz; use super::common::{ activate_version, begin_download, begin_staged_install, complete_staged_install, - download_with_progress, extract_tar_gz, normalize_version, parse_sha256_digest, - print_already_installed, print_installed, + download_with_progress, normalize_version, parse_sha256_digest, print_already_installed, + print_installed, }; use crate::{cli::style, core::http::download_client}; @@ -177,7 +179,7 @@ impl GoManager { let publisher = super::security::record_download("go", version, &version_dir, download_path, url)?; let staging = begin_staged_install(&self.versions_dir)?; - extract_tar_gz(download_path, staging.path(), 1).await?; + let staging = super::common::extract_tar_gz_staged(download_path, staging, 1).await?; self.publish_install(&staging, version)?; publisher.commit(); Ok(()) diff --git a/src/runtimes/java.rs b/src/runtimes/java.rs index 4ed5a23e3..c8efdf79f 100644 --- a/src/runtimes/java.rs +++ b/src/runtimes/java.rs @@ -17,6 +17,8 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::Deserialize; +#[cfg(test)] +use super::common::extract_tar_gz; #[cfg(feature = "pgp")] use super::common::{ GITHUB_USER_AGENT, begin_download, download_with_progress, parse_sha256_digest, @@ -24,7 +26,7 @@ use super::common::{ }; use super::common::{activate_version, normalize_version, print_already_installed}; #[cfg(any(feature = "pgp", test))] -use super::common::{begin_staged_install, complete_staged_install, extract_tar_gz}; +use super::common::{begin_staged_install, complete_staged_install}; #[cfg(feature = "pgp")] use crate::core::http::{bounded_metadata_body_with_limit, fetch_public_download}; #[cfg(feature = "pgp")] @@ -282,7 +284,7 @@ impl JavaManager { ) .context("Failed to record exact Adoptium release metadata")?; let staging = begin_staged_install(&self.versions_dir)?; - extract_tar_gz(&download_path, staging.path(), 1).await?; + let staging = super::common::extract_tar_gz_staged(&download_path, staging, 1).await?; self.publish_install(&staging, version)?; publisher.commit(); diff --git a/src/runtimes/node.rs b/src/runtimes/node.rs index 34b16a37f..2d70acde0 100644 --- a/src/runtimes/node.rs +++ b/src/runtimes/node.rs @@ -16,8 +16,8 @@ use std::path::{Path, PathBuf}; use super::common::{ activate_version_with_lease, begin_download, begin_staged_install, complete_staged_install, - download_with_progress, extract_tar_xz, normalize_version, print_already_installed, - print_installed, print_using, + download_with_progress, normalize_version, print_already_installed, print_installed, + print_using, }; use crate::{cli::style, core::http::download_client}; @@ -215,7 +215,7 @@ impl NodeManager { let publisher = super::security::record_download("node", &version, &version_dir, &download_path, &url)?; let staging = begin_staged_install(&self.versions_dir)?; - extract_tar_xz(&download_path, staging.path(), 1).await?; + let staging = super::common::extract_tar_xz_staged(&download_path, staging, 1).await?; self.publish_install(&staging, &version)?; publisher.commit(); diff --git a/src/runtimes/php.rs b/src/runtimes/php.rs index 6a9c9e2a8..e0c28919d 100644 --- a/src/runtimes/php.rs +++ b/src/runtimes/php.rs @@ -33,10 +33,9 @@ use std::path::{Path, PathBuf}; use super::common::{ GithubAsset, GithubRelease, activate_version_with_linked_binary, begin_staged_install, - clear_dir_contents, complete_staged_install, download_with_progress, extract_tar_xz, - fetch_github_releases, is_valid_version_dir, normalize_version, parse_sha256_digest, - print_installed, print_using, remove_file_best_effort, replace_staged_install, - uninstall_version, validate_download_filename, + clear_dir_contents, complete_staged_install, download_with_progress, fetch_github_releases, + is_valid_version_dir, normalize_version, parse_sha256_digest, print_installed, print_using, + remove_file_best_effort, replace_staged_install, uninstall_version, validate_download_filename, }; use crate::{cli::style, core::http::download_client}; @@ -497,11 +496,11 @@ impl PhpManager { let staging = begin_staged_install(&self.versions_dir)?; // System-root tarballs unwrap one level (`usr/bin/php8.5` becomes // `bin/php8.5`); flat archives fall back to strip 0. - extract_tar_xz(download_path, staging.path(), 1).await?; + let mut staging = super::common::extract_tar_xz_staged(download_path, staging, 1).await?; let mut found = find_php_binary(staging.path(), version); if found.is_none() { clear_dir_contents(staging.path())?; - extract_tar_xz(download_path, staging.path(), 0).await?; + staging = super::common::extract_tar_xz_staged(download_path, staging, 0).await?; found = find_php_binary(staging.path(), version); } let found = found.with_context(|| { @@ -516,7 +515,7 @@ impl PhpManager { .prepare_staged("php", version, staging.path(), &version_dir)?; admission.before_execution(staging.path())?; println!("{} Verifying installation...", style::informative("→")); - if let Err(error) = smoke_php(staging.path()) { + if let Err(error) = smoke_php_async(staging.path()).await { return Err(error.context(format!( "The prebuilt PHP {version} binary does not run here (likely a foreign distro build); try OMG_PHP_DISTRO=" ))); @@ -563,6 +562,7 @@ super::common::impl_runtime_common!(PhpManager); /// Smoke-test the installed runtime: the interpreter must start and report /// its version. This is also the distro-compatibility probe: a build for a /// foreign distro fails here and the install is removed. +#[cfg(test)] fn smoke_php(version_dir: &Path) -> Result<()> { let php = version_dir.join("bin/php"); let mut command = std::process::Command::new(&php); @@ -576,6 +576,20 @@ fn smoke_php(version_dir: &Path) -> Result<()> { Ok(()) } +async fn smoke_php_async(version_dir: &Path) -> Result<()> { + let php = version_dir.join("bin/php"); + let mut command = std::process::Command::new(&php); + super::common::harden_untrusted_runtime_command(&mut command, version_dir); + command.arg("-v"); + super::tool_artifacts::run_with_timeout_async( + command, + "PHP smoke test (`php -v`)", + std::time::Duration::from_secs(30), + ) + .await?; + Ok(()) +} + /// Ensure the installed `php` is executable (tarballs may drop modes). #[cfg(unix)] fn make_staged_executable(path: &Path) -> Result<()> { diff --git a/src/runtimes/python.rs b/src/runtimes/python.rs index e8d118c9f..750b202aa 100644 --- a/src/runtimes/python.rs +++ b/src/runtimes/python.rs @@ -15,8 +15,8 @@ mod catalog; use super::common::{ GithubRelease, activate_version_with_linked_binary, begin_download, begin_staged_install, - complete_staged_install, download_with_progress, extract_tar_gz, fetch_github_releases, - normalize_version, parse_sha256_digest, print_already_installed, print_installed, print_using, + complete_staged_install, download_with_progress, fetch_github_releases, normalize_version, + parse_sha256_digest, print_already_installed, print_installed, print_using, validate_download_filename, version_cmp, }; use crate::{cli::style, core::http::download_client}; @@ -298,7 +298,7 @@ impl PythonManager { let publisher = super::security::record_download("python", version, &version_dir, download_path, url)?; let staging = begin_staged_install(&self.versions_dir)?; - extract_tar_gz(download_path, staging.path(), 1).await?; + let staging = super::common::extract_tar_gz_staged(download_path, staging, 1).await?; self.publish_install(&staging, version)?; publisher.commit(); Ok(()) diff --git a/src/runtimes/ruby.rs b/src/runtimes/ruby.rs index 75c293fb9..c46812446 100644 --- a/src/runtimes/ruby.rs +++ b/src/runtimes/ruby.rs @@ -11,11 +11,12 @@ use anyhow::{Context, Result}; use std::fs; use std::path::{Path, PathBuf}; +#[cfg(test)] +use super::common::extract_tar_gz; use super::common::{ GITHUB_USER_AGENT, GithubRelease, activate_version, begin_download, begin_staged_install, - complete_staged_install, download_with_progress, extract_tar_gz, normalize_version, - parse_sha256_digest, print_already_installed, print_installed, print_using, - validate_download_filename, version_cmp, + complete_staged_install, download_with_progress, normalize_version, parse_sha256_digest, + print_already_installed, print_installed, print_using, validate_download_filename, version_cmp, }; use crate::{cli::style, core::http::download_client}; @@ -165,7 +166,7 @@ impl RubyManager { let publisher = super::security::record_download("ruby", version, &version_dir, download_path, url)?; let staging = begin_staged_install(&self.versions_dir)?; - extract_tar_gz(download_path, staging.path(), 1).await?; + let staging = super::common::extract_tar_gz_staged(download_path, staging, 1).await?; self.publish_install(&staging, version)?; publisher.commit(); Ok(()) diff --git a/src/runtimes/swift.rs b/src/runtimes/swift.rs index e1aab8eed..74f1564c1 100644 --- a/src/runtimes/swift.rs +++ b/src/runtimes/swift.rs @@ -42,10 +42,9 @@ use std::path::{Path, PathBuf}; use super::common::{ GithubRelease, activate_version_with_linked_binary, begin_staged_install, - complete_staged_install, download_to_temp_for_signature, extract_tar_gz_with_budget, - fetch_github_releases, is_valid_version_dir, normalize_version, print_already_installed, - print_installed, print_using, remove_file_best_effort, uninstall_version, - validate_download_filename, + complete_staged_install, download_to_temp_for_signature, fetch_github_releases, + is_valid_version_dir, normalize_version, print_already_installed, print_installed, print_using, + remove_file_best_effort, uninstall_version, validate_download_filename, }; // Published at https://www.swift.org/keys/active/. Keep this list explicit so @@ -233,7 +232,13 @@ async fn verify_and_extract_tarball( println!("{} Extracting (pure Rust)...", style::informative("→")); let staging = begin_staged_install(versions_dir)?; // Strip only the vendor's top directory, preserving its usr/ tree. - extract_tar_gz_with_budget(tarball, staging.path(), 1, MAX_SWIFT_DECOMPRESSED_BYTES).await?; + let staging = super::common::extract_tar_gz_staged_with_budget( + tarball, + staging, + 1, + MAX_SWIFT_DECOMPRESSED_BYTES, + ) + .await?; Ok(staging) } diff --git a/src/runtimes/tool_artifacts.rs b/src/runtimes/tool_artifacts.rs index a8c56a6a0..8a88011b0 100644 --- a/src/runtimes/tool_artifacts.rs +++ b/src/runtimes/tool_artifacts.rs @@ -114,6 +114,18 @@ pub(crate) fn run_with_timeout( ) } +/// Async wrapper around [`run_with_timeout`] so blocking subprocess waits never +/// stall a Tokio runtime worker thread. +pub(crate) async fn run_with_timeout_async( + command: Command, + phase: &'static str, + timeout: Duration, +) -> Result> { + tokio::task::spawn_blocking(move || run_with_timeout(command, phase, timeout)) + .await + .with_context(|| format!("{phase} task failed"))? +} + fn run_owned( mut command: Command, phase: &str, @@ -1551,4 +1563,42 @@ esac } Ok(()) } + + #[cfg(unix)] + #[tokio::test(flavor = "current_thread")] + async fn run_with_timeout_async_does_not_block_tokio_worker() -> Result<()> { + let mut command = Command::new("sh"); + command.args(["-c", "sleep 0.15; printf ok"]); + + let tick_before_exit = std::sync::Arc::new(AtomicBool::new(false)); + let completed = std::sync::Arc::new(AtomicBool::new(false)); + let tick_flag = std::sync::Arc::clone(&tick_before_exit); + let done_flag = std::sync::Arc::clone(&completed); + + let (output, ()) = tokio::join!( + async { + let out = run_with_timeout_async( + command, + "async subprocess probe", + Duration::from_secs(5), + ) + .await; + done_flag.store(true, Ordering::Release); + out + }, + async { + tokio::time::sleep(Duration::from_millis(30)).await; + if !completed.load(Ordering::Acquire) { + tick_flag.store(true, Ordering::Release); + } + } + ); + + assert_eq!(output?, b"ok"); + assert!( + tick_before_exit.load(Ordering::Acquire), + "sibling Tokio task must make progress while subprocess runs" + ); + Ok(()) + } } diff --git a/src/runtimes/zig.rs b/src/runtimes/zig.rs index ac4f94ae3..31da39fd7 100644 --- a/src/runtimes/zig.rs +++ b/src/runtimes/zig.rs @@ -16,8 +16,8 @@ use std::time::Duration; use super::common::{ GITHUB_USER_AGENT, activate_version, begin_staged_install, complete_staged_install, - download_with_progress, extract_tar_xz, normalize_version, parse_sha256_digest, - print_already_installed, print_installed, print_using, remove_file_best_effort, + download_with_progress, normalize_version, parse_sha256_digest, print_already_installed, + print_installed, print_using, remove_file_best_effort, }; use crate::cli::style; use crate::core::http::{ @@ -168,7 +168,7 @@ impl ZigManager { let publisher = super::security::record_download("zig", version, &version_dir, download_path, url)?; let staging = begin_staged_install(&self.versions_dir)?; - stage_zig_tree(download_path, staging.path()).await?; + let staging = stage_zig_tree(download_path, staging).await?; let _admission = self.security .prepare_staged("zig", version, staging.path(), &version_dir)?; @@ -346,25 +346,30 @@ fn verify_publisher_signature( /// Extract a Zig tarball into staging and normalize the layout to /// `bin/zig`, keeping the sibling `lib/` tree the compiler resolves its /// standard library from. -async fn stage_zig_tree(download_path: &Path, staging: &Path) -> Result<()> { +async fn stage_zig_tree( + download_path: &Path, + mut staging: tempfile::TempDir, +) -> Result { for strip in [1_usize, 0] { if strip == 0 { - super::common::clear_dir_contents(staging)?; + super::common::clear_dir_contents(staging.path())?; } - extract_tar_xz(download_path, staging, strip).await?; - if fs::symlink_metadata(staging.join("zig")).is_ok_and(|meta| meta.file_type().is_file()) { + staging = super::common::extract_tar_xz_staged(download_path, staging, strip).await?; + if fs::symlink_metadata(staging.path().join("zig")) + .is_ok_and(|meta| meta.file_type().is_file()) + { break; } if strip == 0 { anyhow::bail!("Installed Zig archive but found no `zig` binary inside"); } } - let binary = staging.join("zig"); + let binary = staging.path().join("zig"); make_staged_executable(&binary)?; - let bin_dir = staging.join("bin"); + let bin_dir = staging.path().join("bin"); fs::create_dir_all(&bin_dir)?; fs::rename(&binary, bin_dir.join("zig")).context("Failed to stage Zig binary into bin dir")?; - Ok(()) + Ok(staging) } /// Ensure a staged binary is executable (archives may drop modes). @@ -717,5 +722,29 @@ mod tests { fixture.corrupt_identity("0.15.0"); assert!(manager.use_version("0.15.0").is_err()); fixture.assert_previous(); + + // Flat archive (no top-level directory) exercises strip=0 fallback & clear_dir_contents. + let mut flat_tar = Vec::new(); + { + let mut builder = tar::Builder::new(&mut flat_tar); + let payload = b"flat zig binary"; + let mut header = tar::Header::new_gnu(); + header.set_size(payload.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + builder + .append_data(&mut header, "zig", &payload[..]) + .expect("append flat zig"); + builder.finish().expect("finish flat tar"); + } + let mut flat_xz = Vec::new(); + lzma_rs::xz_compress(&mut flat_tar.as_slice(), &mut flat_xz).expect("compress flat xz"); + let flat_path = fixture.versions.join("flat.tar.xz"); + fs::write(&flat_path, &flat_xz).expect("write flat archive"); + let flat_staging = tempfile::tempdir_in(&fixture.versions).expect("flat staging"); + let staged = stage_zig_tree(&flat_path, flat_staging) + .await + .expect("flat archive must stage via strip=0 fallback"); + assert!(staged.path().join("bin/zig").is_file()); } }