Skip to content

fix(lockfile): fix installs when pnpm-lock.yaml is a symlink - #13075

Merged
zkochan merged 7 commits into
pnpm:mainfrom
tianrking:agent/allow-symlinked-lockfile-reads
Jul 17, 2026
Merged

zkochan merged 7 commits into
pnpm:mainfrom
tianrking:agent/allow-symlinked-lockfile-reads

Conversation

@tianrking

@tianrking tianrking commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

pnpm install fails with ERR_PNPM_LOCKFILE_IS_SYMLINK when pnpm-lock.yaml is a symlink, breaking build sandboxes (Bazel, Nix) that stage the lockfile that way. This restores those workflows while keeping the protection that matters.

Two halves, from opposite directions:

  • Reads follow symlinks again. That guard never protected anything. readWantedLockfile reads the same file with a plain readFile and has always followed the link, so refusing it on the env-document read only broke sandboxes. A hostile repo can commit a hostile lockfile as a plain file regardless — lockfile content is untrusted either way. The guard arrived as a "consider this too" aside alongside the genuine write fix in fix: switch pacquet to project package manager version #12821.
  • An unchanged lockfile is no longer rewritten. This is what actually fixes the reported command. tryFrozenInstall rewrites an already up-to-date pnpm-lock.yaml, so --frozen-lockfile --lockfile-only died on the write, not the read. Skipping a byte-identical rewrite means a frozen install never writes at all — and it's a small win for every frozen install, symlink or not.

Writing a changed lockfile through a symlink is still refused: write-file-atomic resolves the target with realpath, so writing through one redirects onto any file the user can write.

The same clobber is now closed in pacquet, where save_value_to_path wrote the wanted lockfile with fs::write — following symlinks, with no guard at all. It now refuses a symlinked lockfile and writes atomically.

Fixes #13073

Squash Commit Body

Allowing symlinked reads did not fix pnpm/pnpm#13073. The reported
`--frozen-lockfile --lockfile-only` install fails on the *write*:
tryFrozenInstall rewrites an already up-to-date pnpm-lock.yaml, and the
write path refuses a symlink before it writes.

Skip a byte-identical rewrite instead. An up-to-date install -- every
frozen run -- no longer touches the lockfile at all, so one staged as a
symlink (Bazel, Nix) installs cleanly, while a write that changes bytes
still refuses the symlink: write-file-atomic resolves the target with
realpath, so writing through one redirects onto any file the user can
write.

Reading through a symlink stays allowed. That guard never protected
anything: readWantedLockfile reads the same file with a plain readFile and
has always followed the link, so refusing it on the env-document read only
broke sandboxes. A hostile repo can commit a hostile lockfile as a plain
file regardless -- lockfile content is untrusted either way. The guard
arrived as a "consider this too" aside alongside the write fix in
pnpm/pnpm#12821.

Close the same clobber in pacquet: save_value_to_path wrote the wanted
lockfile with fs::write, which follows symlinks and had no guard. It now
refuses a symlinked lockfile and writes atomically, carrying the target's
mode across the rename and flushing before it, matching write-file-atomic.
Share the symlink guard between both write paths rather than duplicate it.

Add install-level regression coverage for the reported command; the
existing unit tests passed while the bug remained.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.
  • Updated the documentation if needed.

Notes for reviewers

  • The error message changed. Refusing to read or write symlinked lockfile → Refusing to write symlinked lockfile, since only writes refuse now. ERR_PNPM_LOCKFILE_IS_SYMLINK is unchanged, but it is a released string that tooling could match on.
  • pacquet's main-lockfile write is now atomic (temp + rename), where it previously used fs::write. The shared writer carries the target's mode across the rename and flushes before it — fs::write truncated in place and kept the mode, so a naive rename would have silently reset pnpm-lock.yaml to the umask default. Both mirror write-file-atomic. One consequence of rename semantics: writing a read-only lockfile now succeeds, as it already does in the TypeScript CLI.
  • Test coverage. The install-level tests are the ones that matter: the previous unit tests passed while the reported command stayed broken. frozen lockfile-only install succeeds when pnpm-lock.yaml is a symlink reproduces the issue and fails without this change. Atomicity itself is not directly unit-testable; the write now goes through the writer that already has error-path and temp-cleanup coverage.

Written by an agent (Claude Code, claude-opus-4-8).


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes
    • Symlinked pnpm-lock.yaml files no longer fail to read, including --frozen-lockfile installs when no lockfile changes are required.
    • Lockfile writes remain safe: symlinked lockfile targets are updated only when the effective content is unchanged; changed content is still blocked.
    • Improved env-metadata preservation and idempotent lockfile updates (skips rewrites when byte-identical, with BOM/CRLF normalization).
  • Tests
    • Updated and expanded cross-platform coverage for symlink behavior, env document extraction, and lockfile read/write idempotency.

@tianrking
tianrking requested a review from zkochan as a code owner July 16, 2026 10:40
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jul 16, 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

Walkthrough

Lockfile reads now follow symlinks for pnpm-lock.yaml. Unchanged symlinked lockfiles are not rewritten, while writes requiring changed content remain rejected and use atomic replacement for regular files.

Changes

Symlinked lockfile handling

Layer / File(s) Summary
Symlink-following read paths
pnpm/crates/lockfile/src/env_lockfile.rs, pnpm11/lockfile/fs/src/yamlDocuments.ts
Rust and TypeScript readers follow symlinks and extract the leading environment YAML document.
Write orchestration and atomic safety
pnpm11/lockfile/fs/src/write.ts, pnpm/crates/lockfile/src/save_lockfile.rs
Writes preserve environment documents, skip byte-identical output, reject changed writes through symlinks, and atomically replace regular files while preserving permissions.
Behavior validation and release metadata
pnpm/crates/lockfile/src/*/tests.rs, pnpm11/lockfile/fs/test/*, pnpm11/installing/deps-installer/test/lockfile.ts, .changeset/allow-symlinked-lockfile-reads.md
Tests cover successful reads, unchanged symlinked writes, rejected changed writes, atomic-write properties, and the patch release declaration.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant pnpmCLI
  participant lockfileReader
  participant lockfileWriter
  participant filesystem
  pnpmCLI->>lockfileReader: read pnpm-lock.yaml
  lockfileReader->>filesystem: follow symlink and load content
  filesystem-->>lockfileReader: lockfile content
  pnpmCLI->>lockfileWriter: save computed lockfile
  lockfileWriter->>lockfileWriter: compare resulting bytes
  alt content unchanged
    lockfileWriter-->>pnpmCLI: skip write
  else content changed
    lockfileWriter->>filesystem: reject symlink or atomically replace regular file
    filesystem-->>lockfileWriter: write result
    lockfileWriter-->>pnpmCLI: save result
  end
Loading

Possibly related issues

  • pnpm/pnpm#11633 — Supports the lockfile-loading and writer-parity objectives for pnpm and pacquet.
  • pnpm/pnpm#13073 — Allows symlinked lockfile reads while continuing to reject changed writes through symlinks.

Suggested labels: product: pnpm@11, product: pacquet

Suggested reviewers: zkochan

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@greptile-apps

greptile-apps Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge — reads following symlinks introduces no new attack surface since lockfile content is untrusted regardless, and changed-content writes still refuse symlinks via a guard that rename() semantics make impossible to bypass.

Both stacks implement the same logic with matching behavior, the idempotency comparison is correct for LF and CRLF files alike, the double symlink guard in writeWantedLockfileAtomic is sound, and the PR includes integration-level tests that reproduce the exact reported failure and fail without the fix.

No files require special attention.

Reviews (8): Last reviewed commit: "docs(lockfile): let the tests carry the ..." | Re-trigger Greptile

@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.

🧹 Nitpick comments (1)
pnpm11/lockfile/fs/src/yamlDocuments.ts (1)

21-34: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the unused filePath parameter from the internal helper.

The filePath parameter is passed into streamReadFirstYamlDocumentWithOpen, but it is not used anywhere within the function body. The path is already securely captured by the openFile closure from the outer scope. Removing it simplifies the helper's signature.

♻️ Proposed refactor
 export async function streamReadFirstYamlDocument (filePath: string, readBufferSize = READ_BUFFER_SIZE): Promise<string | null> {
-  return streamReadFirstYamlDocumentWithOpen(filePath, readBufferSize, () => open(filePath, constants.O_RDONLY))
+  return streamReadFirstYamlDocumentWithOpen(readBufferSize, () => open(filePath, constants.O_RDONLY))
 }
 
 export async function streamReadFirstYamlDocumentNoFollow (filePath: string, readBufferSize = READ_BUFFER_SIZE): Promise<string | null> {
-  return streamReadFirstYamlDocumentWithOpen(filePath, readBufferSize, () => openLockfileNoFollow(filePath))
+  return streamReadFirstYamlDocumentWithOpen(readBufferSize, () => openLockfileNoFollow(filePath))
 }
 
-async function streamReadFirstYamlDocumentWithOpen (filePath: string, readBufferSize: number, openFile: () => Promise<FileHandle>): Promise<string | null> {
+async function streamReadFirstYamlDocumentWithOpen (readBufferSize: number, openFile: () => Promise<FileHandle>): Promise<string | null> {
   let fileHandle: FileHandle | undefined
🤖 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 `@pnpm11/lockfile/fs/src/yamlDocuments.ts` around lines 21 - 34, Remove the
unused filePath parameter from streamReadFirstYamlDocumentWithOpen and update
both streamReadFirstYamlDocument and streamReadFirstYamlDocumentNoFollow call
sites to pass only readBufferSize and the openFile callback.
🤖 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.

Nitpick comments:
In `@pnpm11/lockfile/fs/src/yamlDocuments.ts`:
- Around line 21-34: Remove the unused filePath parameter from
streamReadFirstYamlDocumentWithOpen and update both streamReadFirstYamlDocument
and streamReadFirstYamlDocumentNoFollow call sites to pass only readBufferSize
and the openFile callback.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ee5228b2-3228-4c69-9536-d319be1ca685

📥 Commits

Reviewing files that changed from the base of the PR and between b0456c6 and 88159e6.

📒 Files selected for processing (7)
  • .changeset/allow-symlinked-lockfile-reads.md
  • pnpm/crates/lockfile/src/env_lockfile.rs
  • pnpm/crates/lockfile/src/env_lockfile/tests.rs
  • pnpm11/lockfile/fs/src/write.ts
  • pnpm11/lockfile/fs/src/yamlDocuments.ts
  • pnpm11/lockfile/fs/test/envLockfile.test.ts
  • pnpm11/lockfile/fs/test/yamlDocuments.test.ts

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 16, 2026
@codecov-commenter

codecov-commenter commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.49%. Comparing base (e4d7a4a) to head (d2a62ae).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/lockfile/src/save_lockfile.rs 94.28% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13075      +/-   ##
==========================================
- Coverage   85.59%   85.49%   -0.11%     
==========================================
  Files         499      501       +2     
  Lines       79945    80508     +563     
==========================================
+ Hits        68431    68831     +400     
- Misses      11514    11677     +163     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 12ff792e74aa

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.558 ± 0.190 2.398 2.857 1.64 ± 0.21
pacquet@main 2.491 ± 0.136 2.338 2.762 1.60 ± 0.19
pnpr@HEAD 1.561 ± 0.165 1.361 1.811 1.00
pnpr@main 1.627 ± 0.197 1.382 1.912 1.04 ± 0.17
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.5583370798,
      "stddev": 0.18955050430998874,
      "median": 2.4522256571999996,
      "user": 1.67801112,
      "system": 1.3683564999999998,
      "min": 2.3983393157,
      "max": 2.8566800747,
      "times": [
        2.4284927787,
        2.4130195117,
        2.5552579167,
        2.8566800747,
        2.8289994427,
        2.4759585357,
        2.4117052477,
        2.3983393157,
        2.4280163227,
        2.7869016517
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.4907915808999994,
      "stddev": 0.13561195877200277,
      "median": 2.4444739686999997,
      "user": 1.64966382,
      "system": 1.4015752,
      "min": 2.3376497367,
      "max": 2.7622717727,
      "times": [
        2.7622717727,
        2.5112157117000002,
        2.4034798897,
        2.3376497367,
        2.4344127007,
        2.3986284187,
        2.4711390537,
        2.7001705876999997,
        2.4363506867,
        2.4525972507
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.5614867943,
      "stddev": 0.16511785712532362,
      "median": 1.5395933412,
      "user": 1.1869633199999998,
      "system": 1.2201746,
      "min": 1.3614348836999999,
      "max": 1.8109792697,
      "times": [
        1.7538984917,
        1.8109792697,
        1.5877380127,
        1.4309023406999999,
        1.3712460257,
        1.7380009947000001,
        1.4490371576999999,
        1.4914486697,
        1.3614348836999999,
        1.6201820967
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.6267049795,
      "stddev": 0.19690466247452879,
      "median": 1.6149781092,
      "user": 1.34161872,
      "system": 1.409887,
      "min": 1.3819812276999999,
      "max": 1.9122585317,
      "times": [
        1.7933220817,
        1.6269630476999999,
        1.6029931707,
        1.5894174426999998,
        1.3819812276999999,
        1.9122585317,
        1.8651416447,
        1.3948420437,
        1.3835738777,
        1.7165567267
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 285.6 ± 22.7 263.8 334.1 1.07 ± 0.15
pacquet@main 295.2 ± 52.0 221.5 394.4 1.10 ± 0.23
pnpr@HEAD 319.7 ± 31.9 279.1 391.3 1.20 ± 0.19
pnpr@main 267.2 ± 31.8 239.3 342.9 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.28555452588,
      "stddev": 0.02265676537477688,
      "median": 0.27743723838,
      "user": 0.24335069999999998,
      "system": 0.55904712,
      "min": 0.26383184088,
      "max": 0.33406477488,
      "times": [
        0.30466635888000004,
        0.27180728788,
        0.27552191888,
        0.26641644888,
        0.28602196188,
        0.26781036688000004,
        0.26383184088,
        0.30605174188,
        0.33406477488,
        0.27935255788
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.29515050668000004,
      "stddev": 0.05197603887696918,
      "median": 0.28232157238,
      "user": 0.26519339999999997,
      "system": 0.7772986199999999,
      "min": 0.22152748088000002,
      "max": 0.39436537588000004,
      "times": [
        0.22152748088000002,
        0.27488633488,
        0.24469506788,
        0.33890380988,
        0.26131696488,
        0.30786153488,
        0.39436537588000004,
        0.34412855888000005,
        0.28975680988,
        0.27406312888
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.3196837014800001,
      "stddev": 0.03191558825278512,
      "median": 0.31500009888,
      "user": 0.25991050000000004,
      "system": 0.5895217199999999,
      "min": 0.27908657888,
      "max": 0.39132372988,
      "times": [
        0.39132372988,
        0.31843789888,
        0.34869077288,
        0.33286578188000004,
        0.31805393788,
        0.31194625988,
        0.29887531588,
        0.29818062088,
        0.29937611788,
        0.27908657888
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.26721680898,
      "stddev": 0.031830984463567566,
      "median": 0.25771423888,
      "user": 0.2326756,
      "system": 0.6565432199999999,
      "min": 0.23925333188,
      "max": 0.34287805888,
      "times": [
        0.24351079288000002,
        0.24425690388000001,
        0.25867070088,
        0.25675777688,
        0.23925333188,
        0.27925700788,
        0.25133799188,
        0.29690813888,
        0.34287805888,
        0.25933738588
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.873 ± 0.121 2.727 3.100 1.80 ± 0.18
pacquet@main 2.899 ± 0.133 2.755 3.190 1.81 ± 0.18
pnpr@HEAD 1.599 ± 0.141 1.422 1.813 1.00
pnpr@main 1.673 ± 0.184 1.441 1.909 1.05 ± 0.15
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.87295957826,
      "stddev": 0.12083133190964608,
      "median": 2.86423707606,
      "user": 2.00128082,
      "system": 1.5486594,
      "min": 2.7265560485600004,
      "max": 3.0997822465600002,
      "times": [
        2.8278643525600002,
        2.8608841345600005,
        2.86759001756,
        3.0997822465600002,
        3.0375243475600002,
        2.90370103956,
        2.8917058675600003,
        2.73422288656,
        2.7265560485600004,
        2.77976484156
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.8992348990600005,
      "stddev": 0.13283636146469427,
      "median": 2.86201180906,
      "user": 2.0188763199999995,
      "system": 1.5337503,
      "min": 2.7546364585600003,
      "max": 3.1904429595600003,
      "times": [
        2.8189343705600005,
        2.7800304615600004,
        2.8183043475600003,
        2.97556909656,
        2.8182528805600002,
        2.9050892475600003,
        2.7546364585600003,
        3.1904429595600003,
        3.01390676356,
        2.91718240456
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.59858092936,
      "stddev": 0.14059764858371218,
      "median": 1.60018715556,
      "user": 1.31990682,
      "system": 1.4884903999999999,
      "min": 1.42189635156,
      "max": 1.81279559156,
      "times": [
        1.47940768056,
        1.6044244485599999,
        1.6168744555599999,
        1.81279559156,
        1.5959498625600002,
        1.49492490056,
        1.70588094156,
        1.42189635156,
        1.45023147156,
        1.8034235895600002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.6734244532600002,
      "stddev": 0.1842550285223946,
      "median": 1.67698522906,
      "user": 1.26548402,
      "system": 1.4425801,
      "min": 1.44123855156,
      "max": 1.90943856856,
      "times": [
        1.76212234356,
        1.48790763356,
        1.90943856856,
        1.49945031556,
        1.89497144056,
        1.44123855156,
        1.82615687956,
        1.51224942756,
        1.80886125756,
        1.59184811456
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 762.0 ± 46.1 687.4 853.1 3.01 ± 0.22
pacquet@main 641.1 ± 40.8 593.5 706.3 2.53 ± 0.19
pnpr@HEAD 315.2 ± 32.4 287.2 389.5 1.24 ± 0.14
pnpr@main 253.3 ± 10.3 238.5 269.9 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.76198860306,
      "stddev": 0.04605735528625471,
      "median": 0.7725024713599999,
      "user": 0.99546938,
      "system": 0.7925347400000001,
      "min": 0.68743621536,
      "max": 0.85312175936,
      "times": [
        0.75127461436,
        0.7218655873600001,
        0.85312175936,
        0.77634241236,
        0.78687130936,
        0.68743621536,
        0.7165811453600001,
        0.76941023536,
        0.77559470736,
        0.78138804436
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.64105751676,
      "stddev": 0.04076523822262947,
      "median": 0.63567445136,
      "user": 0.8167391799999999,
      "system": 0.6927165399999999,
      "min": 0.59345457936,
      "max": 0.7063430753600001,
      "times": [
        0.6733043173600001,
        0.67874964136,
        0.7063430753600001,
        0.67406654136,
        0.65552373336,
        0.61582516936,
        0.6067377323600001,
        0.60275508736,
        0.60381529036,
        0.59345457936
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.31522321725999997,
      "stddev": 0.03235326195030757,
      "median": 0.30790322086,
      "user": 0.21389718000000002,
      "system": 0.5445565400000001,
      "min": 0.28721950736,
      "max": 0.38947377736,
      "times": [
        0.33449726336,
        0.38947377736,
        0.34183041336,
        0.31117923236,
        0.31345188436,
        0.30462720936,
        0.29069856435999997,
        0.28925623336,
        0.28999808736,
        0.28721950736
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.25327107886,
      "stddev": 0.01031098803849034,
      "median": 0.25219093336,
      "user": 0.19357988,
      "system": 0.5200199400000001,
      "min": 0.23851446736,
      "max": 0.26989434836,
      "times": [
        0.23851446736,
        0.24849563436000002,
        0.24015303636000002,
        0.25917394235999996,
        0.25102822335999997,
        0.24802572236,
        0.25335364336,
        0.26989434836,
        0.26687485435999997,
        0.25719691635999997
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.043 ± 0.065 1.976 2.158 7.67 ± 0.48
pacquet@main 1.981 ± 0.020 1.940 2.004 7.44 ± 0.40
pnpr@HEAD 0.349 ± 0.042 0.302 0.449 1.31 ± 0.17
pnpr@main 0.266 ± 0.014 0.245 0.289 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.0427905655,
      "stddev": 0.06501677778579305,
      "median": 2.0275477083,
      "user": 1.2076832199999996,
      "system": 0.8774343799999998,
      "min": 1.9755673393000002,
      "max": 2.1578429013,
      "times": [
        1.9755673393000002,
        2.0509619443,
        2.0041334723,
        2.0789795762999996,
        1.9935593303,
        2.0015279553,
        2.1578429013,
        2.1365681302999997,
        1.9764137103000001,
        2.0523512953
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.9814589726000005,
      "stddev": 0.01986340874983789,
      "median": 1.9835196283000003,
      "user": 1.12408912,
      "system": 0.79571948,
      "min": 1.9397545073000002,
      "max": 2.0040991973,
      "times": [
        1.9981016773,
        1.9975838533,
        1.9706341483,
        1.9864276783,
        1.9984557413000001,
        1.9740850623000001,
        2.0040991973,
        1.9648362823,
        1.9806115783000002,
        1.9397545073000002
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.34926832790000006,
      "stddev": 0.0424558676650878,
      "median": 0.3437646828,
      "user": 0.23899261999999996,
      "system": 0.61676988,
      "min": 0.3018665603,
      "max": 0.4485532223,
      "times": [
        0.3723855543,
        0.4485532223,
        0.3671819453,
        0.3573408213,
        0.3478021453,
        0.3305590513,
        0.3397272203,
        0.3239943853,
        0.3018665603,
        0.3032723733
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.26632023709999997,
      "stddev": 0.01418307033404827,
      "median": 0.26734183479999996,
      "user": 0.19511662,
      "system": 0.5575638800000001,
      "min": 0.24495824630000002,
      "max": 0.2893397793,
      "times": [
        0.2701343873,
        0.2585613293,
        0.2750086273,
        0.26454928229999997,
        0.2736386833,
        0.24838182930000002,
        0.24495824630000002,
        0.2575349503,
        0.2893397793,
        0.2810952563
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 404.5 ± 64.7 336.9 521.5 4.88 ± 0.80
pacquet@main 463.1 ± 60.4 410.5 587.4 5.58 ± 0.75
pnpr@HEAD 84.4 ± 2.7 80.9 93.3 1.02 ± 0.05
pnpr@main 83.0 ± 3.0 77.8 91.9 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.40449552850000003,
      "stddev": 0.06473679041624969,
      "median": 0.3751130065,
      "user": 0.39618916000000004,
      "system": 0.06588575999999999,
      "min": 0.3369437665,
      "max": 0.5215060755,
      "times": [
        0.41069929150000006,
        0.37209814150000003,
        0.3369437665,
        0.3468267695,
        0.37812787150000005,
        0.36918371350000007,
        0.35476723150000006,
        0.47874991650000004,
        0.47605250750000005,
        0.5215060755
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.46305249569999996,
      "stddev": 0.060351107898656865,
      "median": 0.4328995925000001,
      "user": 0.45223506,
      "system": 0.07647295999999999,
      "min": 0.41050186150000006,
      "max": 0.5873831445000001,
      "times": [
        0.5873831445000001,
        0.5248976485000001,
        0.41050186150000006,
        0.5197627695000001,
        0.46313536150000006,
        0.4163971705,
        0.43683385650000006,
        0.41896591650000004,
        0.4289653285000001,
        0.42368189950000007
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.08442840362121212,
      "stddev": 0.002668504042999616,
      "median": 0.0842480275,
      "user": 0.016462547878787884,
      "system": 0.010946520606060606,
      "min": 0.0808791865,
      "max": 0.0932959505,
      "times": [
        0.0857925395,
        0.0821890875,
        0.0883042795,
        0.0869346255,
        0.0837074215,
        0.0866641575,
        0.0831994365,
        0.0849673895,
        0.08675566950000001,
        0.0836369985,
        0.0827287615,
        0.0816886675,
        0.0860126625,
        0.0842480275,
        0.0845455265,
        0.0827106575,
        0.0867179595,
        0.0932959505,
        0.0818589975,
        0.0820295375,
        0.0808791865,
        0.0817095975,
        0.0875171705,
        0.0860374495,
        0.0811535315,
        0.0858902035,
        0.0824189095,
        0.0855597925,
        0.0860513255,
        0.0817673955,
        0.0817496525,
        0.0854345865,
        0.08198016550000001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.0829690368888889,
      "stddev": 0.002973515471398451,
      "median": 0.08228869550000001,
      "user": 0.016910065555555555,
      "system": 0.009177866111111111,
      "min": 0.0777785405,
      "max": 0.0918594605,
      "times": [
        0.0790974065,
        0.0777785405,
        0.0808266275,
        0.0821384325,
        0.0821515475,
        0.0819888815,
        0.08224677650000001,
        0.0876871805,
        0.0823306145,
        0.0793277415,
        0.0826317905,
        0.0818183405,
        0.0823592875,
        0.0802114215,
        0.0828065685,
        0.0852614315,
        0.0805023985,
        0.0809845445,
        0.0872819285,
        0.0918594605,
        0.0868768575,
        0.0850497635,
        0.0799034815,
        0.0813450215,
        0.0806205795,
        0.0850909715,
        0.0837307145,
        0.0806911325,
        0.0807220705,
        0.0830160615,
        0.0828923595,
        0.0866754795,
        0.0883961925,
        0.0816864235,
        0.0846942555,
        0.0842030425
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, cold cache + cold store + cold pnpr

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.704 ± 0.093 4.528 4.865 1.31 ± 0.05
pacquet@main 4.732 ± 0.151 4.536 4.946 1.32 ± 0.06
pnpr@HEAD 3.654 ± 0.111 3.564 3.887 1.02 ± 0.05
pnpr@main 3.581 ± 0.130 3.459 3.893 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.704427422139999,
      "stddev": 0.09330976997549684,
      "median": 4.717729459939999,
      "user": 2.5164295000000005,
      "system": 1.8716117199999995,
      "min": 4.527536950439999,
      "max": 4.864808238439999,
      "times": [
        4.864808238439999,
        4.773917701439999,
        4.714333788439999,
        4.69586949844,
        4.527536950439999,
        4.712876179439999,
        4.72970545744,
        4.722307563439999,
        4.58179371244,
        4.72112513144
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.731916929839999,
      "stddev": 0.1510376268904435,
      "median": 4.75160470044,
      "user": 2.1417523,
      "system": 1.6477613199999996,
      "min": 4.536000104439999,
      "max": 4.94615876644,
      "times": [
        4.94615876644,
        4.894529061439999,
        4.54663416844,
        4.8071821544399995,
        4.69602724644,
        4.8320693734399995,
        4.56935286244,
        4.654859451439999,
        4.83635610944,
        4.536000104439999
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.6536818589399997,
      "stddev": 0.11072966351968622,
      "median": 3.61030846494,
      "user": 1.6512562,
      "system": 1.6524283199999998,
      "min": 3.56395542644,
      "max": 3.8866968394400003,
      "times": [
        3.59267387544,
        3.62086919144,
        3.56395542644,
        3.61404626944,
        3.6110075584400003,
        3.60960937144,
        3.6016846994400002,
        3.8866968394400003,
        3.83401864444,
        3.60225671344
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.5808876897400004,
      "stddev": 0.12956436359124116,
      "median": 3.5458581584399997,
      "user": 1.2985049,
      "system": 1.3431429199999998,
      "min": 3.45935949444,
      "max": 3.89274695744,
      "times": [
        3.58643476144,
        3.6550332944400004,
        3.52066409044,
        3.64916529644,
        3.48067464044,
        3.51905024744,
        3.45935949444,
        3.57105222644,
        3.89274695744,
        3.47469588844
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/13075
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
2,872.96 ms
(-12.83%)Baseline: 3,295.98 ms
3,955.18 ms
(72.64%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
2,042.79 ms
(-12.44%)Baseline: 2,332.92 ms
2,799.50 ms
(72.97%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
761.99 ms
(-16.80%)Baseline: 915.90 ms
1,099.08 ms
(69.33%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
404.50 ms
(-15.17%)Baseline: 476.85 ms
572.22 ms
(70.69%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,558.34 ms
(-15.24%)Baseline: 3,018.16 ms
3,621.80 ms
(70.64%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,704.43 ms
(-14.44%)Baseline: 5,498.53 ms
6,598.24 ms
(71.30%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
285.55 ms
(-26.32%)Baseline: 387.54 ms
465.05 ms
(61.40%)
🐰 View full continuous benchmarking report in Bencher

@qodo-code-review

qodo-code-review Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (5) 📘 Rule violations (2) 📎 Requirement gaps (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Action required

1. Symlink guard TOCTOU ✓ Resolved 🐞 Bug ⛨ Security
Description
writeLockfileDoc() checks ensureLockfileIsNotSymlink() and then calls writeFileAtomic(),
leaving a race window where pnpm-lock.yaml can be swapped to a symlink after the lstat check but
before the pathname-based write. This undermines the new “refuse writes through symlinks” guarantee
and can re-enable redirected writes for a concurrent filesystem attacker.
Code

pnpm11/lockfile/fs/src/write.ts[R105-108]

+  if (existing === content) return
+  await ensureLockfileIsNotSymlink(lockfilePath)
+  await writeFileAtomic(lockfilePath, content)
+}
Evidence
The write path performs a pre-write lstat-based symlink check and then writes by pathname; the
code comment explicitly notes write-file-atomic resolves the target via realpath, so a swap
between these operations can redirect the write.

pnpm11/lockfile/fs/src/write.ts[95-108]
pnpm11/lockfile/fs/src/yamlDocuments.ts[115-139]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`writeLockfileDoc()` performs a separate symlink check (`lstat`) and then writes via `write-file-atomic`, which (per comment) resolves the destination via `realpath`. A concurrent swap can reintroduce redirected writes.

### Issue Context
This PR’s intent is to allow symlinked reads but keep all write paths protected from symlink redirection.

### Fix Focus Areas
- pnpm11/lockfile/fs/src/write.ts[95-108]
- pnpm11/lockfile/fs/src/yamlDocuments.ts[115-139]

### Implementation notes
- Prefer replacing `writeFileAtomic(lockfilePath, content)` for `pnpm-lock.yaml` with an in-repo atomic writer that **does not** resolve the destination via `realpath` and writes via temp-file + rename to the original `lockfilePath`.
- Ensure the last path component isn’t a symlink at the moment you publish (e.g., check `lstat` immediately before rename), or rely on rename semantics that replace the symlink itself (never follow it).
- Keep the current behavior of allowing symlinked lockfile when unchanged, but ensure the *actual write path* cannot be redirected by a mid-operation swap.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Symlink write threat misstated 🐞 Bug ⚙ Maintainability ⭐ New
Description
The docstrings for ensureLockfileIsNotSymlink / ensure_lockfile_is_not_symlink claim a write
would land on the symlink’s target, but the new wanted-lockfile write path publishes via temp-file +
rename, which replaces the symlink entry instead of following it. This incorrect security
rationale can mislead future maintenance/security decisions about what the guard is actually
protecting (policy: preserve staged symlink; not preventing redirected writes).
Code

pnpm11/lockfile/fs/src/yamlDocuments.ts[R107-110]

+ * Refuses a symlinked lockfile before a write, which would land on the link's
+ * target — any file the user can write. Reads may follow it: sandboxes stage
+ * `pnpm-lock.yaml` as a symlink, and lockfile content is untrusted either way
+ * (https://github.com/pnpm/pnpm/issues/13073).
Evidence
The docstrings explicitly claim a symlinked write would land on the link’s target, but both
implementations shown use temp-file + rename publication, which does not write through the
destination symlink path (it replaces the directory entry). Therefore the documented threat model is
outdated relative to the actual write mechanism.

pnpm11/lockfile/fs/src/yamlDocuments.ts[106-110]
pnpm11/lockfile/fs/src/write.ts[104-138]
pnpm/crates/lockfile/src/save_lockfile.rs[99-102]
pnpm/crates/lockfile/src/save_lockfile.rs[196-257]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The comments on the symlink guard functions say that writing a symlinked lockfile would write into the symlink target (i.e., redirect the write). However, the current wanted-lockfile writer publishes with a sibling temp file + `rename`, which replaces the final path entry (the symlink itself) rather than following it. The docs should reflect the real behavior and the real reason for the refusal (policy/UX: don’t replace staged symlinks; consistency with other implementations), instead of an outdated redirection threat model.

### Issue Context
- In TS, `writeWantedLockfileAtomic` uses `rename` after writing a temp file.
- In Rust, `save_value_to_path` writes via `write_atomic` which also uses temp+`rename`.
- The symlink guard may still be desired, but the current explanatory text is inaccurate.

### Fix Focus Areas
- pnpm11/lockfile/fs/src/yamlDocuments.ts[106-110]
- pnpm/crates/lockfile/src/save_lockfile.rs[99-102]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Historical JSDoc in streamReadFirstYamlDocument ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The updated JSDoc and Rust doc comment include historical phrasing like `Refusing it here bought
nothing and has always followed the link`, describing past context rather than current behavior
and guarantees. This violates the requirement that comments stay focused on present-day contracts
and increases drift risk by encoding prior-implementation rationale instead of current constraints.
Code

pnpm11/lockfile/fs/src/yamlDocuments.ts[R21-28]

+ * Follows a symlinked lockfile, as build sandboxes stage `pnpm-lock.yaml`
+ * (https://github.com/pnpm/pnpm/issues/13073). Refusing it here bought nothing:
+ * `readWantedLockfile` reads the same file with a plain `readFile` and has always
+ * followed the link, and a hostile repo can commit a hostile lockfile as a plain
+ * file regardless — the content is untrusted either way.
+ *
+ * Writes are the real boundary and still refuse a symlink, because a write
+ * follows the link and lands on its target; see {@link ensureLockfileIsNotSymlink}.
Evidence
In pnpm11/lockfile/fs/src/yamlDocuments.ts[21-28], the changed JSDoc contains explicit
temporal/historical references such as Refusing it here bought nothing and `has always followed
the link`, which the checklist rule disallows because comments must describe current behavior rather
than past implementations. Similarly, pnpm/crates/lockfile/src/env_lockfile.rs[145-150] includes
the same historical framing (Refusing it here bought nothing) instead of stating the present-tense
behavior contract, demonstrating the same compliance violation in Rust doc comments.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/lockfile/fs/src/yamlDocuments.ts[21-28]
pnpm/crates/lockfile/src/env_lockfile.rs[145-150]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The newly added/updated JSDoc and Rust doc comments use temporal/historical language (e.g., `Refusing it here bought nothing`, `has always ...`) rather than describing the current behavior contract, guarantees, and constraints in present tense.

## Issue Context
Compliance requires source comments to describe current behavior and guarantees, not historical implementations; rationale should be framed in terms of current constraints and security boundaries and avoid temporal references that can drift as implementations change.

## Fix Focus Areas
- pnpm11/lockfile/fs/src/yamlDocuments.ts[21-28]
- pnpm/crates/lockfile/src/env_lockfile.rs[145-150]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Windows-skipped tests lack issue link 📘 Rule violation ▣ Testability
Description
New Jest tests are conditionally skipped on Windows via testOnNonWindows, but the skip has no
explicit issue reference/justification comment. This can hide platform regressions and violates the
requirement to document newly skipped tests with a tracking reference.
Code

pnpm11/lockfile/fs/test/write.test.ts[R559-564]

+testOnNonWindows('writeWantedLockfile() leaves no temp file behind', async () => {
+  const projectPath = temporaryDirectory()
+  await writeWantedLockfile(projectPath, upToDateLockfile)
+
+  expect(fs.readdirSync(projectPath)).toStrictEqual([WANTED_LOCKFILE])
+})
Evidence
PR Compliance ID 713440 requires that newly skipped tests include an explicit issue reference and
justification. The new testOnNonWindows helper skips tests on Windows, and is used for newly added
tests without any linked issue/rationale near the skip.

Rule 713440: Investigate and resolve all failing tests before merge
pnpm11/lockfile/fs/test/write.test.ts[426-426]
pnpm11/lockfile/fs/test/write.test.ts[559-564]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Some newly added tests are skipped on Windows (`process.platform === 'win32' ? test.skip : test`) without an explicit issue reference and justification.

## Issue Context
Compliance requires newly skipped/ignored tests to include a clear tracking issue reference and rationale so platform gaps are visible and intentional.

## Fix Focus Areas
- pnpm11/lockfile/fs/test/write.test.ts[426-426]
- pnpm11/lockfile/fs/test/write.test.ts[559-564]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (3)
5. writeLockfileDoc JSDoc narrates steps 📘 Rule violation ⚙ Maintainability
Description
The new JSDoc for writeLockfileDoc describes internal implementation/workarounds (e.g., “threading
it through 25+ call sites”, “OS page cache”) rather than focusing on the function’s contract
(inputs/outputs, guarantees, error conditions). This increases maintenance risk because the comment
is likely to drift as implementation details change.
Code

pnpm11/lockfile/fs/src/write.ts[R81-94]

+/**
+ * Writes a serialized lockfile. Only `pnpm-lock.yaml` is led by an env
+ * document; `lock.yaml` and git-branch lockfiles are written as-is.
+ *
+ * The env document is preserved by re-reading it. Ideally it would be captured
+ * during the initial lockfile read and passed through to the write functions,
+ * but that would require threading it through 25+ call sites. Re-reading is
+ * cheap since the file is likely still in the OS page cache.
+ *
+ * A byte-identical rewrite is skipped. An up-to-date install — every
+ * `--frozen-lockfile` run — would otherwise rewrite the lockfile for nothing,
+ * and refuse a symlinked one over a write that changes no bytes
+ * (https://github.com/pnpm/pnpm/issues/13073).
+ */
Evidence
PR Compliance ID 713430 requires JSDoc to document function contracts rather than re-describing
implementation. The added block for writeLockfileDoc focuses on internal mechanics and rationale
(call-site threading, page cache) instead of clear pre/postconditions and edge cases.

Rule 713430: JSDoc must document function contracts, not re-describe implementation
pnpm11/lockfile/fs/src/write.ts[81-94]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The JSDoc on `writeLockfileDoc` currently explains implementation details and rationale (call-site count, OS page cache) rather than documenting the function’s contract (what it guarantees, when it writes, and error behavior).

## Issue Context
Compliance requires JSDoc to document contracts (preconditions/postconditions/edge cases) and avoid step-by-step narration or implementation trivia.

## Fix Focus Areas
- pnpm11/lockfile/fs/src/write.ts[81-94]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Mode sync ordering wrong 🐞 Bug ☼ Reliability
Description
fill_temp_file() calls sync_all() before carry_mode_across() updates permissions, so the
permission change is not covered by the durability sync and may be lost after a power failure/crash.
This conflicts with the function’s stated goal of publishing a “faithful stand-in” that preserves
the target’s mode.
Code

pnpm/crates/lockfile/src/save_lockfile.rs[R179-183]

+fn fill_temp_file(file: &mut fs::File, content: &[u8], target: &Path) -> io::Result<()> {
+    file.write_all(content)?;
+    file.sync_all()?;
+    carry_mode_across(file, target)
+}
Evidence
The code explicitly syncs the temp file before calling set_permissions in carry_mode_across, so
permission updates occur after the durability sync.

pnpm/crates/lockfile/src/save_lockfile.rs[174-183]
pnpm/crates/lockfile/src/save_lockfile.rs[185-197]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`fill_temp_file()` fsyncs the temp file before copying the target’s mode onto it, meaning the mode change is not included in the fsync’s durability window.

### Issue Context
The surrounding comments claim mode preservation and durability properties for atomic lockfile writes.

### Fix Focus Areas
- pnpm/crates/lockfile/src/save_lockfile.rs[174-183]
- pnpm/crates/lockfile/src/save_lockfile.rs[185-197]

### Implementation notes
- Reorder to: `write_all` → `carry_mode_across` → `sync_all`.
- This preserves the single fsync while ensuring the permission metadata is included.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Symlink target can hang 🐞 Bug ⛨ Security
Description
EnvLockfile::read/streamReadFirstYamlDocument now follows symlinks and reads the resolved
lockfile target via a plain open plus full read, without verifying the target is a regular file. A
pnpm-lock.yaml symlink to a FIFO/device (or other special file) can therefore block on open/read
or consume unbounded input, causing a local DoS (or unexpected failures) in common install/CLI
flows.
Code

pnpm/crates/lockfile/src/env_lockfile.rs[R108-113]

    pub fn read(root_dir: &Path) -> Result<Option<Self>, LoadLockfileError> {
        let path = root_dir.join(Lockfile::FILE_NAME);
-        let Some(content) =
-            read_lockfile_to_string_no_follow(&path).map_err(LoadLockfileError::ReadFile)?
+        let Some(content) = read_lockfile_to_string(&path).map_err(LoadLockfileError::ReadFile)?
        else {
            return Ok(None);
        };
Evidence
The cited PR changes switch env-lockfile/YAML reading to a symlink-following open-by-path (e.g.,
File::open/open(..., O_RDONLY)) and then read to EOF (e.g., read_to_string or equivalent
first-document reader plumbing), rather than preserving a no-follow approach or validating the
resolved target type. Because these readers feed readEnvLockfile/EnvLockfile::read and are
invoked from install and other CLI paths, a workspace that makes pnpm-lock.yaml a symlink to a
FIFO or other non-regular file can trigger blocking behavior at open/read time (or other runtime
failures), making the hang/DoS reachable in normal flows.

pnpm/crates/lockfile/src/env_lockfile.rs[101-163]
pnpm/crates/env-installer/src/resolve_and_install_config_deps.rs[27-37]
pnpm/crates/cli/src/cli_args/audit.rs[173-197]
pnpm/crates/cli/src/cli_args/self_update.rs[225-244]
pnpm11/lockfile/fs/src/yamlDocuments.ts[12-74]
pnpm11/lockfile/fs/src/envLockfile.ts[25-31]
pnpm11/installing/deps-installer/src/install/index.ts[2241-2253]
pnpm11/lockfile/fs/src/write.ts[62-83]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The env lockfile reading path now follows symlinks and performs a plain open plus read-to-EOF (or equivalent) without confirming the resolved target is a regular file. This allows a crafted `pnpm-lock.yaml` symlink to a FIFO/device/special file to block at open/read time or read unbounded data, causing a local denial-of-service (or unexpected failures) during installs and other CLI operations.

## Issue Context
This code path is exercised by multiple CLI commands and env-installer/install flows (including `readEnvLockfile()` usage), so a malicious or simply unusual workspace can reliably hang the process during routine operations (e.g., install/audit/self-update). The change specifically introduced symlink-following open behavior (e.g., `O_RDONLY`/`File::open`) and removed/avoided safeguards that previously prevented following symlinks or constrained reading.

## Fix Focus Areas
- pnpm/crates/lockfile/src/env_lockfile.rs[108-163]
- pnpm11/lockfile/fs/src/yamlDocuments.ts[21-74]
- pnpm11/lockfile/fs/src/envLockfile.ts[25-31]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

8. Byte-identical comment misleading ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
writeLockfileDoc claims it skips only a “byte-identical” rewrite, but it compares *normalized*
content (BOM stripped, CRLF→LF), so it can skip even when on-disk bytes differ. This is
documentation drift risk around the exact conditions under which a write (and thus the symlink
write-guard) will run.
Code

pnpm11/lockfile/fs/src/write.ts[R92-94]

+ * A byte-identical rewrite is skipped, so an up-to-date install — every
+ * `--frozen-lockfile` run — leaves the lockfile and its mtime untouched, and a
+ * symlinked lockfile that nothing changes is never refused
Evidence
The JSDoc states “byte-identical rewrite”, but the value compared against freshly serialized output
is produced by a reader that strips BOM and normalizes CRLF to LF, so equality is not byte-level
equality of the on-disk file.

pnpm11/lockfile/fs/src/write.ts[83-109]
pnpm11/lockfile/fs/src/yamlDocuments.ts[71-88]
pnpm/crates/lockfile/src/save_lockfile.rs[74-103]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`writeLockfileDoc`’s comment says only a “byte-identical rewrite” is skipped, but the code compares normalized text (BOM stripped and CRLF normalized). This means the write can be skipped even when the file’s raw bytes differ, which is intentional for preserving CRLF/BOM, but the current wording is inaccurate.

## Issue Context
The implementation uses `readLockfileToString()` which normalizes BOM/CRLF before `existing === content`.

## Fix Focus Areas
- pnpm11/lockfile/fs/src/write.ts[92-94]

## Suggested change
Replace “byte-identical rewrite” wording with something like:
- “A rewrite is skipped when the existing lockfile content matches after BOM stripping and CRLF→LF normalization (so encoding-only differences don’t count as changes).”

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Unneeded CRLF copy alloc 🐞 Bug ➹ Performance
Description
save_value_to_path() always allocates a new normalized string via replace("\r\n", "\n"), even
when the existing lockfile already uses LF and has no BOM. This adds avoidable transient peak memory
and copying proportional to lockfile size on every save.
Code

pnpm/crates/lockfile/src/save_lockfile.rs[R88-90]

+        Ok(existing) => {
+            Some(existing.strip_prefix('\u{feff}').unwrap_or(&existing).replace("\r\n", "\n"))
+        }
Evidence
The current normalization path always calls replace("\r\n", "\n") on the existing lockfile string,
which necessarily creates a new String even when the input contains no CRLF sequences, adding an
avoidable allocation/copy for the common LF-only case.

pnpm/crates/lockfile/src/save_lockfile.rs[82-103]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
In `save_value_to_path()`, the existing lockfile string is always transformed with `str::replace("\r\n", "\n")`, which allocates a new `String` even when there are no CRLF sequences. This creates an avoidable extra allocation/copy on a hot path.

### Issue Context
This normalization is only needed when the file contains CRLF or a BOM; the common case (LF-only, no BOM) can reuse the original allocation.

### Fix Focus Areas
- pnpm/crates/lockfile/src/save_lockfile.rs[87-90]

### Suggested approach
- Change normalization to be conditional:
 - If the string starts with `\u{feff}`, remove it in-place (`remove(0)`) or otherwise strip it.
 - Only call `.replace("\r\n", "\n")` when `existing.contains("\r\n")`.
- Keep behavior identical for CRLF/BOM inputs (still normalize for comparison/extraction).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. Extra full-file read 🐞 Bug ➹ Performance
Description
writeLockfileDoc() now reads the entire existing pnpm-lock.yaml into memory (`readFile(...,
'utf8')`) to preserve the env doc and detect byte-identical output, even when it will proceed to
write. This adds an extra full-file read and additional string allocations on a hot path (lockfile
writes).
Code

pnpm11/lockfile/fs/src/write.ts[R100-106]

+  const existing = await readLockfileToString(lockfilePath)
+  const envDoc = existing == null ? null : extractEnvDocument(existing)
+  const content = envDoc == null
+    ? mainDoc
+    : `${YAML_DOCUMENT_START}${envDoc}${YAML_DOCUMENT_SEPARATOR}${mainDoc}`
+  if (existing === content) return
+  await ensureLockfileIsNotSymlink(lockfilePath)
Evidence
The new helper reads the whole file via readFile and writeLockfileDoc unconditionally performs
that read for pnpm-lock.yaml before deciding whether to write.

pnpm11/lockfile/fs/src/write.ts[95-108]
pnpm11/lockfile/fs/src/yamlDocuments.ts[73-86]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The wanted-lockfile write path always does a full `readFile` of the existing lockfile to compute the env prefix and to decide if the write is a no-op.

### Issue Context
Skipping byte-identical rewrites is desirable, but the current implementation pays the full read cost even on runs that will definitely write.

### Fix Focus Areas
- pnpm11/lockfile/fs/src/write.ts[95-106]
- pnpm11/lockfile/fs/src/yamlDocuments.ts[73-86]

### Implementation notes
Options (pick one):
- If the caller already has the original raw lockfile content from the read phase, thread it through to avoid re-reading.
- Or, instead of `readFile` into a string, stream-hash the existing file and compare to the new output hash (still O(N) I/O but avoids holding two large strings).
- Or, keep the full read but gate it behind a cheap heuristic (e.g., only do the full read when `--frozen-lockfile`/no-op is expected).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to d2a62ae

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
General
Propagate permission metadata failures

Only ignore NotFound errors when calling fs::symlink_metadata to ensure other
failures are correctly propagated.

pnpm/crates/lockfile/src/save_lockfile.rs [184-188]

-let Ok(metadata) = fs::symlink_metadata(target) else { return Ok(()) };
+let metadata = match fs::symlink_metadata(target) {
+    Ok(metadata) => metadata,
+    Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
+    Err(error) => return Err(error),
+};
 if metadata.file_type().is_symlink() {
     return Ok(());
 }
 file.set_permissions(fs::Permissions::from_mode(metadata.permissions().mode()))
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: Properly propagating unexpected I/O or permission errors prevents silent failures when preserving lockfile permissions, serving as a solid error-handling improvement.

Medium
  • More

Previous suggestions

Suggestions up to commit 84d7acb
CategorySuggestion                                                                                                                                    Impact
General
Keep ownership restoration best-effort

Tolerate EPERM and EINVAL errors in ignoreUnprivilegedChown regardless of
effective UID to better support root-squashed or restricted environments.

pnpm11/lockfile/fs/src/write.ts [161-165]

 function ignoreUnprivilegedChown (error: NodeJS.ErrnoException): void {
-  const tolerated = error.code === 'ENOSYS' ||
-    ((process.getuid == null || process.getuid() !== 0) && (error.code === 'EINVAL' || error.code === 'EPERM'))
-  if (!tolerated) throw error
+  if (error.code !== 'ENOSYS' && error.code !== 'EINVAL' && error.code !== 'EPERM') {
+    throw error
+  }
 }
Suggestion importance[1-10]: 8

__

Why: Root processes can fail to chown in environments like NFS with root squash or rootless containers, so tolerating these errors universally avoids fatal write failures.

Medium
Suggestions up to commit d2a05cc
CategorySuggestion                                                                                                                                    Impact
General
Propagate target metadata failures

Only ignore NotFound errors when retrieving metadata. Propagate other errors to
prevent silently overriding permission modes.

pnpm/crates/lockfile/src/save_lockfile.rs [194]

-let Ok(metadata) = fs::symlink_metadata(target) else { return Ok(()) };
+let metadata = match fs::symlink_metadata(target) {
+    Ok(metadata) => metadata,
+    Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
+    Err(error) => return Err(error),
+};
Suggestion importance[1-10]: 7

__

Why: Propagating errors other than NotFound ensures that permission or I/O issues are not silently swallowed, leading to more robust metadata handling.

Medium
Suggestions
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve BOM-prefixed environment documents

Strip the UTF-8 BOM before processing the lockfile content. This matches the
behavior of streamReadFirstYamlDocument and ensures the environment document is
correctly extracted.

pnpm11/lockfile/fs/src/yamlDocuments.ts [157-163]

 export function extractEnvDocument (content: string): string | null {
-  content = content.replace(/\r\n/g, '\n')
+  content = stripBom(content).replace(/\r\n/g, '\n')
   if (!content.startsWith(YAML_DOCUMENT_START)) return null
   const sep = content.indexOf(YAML_DOCUMENT_SEPARATOR, YAML_DOCUMENT_START.length)
   if (sep === -1) return null
   return content.slice(YAML_DOCUMENT_START.length, sep)
 }
Suggestion importance[1-10]: 8

__

Why: Stripping the BOM ensures that lockfiles with a Byte Order Mark are correctly parsed, preventing the silent dropping of the environment document.

Medium
Security
Eliminate symlink write race

Use a single atomic writer that does not follow symlinks instead of checking and
then writing. This eliminates a Time-of-Check to Time-of-Use (TOCTOU) race
condition.

pnpm11/lockfile/fs/src/write.ts [106-107]

-await ensureLockfileIsNotSymlink(lockfilePath)
-await writeFileAtomic(lockfilePath, content)
+await writeLockfileAtomicNoFollow(lockfilePath, content)
Suggestion importance[1-10]: 8

__

Why: A check-then-write sequence introduces a TOCTOU race condition where an attacker can swap the file for a symlink after the check, bypassing the security guard since write-file-atomic resolves realpath.

Medium

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/13075
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,598.58 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
349.27 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
315.22 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
84.43 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,561.49 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,653.68 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
319.68 ms
🐰 View full continuous benchmarking report in Bencher

Allowing symlinked reads did not fix #13073. The reported
`--frozen-lockfile --lockfile-only` install fails on the *write*:
tryFrozenInstall rewrites an already up-to-date pnpm-lock.yaml, and the
write path refuses a symlink before it writes.

Skip a byte-identical rewrite instead. An up-to-date install -- every
frozen run -- no longer touches the lockfile at all, so one staged as a
symlink (Bazel, Nix) installs cleanly, while a write that changes bytes
still refuses the symlink: write-file-atomic resolves the target with
realpath, so writing through one redirects onto any file the user can
write.

Reading through a symlink stays allowed. That guard was never justified
on its own -- it arrived as a "consider this too" aside alongside the
write fix in #12821 -- and planting the symlink already requires
write access to the working tree.

Close the same clobber in pacquet: save_value_to_path wrote the wanted
lockfile with fs::write, which follows symlinks and had no guard. It now
refuses a symlinked lockfile and writes atomically, carrying the target's
mode across the rename and flushing before it, matching write-file-atomic.
Share the symlink guard between both write paths rather than duplicate it.

Add install-level regression coverage for the reported command; the
existing unit tests passed while the bug remained.
@zkochan zkochan changed the title fix(lockfile): allow symlinked lockfile reads fix(lockfile): fix installs when pnpm-lock.yaml is a symlink Jul 16, 2026
@zkochan

zkochan commented Jul 16, 2026

Copy link
Copy Markdown
Member

Thanks — all four findings were valid and are fixed in b12578d. Since that review the PR also grew well beyond its original scope, so here's what changed and why.

The findings

Finding Resolution
P1: missing @pnpm/lockfile.fs in changeset Fixed — replied on the thread.
symlinkedLockfileError still says "read or write" Fixed — now Refusing to write symlinked lockfile at ….
symlinked_lockfile_error (Rust) same stale text Fixed — now refusing to write symlinked lockfile at ….
Stale #[expect] reason naming "the no-follow file handle" Fixed — now caller-agnostic: "Reading from the caller's file handle avoids reopening the lockfile by path."

Both error strings are reachable only from write paths now, so the wording is accurate. ERR_PNPM_LOCKFILE_IS_SYMLINK is unchanged.

The bigger issue: this PR did not fix #13073

Worth flagging, because the review confidence score rested on the read/write boundary being the whole story. It wasn't. Building the bundle and running the issue's exact repro still failed:

[ERR_PNPM_LOCKFILE_IS_SYMLINK] Refusing to read or write symlinked lockfile at .../work/pnpm-lock.yaml
    at ensureLockfileIsNotSymlink → openLockfileNoFollow
    at streamReadFirstYamlDocumentWithOpen
    at writeLockfile              ← the write path, not the read
    at tryFrozenInstall

tryFrozenInstall rewrites an already up-to-date pnpm-lock.yaml, so the reported --frozen-lockfile --lockfile-only command dies on the write. Allowing reads through was necessary but not sufficient.

The fix is to skip a byte-identical rewrite: an up-to-date install now writes nothing at all, so the guard is never reached over a write that changes no bytes. Genuine writes through a symlink are still refused.

A vulnerability found along the way

pacquet's save_value_to_path wrote the wanted lockfile with fs::write — which follows symlinks, with no guard. That is the same arbitrary-file clobber #12821 set out to close, still open on the main-lockfile path: the TypeScript CLI refused, pacquet clobbered. It now refuses a symlinked lockfile and writes atomically.

On test coverage

The most useful lesson here: this PR's original tests all passed while the reported command stayed broken. They covered the read path in isolation and never exercised an install. Coverage is now at the level that actually reproduces the issue (deps-installer/test/lockfile.ts), verified to fail against the previous commit and pass with the fix.


Written by an agent (Claude Code, claude-opus-4-8).

Comment thread pnpm11/lockfile/fs/src/write.ts Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit b12578d

@qodo-code-review

qodo-code-review Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve BOM-prefixed environment documents

Strip the UTF-8 BOM before processing the lockfile content. This matches the
behavior of streamReadFirstYamlDocument and ensures the environment document is
correctly extracted.

pnpm11/lockfile/fs/src/yamlDocuments.ts [157-163]

 export function extractEnvDocument (content: string): string | null {
-  content = content.replace(/\r\n/g, '\n')
+  content = stripBom(content).replace(/\r\n/g, '\n')
   if (!content.startsWith(YAML_DOCUMENT_START)) return null
   const sep = content.indexOf(YAML_DOCUMENT_SEPARATOR, YAML_DOCUMENT_START.length)
   if (sep === -1) return null
   return content.slice(YAML_DOCUMENT_START.length, sep)
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: Stripping the BOM ensures that lockfiles with a Byte Order Mark are correctly parsed, preventing the silent dropping of the environment document.

Medium
Security
Eliminate symlink write race

Use a single atomic writer that does not follow symlinks instead of checking and
then writing. This eliminates a Time-of-Check to Time-of-Use (TOCTOU) race
condition.

pnpm11/lockfile/fs/src/write.ts [106-107]

-await ensureLockfileIsNotSymlink(lockfilePath)
-await writeFileAtomic(lockfilePath, content)
+await writeLockfileAtomicNoFollow(lockfilePath, content)
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: A check-then-write sequence introduces a TOCTOU race condition where an attacker can swap the file for a symlink after the check, bypassing the security guard since write-file-atomic resolves realpath.

Medium
  • More

@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.

Actionable comments posted: 4

🧹 Nitpick comments (1)
pnpm/crates/lockfile/src/save_lockfile/tests.rs (1)

455-470: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a CRLF regression case alongside this LF-only env-document test.

This test hard-codes env_doc with only \n line endings, so it wouldn't catch the CRLF-comparison bug flagged on save_value_to_path (lines 87-98 of save_lockfile.rs): if existing on disk used CRLF anywhere, the unchanged-write check would spuriously fail. A companion test using \r\n in the prepended env_doc/existing content would pin this behavior down once fixed.

🤖 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 `@pnpm/crates/lockfile/src/save_lockfile/tests.rs` around lines 455 - 470, Add
a companion regression test next to
save_leaves_an_unchanged_lockfile_with_env_document_untouched using \r\n line
endings throughout the prepended env_doc and existing lockfile content. Reuse
the same save_to_path flow and assert the file modification time remains
unchanged on the second save, covering the CRLF comparison behavior in
save_value_to_path.
🤖 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.

Inline comments:
In `@pnpm11/lockfile/fs/src/write.ts`:
- Around line 95-108: Normalize the existing lockfile content from CRLF to LF
once in writeLockfileDoc before both extractEnvDocument and the existing ===
content comparison, so unchanged files skip writing. Apply the same
normalization in pnpm/crates/lockfile/src/save_lockfile.rs within
save_value_to_path before extract_env_document and the existing.as_deref()
comparison; both sites must preserve the existing symlink-protection behavior.

In `@pnpm11/lockfile/fs/src/yamlDocuments.ts`:
- Around line 137-139: The symlinked-lockfile refusal message has inconsistent
capitalization between implementations. Update the message in
pnpm11/lockfile/fs/src/yamlDocuments.ts lines 137-139 and
pnpm/crates/lockfile/src/save_lockfile.rs lines 117-121 so
symlinkedLockfileError and the Rust save-lockfile path emit exactly matching
text, preserving the existing error code and behavior.
- Around line 73-86: Update readLockfileToString to remove a leading UTF-8 BOM
from the string returned by readFile, matching streamReadFirstYamlDocument
before extractEnvDocument processes it. Preserve the existing ENOENT-to-null
behavior and rethrow all other errors.

In `@pnpm11/lockfile/fs/test/write.test.ts`:
- Around line 452-461: Strengthen the no-op assertion in the test
“writeWantedLockfile() accepts a symlinked lockfile when nothing changes” by
recording the symlink target’s content and modification time before the second
write, then asserting both remain unchanged afterward. Keep the existing
symlink-preservation assertion and follow the analogous unchanged-lockfile tests
for the comparison approach.

---

Nitpick comments:
In `@pnpm/crates/lockfile/src/save_lockfile/tests.rs`:
- Around line 455-470: Add a companion regression test next to
save_leaves_an_unchanged_lockfile_with_env_document_untouched using \r\n line
endings throughout the prepended env_doc and existing lockfile content. Reuse
the same save_to_path flow and assert the file modification time remains
unchanged on the second save, covering the CRLF comparison behavior in
save_value_to_path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 500b843d-c728-4d37-84f4-01669da54fc9

📥 Commits

Reviewing files that changed from the base of the PR and between fd1e991 and b12578d.

📒 Files selected for processing (9)
  • .changeset/allow-symlinked-lockfile-reads.md
  • pnpm/crates/lockfile/src/env_lockfile.rs
  • pnpm/crates/lockfile/src/save_lockfile.rs
  • pnpm/crates/lockfile/src/save_lockfile/tests.rs
  • pnpm11/installing/deps-installer/test/lockfile.ts
  • pnpm11/lockfile/fs/src/write.ts
  • pnpm11/lockfile/fs/src/yamlDocuments.ts
  • pnpm11/lockfile/fs/test/write.test.ts
  • pnpm11/lockfile/fs/test/yamlDocuments.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • .changeset/allow-symlinked-lockfile-reads.md
  • pnpm/crates/lockfile/src/env_lockfile.rs

Comment thread pnpm11/lockfile/fs/src/write.ts Resolved
Comment thread pnpm11/lockfile/fs/src/yamlDocuments.ts Resolved
Comment thread pnpm11/lockfile/fs/src/yamlDocuments.ts Resolved
Comment thread pnpm11/lockfile/fs/test/write.test.ts Resolved

@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.

🧹 Nitpick comments (2)
pnpm11/lockfile/fs/test/write.test.ts (2)

468-469: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use WANTED_LOCKFILE constant for consistency.

The subsequent test uses WANTED_LOCKFILE when defining realLockfile. Consider using it here as well for consistency.

♻️ Proposed refactor
   const realDir = temporaryDirectory()
-  const realLockfile = path.join(realDir, 'pnpm-lock.yaml')
+  const realLockfile = path.join(realDir, WANTED_LOCKFILE)
🤖 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 `@pnpm11/lockfile/fs/test/write.test.ts` around lines 468 - 469, Update the
realLockfile definition in the affected test to join realDir with the existing
WANTED_LOCKFILE constant instead of duplicating the literal lockfile name,
preserving the current temporary-directory setup and path behavior.

491-493: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Assert that the symlink is preserved.

Similar to the previous test, ensure that the symlink itself was not silently replaced by a regular file during the execution.

✅ Proposed refactor
   await expect(writeWantedLockfile(projectPath, upToDateLockfile)).resolves.toBeTruthy()
+  expect(fs.lstatSync(path.join(projectPath, WANTED_LOCKFILE)).isSymbolicLink()).toBe(true)
   expect(fs.readFileSync(realLockfile, 'utf8')).toBe(crlfContent)
   expect(fs.statSync(realLockfile).mtimeMs).toBe(mtimeBefore)
🤖 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 `@pnpm11/lockfile/fs/test/write.test.ts` around lines 491 - 493, Extend the
test around writeWantedLockfile to verify that realLockfile remains a symbolic
link after the write, using the filesystem metadata or symlink assertion already
established by the preceding test. Keep the existing content and mtime checks
unchanged.
🤖 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.

Nitpick comments:
In `@pnpm11/lockfile/fs/test/write.test.ts`:
- Around line 468-469: Update the realLockfile definition in the affected test
to join realDir with the existing WANTED_LOCKFILE constant instead of
duplicating the literal lockfile name, preserving the current
temporary-directory setup and path behavior.
- Around line 491-493: Extend the test around writeWantedLockfile to verify that
realLockfile remains a symbolic link after the write, using the filesystem
metadata or symlink assertion already established by the preceding test. Keep
the existing content and mtime checks unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 42f81d41-a39f-4d31-bb11-2275a0f273ef

📥 Commits

Reviewing files that changed from the base of the PR and between b12578d and 12ff792.

📒 Files selected for processing (6)
  • pnpm/crates/lockfile/src/save_lockfile.rs
  • pnpm/crates/lockfile/src/save_lockfile/tests.rs
  • pnpm11/lockfile/fs/src/write.ts
  • pnpm11/lockfile/fs/src/yamlDocuments.ts
  • pnpm11/lockfile/fs/test/write.test.ts
  • pnpm11/lockfile/fs/test/yamlDocuments.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • pnpm/crates/lockfile/src/save_lockfile/tests.rs
  • pnpm/crates/lockfile/src/save_lockfile.rs
  • pnpm11/lockfile/fs/src/write.ts
  • pnpm11/lockfile/fs/src/yamlDocuments.ts

Replacing pnpm-lock.yaml through a temp file and rename drops what the
previous write-file-atomic call preserved: it stats the target and restores
its owner onto the replacement. Without that, an install running as another
user -- root in a container over a bind-mounted repo is the common case --
leaves the lockfile owned by root, and its owner can no longer write it.

Carry the target's ownership across, tolerating an ownership change we lack
the privileges for exactly as write-file-atomic does: the file simply stays
ours rather than failing the install.

Cover the mode against a umask that would strip it, which the create-time
mode argument alone does not survive.

@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.

🧹 Nitpick comments (1)
pnpm11/lockfile/fs/test/write.test.ts (1)

559-564: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Strengthen the temp-file cleanup test to cover the update path.

The current test successfully verifies that temporary files are cleaned up during the initial lockfile creation. To ensure they are also cleaned up during a lockfile rewrite (which executes additional chown and chmod logic), consider triggering an update by calling writeWantedLockfile again with changed content before the assertion.

♻️ Proposed strengthening
 testOnNonWindows('writeWantedLockfile() leaves no temp file behind', async () => {
   const projectPath = temporaryDirectory()
   await writeWantedLockfile(projectPath, upToDateLockfile)
+  await writeWantedLockfile(projectPath, changedLockfile)
 
   expect(fs.readdirSync(projectPath)).toStrictEqual([WANTED_LOCKFILE])
 })
🤖 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 `@pnpm11/lockfile/fs/test/write.test.ts` around lines 559 - 564, Strengthen the
test “writeWantedLockfile() leaves no temp file behind” by calling
writeWantedLockfile a second time with changed lockfile content before
inspecting the directory. Keep the final readdirSync assertion verifying that
only WANTED_LOCKFILE remains, covering cleanup during the rewrite path and its
chown/chmod logic.
🤖 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.

Nitpick comments:
In `@pnpm11/lockfile/fs/test/write.test.ts`:
- Around line 559-564: Strengthen the test “writeWantedLockfile() leaves no temp
file behind” by calling writeWantedLockfile a second time with changed lockfile
content before inspecting the directory. Keep the final readdirSync assertion
verifying that only WANTED_LOCKFILE remains, covering cleanup during the rewrite
path and its chown/chmod logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 668508eb-0b96-40ab-b755-c94778799ebb

📥 Commits

Reviewing files that changed from the base of the PR and between 12ff792 and c793be8.

📒 Files selected for processing (3)
  • pnpm11/lockfile/fs/src/write.ts
  • pnpm11/lockfile/fs/src/yamlDocuments.ts
  • pnpm11/lockfile/fs/test/write.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • pnpm11/lockfile/fs/src/write.ts
  • pnpm11/lockfile/fs/src/yamlDocuments.ts

zkochan added a commit that referenced this pull request Oct 22, 2026
…nfig

A repository commits the lockfile symlink, so it decides where the link
points. If its pnpm-workspace.yaml could also allow writing through the
link, a cloned repository could overwrite any file the user can write,
even with scripts disabled. The refusal kept by #13075 exists
to prevent exactly that.

Treat the setting as machine-only, like tools and ci: it is honored from
the global config.yaml and PNPM_CONFIG_ALLOW_SYMLINKED_LOCKFILE, and
dropped from pnpm-workspace.yaml and config dependency entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zkochan added a commit that referenced this pull request Oct 25, 2026
…nfig

A repository commits the lockfile symlink, so it decides where the link
points. If its pnpm-workspace.yaml could also allow writing through the
link, a cloned repository could overwrite any file the user can write,
even with scripts disabled. The refusal kept by #13075 exists
to prevent exactly that.

Treat the setting as machine-only, like tools and ci: it is honored from
the global config.yaml and PNPM_CONFIG_ALLOW_SYMLINKED_LOCKFILE, and
dropped from pnpm-workspace.yaml and config dependency entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zkochan added a commit that referenced this pull request Oct 25, 2026
…nfig

A repository commits the lockfile symlink, so it decides where the link
points. If its pnpm-workspace.yaml could also allow writing through the
link, a cloned repository could overwrite any file the user can write,
even with scripts disabled. The refusal kept by #13075 exists
to prevent exactly that.

Treat the setting as machine-only, like tools and ci: it is honored from
the global config.yaml and PNPM_CONFIG_ALLOW_SYMLINKED_LOCKFILE, and
dropped from pnpm-workspace.yaml and config dependency entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pnpm 11.11.0 refuses to read symlinked pnpm-lock.yaml (ERR_PNPM_LOCKFILE_IS_SYMLINK)

3 participants