From a437039885577477ef7ae2ff960eb8c41d445c57 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 21:28:45 +0000 Subject: [PATCH 1/8] install: reject workspace members outside the workspace root A `workspaces` entry that resolves outside the root was adopted as a workspace member, and `bun install` then created `/node_modules` inside it. A cloned repository could list its sibling directories, which are the user's other projects, and write into them. `process_names_array` now resolves each candidate member directory against the directory that holds the root package.json and rejects the entry when the result leaves that directory. Listed paths and glob matches both go through the check, so `bun install`, `bun add --filter`, `bun pm` and the yarn, npm and pnpm lockfile migrations all refuse it. --- src/install/lockfile/Package/WorkspaceMap.rs | 55 ++++++++++++- test/cli/install/bad-workspace.test.ts | 83 +++++++++++++++++++- 2 files changed, 133 insertions(+), 5 deletions(-) diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index a971fc83635e..58a97b1f90d6 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -231,6 +231,19 @@ fn workspace_dir_of(abs_package_json_path: &[u8]) -> &[u8] { ) } +/// True when a `workspaces` entry resolves outside the workspace root: a path +/// that climbs out of it (`../sibling`), an absolute path elsewhere on disk, or +/// a different Windows drive (which `relative` spells as an absolute path). +/// +/// `bun install` creates `/node_modules` for every member, so without +/// this check a cloned repository could name its sibling directories (the +/// user's other projects) as members and write into them. +fn escapes_root(root_relative_dir: &[u8]) -> bool { + root_relative_dir == b".." + || root_relative_dir.starts_with(b"../") + || path::is_absolute(root_relative_dir) +} + fn relative_workspace_path<'b>( buf: &'b mut [u8], root_dir: &[u8], @@ -265,7 +278,7 @@ 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(); @@ -293,7 +306,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 +326,22 @@ impl WorkspaceMap { continue; } + if escapes_root(relative_workspace_path( + &mut rel_path_buf.0, + root_dir, + workspace_dir_of(abs_package_json_path), + )) { + log.add_error_fmt( + Some(source), + arr.item_loc(source, i), + format_args!( + "Workspace \"{}\" is outside the workspace root", + BStr::new(input_path) + ), + ); + continue; + } + process_workspace_name(json_cache, abs_package_json_path, log) .map(|entry| (abs_package_json_path, entry)) } @@ -411,7 +440,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. @@ -506,7 +535,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 +563,24 @@ impl WorkspaceMap { cwd, filepath_buf, &[entry_dir, b"package.json"] ) { Some(abs_package_json_path) => { + if escapes_root(relative_workspace_path( + &mut rel_path_buf.0, + root_dir, + workspace_dir_of(abs_package_json_path), + )) { + log.add_error_fmt( + Some(source), + *pattern_loc, + format_args!( + "Workspace \"{}\" is outside the workspace root", + BStr::new(entry_dir) + ), + ); + // One error names the pattern; the rest of its + // matches would repeat it. + break; + } + process_workspace_name(json_cache, abs_package_json_path, log) .map(|entry| (abs_package_json_path, entry)) } diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index 81c5a2af0bf4..88bcc871d21f 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, writeFileSync } from "fs"; import { bunEnv, bunExe, isLinux, isWindows, tempDir, tmpdirSync } from "harness"; import { dirname, join } from "path"; @@ -312,3 +312,84 @@ 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";`, + }; + + async function expectRejected(dir: string, entry: string) { + const { stderr, exitCode } = await runInstall(join(dir, "clone")); + + expect(stderr).toContain(`error: Workspace "${entry}" is outside the workspace root`); + expect(exitCode).toBe(1); + expect(existsSync(join(dir, "victim", "node_modules"))).toBe(false); + expect(existsSync(join(dir, "clone", "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), "../victim"); + }); + + 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. + const { stderr, exitCode } = await runInstall(join(String(dir), "clone")); + + expect(stderr).toMatch(/error: Workspace "\.\.[\\/]victim" is outside the workspace root/); + expect(exitCode).toBe(1); + expect(existsSync(join(String(dir), "victim", "node_modules"))).toBe(false); + expect(existsSync(join(String(dir), "clone", "bun.lock"))).toBe(false); + }); + + 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), join(String(dir), "victim")); + }); + + 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), "packages/../../victim"); + }); + + 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", + ]); + }); +}); From fee2962ed907f59a1ffe618468302cabe34abbd2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 15:17:44 +0000 Subject: [PATCH 2/8] install: reject a workspace member whose real path is outside the root A symlink that the repository ships can name a directory outside the root while the entry stays inside it by its path: `link` with `link -> ../sibling`, or `up/*` with `up -> ..`. Resolve the member directory and the root, and reject the member when it is not beneath the root. A symlink to a directory inside the root is still a member. --- src/install/lockfile/Package/WorkspaceMap.rs | 179 +++++++++++++++---- test/cli/install/bad-workspace.test.ts | 63 +++++-- 2 files changed, 199 insertions(+), 43 deletions(-) diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index 58a97b1f90d6..55e817900083 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::{ @@ -231,19 +232,120 @@ fn workspace_dir_of(abs_package_json_path: &[u8]) -> &[u8] { ) } -/// True when a `workspaces` entry resolves outside the workspace root: a path -/// that climbs out of it (`../sibling`), an absolute path elsewhere on disk, or -/// a different Windows drive (which `relative` spells as an absolute path). -/// -/// `bun install` creates `/node_modules` for every member, so without -/// this check a cloned repository could name its sibling directories (the -/// user's other projects) as members and write into them. +/// A path from the workspace root that leaves it: it climbs out (`../sibling`), or it +/// is absolute, which is how `relative` spells a different Windows drive. fn escapes_root(root_relative_dir: &[u8]) -> bool { root_relative_dir == b".." || root_relative_dir.starts_with(b"../") || 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) +} + +/// The directory of the root package.json. Every workspace member has to lie inside +/// it: `bun install` creates `/node_modules`, 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. +struct WorkspaceRoot<'a> { + dir: &'a [u8], + /// `dir` with its symlinks resolved, on first use. + real_dir: Option>, +} + +impl WorkspaceRoot<'_> { + /// Outside the root by its path alone, so nothing at that path is read: `../sibling`, + /// `packages/../../sibling`, an absolute path elsewhere. + fn rejects_path( + &self, + abs_workspace_dir: &[u8], + entry: &[u8], + log: &mut bun_ast::Log, + source: &bun_ast::Source, + loc: bun_ast::Loc, + ) -> bool { + 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; + } + log.add_error_fmt( + Some(source), + loc, + format_args!( + "Workspace \"{}\" is outside the workspace root", + BStr::new(entry) + ), + ); + true + } + + /// Inside the root by its path and outside it on disk: `link` when the repository + /// ships `link -> ../sibling`, `up/*` when it ships `up -> ..`. The directory has to + /// exist. A directory that cannot be resolved is rejected too. + fn rejects_real_path( + &mut self, + abs_workspace_dir: &[u8], + entry: &[u8], + 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) => { + 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; + } + 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], @@ -283,6 +385,13 @@ impl WorkspaceMap { 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(); @@ -326,19 +435,13 @@ impl WorkspaceMap { continue; } - if escapes_root(relative_workspace_path( - &mut rel_path_buf.0, - root_dir, + if root.rejects_path( workspace_dir_of(abs_package_json_path), - )) { - log.add_error_fmt( - Some(source), - arr.item_loc(source, i), - format_args!( - "Workspace \"{}\" is outside the workspace root", - BStr::new(input_path) - ), - ); + input_path, + log, + source, + arr.item_loc(source, i), + ) { continue; } @@ -411,6 +514,16 @@ impl WorkspaceMap { continue; } + if root.rejects_real_path( + workspace_dir_of(abs_package_json_path), + input_path, + log, + source, + arr.item_loc(source, i), + ) { + continue; + } + let rel_input_path = relative_workspace_path( &mut rel_path_buf.0, root_dir, @@ -563,19 +676,13 @@ impl WorkspaceMap { cwd, filepath_buf, &[entry_dir, b"package.json"] ) { Some(abs_package_json_path) => { - if escapes_root(relative_workspace_path( - &mut rel_path_buf.0, - root_dir, + if root.rejects_path( workspace_dir_of(abs_package_json_path), - )) { - log.add_error_fmt( - Some(source), - *pattern_loc, - format_args!( - "Workspace \"{}\" is outside the workspace root", - BStr::new(entry_dir) - ), - ); + entry_dir, + log, + source, + *pattern_loc, + ) { // One error names the pattern; the rest of its // matches would repeat it. break; @@ -625,6 +732,16 @@ impl WorkspaceMap { continue; } + if root.rejects_real_path( + workspace_dir_of(abs_package_json_path), + entry_dir, + log, + source, + *pattern_loc, + ) { + break; + } + 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 88bcc871d21f..b4735bdd75bb 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 { existsSync, mkdirSync, writeFileSync } from "fs"; +import { existsSync, mkdirSync, symlinkSync, writeFileSync } from "fs"; import { bunEnv, bunExe, isLinux, isWindows, tempDir, tmpdirSync } from "harness"; import { dirname, join } from "path"; @@ -327,10 +327,11 @@ describe.concurrent("workspaces entries outside the workspace root", () => { "clone/packages/inner/index.js": `module.exports = "from the clone";`, }; - async function expectRejected(dir: string, entry: string) { + // The install fails, names the entry, and leaves both projects as they were. + async function expectRejected(dir: string, message: string) { const { stderr, exitCode } = await runInstall(join(dir, "clone")); - expect(stderr).toContain(`error: Workspace "${entry}" is outside the workspace root`); + 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); @@ -342,7 +343,7 @@ describe.concurrent("workspaces entries outside the workspace root", () => { "clone/package.json": rootPackageJson(["packages/*", "../victim"]), }); - await expectRejected(String(dir), "../victim"); + await expectRejected(String(dir), `Workspace "../victim" is outside the workspace root`); }); test("a glob that leaves the root is rejected", async () => { @@ -352,12 +353,7 @@ describe.concurrent("workspaces entries outside the workspace root", () => { }); // The glob walker reports the match with the platform separator. - const { stderr, exitCode } = await runInstall(join(String(dir), "clone")); - - expect(stderr).toMatch(/error: Workspace "\.\.[\\/]victim" is outside the workspace root/); - expect(exitCode).toBe(1); - expect(existsSync(join(String(dir), "victim", "node_modules"))).toBe(false); - expect(existsSync(join(String(dir), "clone", "bun.lock"))).toBe(false); + await expectRejected(String(dir), `Workspace "${join("..", "victim")}" is outside the workspace root`); }); test("an absolute path outside the root is rejected", async () => { @@ -366,7 +362,7 @@ describe.concurrent("workspaces entries outside the workspace root", () => { "clone/package.json": ({ root }) => rootPackageJson(["packages/*", join(root, "victim")]), }); - await expectRejected(String(dir), join(String(dir), "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 () => { @@ -375,7 +371,50 @@ describe.concurrent("workspaces entries outside the workspace root", () => { "clone/package.json": rootPackageJson(["packages/*", "packages/../../victim"]), }); - await expectRejected(String(dir), "packages/../../victim"); + await expectRejected(String(dir), `Workspace "packages/../../victim" is outside the workspace root`); + }); + + // 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}"`, + ); + }); + + 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 () => { From f8eab89c20c06d47ab59582963cbe25e1f88cf83 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 15:22:05 +0000 Subject: [PATCH 3/8] install: shorten the comments in WorkspaceMap --- src/install/lockfile/Package/WorkspaceMap.rs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index 55e817900083..8e8604fda974 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -232,11 +232,10 @@ fn workspace_dir_of(abs_package_json_path: &[u8]) -> &[u8] { ) } -/// A path from the workspace root that leaves it: it climbs out (`../sibling`), or it -/// is absolute, which is how `relative` spells a different Windows drive. 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) } @@ -247,10 +246,7 @@ fn real_dir_path<'b>(abs_dir: &[u8], buf: &'b mut path::PathBuffer) -> bun_sys:: real.map(|real| &*real) } -/// The directory of the root package.json. Every workspace member has to lie inside -/// it: `bun install` creates `/node_modules`, 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. +/// 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. @@ -258,8 +254,6 @@ struct WorkspaceRoot<'a> { } impl WorkspaceRoot<'_> { - /// Outside the root by its path alone, so nothing at that path is read: `../sibling`, - /// `packages/../../sibling`, an absolute path elsewhere. fn rejects_path( &self, abs_workspace_dir: &[u8], @@ -287,9 +281,7 @@ impl WorkspaceRoot<'_> { true } - /// Inside the root by its path and outside it on disk: `link` when the repository - /// ships `link -> ../sibling`, `up/*` when it ships `up -> ..`. The directory has to - /// exist. A directory that cannot be resolved is rejected too. + /// For a symlink that leaves the root: `link -> ../sibling`, or `up/*` with `up -> ..`. fn rejects_real_path( &mut self, abs_workspace_dir: &[u8], @@ -683,8 +675,7 @@ impl WorkspaceMap { source, *pattern_loc, ) { - // One error names the pattern; the rest of its - // matches would repeat it. + // One error per pattern. break; } From c75f467b26e6dfc2c8f9b3df021f9d27f11273e9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 15:42:59 +0000 Subject: [PATCH 4/8] install: report a workspace entry outside the root from inside a member too The upward search for the workspace root parses each ancestor manifest with a private log and treats any error as "not my root". With the new rejection, `bun install` inside a member of a root that lists `../shared` installed that member alone, exit 0, with no message. When the only failure is an entry outside the root, keep the search going: if the current directory is one of the other members, adopt the root. The install then parses the root manifest with the real log and fails with the same error as an install in the root. --- src/install/PackageManager.rs | 11 +++--- src/install/lockfile/Package/WorkspaceMap.rs | 7 ++++ test/cli/install/bad-workspace.test.ts | 35 ++++++++++++++++++-- 3 files changed, 46 insertions(+), 7 deletions(-) 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 8e8604fda974..d480fbacac33 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -18,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; @@ -39,6 +41,7 @@ impl WorkspaceMap { pub(crate) fn init() -> WorkspaceMap { WorkspaceMap { map: Map::default(), + rejected_outside_root: false, } } @@ -434,6 +437,7 @@ impl WorkspaceMap { source, arr.item_loc(source, i), ) { + workspace_names.rejected_outside_root = true; continue; } @@ -513,6 +517,7 @@ impl WorkspaceMap { source, arr.item_loc(source, i), ) { + workspace_names.rejected_outside_root = true; continue; } @@ -675,6 +680,7 @@ impl WorkspaceMap { source, *pattern_loc, ) { + workspace_names.rejected_outside_root = true; // One error per pattern. break; } @@ -730,6 +736,7 @@ impl WorkspaceMap { source, *pattern_loc, ) { + workspace_names.rejected_outside_root = true; break; } diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index b4735bdd75bb..b1968c0c7abc 100644 --- a/test/cli/install/bad-workspace.test.ts +++ b/test/cli/install/bad-workspace.test.ts @@ -328,13 +328,14 @@ describe.concurrent("workspaces entries outside the workspace root", () => { }; // The install fails, names the entry, and leaves both projects as they were. - async function expectRejected(dir: string, message: string) { - const { stderr, exitCode } = await runInstall(join(dir, "clone")); + 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 () => { @@ -401,6 +402,36 @@ describe.concurrent("workspaces entries outside the workspace root", () => { ); }); + // 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"), + ); + }); + test("a symlink to a directory inside the root is still a workspace", async () => { using dir = tempDir("bad-workspace-symlink-inside", { ...SIBLING_PROJECTS, From cd7bca13de6dffe1fc9a4e964930b837c7cddddf Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:17:42 +0000 Subject: [PATCH 5/8] install: decide an absolute workspace entry by its real path, and keep a glob's other matches Two cases the first commits got wrong. An absolute entry can be another spelling of a directory inside the root: the root directory comes from the manifest's file descriptor, so it is resolved, while the entry is not. On macOS an entry under `/tmp` against a root under `/private/tmp` looked like an escape. Let the real path decide an absolute entry, which is what rejects it when it really is outside. A glob stopped enumerating its matches at the first rejected one, so the members after it were never recorded. An install that runs in one of them then found no root of its own and installed that member alone. Keep walking, and report one error per pattern. --- src/install/lockfile/Package/WorkspaceMap.rs | 100 +++++++++++++------ test/cli/install/bad-workspace.test.ts | 47 +++++++++ 2 files changed, 118 insertions(+), 29 deletions(-) diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index d480fbacac33..61b0f98f7a5b 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -256,15 +256,29 @@ struct WorkspaceRoot<'a> { real_dir: Option>, } +/// How a rejection is reported. A glob pattern reports its first rejected match and +/// stays `Silent` for the rest, which would repeat the same error. +#[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 { + // An absolute entry can be another spelling of a directory inside the root: a + // symlinked ancestor (`/tmp` on macOS), an automount. `rejects_real_path` decides it. + 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, @@ -273,14 +287,16 @@ impl WorkspaceRoot<'_> { )) { return false; } - log.add_error_fmt( - Some(source), - loc, - format_args!( - "Workspace \"{}\" is outside the workspace root", - BStr::new(entry) - ), - ); + if report == Report::Error { + log.add_error_fmt( + Some(source), + loc, + format_args!( + "Workspace \"{}\" is outside the workspace root", + BStr::new(entry) + ), + ); + } true } @@ -289,6 +305,7 @@ impl WorkspaceRoot<'_> { &mut self, abs_workspace_dir: &[u8], entry: &[u8], + report: Report, log: &mut bun_ast::Log, source: &bun_ast::Source, loc: bun_ast::Loc, @@ -308,15 +325,17 @@ impl WorkspaceRoot<'_> { let (real_root, real_dir) = match resolved { Ok(resolved) => resolved, Err(err) => { - log.add_error_fmt( - Some(source), - loc, - format_args!( - "{} resolving the directory of workspace package \"{}\"", - crate::Error::from(err).name(), - BStr::new(entry), - ), - ); + 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; } }; @@ -328,15 +347,30 @@ impl WorkspaceRoot<'_> { )) { return false; } - 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), - ), - ); + if report == Report::Error { + // The resolved path only when it is not the entry's own: `..` spellings and an + // absolute entry outside the root resolve to themselves. + 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 } } @@ -433,6 +467,7 @@ impl WorkspaceMap { if root.rejects_path( workspace_dir_of(abs_package_json_path), input_path, + Report::Error, log, source, arr.item_loc(source, i), @@ -513,6 +548,7 @@ impl WorkspaceMap { if root.rejects_real_path( workspace_dir_of(abs_package_json_path), input_path, + Report::Error, log, source, arr.item_loc(source, i), @@ -613,6 +649,9 @@ impl WorkspaceMap { return Err(crate::Error::GlobError); } + // The other matches of this pattern are still members: an install that runs + // in one of them has to find it (`PackageManager::init`). + let mut report = Report::Error; 'next_match: loop { let matched_path_owned = match iter.next()? { Ok(Some(r)) => r, @@ -676,13 +715,14 @@ impl WorkspaceMap { if root.rejects_path( workspace_dir_of(abs_package_json_path), entry_dir, + report, log, source, *pattern_loc, ) { workspace_names.rejected_outside_root = true; - // One error per pattern. - break; + report = Report::Silent; + continue; } process_workspace_name(json_cache, abs_package_json_path, log) @@ -732,12 +772,14 @@ impl WorkspaceMap { 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; - break; + report = Report::Silent; + continue; } let workspace_path: &[u8] = relative_workspace_path( diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index b1968c0c7abc..290a98eb0517 100644 --- a/test/cli/install/bad-workspace.test.ts +++ b/test/cli/install/bad-workspace.test.ts @@ -432,6 +432,53 @@ describe.concurrent("workspaces entries outside the workspace root", () => { ); }); + // 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", { + "victimA/packages/a/package.json": JSON.stringify({ name: "victim-a-pkg" }), + "victimB/packages/b/package.json": JSON.stringify({ name: "victim-b-pkg" }), + "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", "node_modules"))).toBe(false); + expect(existsSync(join(String(dir), "victimB", "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, From e25bafb19a07a254dc6bbf4a3eb41cd4619a4f6a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:20:29 +0000 Subject: [PATCH 6/8] install: one-line comments in WorkspaceMap --- src/install/lockfile/Package/WorkspaceMap.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index 61b0f98f7a5b..15edd8bef198 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -256,8 +256,7 @@ struct WorkspaceRoot<'a> { real_dir: Option>, } -/// How a rejection is reported. A glob pattern reports its first rejected match and -/// stays `Silent` for the rest, which would repeat the same error. +/// A glob reports its first rejected match. The rest would repeat it. #[derive(Clone, Copy, PartialEq)] enum Report { Error, @@ -274,8 +273,7 @@ impl WorkspaceRoot<'_> { source: &bun_ast::Source, loc: bun_ast::Loc, ) -> bool { - // An absolute entry can be another spelling of a directory inside the root: a - // symlinked ancestor (`/tmp` on macOS), an automount. `rejects_real_path` decides it. + // Could be another spelling of a directory inside the root (`/tmp` on macOS). if path::is_absolute(entry) { return false; } @@ -348,8 +346,7 @@ impl WorkspaceRoot<'_> { return false; } if report == Report::Error { - // The resolved path only when it is not the entry's own: `..` spellings and an - // absolute entry outside the root resolve to themselves. + // A `..` spelling, or an absolute entry outside the root, resolves to itself. if real_dir == abs_workspace_dir { log.add_error_fmt( Some(source), @@ -649,8 +646,7 @@ impl WorkspaceMap { return Err(crate::Error::GlobError); } - // The other matches of this pattern are still members: an install that runs - // in one of them has to find it (`PackageManager::init`). + // 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()? { From 154c63772dbe0e0574852f88d553a4e16119daaf Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:34:54 +0000 Subject: [PATCH 7/8] test(install): cover the backslash and pnpm-workspace.yaml forms, and check the directories a glob would write The glob case asserted on `victimA/node_modules`, which no install writes: the members are `victimA/packages/a` and `victimB/packages/b`. Give them a dependency and assert on their own `node_modules`, which stock bun creates. --- test/cli/install/bad-workspace.test.ts | 54 +++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index 290a98eb0517..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 { existsSync, mkdirSync, symlinkSync, 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"; @@ -375,6 +375,48 @@ describe.concurrent("workspaces entries outside the workspace root", () => { 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 () => { @@ -459,8 +501,10 @@ describe.concurrent("workspaces entries outside the workspace root", () => { // 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", { - "victimA/packages/a/package.json": JSON.stringify({ name: "victim-a-pkg" }), - "victimB/packages/b/package.json": JSON.stringify({ name: "victim-b-pkg" }), + // 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" }), }); @@ -475,8 +519,8 @@ describe.concurrent("workspaces entries 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", "node_modules"))).toBe(false); - expect(existsSync(join(String(dir), "victimB", "node_modules"))).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 () => { From 534dab31df6ad010f807ea888731b31347250ffd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:26:07 +0000 Subject: [PATCH 8/8] ci: retrigger