diff --git a/src/install/PackageManager.rs b/src/install/PackageManager.rs index d1075ccba9a3..daf43cdaf4ca 100644 --- a/src/install/PackageManager.rs +++ b/src/install/PackageManager.rs @@ -1770,7 +1770,7 @@ pub fn init( break; }; let mut log = bun_ast::Log::init(); - let _ = match workspace_names.process_names_array( + let processed = workspace_names.process_names_array( &mut workspace_package_json_cache, &mut log, names, @@ -1778,11 +1778,12 @@ pub fn init( prop.loc, None, Package::WorkspaceMap::MissingWorkspace::Skip, - ) { - Ok(v) => v, - Err(_) => break, - }; + ); drop(log); + // Still the root of its other members. The install reports the entry. + if processed.is_err() && !workspace_names.rejected_outside_root { + break; + } debug_assert_eq!( workspace_names.keys().len(), diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index a971fc83635e..15edd8bef198 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -7,6 +7,7 @@ use bun_glob as glob; use bun_paths as path; use bun_paths::resolve_path; use bun_paths::{MAX_PATH_BYTES, SEP_STR}; +use bun_sys::FdExt as _; use crate::lockfile_real::{Lockfile, StringBuilder, pruned_workspaces}; use crate::package_manager::workspace_package_json_cache::{ @@ -17,6 +18,8 @@ bun_output::declare_scope!(Lockfile, hidden); pub(crate) struct WorkspaceMap { map: Map, + /// `process_names_array` rejected an entry that is outside the workspace root. + pub(crate) rejected_outside_root: bool, } type Map = StringArrayHashMap; @@ -38,6 +41,7 @@ impl WorkspaceMap { pub(crate) fn init() -> WorkspaceMap { WorkspaceMap { map: Map::default(), + rejected_outside_root: false, } } @@ -231,6 +235,143 @@ fn workspace_dir_of(abs_package_json_path: &[u8]) -> &[u8] { ) } +fn escapes_root(root_relative_dir: &[u8]) -> bool { + root_relative_dir == b".." + || root_relative_dir.starts_with(b"../") + // `relative` spells a different Windows drive as an absolute path. + || path::is_absolute(root_relative_dir) +} + +fn real_dir_path<'b>(abs_dir: &[u8], buf: &'b mut path::PathBuffer) -> bun_sys::Maybe<&'b [u8]> { + let fd = bun_sys::open_dir_absolute(abs_dir)?; + let real = bun_sys::get_fd_path(fd, buf); + fd.close(); + real.map(|real| &*real) +} + +/// Every member gets a `node_modules`, so one outside the root is a write outside the project. +struct WorkspaceRoot<'a> { + dir: &'a [u8], + /// `dir` with its symlinks resolved, on first use. + real_dir: Option>, +} + +/// A glob reports its first rejected match. The rest would repeat it. +#[derive(Clone, Copy, PartialEq)] +enum Report { + Error, + Silent, +} + +impl WorkspaceRoot<'_> { + fn rejects_path( + &self, + abs_workspace_dir: &[u8], + entry: &[u8], + report: Report, + log: &mut bun_ast::Log, + source: &bun_ast::Source, + loc: bun_ast::Loc, + ) -> bool { + // Could be another spelling of a directory inside the root (`/tmp` on macOS). + if path::is_absolute(entry) { + return false; + } + let mut rel_path_buf = path::path_buffer_pool::get(); + if !escapes_root(relative_workspace_path( + &mut rel_path_buf.0, + self.dir, + abs_workspace_dir, + )) { + return false; + } + if report == Report::Error { + log.add_error_fmt( + Some(source), + loc, + format_args!( + "Workspace \"{}\" is outside the workspace root", + BStr::new(entry) + ), + ); + } + true + } + + /// For a symlink that leaves the root: `link -> ../sibling`, or `up/*` with `up -> ..`. + fn rejects_real_path( + &mut self, + abs_workspace_dir: &[u8], + entry: &[u8], + report: Report, + log: &mut bun_ast::Log, + source: &bun_ast::Source, + loc: bun_ast::Loc, + ) -> bool { + let mut real_dir_buf = path::path_buffer_pool::get(); + let resolved = real_dir_path(abs_workspace_dir, &mut real_dir_buf).and_then(|real_dir| { + let real_root = match &self.real_dir { + Some(real_root) => real_root, + None => { + let mut real_root_buf = path::path_buffer_pool::get(); + let real_root = real_dir_path(self.dir, &mut real_root_buf)?; + self.real_dir.insert(Box::from(real_root)) + } + }; + Ok((real_root, real_dir)) + }); + let (real_root, real_dir) = match resolved { + Ok(resolved) => resolved, + Err(err) => { + if report == Report::Error { + log.add_error_fmt( + Some(source), + loc, + format_args!( + "{} resolving the directory of workspace package \"{}\"", + crate::Error::from(err).name(), + BStr::new(entry), + ), + ); + } + return true; + } + }; + let mut rel_path_buf = path::path_buffer_pool::get(); + if !escapes_root(relative_workspace_path( + &mut rel_path_buf.0, + real_root, + real_dir, + )) { + return false; + } + if report == Report::Error { + // A `..` spelling, or an absolute entry outside the root, resolves to itself. + if real_dir == abs_workspace_dir { + log.add_error_fmt( + Some(source), + loc, + format_args!( + "Workspace \"{}\" is outside the workspace root", + BStr::new(entry) + ), + ); + } else { + log.add_error_fmt( + Some(source), + loc, + format_args!( + "Workspace \"{}\" is outside the workspace root: it resolves to \"{}\"", + BStr::new(entry), + BStr::new(real_dir), + ), + ); + } + } + true + } +} + fn relative_workspace_path<'b>( buf: &'b mut [u8], root_dir: &[u8], @@ -265,11 +406,18 @@ impl WorkspaceMap { let orig_msgs_len = log.msgs.len(); - let mut workspace_globs: Vec> = Vec::new(); + let mut workspace_globs: Vec<(Box<[u8]>, bun_ast::Loc)> = Vec::new(); let mut filepath_buf_os = path::path_buffer_pool::get(); let filepath_buf: &mut [u8] = &mut filepath_buf_os.0[..]; let mut rel_path_buf = path::path_buffer_pool::get(); let root_dir: &[u8] = source.path.name().dir; + let mut root = WorkspaceRoot { + // Not `root_dir`: that is empty for a package.json at the filesystem root. + dir: path::dirname(source.path.text) + .filter(|dir| !dir.is_empty()) + .unwrap_or_else(|| bun_resolver::fs::FileSystem::instance().top_level_dir()), + real_dir: None, + }; let scratch = Arena::new(); @@ -293,7 +441,7 @@ impl WorkspaceMap { } if glob::detect_glob_syntax(input_path) { - workspace_globs.push(Box::<[u8]>::from(input_path)); + workspace_globs.push((Box::<[u8]>::from(input_path), arr.item_loc(source, i))); continue; } @@ -313,6 +461,18 @@ impl WorkspaceMap { continue; } + if root.rejects_path( + workspace_dir_of(abs_package_json_path), + input_path, + Report::Error, + log, + source, + arr.item_loc(source, i), + ) { + workspace_names.rejected_outside_root = true; + continue; + } + process_workspace_name(json_cache, abs_package_json_path, log) .map(|entry| (abs_package_json_path, entry)) } @@ -382,6 +542,18 @@ impl WorkspaceMap { continue; } + if root.rejects_real_path( + workspace_dir_of(abs_package_json_path), + input_path, + Report::Error, + log, + source, + arr.item_loc(source, i), + ) { + workspace_names.rejected_outside_root = true; + continue; + } + let rel_input_path = relative_workspace_path( &mut rel_path_buf.0, root_dir, @@ -411,7 +583,7 @@ impl WorkspaceMap { if workspace_globs.len() > 0 { let mut arena = Arena::new(); - for (i, user_pattern) in workspace_globs.iter().enumerate() { + for (i, (user_pattern, pattern_loc)) in workspace_globs.iter().enumerate() { // walker/iter borrow `&arena` and Drop at scope exit, // so resetting here (top of next iter) ensures they drop before invalidation. // Last iter's allocs are freed when `arena` itself drops after the loop. @@ -474,6 +646,8 @@ impl WorkspaceMap { return Err(crate::Error::GlobError); } + // The pattern's other matches stay members, for `PackageManager::init`. + let mut report = Report::Error; 'next_match: loop { let matched_path_owned = match iter.next()? { Ok(Some(r)) => r, @@ -506,7 +680,7 @@ impl WorkspaceMap { ); // check if it's negated by any remaining patterns - for next_pattern in &workspace_globs[i + 1..] { + for (next_pattern, _) in &workspace_globs[i + 1..] { let result = glob::r#match(next_pattern, matched_path_without_package_json); if result.is_negated() && !result.matches() { @@ -534,6 +708,19 @@ impl WorkspaceMap { cwd, filepath_buf, &[entry_dir, b"package.json"] ) { Some(abs_package_json_path) => { + if root.rejects_path( + workspace_dir_of(abs_package_json_path), + entry_dir, + report, + log, + source, + *pattern_loc, + ) { + workspace_names.rejected_outside_root = true; + report = Report::Silent; + continue; + } + process_workspace_name(json_cache, abs_package_json_path, log) .map(|entry| (abs_package_json_path, entry)) } @@ -578,6 +765,19 @@ impl WorkspaceMap { continue; } + if root.rejects_real_path( + workspace_dir_of(abs_package_json_path), + entry_dir, + report, + log, + source, + *pattern_loc, + ) { + workspace_names.rejected_outside_root = true; + report = Report::Silent; + continue; + } + let workspace_path: &[u8] = relative_workspace_path( &mut rel_path_buf.0, root_dir, diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index 81c5a2af0bf4..eb8215317174 100644 --- a/test/cli/install/bad-workspace.test.ts +++ b/test/cli/install/bad-workspace.test.ts @@ -1,7 +1,7 @@ import { spawn, spawnSync } from "bun"; import { install_test_helpers } from "bun:internal-for-testing"; import { beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { mkdirSync, writeFileSync } from "fs"; +import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "fs"; import { bunEnv, bunExe, isLinux, isWindows, tempDir, tmpdirSync } from "harness"; import { dirname, join } from "path"; @@ -312,3 +312,245 @@ describe.concurrent("workspaces entries longer than the path buffer", () => { }, ); }); + +// `bun install` creates `/node_modules` for every workspace member, so a member +// outside the root is a write into a directory the project does not own. A cloned +// repository could name the directories next to it (the user's other projects) as its +// members: the sibling then loads the clone's code, with no lifecycle script involved. +describe.concurrent("workspaces entries outside the workspace root", () => { + // A clone in `clone/` next to the user's own project in `victim/`. `inner@1.99.0` in the + // clone satisfies the range the victim depends on, so a member link written into + // `victim/node_modules` makes the victim load the clone's copy. + const SIBLING_PROJECTS = { + "victim/package.json": JSON.stringify({ name: "victim", dependencies: { inner: "^1.0.0" } }), + "clone/packages/inner/package.json": JSON.stringify({ name: "inner", version: "1.99.0", main: "index.js" }), + "clone/packages/inner/index.js": `module.exports = "from the clone";`, + }; + + // The install fails, names the entry, and leaves both projects as they were. + async function expectRejected(dir: string, message: string, cwd = join(dir, "clone")) { + const { stderr, exitCode } = await runInstall(cwd); + + expect(stderr).toContain(`error: ${message}\n`); + expect(exitCode).toBe(1); + expect(existsSync(join(dir, "victim", "node_modules"))).toBe(false); + expect(existsSync(join(dir, "clone", "bun.lock"))).toBe(false); + expect(existsSync(join(cwd, "bun.lock"))).toBe(false); + } + + test("a listed sibling directory is rejected", async () => { + using dir = tempDir("bad-workspace-sibling-path", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "../victim"]), + }); + + await expectRejected(String(dir), `Workspace "../victim" is outside the workspace root`); + }); + + test("a glob that leaves the root is rejected", async () => { + using dir = tempDir("bad-workspace-sibling-glob", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "../*"]), + }); + + // The glob walker reports the match with the platform separator. + await expectRejected(String(dir), `Workspace "${join("..", "victim")}" is outside the workspace root`); + }); + + test("an absolute path outside the root is rejected", async () => { + using dir = tempDir("bad-workspace-absolute-outside", { + ...SIBLING_PROJECTS, + "clone/package.json": ({ root }) => rootPackageJson(["packages/*", join(root, "victim")]), + }); + + await expectRejected(String(dir), `Workspace "${join(String(dir), "victim")}" is outside the workspace root`); + }); + + test("a path that climbs out and back in is rejected", async () => { + using dir = tempDir("bad-workspace-climb-out-and-back", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "packages/../../victim"]), + }); + + await expectRejected(String(dir), `Workspace "packages/../../victim" is outside the workspace root`); + }); + + // A backslash is a separator on every platform here, so this is `../victim`. + test("a sibling directory spelled with a backslash is rejected", async () => { + using dir = tempDir("bad-workspace-sibling-backslash", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "..\\victim"]), + }); + + await expectRejected(String(dir), `Workspace "..\\victim" is outside the workspace root`); + }); + + // The pnpm migration moves `packages` from pnpm-workspace.yaml into `workspaces` in + // package.json, and the same install then reads that manifest. + test("a sibling directory named in pnpm-workspace.yaml is rejected", async () => { + using dir = tempDir("bad-workspace-sibling-pnpm", { + ...SIBLING_PROJECTS, + "clone/package.json": JSON.stringify({ name: "root" }), + "clone/pnpm-workspace.yaml": `packages:\n - 'packages/*'\n - '../victim'\n`, + "clone/pnpm-lock.yaml": [ + `lockfileVersion: '9.0'`, + ``, + `settings:`, + ` autoInstallPeers: true`, + ` excludeLinksFromLockfile: false`, + ``, + `importers:`, + ``, + ` .:`, + ` dependencies: {}`, + ``, + ` packages/inner:`, + ` dependencies: {}`, + ``, + ].join("\n"), + }); + + await expectRejected(String(dir), `Workspace "../victim" is outside the workspace root`); + expect(JSON.parse(readFileSync(join(String(dir), "clone", "package.json"), "utf8")).workspaces).toEqual([ + "packages/*", + "../victim", + ]); + }); + + // git stores symlinks, so the clone can ship one. The entry is inside the root by its + // path, and the directory that receives `node_modules` is not. A junction on Windows. + test("a listed symlink to a sibling directory is rejected", async () => { + using dir = tempDir("bad-workspace-symlink-path", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "link"]), + }); + const victim = join(String(dir), "victim"); + symlinkSync(victim, join(String(dir), "clone", "link"), "junction"); + + await expectRejected(String(dir), `Workspace "link" is outside the workspace root: it resolves to "${victim}"`); + }); + + test("a glob under a symlink that leaves the root is rejected", async () => { + using dir = tempDir("bad-workspace-symlink-glob", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "up/*"]), + }); + const victim = join(String(dir), "victim"); + symlinkSync(String(dir), join(String(dir), "clone", "up"), "junction"); + + await expectRejected( + String(dir), + `Workspace "${join("up", "victim")}" is outside the workspace root: it resolves to "${victim}"`, + ); + }); + + // The search for the root, upward from a member, reads the same manifest. It must not + // take the rejected entry as "this is not a workspace root" and install the member alone. + test("an install inside a member reports a listed sibling directory", async () => { + using dir = tempDir("bad-workspace-sibling-from-member", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "../victim"]), + }); + + await expectRejected( + String(dir), + `Workspace "../victim" is outside the workspace root`, + join(String(dir), "clone", "packages", "inner"), + ); + }); + + test("an install inside a member reports a glob under a symlink that leaves the root", async () => { + using dir = tempDir("bad-workspace-symlink-from-member", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["packages/*", "up/*"]), + }); + const victim = join(String(dir), "victim"); + symlinkSync(String(dir), join(String(dir), "clone", "up"), "junction"); + + await expectRejected( + String(dir), + `Workspace "${join("up", "victim")}" is outside the workspace root: it resolves to "${victim}"`, + join(String(dir), "clone", "packages", "inner"), + ); + }); + + // The root directory is the resolved path of the manifest, so an absolute entry spelled + // through a symlinked ancestor names a directory inside the root, not an escape. It is + // recorded under the path relative to the root as written, which is what bun did before + // this check existed. + test("an absolute path inside the root through a symlinked ancestor is still a workspace", async () => { + using dir = tempDir("bad-workspace-absolute-through-symlink", SIBLING_PROJECTS); + // /link/clone/packages/inner is /clone/packages/inner through /link. + symlinkSync(String(dir), join(String(dir), "link"), "junction"); + writeFileSync( + join(String(dir), "clone", "package.json"), + rootPackageJson([join(String(dir), "link", "clone", "packages", "inner")]), + ); + + const { stderr, exitCode } = await runInstall(join(String(dir), "clone")); + + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect(Object.values(install_test_helpers.parseLockfile(join(String(dir), "clone")).workspace_paths)).toEqual([ + "../link/clone/packages/inner", + ]); + }); + + // One rejected match of a glob must not hide the pattern's other matches: an install that + // runs in one of them still has to find its own root. `../*/packages/*` matches a + // directory in each sibling project and `packages/inner` in the clone itself. + test("a glob reports one error and keeps its other matches", async () => { + using dir = tempDir("bad-workspace-glob-keeps-matches", { + // Each sibling member depends on `inner`, so an install that adopted it would write + // its `node_modules`. + "victimA/packages/a/package.json": JSON.stringify({ name: "victim-a-pkg", dependencies: { inner: "^1.0.0" } }), + "victimB/packages/b/package.json": JSON.stringify({ name: "victim-b-pkg", dependencies: { inner: "^1.0.0" } }), + "clone/package.json": rootPackageJson(["../*/packages/*"]), + "clone/packages/inner/package.json": JSON.stringify({ name: "inner", version: "1.0.0" }), + }); + + const { stderr, exitCode } = await runInstall(join(String(dir), "clone", "packages", "inner")); + + // One error, whichever sibling the walker reports first. + expect(stderr.match(/is outside the workspace root/g)).toHaveLength(1); + expect(stderr).toMatch( + /error: Workspace "\.\.[\\/]victim[AB][\\/]packages[\\/][ab]" is outside the workspace root/, + ); + expect(exitCode).toBe(1); + expect(existsSync(join(String(dir), "clone", "packages", "inner", "bun.lock"))).toBe(false); + expect(existsSync(join(String(dir), "clone", "bun.lock"))).toBe(false); + expect(existsSync(join(String(dir), "victimA", "packages", "a", "node_modules"))).toBe(false); + expect(existsSync(join(String(dir), "victimB", "packages", "b", "node_modules"))).toBe(false); + }); + + test("a symlink to a directory inside the root is still a workspace", async () => { + using dir = tempDir("bad-workspace-symlink-inside", { + ...SIBLING_PROJECTS, + "clone/package.json": rootPackageJson(["link"]), + }); + symlinkSync(join(String(dir), "clone", "packages", "inner"), join(String(dir), "clone", "link"), "junction"); + + const { stderr, exitCode } = await runInstall(join(String(dir), "clone")); + + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect(Object.values(install_test_helpers.parseLockfile(join(String(dir), "clone")).workspace_paths)).toEqual([ + "link", + ]); + }); + + test("an absolute path inside the root is still a workspace", async () => { + using dir = tempDir("bad-workspace-absolute-inside", { + ...SIBLING_PROJECTS, + "clone/package.json": ({ root }) => rootPackageJson([join(root, "clone", "packages", "inner")]), + }); + + const { stderr, exitCode } = await runInstall(join(String(dir), "clone")); + + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + expect(Object.values(install_test_helpers.parseLockfile(join(String(dir), "clone")).workspace_paths)).toEqual([ + "packages/inner", + ]); + }); +});