Skip to content

install: synchronize trusted dependency lookups in the isolated installer - #31245

Closed
Jarred-Sumner wants to merge 5 commits into
mainfrom
claude/isolated-trusted-dep-race
Closed

Jarred-Sumner wants to merge 5 commits into
mainfrom
claude/isolated-trusted-dep-race

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

In the isolated installer, Task::run() reads lockfile.trusted_dependencies from concurrent task threads (the trust check in Step::RunPreinstall and the node-gyp heuristic inside Scripts::get_list) without taking trusted_dependencies_mutex, while another task may be inserting into the same map under that mutex — an insert can reallocate the map's backing storage out from under the readers. Both reads now take the existing mutex (scoped so the guard is dropped before the writer reacquires it), and the SAFETY comments that claimed task threads never touch the map are corrected.

No regression test: the race requires a specific interleaving of an insert-triggered reallocation with a concurrent read across thread-pool tasks, which cannot be exercised deterministically from a JS test. Verified with test/cli/install/bun-install-lifecycle-scripts.test.ts + test/cli/install/isolated-install.test.ts (149 pass / 0 fail).

Follow-up requested in #31218 (comment)

@robobun

robobun commented May 23, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 9:23 PM PT - May 28th, 2026

❌ @Jarred-Sumner, your commit 8ab020b has some failures in Build #58771 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 31245

That installs a local version of the PR into your bun-31245 executable, so you can run:

bun-31245 --bun

@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This PR enforces mutex-serialized reads of lockfile.trusted_dependencies in preinstall tasks and threads a precomputed trusted boolean into Scripts::get_list and its callers so node-gyp rebuild decisions use that value rather than querying the lockfile inside get_list.

Changes

Trusted Dependencies Concurrency Fix

Layer / File(s) Summary
Scripts trust propagation
src/install/lockfile/Package/Scripts.rs, src/install/PackageInstaller.rs, src/runtime/cli/pm_trusted_command.rs
Scripts::get_list now accepts a trusted: bool parameter. Callers compute trusted_for_node_gyp via lockfile.has_trusted_dependency(...) and pass it into get_list so the node-gyp rebuild heuristic uses the precomputed flag; postinstall script insertion now uses postinstall.slice(...).
Concurrency contract and RunPreinstall mutex serialization
src/install/isolated_install/Installer.rs
Documentation requires task-thread projections into lockfile.trusted_dependencies to hold trusted_dependencies_mutex. Step::RunPreinstall now computes trust under that mutex (including trusted_for_node_gyp) and releases the lock before calling pkg_scripts.get_list(...). Comments near the trusted_dependencies insertion are adjusted to describe the serialization and borrowing boundaries.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: synchronizing trusted dependency lookups to fix a data race in the isolated installer, which is the primary objective of this PR.
Description check ✅ Passed The description covers both required template sections: it explains what the PR does (fixes a data race in trusted dependency lookups) and how it was verified (with specific test suites showing 149 pass/0 fail).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@robobun

robobun commented May 23, 2026

Copy link
Copy Markdown
Collaborator

I had the same fix staged when this went up, so no competing PR — two things on farm/ad8e5e20/isolated-trusted-deps-race that might be useful here:

  • 0cc4f97 adds a regression test for --trust under linker = "isolated" (postinstall runs + trustedDependencies written back to package.json and bun.lock). Nothing currently covers that combination, and it's green against either fix — feel free to cherry-pick it into this PR.
  • 215b293 is an alternative shape in case you'd rather not hold the mutex across get_list's filesystem work: task threads only record the names (the existing trusted_deps_to_add_to_package_json push under the mutex), and the lockfile fold happens on the main thread after the task drain, so the read path needs no lock. Take it or leave it — this PR closes the race either way.

Comment thread src/install/lockfile/Package/Scripts.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All my earlier comments are addressed and I found nothing further, but since this rewrites the mutex/aliasing discipline around an unsafe write to lockfile.trusted_dependencies (which gates lifecycle-script execution), it's worth a human pass on the final lock scoping and SAFETY comments.

Extended reasoning...

Overview

The PR closes a data race in the isolated installer where Task::run() read lockfile.trusted_dependencies on thread-pool workers while another task could insert into the same map under trusted_dependencies_mutex. The fix (after iteration on this PR) precomputes the trust decision under the mutex and threads it into Scripts::get_list as a new trusted: bool parameter, so the lock is held only for the hashmap lookup and not across the binding.gyp stat / package.json parse. Four call sites are updated (isolated installer, hoisted PackageInstaller, bun pm trust, bun pm untrusted), the SAFETY comments on the writer's unsafe block are rewritten, and a pre-existing preinstall→postinstall copy-paste bug in get_script_entries is fixed as a drive-by.

Security risks

trusted_dependencies is the gate that decides which packages are allowed to run install/postinstall scripts. The change does not alter the trust policy — each caller now passes lockfile.has_trusted_dependency(folder_name, folder_name, resolution), which is exactly what get_list previously computed inline — so there is no widening of which packages are trusted. The drive-by postinstall fix means a script that was previously (incorrectly) dropped will now run, but only for packages already in trustedDependencies, which is the intended behavior. I don't see an injection or privilege-escalation vector, but because the consequence of a mistake here is "an untrusted package's lifecycle script runs," the bar for review is higher than a typical refactor.

Level of scrutiny

High. This is hand-rolled concurrency in unsafe Rust: a &mut is formed via addr_of_mut! on a field of a struct that other threads concurrently hold & to, with correctness resting entirely on the mutex discipline and the SAFETY comments this PR rewrites. The lock is non-reentrant and the guard must be dropped before the writer reacquires it in the same step — the new code does this correctly via block-scoped guards, but it's exactly the kind of invariant a human reviewer should sanity-check. The author also explicitly deferred a related pre-existing race (the unguarded extraction-worker read in extract_tarball.rs) to a follow-up, which is a reasonable scoping call but worth a maintainer's nod.

Other factors

All four of my earlier inline comments (over-wide lock scope, the extraction-worker race, the preinstall/postinstall typo, and stale lock-discipline comments) were addressed in 9767a69 / 4bfefdf / 5457322, and the latest bug-hunting pass found nothing. The existing lifecycle-script and isolated-install test suites pass per the PR description; no new regression test was added (the race isn't deterministically reproducible from JS), though robobun offered a cherry-pickable --trust + isolated-linker test on a side branch that the author may or may not want to pull in. Net: the change looks correct to me, but unsafe concurrency around the trust gate is not something I'll auto-approve.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/install/PackageInstaller.rs (1)

2192-2215: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don’t recompute trusted_for_node_gyp from the lockfile alone.

Line 2204 drops trust that exists only in trusted_dependencies_from_update_requests or summary.added_trusted_dependencies. In those paths this helper runs before lockfile.trusted_dependencies is updated, so a binding.gyp-only package can return None, skip the synthetic rebuild, and never reach the later write-back gated by if self.enqueue_lifecycle_scripts(...).

Suggested refactor
 fn enqueue_lifecycle_scripts(
     &mut self,
     folder_name: &[u8],
     log_level: Options::LogLevel,
     package_path: &mut bun_paths::AutoAbsPath,
     package_id: PackageID,
     optional: bool,
     resolution: &Resolution,
+    trusted_for_node_gyp: bool,
 ) -> bool {
     let mut scripts: PackageScripts =
         self.lockfile().packages.items_scripts()[package_id as usize];
-    let trusted_for_node_gyp =
-        self.lockfile()
-            .has_trusted_dependency(folder_name, folder_name, resolution);
     let log = self.manager().log_mut();

Callers should pass an effective value that includes newly trusted in-memory state, e.g. newly_trusted || self.lockfile().has_trusted_dependency(folder_name, folder_name, resolution).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/install/PackageInstaller.rs` around lines 2192 - 2215, The function
enqueue_lifecycle_scripts currently recomputes trusted_for_node_gyp from
lockfile().has_trusted_dependency which misses in-memory newly trusted state;
change the function signature to accept a trusted_for_node_gyp: bool parameter
(use that value instead of recomputing) and update all callers to pass the
effective value (e.g. newly_trusted ||
self.lockfile().has_trusted_dependency(folder_name, folder_name, resolution)) so
packages trusted only in trusted_dependencies_from_update_requests or
summary.added_trusted_dependencies are honored.
src/install/isolated_install/Installer.rs (1)

1694-1709: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve update-request trust in trusted_for_node_gyp.

Line 1698 only consults lockfile.trusted_dependencies. When trust comes from trusted_dependencies_from_update_requests, this stays false until after get_list() runs, so a binding.gyp-only package never gets the synthetic rebuild script and the later write-back is skipped because it lives under if let Some(list) = scripts_list).

Proposed fix
-                        let trusted_for_node_gyp = {
-                            let _lock = installer.trusted_dependencies_mutex.lock_guard();
-                            lockfile.has_trusted_dependency(folder_name, folder_name, &pkg_res)
-                        };
+                        let trusted_for_node_gyp = if is_trusted_through_update_request {
+                            true
+                        } else {
+                            let _lock = installer.trusted_dependencies_mutex.lock_guard();
+                            lockfile.has_trusted_dependency(folder_name, folder_name, &pkg_res)
+                        };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/install/isolated_install/Installer.rs` around lines 1694 - 1709, The
trust decision for node-gyp should include update-request-derived trust as well
as lockfile.trusted_dependencies: when computing trusted_for_node_gyp (before
calling pkg_scripts.get_list), acquire the installer.trusted_dependencies_mutex
lock and set trusted_for_node_gyp to true if either
lockfile.has_trusted_dependency(folder_name, folder_name, &pkg_res) is true or
the lockfile's trusted_dependencies_from_update_requests contains the
folder_name (i.e., use a logical OR of both sources); keep the lock around this
check so get_list sees the correct trust value.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/install/isolated_install/Installer.rs`:
- Around line 1694-1709: The trust decision for node-gyp should include
update-request-derived trust as well as lockfile.trusted_dependencies: when
computing trusted_for_node_gyp (before calling pkg_scripts.get_list), acquire
the installer.trusted_dependencies_mutex lock and set trusted_for_node_gyp to
true if either lockfile.has_trusted_dependency(folder_name, folder_name,
&pkg_res) is true or the lockfile's trusted_dependencies_from_update_requests
contains the folder_name (i.e., use a logical OR of both sources); keep the lock
around this check so get_list sees the correct trust value.

In `@src/install/PackageInstaller.rs`:
- Around line 2192-2215: The function enqueue_lifecycle_scripts currently
recomputes trusted_for_node_gyp from lockfile().has_trusted_dependency which
misses in-memory newly trusted state; change the function signature to accept a
trusted_for_node_gyp: bool parameter (use that value instead of recomputing) and
update all callers to pass the effective value (e.g. newly_trusted ||
self.lockfile().has_trusted_dependency(folder_name, folder_name, resolution)) so
packages trusted only in trusted_dependencies_from_update_requests or
summary.added_trusted_dependencies are honored.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 12050b9a-f3c3-4bd1-87d1-6e65195e7733

📥 Commits

Reviewing files that changed from the base of the PR and between 5457322 and 73b54c8.

📒 Files selected for processing (3)
  • src/install/PackageInstaller.rs
  • src/install/isolated_install/Installer.rs
  • src/runtime/cli/pm_trusted_command.rs
💤 Files with no reviewable changes (1)
  • src/runtime/cli/pm_trusted_command.rs

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delete your slop comments.

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delete your slop comments.

@Jarred-Sumner
Jarred-Sumner force-pushed the claude/isolated-trusted-dep-race branch 3 times, most recently from 73b54c8 to 8ab020b Compare May 28, 2026 21:19
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator Author

The single failing check is the darwin 14 aarch64 test-bun job (1 of 286), where test/js/node/async_hooks/AsyncLocalStorage-tracking.test.ts segfaults inside the async-context-fs-watch.js subprocess. That test only exercises fs.watch + AsyncLocalStorage on macOS and doesn't run bun install, so it isn't caused by this diff (which only touches the install/trusted-deps paths); it's the known macOS FSEvents teardown crash (#30758), and the build was on a base from May 22. Rebased the branch onto current main (clean, no conflicts) and pushed to get a fresh CI run; test/cli/install/isolated-install.test.ts and test/cli/install/bun-install-lifecycle-scripts.test.ts pass locally with the debug build.

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator Author

Adjacent, not a duplicate: #33646 (just opened) fixes a different concurrency bug in isolated_install/Installer.rs — each peer variant of a patched package was rebuilding the shared content-addressed patch cache dir, deleting it under earlier variants' in-flight hardlinks (#28147). Distinct from the trusted-dependency lookup race here. Cross-linking so a reviewer of either sees the isolated-installer race family.

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator Author

This is Claude (an AI assistant) writing on Jarred's behalf.

Included in #44968, in a different form: task threads write nothing; the names are recorded on the main thread after the wait.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants