From edf37a510e311bb3f97d6ae7b24475f9b6fa7f6d Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Mon, 23 Nov 2026 13:22:44 +0900 Subject: [PATCH 1/5] fix(pm): verify unpinned package-manager downloads against registry integrity Without a `packageManager` hash, npm, pnpm 11 and earlier, and Yarn were installed without any integrity check, while bun and pnpm 12+ already verified their platform tarball against the registry `dist.integrity`. Corepack used to verify these downloads before it was removed. An unpinned download now fetches the version metadata and verifies the tarball against `dist.integrity` before extraction. A pinned download keeps using the pin and does not fetch metadata. A registry that omits `dist.integrity` now fails the install with `MissingRegistryIntegrity` for every manager, including the bun and pnpm 12+ platform tarballs. --- crates/vp_error/src/lib.rs | 12 +- crates/vp_pm_cli/src/package_manager.rs | 196 +++++++++++++----- crates/vp_pm_cli/src/request.rs | 10 + .../tests/package_manager_pin_verification.rs | 34 ++- 4 files changed, 193 insertions(+), 59 deletions(-) diff --git a/crates/vp_error/src/lib.rs b/crates/vp_error/src/lib.rs index ac1662ed7e..883007a12b 100644 --- a/crates/vp_error/src/lib.rs +++ b/crates/vp_error/src/lib.rs @@ -95,6 +95,11 @@ pub enum Error { #[error(transparent)] PackageManagerHashMismatch(#[from] Box), + #[error( + "Registry metadata for {package}@{version} has no `dist.integrity`, so Vite+ cannot verify the download" + )] + MissingRegistryIntegrity { package: Str, version: Str }, + #[error("Invalid hash format: {0}")] InvalidHashFormat(Str), @@ -131,7 +136,12 @@ impl Error { /// hides the cause behind a later, unrelated failure. #[must_use] pub const fn is_integrity_failure(&self) -> bool { - matches!(self, Self::PackageManagerHashMismatch(_) | Self::HashMismatch { .. }) + matches!( + self, + Self::PackageManagerHashMismatch(_) + | Self::HashMismatch { .. } + | Self::MissingRegistryIntegrity { .. } + ) } } diff --git a/crates/vp_pm_cli/src/package_manager.rs b/crates/vp_pm_cli/src/package_manager.rs index 59b1b03fc4..0d8f4d08d4 100644 --- a/crates/vp_pm_cli/src/package_manager.rs +++ b/crates/vp_pm_cli/src/package_manager.rs @@ -1839,6 +1839,16 @@ async fn download_package_manager_inner( return Ok((install_dir, package_name, version)); } + // A pin covers the executed files and takes precedence. Without one, the + // registry's integrity still rejects a corrupted or swapped tarball. + let registry_integrity = match expected_hash { + Some(_) => None, + None => Some( + fetch_registry_integrity(package_manager_type, &package_name, &version, npm_config) + .await?, + ), + }; + // Stage the download in a temp directory beside the version directory, not // inside it. A reader that scans the version directory for key subdirectories // then never sees the half-written staging copy. Only create the manager @@ -1860,6 +1870,7 @@ async fn download_package_manager_inner( &target_dir_tmp, archive_file.as_deref(), expected_hash, + registry_integrity.as_deref(), Some(&download_message), npm_config, ) @@ -1875,8 +1886,10 @@ async fn download_package_manager_inner( version: version.clone(), url: tgz_url.into(), } - } else { + } else if expected_hash.is_some() { name_hashed_artifact(err, package_manager_type, &version) + } else { + err } })?; @@ -2024,6 +2037,7 @@ async fn download_bun_package_manager( verify_dir.path(), None, Some(expected_hash), + None, Some(&verify_message), npm_config, ) @@ -2033,8 +2047,13 @@ async fn download_bun_package_manager( // The declared hash never covers the platform tarball, so verify it // against the registry's `dist.integrity` for the platform package. - let platform_hash = - fetch_platform_integrity("bun", &platform_package_name, version, npm_config).await?; + let platform_hash = fetch_registry_integrity( + PackageManagerType::Bun, + &platform_package_name, + version, + npm_config, + ) + .await?; // Stage the download in a temp directory beside the version directory, not // inside it, so a reader scanning key subdirectories never sees the staging @@ -2054,7 +2073,8 @@ async fn download_bun_package_manager( &platform_tgz_url, &target_dir_tmp, None, - platform_hash.as_deref(), + None, + Some(&platform_hash), Some(&download_message), npm_config, ) @@ -2155,16 +2175,13 @@ struct RegistryDist { integrity: Option, } -/// Fetch the registry `dist.integrity` (SRI) of a platform package version, -/// so a platform tarball that no declared hash covers can still be verified. -/// Returns `None` when the registry omits the field. -async fn fetch_platform_integrity( - bin_name: &str, - platform_package_name: &str, +async fn fetch_registry_integrity( + package_manager_type: PackageManagerType, + package_name: &str, version: &Str, npm_config: &NpmConfig, -) -> Result, Error> { - let metadata_url = npm_config.package_version_url(platform_package_name, version); +) -> Result { + let metadata_url = npm_config.package_version_url(package_name, version); let metadata: RegistryVersionMetadata = HttpClient::with_npm_config(3, 500, npm_config.clone()) .get_json(&metadata_url) .await @@ -2174,7 +2191,7 @@ async fn fetch_platform_integrity( && status == reqwest::StatusCode::NOT_FOUND { Error::PackageManagerVersionNotFound { - name: bin_name.into(), + name: package_manager_type.to_string().into(), version: version.clone(), url: metadata_url.as_str().into(), } @@ -2183,12 +2200,16 @@ async fn fetch_platform_integrity( } })?; // SRI allows several space-separated hashes; npm registries serve one. - Ok(metadata + metadata .dist .integrity .as_deref() .and_then(|sri| sri.split_whitespace().next()) - .map(Str::from)) + .map(Str::from) + .ok_or_else(|| Error::MissingRegistryIntegrity { + package: package_name.into(), + version: version.clone(), + }) } /// Download pnpm >= 12 (native binary) via its platform-specific npm package. @@ -2235,6 +2256,7 @@ async fn download_pnpm_native_package_manager( verify_dir.path(), None, Some(expected_hash), + None, Some(&verify_message), npm_config, ) @@ -2244,8 +2266,13 @@ async fn download_pnpm_native_package_manager( // The declared hash never covers the platform tarball, so verify it // against the registry's `dist.integrity` for the platform package. - let platform_hash = - fetch_platform_integrity("pnpm", platform_package_name, version, npm_config).await?; + let platform_hash = fetch_registry_integrity( + PackageManagerType::Pnpm, + platform_package_name, + version, + npm_config, + ) + .await?; // Stage the download in a temp directory beside the version directory, not // inside it, so a reader scanning key subdirectories never sees the staging @@ -2265,7 +2292,8 @@ async fn download_pnpm_native_package_manager( &platform_tgz_url, &target_dir_tmp, None, - platform_hash.as_deref(), + None, + Some(&platform_hash), Some(&download_message), npm_config, ) @@ -2647,6 +2675,39 @@ mod tests { }); } + fn sri(bytes: &[u8]) -> String { + format!("sha512-{}", base64_simd::STANDARD.encode_to_string(sha2::Sha512::digest(bytes))) + } + + fn mount_package<'a>( + server: &'a httpmock::MockServer, + package: &str, + version: &str, + tgz: Vec, + ) -> httpmock::Mock<'a> { + let integrity = sri(&tgz); + mount_package_with_integrity(server, package, version, tgz, Some(&integrity)) + } + + fn mount_package_with_integrity<'a>( + server: &'a httpmock::MockServer, + package: &str, + version: &str, + tgz: Vec, + integrity: Option<&str>, + ) -> httpmock::Mock<'a> { + use httpmock::prelude::*; + server.mock(|when, then| { + when.method(GET).path(format!("/{package}/{version}")); + then.status(200).json_body(serde_json::json!({"dist": {"integrity": integrity}})); + }); + let basename = package.rsplit('/').next().unwrap(); + server.mock(|when, then| { + when.method(GET).path(format!("/{package}/-/{basename}-{version}.tgz")); + then.status(200).body(tgz); + }) + } + /// A JavaScript CLI that prints `version`, standing in for a package manager entry point. fn version_cli(version: &str) -> Vec { format!("console.log('{version}');\n").into_bytes() @@ -2858,13 +2919,19 @@ mod tests { ) .unwrap(); let yarn_js = b"#!/usr/bin/env node\nconsole.log('mock yarn');\n"; + let tgz = create_yarn_package_tgz(yarn_js, None); + let integrity = sri(&tgz); + let metadata = server.mock(|when, then| { + when.method(GET) + .path("/@yarnpkg/cli-dist/4.17.1") + .header("authorization", "Bearer SECRET"); + then.status(200).json_body(serde_json::json!({"dist": {"integrity": integrity}})); + }); let tarball = server.mock(|when, then| { when.method(GET) .path("/@yarnpkg/cli-dist/-/cli-dist-4.17.1.tgz") .header("authorization", "Bearer SECRET"); - then.status(200) - .header("content-type", "application/octet-stream") - .body(create_yarn_package_tgz(yarn_js, None)); + then.status(200).header("content-type", "application/octet-stream").body(tgz); }); let vp_home = create_temp_dir(); @@ -2876,6 +2943,7 @@ mod tests { assert_eq!(package_name, "@yarnpkg/cli-dist"); assert_eq!(version, "4.17.1"); assert!(install_dir.join("bin/yarn").as_path().is_file()); + metadata.assert_hits(1); tarball.assert_hits(1); }) .await; @@ -3807,10 +3875,10 @@ mod tests { use httpmock::prelude::*; let server = MockServer::start(); - for (spec, tarball_path, tarball, entry, shims) in [ + for (spec, package, tarball, entry, shims) in [ ( "pnpm@8.15.0", - "/pnpm/-/pnpm-8.15.0.tgz", + "pnpm", create_tgz(&[ ("package/bin/pnpm.cjs", &version_cli("8.15.0")), ("package/bin/pnpx.cjs", &version_cli("8.15.0")), @@ -3820,24 +3888,21 @@ mod tests { ), ( "yarn@1.22.22", - "/yarn/-/yarn-1.22.22.tgz", + "yarn", create_tgz(&[("package/bin/yarn.js", &version_cli("1.22.22"))]), "yarn.js", ["yarn", "yarnpkg"], ), ( "yarn@4.0.0", - "/@yarnpkg/cli-dist/-/cli-dist-4.0.0.tgz", + "@yarnpkg/cli-dist", create_yarn_package_tgz(&version_cli("4.0.0"), None), "yarn.js", ["yarn", "yarnpkg"], ), ] { - server.mock(|when, then| { - when.method(GET).path(tarball_path); - then.status(200).body(tarball); - }); let (name, version) = spec.split_once('@').unwrap(); + mount_package(&server, package, version, tarball); let temp_dir = create_temp_dir(); let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap(); create_package_json(&temp_dir_path, &format!(r#"{{"packageManager": "{spec}"}}"#)); @@ -4510,7 +4575,7 @@ mod tests { }; assert_eq!(name, "yarn"); assert_eq!(version, "10000000000.0.0"); - assert!(url.ends_with("/@yarnpkg/cli-dist/-/cli-dist-10000000000.0.0.tgz"), "{url}"); + assert!(url.ends_with("/@yarnpkg/cli-dist/10000000000.0.0"), "{url}"); } #[tokio::test] @@ -4627,15 +4692,63 @@ mod tests { assert!(matches!(result, Err(Error::InvalidArgument(_)))); } + #[tokio::test] + async fn unpinned_download_verifies_registry_integrity() { + let pnpm_tgz = create_tgz(&[("package/bin/pnpm.cjs", &version_cli("10.0.0"))]); + let yarn_tgz = create_yarn_package_tgz(&version_cli("4.9.2"), None); + let other = sri(b"other"); + let cases = [ + (PackageManagerType::Pnpm, "10.0.0", "pnpm", &pnpm_tgz, Some(other.as_str())), + (PackageManagerType::Pnpm, "10.0.0", "pnpm", &pnpm_tgz, None), + ( + PackageManagerType::Yarn, + "4.9.2", + "@yarnpkg/cli-dist", + &yarn_tgz, + Some(other.as_str()), + ), + ]; + for (kind, version, package, tgz, integrity) in cases { + let server = httpmock::MockServer::start(); + let tarball = + mount_package_with_integrity(&server, package, version, tgz.clone(), integrity); + let vp_home = create_temp_dir(); + let result = EnvConfig::with_vars_async( + [ + (env_vars::VP_HOME, vp_home.path().as_os_str()), + (env_vars::NPM_CONFIG_REGISTRY, std::ffi::OsStr::new(&server.base_url())), + ], + |_| async { download_package_manager(kind, version, None).await }, + ) + .await; + + let case = format!("{kind}@{version} integrity={integrity:?}"); + let error = result.expect_err(&case); + assert!(error.is_integrity_failure(), "{case}: {error:?}"); + if integrity.is_none() { + assert!(matches!(error, Error::MissingRegistryIntegrity { .. }), "{case}"); + tarball.assert_hits(0); + } else { + assert!(matches!(error, Error::HashMismatch { .. }), "{case}: {error:?}"); + } + assert!( + !vp_home.path().join(format!("package_manager/{kind}/{version}")).exists(), + "{case}: a failed download left an install" + ); + } + } + #[tokio::test] async fn test_download_package_manager() { use httpmock::prelude::*; let server = MockServer::start(); - let tarball = server.mock(|when, then| { - when.method(GET).path("/@yarnpkg/cli-dist/-/cli-dist-4.9.2.tgz"); - then.status(200).body(create_yarn_package_tgz(&version_cli("4.9.2"), None)); - }); + let tarball = mount_package( + &server, + "@yarnpkg/cli-dist", + "4.9.2", + create_yarn_package_tgz(&version_cli("4.9.2"), None), + ); let vp_home = create_temp_dir(); EnvConfig::with_vars_async( [ @@ -4688,21 +4801,13 @@ mod tests { ] { let vp_home = create_temp_dir(); let server = MockServer::start(); - server.mock(|when, then| { - when.method(GET).path(format!("/{package}/{version}")); - then.status(200).json_body(serde_json::json!({"dist": {}})); - }); - let basename = package.rsplit('/').next().unwrap(); let tarball = create_tgz( &entries .iter() .map(|path| (*path, b"mock executable".as_slice())) .collect::>(), ); - server.mock(|when, then| { - when.method(GET).path(format!("/{package}/-/{basename}-{version}.tgz")); - then.status(200).body(tarball); - }); + mount_package(&server, &package, version, tarball); EnvConfig::with_vars_async( [ @@ -6102,10 +6207,7 @@ mod tests { &[("package/bin/pnpm", link.as_str())], ); let registry = MockServer::start(); - registry.mock(move |when, then| { - when.method(GET).path("/pnpm/-/pnpm-10.99.0.tgz"); - then.status(200).body(tgz); - }); + mount_package(®istry, "pnpm", "10.99.0", tgz); let (installed, _, _) = EnvConfig::with_vars_async( [ (env_vars::VP_HOME, vp_home.path().as_os_str()), diff --git a/crates/vp_pm_cli/src/request.rs b/crates/vp_pm_cli/src/request.rs index 434383762e..52672661c7 100644 --- a/crates/vp_pm_cli/src/request.rs +++ b/crates/vp_pm_cli/src/request.rs @@ -503,6 +503,7 @@ pub(crate) async fn download_and_extract_tgz_with_hash_and_config( target_dir: impl AsRef, archive_file: Option<&Path>, expected_hash: Option<&str>, + tarball_hash: Option<&str>, message: Option<&str>, npm_config: &NpmConfig, ) -> Result<(), Error> { @@ -533,6 +534,7 @@ pub(crate) async fn download_and_extract_tgz_with_hash_and_config( &target_dir, archive_file, expected_hash, + tarball_hash, message, npm_config, ) @@ -557,6 +559,7 @@ async fn download_and_extract_tgz_once( target_dir: &Path, archive_file: Option<&Path>, expected_hash: Option<&str>, + tarball_hash: Option<&str>, message: Option<&str>, npm_config: &NpmConfig, ) -> Result<(), Error> { @@ -574,6 +577,10 @@ async fn download_and_extract_tgz_once( let client = HttpClient::with_npm_config(0, 0, npm_config.clone()); client.download_file(url, &tgz_file, message).await?; + if let Some(tarball_hash) = tarball_hash { + verify_file_hash(&tgz_file, tarball_hash).await?; + } + if let Some(archive_file) = archive_file { // The hash covers one entry. The rest of the archive is unauthenticated, // so vp writes only that entry. @@ -1278,6 +1285,7 @@ mod tests { None, None, None, + None, &NpmConfig { values: Default::default() }, ) .await; @@ -1318,6 +1326,7 @@ mod tests { None, None, None, + None, &NpmConfig { values: Default::default() }, ) .await; @@ -1353,6 +1362,7 @@ mod tests { None, Some(wrong_hash), None, + None, &NpmConfig { values: Default::default() }, ) .await; diff --git a/crates/vp_pm_cli/tests/package_manager_pin_verification.rs b/crates/vp_pm_cli/tests/package_manager_pin_verification.rs index 53a9d43b53..a26a575c38 100644 --- a/crates/vp_pm_cli/tests/package_manager_pin_verification.rs +++ b/crates/vp_pm_cli/tests/package_manager_pin_verification.rs @@ -110,12 +110,14 @@ fn pin(tgz: &[u8]) -> String { /// mocks stay active without their handles, like the runner's other cases. fn mount_pnpm_registry(server: &MockServer, tgz: Vec) { let tarball_url = format!("{}/pnpm/-/pnpm-{PINNED_PNPM_VERSION}.tgz", server.base_url()); + let integrity = + format!("sha512-{}", base64_simd::STANDARD.encode_to_string(Sha512::digest(&tgz))); server.mock(|when, then| { when.method(GET).path(format!("/pnpm/{PINNED_PNPM_VERSION}")); then.status(200).json_body(serde_json::json!({ "name": "pnpm", "version": PINNED_PNPM_VERSION, - "dist": { "tarball": tarball_url }, + "dist": { "tarball": tarball_url, "integrity": integrity }, })); }); server.mock(|when, then| { @@ -347,16 +349,26 @@ async fn archive_entries_cannot_escape_the_install_directory() { for (vector, archive) in [("traversal", traversal), ("symlink", through_symlink)] { let server = MockServer::start(); mount_pnpm_registry(&server, archive); - let ((escaped, extraction), _vp_home) = in_project_env(&server.base_url(), || async { - let extraction = - download_package_manager(PackageManagerType::Pnpm, PINNED_PNPM_VERSION, None).await; - // The managed directory holding this version's installs. - let install = - package_manager_install_dir(PackageManagerType::Pnpm, PINNED_PNPM_VERSION, None); - let manager_dir = install.parent().unwrap().parent().unwrap(); - (manager_dir.join(escape_name).as_path().exists(), format!("{extraction:?}")) - }) - .await; + let ((escaped, integrity_failed, extraction), _vp_home) = + in_project_env(&server.base_url(), || async { + let extraction = + download_package_manager(PackageManagerType::Pnpm, PINNED_PNPM_VERSION, None) + .await; + // The managed directory holding this version's installs. + let install = package_manager_install_dir( + PackageManagerType::Pnpm, + PINNED_PNPM_VERSION, + None, + ); + let manager_dir = install.parent().unwrap().parent().unwrap(); + ( + manager_dir.join(escape_name).as_path().exists(), + matches!(&extraction, Err(error) if error.is_integrity_failure()), + format!("{extraction:?}"), + ) + }) + .await; + assert!(!integrity_failed, "the {vector} archive must reach extraction: {extraction}"); assert!( !escaped, "a {vector} entry wrote a file beside the version directory (extraction: {extraction})" From 2cd4596c69c08c649aaacb08ecdc705e892c51ea Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Mon, 23 Nov 2026 13:32:00 +0900 Subject: [PATCH 2/5] fix(pm): install unverified when the registry omits dist.integrity Match the existing bun and pnpm 12+ platform tarball behavior instead of failing the install, so a mirror without dist.integrity keeps working. --- crates/vp_error/src/lib.rs | 12 +-------- crates/vp_pm_cli/src/package_manager.rs | 35 +++++++++++-------------- 2 files changed, 16 insertions(+), 31 deletions(-) diff --git a/crates/vp_error/src/lib.rs b/crates/vp_error/src/lib.rs index 883007a12b..ac1662ed7e 100644 --- a/crates/vp_error/src/lib.rs +++ b/crates/vp_error/src/lib.rs @@ -95,11 +95,6 @@ pub enum Error { #[error(transparent)] PackageManagerHashMismatch(#[from] Box), - #[error( - "Registry metadata for {package}@{version} has no `dist.integrity`, so Vite+ cannot verify the download" - )] - MissingRegistryIntegrity { package: Str, version: Str }, - #[error("Invalid hash format: {0}")] InvalidHashFormat(Str), @@ -136,12 +131,7 @@ impl Error { /// hides the cause behind a later, unrelated failure. #[must_use] pub const fn is_integrity_failure(&self) -> bool { - matches!( - self, - Self::PackageManagerHashMismatch(_) - | Self::HashMismatch { .. } - | Self::MissingRegistryIntegrity { .. } - ) + matches!(self, Self::PackageManagerHashMismatch(_) | Self::HashMismatch { .. }) } } diff --git a/crates/vp_pm_cli/src/package_manager.rs b/crates/vp_pm_cli/src/package_manager.rs index 0d8f4d08d4..bb5f08bf11 100644 --- a/crates/vp_pm_cli/src/package_manager.rs +++ b/crates/vp_pm_cli/src/package_manager.rs @@ -1843,10 +1843,10 @@ async fn download_package_manager_inner( // registry's integrity still rejects a corrupted or swapped tarball. let registry_integrity = match expected_hash { Some(_) => None, - None => Some( + None => { fetch_registry_integrity(package_manager_type, &package_name, &version, npm_config) - .await?, - ), + .await? + } }; // Stage the download in a temp directory beside the version directory, not @@ -2074,7 +2074,7 @@ async fn download_bun_package_manager( &target_dir_tmp, None, None, - Some(&platform_hash), + platform_hash.as_deref(), Some(&download_message), npm_config, ) @@ -2180,7 +2180,7 @@ async fn fetch_registry_integrity( package_name: &str, version: &Str, npm_config: &NpmConfig, -) -> Result { +) -> Result, Error> { let metadata_url = npm_config.package_version_url(package_name, version); let metadata: RegistryVersionMetadata = HttpClient::with_npm_config(3, 500, npm_config.clone()) .get_json(&metadata_url) @@ -2200,16 +2200,12 @@ async fn fetch_registry_integrity( } })?; // SRI allows several space-separated hashes; npm registries serve one. - metadata + Ok(metadata .dist .integrity .as_deref() .and_then(|sri| sri.split_whitespace().next()) - .map(Str::from) - .ok_or_else(|| Error::MissingRegistryIntegrity { - package: package_name.into(), - version: version.clone(), - }) + .map(Str::from)) } /// Download pnpm >= 12 (native binary) via its platform-specific npm package. @@ -2293,7 +2289,7 @@ async fn download_pnpm_native_package_manager( &target_dir_tmp, None, None, - Some(&platform_hash), + platform_hash.as_deref(), Some(&download_message), npm_config, ) @@ -4710,8 +4706,7 @@ mod tests { ]; for (kind, version, package, tgz, integrity) in cases { let server = httpmock::MockServer::start(); - let tarball = - mount_package_with_integrity(&server, package, version, tgz.clone(), integrity); + mount_package_with_integrity(&server, package, version, tgz.clone(), integrity); let vp_home = create_temp_dir(); let result = EnvConfig::with_vars_async( [ @@ -4723,14 +4718,14 @@ mod tests { .await; let case = format!("{kind}@{version} integrity={integrity:?}"); - let error = result.expect_err(&case); - assert!(error.is_integrity_failure(), "{case}: {error:?}"); if integrity.is_none() { - assert!(matches!(error, Error::MissingRegistryIntegrity { .. }), "{case}"); - tarball.assert_hits(0); - } else { - assert!(matches!(error, Error::HashMismatch { .. }), "{case}: {error:?}"); + // Like the bun and pnpm 12+ platform tarballs, a registry without + // `dist.integrity` installs unverified. + result.unwrap_or_else(|error| panic!("{case}: {error}")); + continue; } + let error = result.expect_err(&case); + assert!(matches!(error, Error::HashMismatch { .. }), "{case}: {error:?}"); assert!( !vp_home.path().join(format!("package_manager/{kind}/{version}")).exists(), "{case}: a failed download left an install" From e4ef501ee81455091fe2b1de8f97c85f6f6afa0a Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Mon, 23 Nov 2026 13:47:17 +0900 Subject: [PATCH 3/5] test(pm): keep the temp-dir cleanup test reaching extraction The test served only the tarball, so the new metadata request returned 404 before the temp dir existed and the cleanup assertion passed vacuously. --- crates/vp_pm_cli/src/package_manager.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/vp_pm_cli/src/package_manager.rs b/crates/vp_pm_cli/src/package_manager.rs index bb5f08bf11..ce1f3de5d5 100644 --- a/crates/vp_pm_cli/src/package_manager.rs +++ b/crates/vp_pm_cli/src/package_manager.rs @@ -5919,12 +5919,8 @@ mod tests { let server = MockServer::start(); // A 200 body that is not a valid gzip: the download succeeds but // extraction fails, so the install errors out after the temp dir exists. - server.mock(|when, then| { - when.method(GET).path("/pnpm/-/pnpm-10.0.0.tgz"); - then.status(200) - .header("content-type", "application/octet-stream") - .body("this is not a valid gzip archive"); - }); + let tarball = + mount_package(&server, "pnpm", "10.0.0", b"this is not a valid gzip archive".to_vec()); // VP_HOME pins to the root, so installs land directly under it. let pnpm_dir = vp_home.path().join("package_manager").join("pnpm"); @@ -5937,6 +5933,7 @@ mod tests { let result = download_package_manager(PackageManagerType::Pnpm, "10.0.0", None).await; assert!(result.is_err(), "corrupt tarball should fail the install, got {result:?}"); + assert!(tarball.hits() > 0, "the install must fail at extraction: {result:?}"); // The per-install temp dir must be gone after the failure. let leftovers: Vec<_> = fs::read_dir(&pnpm_dir) From 75fc3cc5d800a8ebf08eb91ee3c331825ef3a966 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Mon, 23 Nov 2026 13:59:55 +0900 Subject: [PATCH 4/5] refactor(pm): reuse download helpers and drop redundant comments Use is_not_found for registry 404 mapping, name managers by PackageManagerType, and share the test sri and mount helpers. Remove doc and inline comments that restate the code. --- crates/vp_pm_cli/src/package_manager.rs | 101 +++++------------- crates/vp_pm_cli/src/request.rs | 14 --- .../tests/package_manager_pin_verification.rs | 1 - 3 files changed, 26 insertions(+), 90 deletions(-) diff --git a/crates/vp_pm_cli/src/package_manager.rs b/crates/vp_pm_cli/src/package_manager.rs index ce1f3de5d5..1174384bd6 100644 --- a/crates/vp_pm_cli/src/package_manager.rs +++ b/crates/vp_pm_cli/src/package_manager.rs @@ -1877,10 +1877,7 @@ async fn download_package_manager_inner( .await .map_err(|err| { // status 404 means the version is not found, convert to PackageManagerVersionNotFound error - if let Error::Reqwest(e) = &err - && let Some(status) = e.status() - && status == reqwest::StatusCode::NOT_FOUND - { + if is_not_found(&err) { Error::PackageManagerVersionNotFound { name: package_manager_type.to_string().into(), version: version.clone(), @@ -2080,12 +2077,9 @@ async fn download_bun_package_manager( ) .await .map_err(|err| { - if let Error::Reqwest(e) = &err - && let Some(status) = e.status() - && status == reqwest::StatusCode::NOT_FOUND - { + if is_not_found(&err) { Error::PackageManagerVersionNotFound { - name: "bun".into(), + name: PackageManagerType::Bun.to_string().into(), version: version.clone(), url: platform_tgz_url.into(), } @@ -2186,10 +2180,7 @@ async fn fetch_registry_integrity( .get_json(&metadata_url) .await .map_err(|err| { - if let Error::Reqwest(e) = &err - && let Some(status) = e.status() - && status == reqwest::StatusCode::NOT_FOUND - { + if is_not_found(&err) { Error::PackageManagerVersionNotFound { name: package_manager_type.to_string().into(), version: version.clone(), @@ -2295,12 +2286,9 @@ async fn download_pnpm_native_package_manager( ) .await .map_err(|err| { - if let Error::Reqwest(e) = &err - && let Some(status) = e.status() - && status == reqwest::StatusCode::NOT_FOUND - { + if is_not_found(&err) { Error::PackageManagerVersionNotFound { - name: "pnpm".into(), + name: PackageManagerType::Pnpm.to_string().into(), version: version.clone(), url: platform_tgz_url.into(), } @@ -2648,27 +2636,22 @@ mod tests { ) { use httpmock::prelude::*; let bin = package_manager_type.to_string(); - let (platform_package, prefix) = match package_manager_type { - PackageManagerType::Bun => (get_bun_platform_package_name().unwrap(), "@oven/"), - PackageManagerType::Pnpm => { - (get_pnpm_platform_package_name().unwrap().to_string(), "@pnpm/") - } + let platform_package = match package_manager_type { + PackageManagerType::Bun => get_bun_platform_package_name().unwrap(), + PackageManagerType::Pnpm => get_pnpm_platform_package_name().unwrap().to_string(), other => panic!("{other} is not a platform-binary manager"), }; - let basename = platform_package.strip_prefix(prefix).unwrap(); server.mock(|when, then| { when.method(GET).path(format!("/{bin}/-/{bin}-{version}.tgz")); then.status(200).body(main_tgz); }); - server.mock(|when, then| { - when.method(GET).path(format!("/{platform_package}/{version}")); - then.status(200) - .json_body(serde_json::json!({"dist": {"integrity": platform_integrity}})); - }); - server.mock(|when, then| { - when.method(GET).path(format!("/{platform_package}/-/{basename}-{version}.tgz")); - then.status(200).body(platform_tgz); - }); + mount_package_with_integrity( + server, + &platform_package, + version, + platform_tgz, + Some(platform_integrity), + ); } fn sri(bytes: &[u8]) -> String { @@ -4719,8 +4702,6 @@ mod tests { let case = format!("{kind}@{version} integrity={integrity:?}"); if integrity.is_none() { - // Like the bun and pnpm 12+ platform tarballs, a registry without - // `dist.integrity` installs unverified. result.unwrap_or_else(|error| panic!("{case}: {error}")); continue; } @@ -4855,15 +4836,13 @@ mod tests { #[tokio::test] async fn test_download_package_manager_pnpm_v12_native() { use httpmock::prelude::*; - use sha2::Sha512; let binary = b"mock pnpm executable"; let tarball = create_tgz(&[( if cfg!(windows) { "package/pnpm.exe" } else { "package/pnpm" }, binary, )]); - let integrity = - format!("sha512-{}", base64_simd::STANDARD.encode_to_string(Sha512::digest(&tarball))); + let integrity = sri(&tarball); let platform_package = get_pnpm_platform_package_name().unwrap(); let platform_basename = platform_package.strip_prefix("@pnpm/").unwrap(); let server = MockServer::start(); @@ -4922,14 +4901,8 @@ mod tests { let other_binary = b"other pnpm binary".to_vec(); let genuine_platform = create_tgz(&[(binary_path, genuine_binary.as_slice())]); let other_platform = create_tgz(&[(binary_path, other_binary.as_slice())]); - let genuine_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&genuine_platform)) - ); - let other_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&other_platform)) - ); + let genuine_integrity = sri(&genuine_platform); + let other_integrity = sri(&other_platform); let other_registry = MockServer::start(); mount_platform_registry( &other_registry, @@ -5444,12 +5417,8 @@ mod tests { let platform_tgz = create_tgz(&[(binary_path, binary)]); let main_hash = format!("sha512.{}", hex::encode(Sha512::digest(&main_tgz))); let wrong_hash = format!("sha512.{}", hex::encode(Sha512::digest(b"other"))); - let platform_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&platform_tgz)) - ); - let wrong_integrity = - format!("sha512-{}", base64_simd::STANDARD.encode_to_string(Sha512::digest(b"other"))); + let platform_integrity = sri(&platform_tgz); + let wrong_integrity = sri(b"other"); let platform_package = get_bun_platform_package_name().unwrap(); let platform_basename = platform_package.strip_prefix("@oven/").unwrap(); // Keep other tests from borrowing this server while its connections use this runtime. @@ -5540,10 +5509,7 @@ mod tests { let binary_path = if cfg!(windows) { "package/bin/bun.exe" } else { "package/bin/bun" }; let platform_tgz = create_tgz(&[(binary_path, binary)]); let wrong_hash = format!("sha512.{}", hex::encode(Sha512::digest(b"other"))); - let platform_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&platform_tgz)) - ); + let platform_integrity = sri(&platform_tgz); let server = MockServer::start(); mount_platform_registry( @@ -5597,14 +5563,8 @@ mod tests { let other_binary = b"other bun binary".to_vec(); let genuine_platform = create_tgz(&[(binary_path, genuine_binary.as_slice())]); let other_platform = create_tgz(&[(binary_path, other_binary.as_slice())]); - let genuine_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&genuine_platform)) - ); - let other_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&other_platform)) - ); + let genuine_integrity = sri(&genuine_platform); + let other_integrity = sri(&other_platform); // Both registries serve the same main tarball, so the same main pin // matches both. They differ only in the platform binary they serve. let other_registry = MockServer::start(); @@ -5680,10 +5640,7 @@ mod tests { let main_pin = format!("sha512.{}", hex::encode(Sha512::digest(&main_tgz))); let binary_path = if cfg!(windows) { "package/bin/bun.exe" } else { "package/bin/bun" }; let platform_tgz = create_tgz(&[(binary_path, b"bun binary")]); - let integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&platform_tgz)) - ); + let integrity = sri(&platform_tgz); let server = MockServer::start(); mount_platform_registry( @@ -5917,8 +5874,6 @@ mod tests { let vp_home = create_temp_dir(); let server = MockServer::start(); - // A 200 body that is not a valid gzip: the download succeeds but - // extraction fails, so the install errors out after the temp dir exists. let tarball = mount_package(&server, "pnpm", "10.0.0", b"this is not a valid gzip archive".to_vec()); @@ -6120,7 +6075,6 @@ mod tests { #[tokio::test] async fn platform_archive_symlink_cannot_write_into_another_pins_install() { - use sha2::Sha512; let vp_home = create_temp_dir(); let (pinned, _, _) = install_pinned_pnpm(vp_home.path()).await; let shim_before = fs::read(pinned.as_path().join("bin/pnpm")).unwrap(); @@ -6133,10 +6087,7 @@ mod tests { &[(binary_path, b"#!/bin/sh\necho planted\n")], &[("pnpm", link.as_str())], ); - let platform_integrity = format!( - "sha512-{}", - base64_simd::STANDARD.encode_to_string(Sha512::digest(&platform_tgz)) - ); + let platform_integrity = sri(&platform_tgz); let main_tgz = create_tgz(&[( "package/package.json", br#"{"name":"pnpm","version":"12.0.0-beta.0"}"#, diff --git a/crates/vp_pm_cli/src/request.rs b/crates/vp_pm_cli/src/request.rs index 52672661c7..8f888e2e8b 100644 --- a/crates/vp_pm_cli/src/request.rs +++ b/crates/vp_pm_cli/src/request.rs @@ -484,20 +484,6 @@ fn extract_tgz_file( } /// Download a tgz file from a URL and extract it to a target directory with optional hash verification. -/// -/// # Arguments -/// * `url` - The URL of the tgz file to download. -/// * `target_dir` - The directory to extract the tgz file to. -/// * `archive_file` - Optional single entry to extract, as a relative path of -/// normal components. vp ignores every other entry, and `expected_hash` -/// covers that one file instead of the tgz. -/// * `expected_hash` - Optional expected hash, "algorithm.hex" or SRI "algorithm-base64" (see [`verify_file_hash`]) -/// * `message` - Optional message shown above a progress bar while downloading (see [`HttpClient::download_file`]) -/// * `npm_config` - npm configuration used for the download. -/// -/// # Returns -/// * `Ok(())` - If the tgz file is downloaded, verified (if hash provided) and extracted successfully. -/// * `Err(e)` - If the tgz file is not downloaded, verified or extracted successfully. pub(crate) async fn download_and_extract_tgz_with_hash_and_config( url: &str, target_dir: impl AsRef, diff --git a/crates/vp_pm_cli/tests/package_manager_pin_verification.rs b/crates/vp_pm_cli/tests/package_manager_pin_verification.rs index a26a575c38..ad710b9ed1 100644 --- a/crates/vp_pm_cli/tests/package_manager_pin_verification.rs +++ b/crates/vp_pm_cli/tests/package_manager_pin_verification.rs @@ -354,7 +354,6 @@ async fn archive_entries_cannot_escape_the_install_directory() { let extraction = download_package_manager(PackageManagerType::Pnpm, PINNED_PNPM_VERSION, None) .await; - // The managed directory holding this version's installs. let install = package_manager_install_dir( PackageManagerType::Pnpm, PINNED_PNPM_VERSION, From bfba722901ca971196dbb6505c19acf1a9eef628 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Mon, 23 Nov 2026 14:16:21 +0900 Subject: [PATCH 5/5] test(snapshots): serve npm metadata in the download progress mock An unpinned npm download now reads dist.integrity from the version metadata, so the mock registry must answer that request. --- .../cli_snapshots/fixtures/download_progress/download.mjs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/download_progress/download.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/download_progress/download.mjs index 0ff7e851b6..43733b4bf8 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/download_progress/download.mjs +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/download_progress/download.mjs @@ -22,6 +22,7 @@ const npmArchive = createArchive({ 'package/bin/npm-cli.js': '// fixture\n', 'package/bin/npx-cli.js': '// fixture\n', }); +const npmIntegrity = `sha512-${createHash('sha512').update(npmArchive).digest('base64')}`; let downloads = 0; const server = createServer(function handleRequest(request, response) { if (request.url.endsWith('/SHASUMS256.txt.asc')) { @@ -32,6 +33,11 @@ const server = createServer(function handleRequest(request, response) { response.end(`${createHash('sha256').update(nodeArchive).digest('hex')} ${nodeRoot}.tar.gz\n`); return; } + if (request.url === `/npm/${version}`) { + response.setHeader('Content-Type', 'application/json'); + response.end(JSON.stringify({ dist: { integrity: npmIntegrity } })); + return; + } let body; if (request.url.endsWith(`/${nodeRoot}.tar.gz`)) { body = nodeArchive;