diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e76f8e9d..5059cfad4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1006,6 +1006,13 @@ jobs: --features extended-formats --test sevenz_sfx_tests --no-fail-fast --no-tests fail --retries 0 + - name: Run public archive 7z path regressions + shell: bash + run: >- + vx cargo nextest run --locked -p vx-runtime-archive + --features extended-formats --test sevenz_path_tests + --no-fail-fast --no-tests fail --retries 0 + # ============================================================================ # Stage 5: Cross-compilation (PR only, skip on main since release builds cover it) # ============================================================================ diff --git a/crates/vx-runtime-archive/src/lib.rs b/crates/vx-runtime-archive/src/lib.rs index ca164ad1c..e5fdcd846 100644 --- a/crates/vx-runtime-archive/src/lib.rs +++ b/crates/vx-runtime-archive/src/lib.rs @@ -397,8 +397,16 @@ impl ArchiveExtractor { #[cfg(feature = "extended-formats")] fn extract_7z(&self, archive: &Path, dest: &Path) -> Result<()> { - sevenz_rust::decompress_file(archive, dest) - .map_err(|e| anyhow!("Failed to extract 7z archive: {}", e))?; + // The upstream default extractor joins untrusted entry names directly + // onto dest (RUSTSEC-2026-0245). Validate before any entry is written. + let file = std::fs::File::open(archive)?; + sevenz_rust::decompress_with_extract_fn(file, dest, |entry, reader, _| { + let path = + safe_sevenz_entry_path(dest, entry.name()).map_err(sevenz_rust::Error::io)?; + sevenz_rust::default_entry_extract_fn(entry, reader, &path)?; + Ok(true) + }) + .map_err(|e| anyhow!("Failed to extract 7z archive: {}", e))?; Ok(()) } @@ -426,6 +434,42 @@ impl Default for ArchiveExtractor { } } +#[cfg(feature = "extended-formats")] +fn safe_sevenz_entry_path(root: &Path, name: &str) -> std::io::Result { + use std::path::Component; + + // Recognize Windows separators and drive prefixes on every host platform. + let normalized = name.replace('\\', "/"); + let relative = Path::new(&normalized); + let mut has_normal_component = false; + let invalid_component = relative.components().any(|part| match part { + Component::Normal(value) => { + has_normal_component = true; + // Win32 may trim trailing dots/spaces and reinterpret a seemingly + // normal component such as ".. ". Reject these on every platform. + value.to_string_lossy().ends_with(['.', ' ']) + } + Component::CurDir => false, + _ => true, + }); + if normalized.is_empty() + || normalized.contains([':', '\0']) + || !has_normal_component + || invalid_component + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Unsafe path in 7z archive", + )); + } + let path = root.join(relative); + // Reuse the existing symlink/reparse-point guard before the default + // extractor can open a file or create a directory through an alias. + // This is not atomic against concurrent filesystem link replacement. + ensure_zip_output_path(root, &path)?; + Ok(path) +} + /// Never follow an existing link while creating an archive entry. fn ensure_zip_output_path(root: &Path, path: &Path) -> std::io::Result<()> { use std::path::Component; diff --git a/crates/vx-runtime-archive/tests/sevenz_path_tests.rs b/crates/vx-runtime-archive/tests/sevenz_path_tests.rs new file mode 100644 index 000000000..6656420d8 --- /dev/null +++ b/crates/vx-runtime-archive/tests/sevenz_path_tests.rs @@ -0,0 +1,154 @@ +//! Public archive API regression coverage for untrusted 7z entry names. + +#![cfg(feature = "extended-formats")] + +use std::io::Cursor; +use std::path::Path; + +use rstest::rstest; +use sevenz_rust::{SevenZArchiveEntry, SevenZWriter}; +use tempfile::tempdir; + +use vx_runtime_archive::ArchiveExtractor; + +const CONTENT: &[u8] = b"archive fixture"; + +fn write_archive(path: &Path, name: &str) { + let mut writer = SevenZWriter::new(Cursor::new(Vec::new())).unwrap(); + let mut entry = SevenZArchiveEntry::new(); + entry.name = name.into(); + entry.has_stream = true; + writer + .push_archive_entry(entry, Some(Cursor::new(CONTENT))) + .unwrap(); + std::fs::write(path, writer.finish().unwrap().into_inner()).unwrap(); +} + +#[rstest] +#[case("runtime/bin/program")] +#[case("runtime\\bin\\program")] +#[case("./runtime/bin/program")] +fn test_sevenz_extracts_nested_entries(#[case] name: &str) { + let temp = tempdir().unwrap(); + let archive = temp.path().join("runtime.7z"); + let dest = temp.path().join("output"); + write_archive(&archive, name); + + ArchiveExtractor::new().extract(&archive, &dest).unwrap(); + + assert_eq!( + std::fs::read(dest.join("runtime/bin/program")).unwrap(), + CONTENT + ); +} + +#[rstest] +#[case("../escaped")] +#[case("..\\escaped")] +#[case("nested/../../escaped")] +#[case("nested\\..\\..\\escaped")] +#[case(".. /escaped")] +#[case(".../escaped")] +#[case("nested/.. /../escaped")] +fn test_sevenz_rejects_parent_traversal(#[case] name: &str) { + let temp = tempdir().unwrap(); + let archive = temp.path().join("unsafe.7z"); + let dest = temp.path().join("output"); + write_archive(&archive, name); + + let result = ArchiveExtractor::new().extract(&archive, &dest); + + assert!(!temp.path().join("escaped").exists()); + assert!(result.is_err()); + assert!(std::fs::read_dir(dest).unwrap().next().is_none()); +} + +#[rstest] +#[case("")] +#[case(".")] +#[case("nested. /program")] +#[case("nested./program")] +#[case("program.")] +#[case("program ")] +#[case("program:stream")] +#[case(r"\\")] +#[case(r"\\?\UNC\")] +fn test_sevenz_rejects_ambiguous_windows_paths(#[case] name: &str) { + let temp = tempdir().unwrap(); + let archive = temp.path().join("unsafe.7z"); + let dest = temp.path().join("output"); + write_archive(&archive, name); + + let result = ArchiveExtractor::new().extract(&archive, &dest); + + assert!(result.is_err(), "{name:?}: accepted ambiguous entry path"); + assert!(std::fs::read_dir(dest).unwrap().next().is_none()); +} + +#[rstest] +fn test_sevenz_rejects_absolute_paths() { + let temp = tempdir().unwrap(); + let escaped = temp.path().join("escaped"); + let absolute = escaped.to_string_lossy().into_owned(); + let windows_absolute = if cfg!(windows) { + absolute.clone() + } else { + format!("C:{absolute}") + }; + let device_absolute = format!("\\\\?\\{}", windows_absolute.replace('/', "\\")); + let unc_absolute = if cfg!(windows) { + // Use the local extended-length path, never contact a UNC server. + device_absolute.clone() + } else { + format!("/{absolute}") + }; + // Even a broken implementation can only target this disposable directory. + for (index, name) in [ + absolute, + windows_absolute.replace('\\', "/"), + windows_absolute.replace('/', "\\"), + device_absolute, + unc_absolute, + ] + .into_iter() + .enumerate() + { + let archive = temp.path().join(format!("unsafe-{index}.7z")); + let dest = temp.path().join(format!("output-{index}")); + write_archive(&archive, &name); + + let result = ArchiveExtractor::new().extract(&archive, &dest); + + assert!(!escaped.exists(), "{name}: wrote outside extraction root"); + assert!(result.is_err(), "{name}: accepted absolute entry path"); + assert!(std::fs::read_dir(dest).unwrap().next().is_none()); + } +} + +#[cfg(unix)] +#[rstest] +#[case(false)] +#[case(true)] +fn test_sevenz_rejects_existing_symlink_paths(#[case] root_link: bool) { + let temp = tempdir().unwrap(); + let archive = temp.path().join("unsafe.7z"); + let dest = temp.path().join("output"); + let outside = temp.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let escaped = outside.join("escaped"); + std::fs::write(&escaped, b"original").unwrap(); + let name = if root_link { + std::os::unix::fs::symlink(&outside, &dest).unwrap(); + "escaped" + } else { + std::fs::create_dir_all(&dest).unwrap(); + std::os::unix::fs::symlink(&outside, dest.join("alias")).unwrap(); + "alias/escaped" + }; + write_archive(&archive, name); + + let result = ArchiveExtractor::new().extract(&archive, &dest); + + assert_eq!(std::fs::read(escaped).unwrap(), b"original"); + assert!(result.is_err()); +} diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml index 9eed4f75e..b0a4f8232 100644 --- a/crates/workspace-hack/Cargo.toml +++ b/crates/workspace-hack/Cargo.toml @@ -98,7 +98,7 @@ serde = { version = "1", features = ["alloc", "derive", "rc"] } serde_core = { version = "1", features = ["alloc", "rc"] } serde_json = { version = "1", features = ["alloc", "arbitrary_precision", "preserve_order", "raw_value"] } smallvec = { version = "1", default-features = false, features = ["const_generics"] } -syn-7b89eefb6aaa9bf3 = { package = "syn", version = "3", features = ["full"] } +syn-7b89eefb6aaa9bf3 = { package = "syn", version = "3", features = ["full", "visit-mut"] } syn-f595c2ba2a3f28df = { package = "syn", version = "2", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } time = { version = "0.3", default-features = false, features = ["formatting", "macros", "parsing"] } time-macros = { version = "0.2", default-features = false, features = ["formatting", "parsing"] } diff --git a/scripts/tests/test_installer_extended_formats_workflow.py b/scripts/tests/test_installer_extended_formats_workflow.py index e13287a80..c2f94d3db 100644 --- a/scripts/tests/test_installer_extended_formats_workflow.py +++ b/scripts/tests/test_installer_extended_formats_workflow.py @@ -52,6 +52,18 @@ def test_contract_and_success_gate_are_wired_into_ci(self) -> None: self.assertIn(f" - {INSTALLER_JOB}\n", job_body("ci-success")) self.assertIn("if: always()", job_body("ci-success")) + def test_public_archive_regressions_are_feature_enabled_and_required(self) -> None: + job = job_body(INSTALLER_JOB) + step = job.split(" - name: Run public archive 7z path regressions\n", 1)[1] + command = " ".join(step.split(" run: >-\n", 1)[1].split()) + self.assertTrue(command.startswith("vx cargo nextest run --locked -p vx-runtime-archive ")) + for required in ("--features extended-formats", "--test sevenz_path_tests", + "--no-fail-fast", "--no-tests fail", "--retries 0"): + self.assertIn(required, command) + for forbidden in ("--no-run", "--target", "--workspace", "|| true", + "continue-on-error", "--run-ignored"): + self.assertNotIn(forbidden, command) + def test_whole_workspace_coverage_is_preserved(self) -> None: coverage = job_body("coverage") self.assertIn("github.event.inputs.force_full_ci == 'true'", coverage) diff --git a/tests/e2e_uninstall_where_tests.rs b/tests/e2e_uninstall_where_tests.rs index f3f4b1f04..4592b5e04 100644 --- a/tests/e2e_uninstall_where_tests.rs +++ b/tests/e2e_uninstall_where_tests.rs @@ -526,16 +526,37 @@ fn test_imagemagick_install_platform_handling() { fn test_where_alias_imagemagick() { let env = E2ETestEnv::new(); - // "imagemagick" is an alias for "magick" - let output_alias = env.run(&["where", "imagemagick"]); - let output_primary = env.run(&["where", "magick"]); - - // Both should give same result (or both fail) - assert_eq!( - output_alias.status.success(), - output_primary.status.success(), - "Alias 'imagemagick' should behave same as 'magick'" - ); + // Use a fixed vx-managed install: system ImageMagick can be changed by + // parallel install/uninstall tests even though each test has its own VX_HOME. + let version = "0.0.0"; + let install_dir = env.home_path().join("store").join("magick").join(version); + std::fs::create_dir_all(&install_dir).unwrap(); + let executable = install_dir.join(if cfg!(windows) { + "magick.exe" + } else { + "magick" + }); + // `where` resolves the path without executing the fixture. + std::fs::write(&executable, b"").unwrap(); + + for runtime in ["imagemagick", "magick"] { + // An explicit version avoids project configuration and system fallback. + let request = format!("{runtime}@{version}"); + let stdout = env.run_success(&["--output-format", "json", "where", &request]); + let result: serde_json::Value = serde_json::from_str(&stdout) + .unwrap_or_else(|error| panic!("Invalid JSON for {request}: {error}\n{stdout}")); + assert_eq!( + result, + serde_json::json!({ + "tool": request, + "version": version, + "path": executable, + "source": "vx", + "all_paths": [], + }), + "Alias and canonical runtime must resolve to the same managed fixture" + ); + } } #[test]