diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 22f89dfd3146..3dda89ccc26d 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -16,6 +16,7 @@ use crate::isolated_install::FileCopier; use crate::lockfile_real::package::{Package, PackageColumns as _}; use crate::lockfile_real::tree; use crate::lockfile_real::{self as lockfile, Lockfile, PackageIndexEntry}; +use crate::package_installer::alias_is_safe_install_target; use crate::package_manager_real::PackageManager; use crate::package_manager_real::options::{LogLevel, PatchFeatures}; use crate::package_manager_real::package_manager_directories::{ @@ -254,12 +255,12 @@ pub fn do_patch_commit( } PatchArgKind::NameAndVersion => 'brk: { let (name, version) = Dependency::split_name_and_maybe_version(argument); - let (pkg_id, node_modules_relative_path) = + let (pkg_id, node_modules_relative_path, folder_name) = pkg_info_for_name_and_version(&lockfile, &mut iterator, argument, name, version); let changes_dir = resolve_path::join_z_buf::( &mut pathbuf[..], - &[&node_modules_relative_path, name], + &[&node_modules_relative_path, &folder_name], ) .as_bytes() .to_vec(); @@ -879,7 +880,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> { let mut iterator = tree::Iterator::<{ tree::IteratorPathStyle::NodeModules }>::init( &manager.lockfile, ); - let (pkg_id, folder_relative_path) = pkg_info_for_name_and_version( + let (pkg_id, folder_relative_path, folder_name) = pkg_info_for_name_and_version( &manager.lockfile, &mut iterator, pkg_maybe_version_to_patch, @@ -896,7 +897,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> { write!( &mut name_and_version, "{}@{}", - bstr::BStr::new(name), + bstr::BStr::new(&pkg_name), pkg.resolution.fmt(strbuf, PathSep::Posix) ) .expect("unreachable"); @@ -926,7 +927,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> { let cache_dir_subpath = cache_result.cache_dir_subpath; let module_folder_ = - resolve_path::join::(&[&folder_relative_path, name]); + resolve_path::join::(&[&folder_relative_path, &folder_name]); #[cfg(windows)] let buf = resolve_path::path_to_posix_buf::(module_folder_, &mut win_normalizer[..]) @@ -1220,18 +1221,14 @@ type NodeModulesIterator<'a> = tree::Iterator<'a, { tree::IteratorPathStyle::Nod fn node_modules_folder_for_dependency_ids( iterator: &mut NodeModulesIterator<'_>, ids: &[IdPair], -) -> Option> { +) -> Option<(IdPair, Vec)> { loop { let node_modules = iterator.next(None)?; - let mut found = false; - for id in ids { - if node_modules.dependencies.contains(&id.0) { - found = true; - break; - } - } - if found { - return Some(node_modules.relative_path.as_bytes().to_vec()); + if let Some(&id) = ids + .iter() + .find(|id| node_modules.dependencies.contains(&id.0)) + { + return Some((id, node_modules.relative_path.as_bytes().to_vec())); } } } @@ -1251,14 +1248,16 @@ fn node_modules_folder_for_dependency_id( type IdPair = (DependencyID, PackageID); +/// Returns the package, the node_modules folder that holds it, and the name of its folder there. fn pkg_info_for_name_and_version( lockfile: &Lockfile, iterator: &mut NodeModulesIterator<'_>, pkg_maybe_version_to_patch: &[u8], name: &[u8], version: Option<&[u8]>, -) -> (PackageID, Vec) { +) -> (PackageID, Vec, Vec) { let mut pairs: Vec = Vec::with_capacity(8); + let mut aliased: Vec = Vec::new(); let name_hash = string_hash(name); @@ -1266,25 +1265,48 @@ fn pkg_info_for_name_and_version( let mut resolution_label = Vec::new(); let dependencies = lockfile.buffers.dependencies.as_slice(); + let pkg_name_hashes = lockfile.packages.items_name_hash(); + // The name becomes a path that `bun patch` deletes and writes, the same as an install. + let folder_name = |dep_id: DependencyID| { + let folder_name = dependencies[dep_id as usize].name.slice(strbuf); + if !alias_is_safe_install_target(folder_name) { + bun_core::pretty_errorln!( + "error: refusing to patch dependency with unsafe name {}", + bun_fmt::quote(folder_name), + ); + Global::crash(); + } + folder_name.to_vec() + }; - for (dep_id, dep) in dependencies.iter().enumerate() { - if dep.name_hash != name_hash { + let resolutions = lockfile.buffers.resolutions.as_slice(); + for (dep_id, (dep, &pkg_id)) in dependencies.iter().zip(resolutions).enumerate() { + // `invalid_package_id` and any other id past the end: the dependency did not resolve. + let Some(&pkg_name_hash) = pkg_name_hashes.get(pkg_id as usize) else { continue; - } - let pkg_id = lockfile.buffers.resolutions.as_slice()[dep_id]; - if pkg_id == invalid_package_id { + }; + let matches = if dep.name_hash == name_hash { + &mut pairs + } else if pkg_name_hash == name_hash { + &mut aliased + } else { continue; - } + }; let pkg = *lockfile.packages.get(pkg_id as usize); if let Some(v) = version { if print_resolution_label(&mut resolution_label, &pkg.resolution, strbuf) == v { - pairs.push((dep_id as DependencyID, pkg_id)); + matches.push((dep_id as DependencyID, pkg_id)); } } else { - pairs.push((dep_id as DependencyID, pkg_id)); + matches.push((dep_id as DependencyID, pkg_id)); } } + // Not a union: an alias of another version must not make a dependency's name ambiguous. + if pairs.is_empty() { + pairs = aliased; + } + if pairs.is_empty() { bun_core::pretty_errorln!( "\nerror: package {} not found", @@ -1307,14 +1329,15 @@ fn pkg_info_for_name_and_version( Global::crash(); } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } // we found multiple dependents of the supplied pkg + version // the final package in the node_modules might be hoisted // so we are going to try looking for each dep id in node_modules - let (_, pkg_id) = pairs[0]; - let folder = match node_modules_folder_for_dependency_ids(iterator, &pairs) { + let ((dep_id, pkg_id), folder) = match node_modules_folder_for_dependency_ids( + iterator, &pairs, + ) { Some(f) => f, None => { bun_core::pretty_error!( @@ -1325,7 +1348,7 @@ fn pkg_info_for_name_and_version( } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } // Otherwise the user did not supply a version, just the pkg name @@ -1343,7 +1366,7 @@ fn pkg_info_for_name_and_version( Global::crash(); } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } // Otherwise we have multiple matches @@ -1366,7 +1389,7 @@ fn pkg_info_for_name_and_version( // Disambiguate case a) from b) if count as usize == pairs.len() { // It may be hoisted, so we'll try the first one that matches - let folder = match node_modules_folder_for_dependency_ids(iterator, &pairs) { + let ((dep_id, _), folder) = match node_modules_folder_for_dependency_ids(iterator, &pairs) { Some(f) => f, None => { bun_core::pretty_error!( @@ -1376,7 +1399,7 @@ fn pkg_info_for_name_and_version( Global::crash(); } }; - return (pkg_id, folder); + return (pkg_id, folder, folder_name(dep_id)); } bun_core::pretty_errorln!( diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 0e61d4526398..111ece2a613c 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1,7 +1,7 @@ import { $, ShellOutput } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { lstatSync, readFileSync } from "fs"; -import { bunEnv, bunExe, isASAN, tempDir, VerdaccioRegistry } from "harness"; +import { existsSync, lstatSync, readFileSync } from "fs"; +import { bunEnv, bunExe, isASAN, readdirSorted, tempDir, VerdaccioRegistry } from "harness"; import { isAbsolute, join, sep } from "path"; const expectNoError = (o: ShellOutput) => expect(o.stderr.toString()).not.toContain("error"); @@ -10,6 +10,30 @@ const platformPath = (path: string) => path; setDefaultTimeout(1000 * 60 * 5); +const registry = new VerdaccioRegistry(); + +beforeAll(async () => { + await registry.start(); +}); + +afterAll(() => { + registry.stop(); +}); + +// CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. Two of these concurrent +// tests install the same tarball spec; sharing one cache, they replace each other's `@T@` folder on Windows. +async function runBun(cwd: string, ...args: string[]) { + await using proc = Bun.spawn({ + cmd: [bunExe(), ...args], + cwd, + env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stdout, stderr, exitCode }; +} + describe("error messages", () => { test("'bun patch' with no package name shows a usage example", async () => { await using dir = tempDir("bun-patch-noarg", { @@ -71,16 +95,6 @@ describe("error messages", () => { // stack buffers (512 bytes in the installer itself), so a long enough spec crashed // every command that formatted it. describe("packages whose label is longer than 1024 bytes", () => { - const registry = new VerdaccioRegistry(); - - beforeAll(async () => { - await registry.start(); - }); - - afterAll(() => { - registry.stop(); - }); - // `x/../` normalizes away, so the tarball still lives at a short path that is valid // on every platform while the recorded spec stays long. const longSpec = (tarball: string) => `./${Buffer.alloc(1050, "x/../").toString()}${tarball}`; @@ -96,20 +110,6 @@ describe("packages whose label is longer than 1024 bytes", () => { return packageDir; } - // CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. Two of these concurrent - // tests install the same tarball spec; sharing one cache, they replace each other's `@T@` folder on Windows. - async function runBun(cwd: string, ...args: string[]) { - await using proc = Bun.spawn({ - cmd: [bunExe(), ...args], - cwd, - env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") }, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - return { stdout, stderr, exitCode }; - } - async function install(cwd: string) { const { stderr, exitCode } = await runBun(cwd, "install"); expect(stderr).not.toContain("error:"); @@ -1234,3 +1234,194 @@ describe.concurrent("bun patch --commit for non-registry dependencies", () => { expect(patchKey).toBe("pkg-to-patch@./dep.tgz"); }); }); + +// `"my-alias": "npm:no-deps@1.0.0"` installs the package `no-deps` into `node_modules/my-alias`. +// `bun patch` prints the package's own name and keys the patch by it (`no-deps@1.0.0`), so that +// name has to select the package too, not only the alias. +describe("an npm: aliased dependency", () => { + async function writeProject(dependencies: Record, linker: "hoisted" | "isolated" = "hoisted") { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker }, + files: { "package.json": JSON.stringify({ name: "root", dependencies }) }, + }); + return packageDir; + } + + async function createProject(dependencies: Record, linker?: "hoisted" | "isolated") { + const packageDir = await writeProject(dependencies, linker); + const { stderr, exitCode } = await runBun(packageDir, "install"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + return packageDir; + } + + async function expectPrepared(packageDir: string, argument: string, folder: string) { + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); + expect(stderr).not.toContain("error:"); + expect(stdout).toContain(`To patch no-deps, edit the following folder:\n\n ${folder}\n`); + expect(stdout).toContain(`bun patch --commit '${folder}'`); + expect(exitCode).toBe(0); + } + + test.concurrent.each(["my-alias", "my-alias@1.0.0", "no-deps", "no-deps@1.0.0"])("bun patch %s", async argument => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["my-alias"]); + }); + + test.concurrent.each(["@my/alias", "no-deps"])("bun patch %s with a scoped alias", async argument => { + const packageDir = await createProject({ "@my/alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, argument, "node_modules/@my/alias"); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["@my"]); + }); + + // The isolated linker makes `node_modules/my-alias` a symlink into `node_modules/.bun`. + test.concurrent("bun patch and --commit with the isolated linker", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }, "isolated"); + const folder = join(packageDir, "node_modules", "my-alias"); + expect(lstatSync(folder).isSymbolicLink()).toBe(true); + + await expectPrepared(packageDir, "no-deps", "node_modules/my-alias"); + expect(lstatSync(folder).isSymbolicLink()).toBe(false); + expect(await readdirSorted(join(packageDir, "node_modules"))).not.toContain("no-deps"); + await Bun.write(join(folder, "index.js"), "module.exports = 'patched';\n"); + + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toEqual({ + "no-deps@1.0.0": "patches/no-deps@1.0.0.patch", + }); + expect(await Bun.file(join(packageDir, "patches", "no-deps@1.0.0.patch")).text()).toContain( + "+module.exports = 'patched';", + ); + }); + + test.concurrent("bun patch --commit ", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + await expectPrepared(packageDir, "no-deps", "node_modules/my-alias"); + await Bun.write(join(packageDir, "node_modules", "my-alias", "index.js"), "module.exports = 'patched';\n"); + + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toEqual({ + "no-deps@1.0.0": "patches/no-deps@1.0.0.patch", + }); + expect(await Bun.file(join(packageDir, "patches", "no-deps@1.0.0.patch")).text()).toContain( + "+module.exports = 'patched';", + ); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual(["my-alias"]); + }); + + // A second `bun patch` starts from the patched package, so the next commit keeps the first change. + test.concurrent.each(["my-alias", "no-deps"])("bun patch %s of a package that is already patched", async argument => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0" }); + const index = join(packageDir, "node_modules", "my-alias", "index.js"); + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + await Bun.write(index, "module.exports = 'patched';\n"); + const { stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "node_modules/my-alias"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + + await expectPrepared(packageDir, argument, "node_modules/my-alias"); + expect(await Bun.file(index).text()).toBe("module.exports = 'patched';\n"); + }); + + test.concurrent("bun patch asks for a version when two aliases install different ones", async () => { + const packageDir = await createProject({ "a1": "npm:no-deps@1.0.0", "a2": "npm:no-deps@2.0.0" }); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "no-deps"); + expect(stderr).toContain( + "error: Found multiple versions of no-deps, please specify a precise version from the following list:\n" + + " no-deps@1.0.0\n" + + " no-deps@2.0.0\n", + ); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/a1"); + await expectPrepared(packageDir, "no-deps@2.0.0", "node_modules/a2"); + await expectPrepared(packageDir, "a2", "node_modules/a2"); + }); + + // An alias of another version does not make the name of a dependency ambiguous. + test.concurrent("bun patch selects the dependency with that name before an alias", async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0", "no-deps": "2.0.0" }); + await expectPrepared(packageDir, "no-deps", "node_modules/no-deps"); + await expectPrepared(packageDir, "no-deps@2.0.0", "node_modules/no-deps"); + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/my-alias"); + await expectPrepared(packageDir, "my-alias", "node_modules/my-alias"); + }); + + test.concurrent( + "bun patch prefers the folder with that name to an alias of the same package", + async () => { + const packageDir = await createProject({ "my-alias": "npm:no-deps@1.0.0", "no-deps": "1.0.0" }); + await expectPrepared(packageDir, "no-deps", "node_modules/no-deps"); + await expectPrepared(packageDir, "no-deps@1.0.0", "node_modules/no-deps"); + await expectPrepared(packageDir, "my-alias", "node_modules/my-alias"); + }, + ); + + // The refused name comes from the lockfile, so the message must not print its control characters. + test.concurrent("bun patch escapes the unsafe name that it refuses", async () => { + const packageDir = await writeProject({ "a/\x1b[31mRED\x1b[0m\rFAKE\nsecond": "npm:no-deps@1.0.0" }); + expect((await runBun(packageDir, "install")).exitCode).toBe(1); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "no-deps"); + expect(stderr).toContain( + String.raw`error: refusing to patch dependency with unsafe name "a/\u001B[31mRED\u001B[0m\rFAKE\nsecond"` + "\n", + ); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + }); + + // `bun.lockb` is read as is. One resolution id past the end of the package list used to be an + // index out of bounds when the id belonged to the named dependency. The name lookup now reads + // the id of every dependency, so it must not trust any of them. + test.concurrent.each([ + ["another dependency", 0, "failed to resolve"], + ["the named dependency", 1, "error: package no-deps not found"], + ])("bun patch --commit with a resolution id past the end for %s", async (_, index, message) => { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker: "hoisted", saveTextLockfile: false }, + files: { + "package.json": JSON.stringify({ name: "root", dependencies: { "a-dep": "1.0.1", "no-deps": "1.0.0" } }), + }, + }); + expect((await runBun(packageDir, "install")).exitCode).toBe(0); + await expectPrepared(packageDir, "no-deps", "node_modules/no-deps"); + + // `buffers.resolutions` is the second u32 array. Its [start, end) offsets come before the prefix. + const lockb = Buffer.from(await Bun.file(join(packageDir, "bun.lockb")).arrayBuffer()); + const prefix = "\n 4 sizeof, 4 alignof\n"; + const at = lockb.indexOf(prefix, lockb.indexOf(prefix) + 1); + const start = Number(lockb.readBigUInt64LE(at - 16)); + const end = Number(lockb.readBigUInt64LE(at - 8)); + expect((end - start) / 4).toBe(2); + lockb.writeUInt32LE(0x7fffffff, start + 4 * index); + await Bun.write(join(packageDir, "bun.lockb"), lockb); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", "--commit", "no-deps"); + expect(stderr).toContain(message); + expect(exitCode).toBe(1); + expect(existsSync(join(packageDir, "patches"))).toBe(false); + expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toBeUndefined(); + }); + + // The alias names the folder. `bun install` refuses to write `node_modules/a/b`, because only + // `@scope/name` can have a `/`, so `bun patch` does not create that folder either. + test.concurrent.each(["no-deps", "a/b"])("bun patch %s refuses an alias that bun install refuses", async argument => { + const packageDir = await writeProject({ "a/b": "npm:no-deps@1.0.0" }); + const install = await runBun(packageDir, "install"); + expect(install.stderr).toContain("error: refusing to install dependency with unsafe name a/b\n"); + expect(install.exitCode).toBe(1); + + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", argument); + expect(stderr).toContain('error: refusing to patch dependency with unsafe name "a/b"\n'); + expect(stdout).not.toContain("To patch"); + expect(exitCode).toBe(1); + expect(await readdirSorted(join(packageDir, "node_modules"))).toEqual([]); + }); +});