Skip to content

Commit 7beca2f

Browse files
Follow a link that leads out of the project when judging a pnpm store, so Bazel workspaces are covered (#2353) (#2443)
* Follow a link that leads out of the project instead of keeping every pnpm entry A link in the project to a directory outside it kept every pnpm store entry, because what that directory's `node_modules` link was not read (#2430). One such link switched the fix of #2353 off for the whole project, and every Bazel workspace has four of them (`bazel-bin`, `bazel-out`, `bazel-testlogs`, `bazel-<name>`); a `link:` dependency on another checkout is one too. Such a link is now followed, since node loads what is behind it from where it really is. A directory behind it is read like the project. So is each `node_modules` in a directory above it, or above a file behind such a link, which is where node looks up the packages of what it loads from there: a member that left the workspace keeps the links pnpm wrote for it. The home directory and what lies above it are not looked at, as in git's own lookup. One budget of 500,000 directories and links holds for everything read, every link goes through the same checks as the ones in the project, and every entry is still kept when a directory cannot be read or the budget runs out. This also replaces the rule for a link to a file outside the project (every entry kept when a `node_modules` sits above the file): those `node_modules` are read, so one that links nothing changes nothing. Measured in a Bazel 9.3.2 workspace that links about 1,200 packages with aspect_rules_js 3.6.0: about 7,000 directories and 6,700 links behind the `bazel-*` links, and 9,200 directories of external repository contents behind those. After a vendored scan and the in-place install, vex attests without a warning; a link to the upstream entry in `bazel-bin`, in an external repository's contents or in a `node_modules` above the output tree's workspace directory brings the warning back. Following the links lists directories and resolves links outside the git checkout. No file is opened there. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Read what a project's links lead to once, up to the home directory Following a link out of the project was done per store and per link, which left several gaps the review found: - A `node_modules` above a directory outside the project that is itself a link was not followed, so a link into the store behind it went unread. - A link to the home directory, or to one above it, was read like any other directory. It now keeps every entry, and no `node_modules` at the home directory or above it is looked at. - Bazel's `bazel-bin`, `bazel-out` and `bazel-<name>` lead to directories inside each other. Each was read in full and charged against the budget again. A directory is now read once, around what was read already. - Each store of a project repeated the whole pass, and a pass that failed was repeated as well. The links reached from a tree are now kept for the run, failures included. - A link to a file outside the project is handled as before this branch: it keeps every entry when a `node_modules` sits in a directory above the file. It is judged after every directory is read, so a file inside a directory that a later link leads to is not held against a `node_modules` that was read. The unit tests take the home directory as a value, so nothing of the machine's own home or temp directory is read by them. Part of #2353. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Bound the read outside a pnpm project by identity, order and budget Review findings on following a link out of the project: - The home directory was told by its path alone, so a link that spells it another way (macOS reaches it under /System/Volumes/Data as well) had the whole home directory read. It is told by identity now. - Each directory read was held against every directory read before it. With many separate directories outside that is quadratic. They are kept in order, and those below one are found by range. - A `node_modules` looked for above a directory outside was not charged to the budget. Each lookup counts now. - The real-pnpm steps read `node_modules` in every directory above the machine's temp directory. They run with the test's own directory as the home directory. - The independent reading in the tests did not record a `node_modules` that is a link, so it missed one that leads into the store. It records it and reads what lies above its target, and a leg now makes such a link. - The docs still said nothing above the scanned directory is read. A directory above it is read when a link leads to it or below it. - Two doc comments named a function that was renamed. Part of #2353. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent dfa9a96 commit 7beca2f

6 files changed

Lines changed: 710 additions & 208 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -894,7 +894,7 @@ Recognition rules that hold for every ecosystem:
894894
| Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#<sha1>` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` |
895895
| Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none |
896896

897-
**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `<name>@socket-<id>+<version>` for a release routed through the registry of its patch and `<name>@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `<name>@<version>` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in or, above the scanned directory, is the home directory or above it; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or the directory holds more than 500,000 directories and links; when a link resolves to a directory outside the directory that was read, to a file outside it that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too.
897+
**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `<name>@socket-<id>+<version>` for a release routed through the registry of its patch and `<name>@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `<name>@<version>` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read for its own sake. A link to a directory outside it is followed: that directory, and each `node_modules` in a directory above it (up to the home directory, which is not read), are read the same way and once each, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read; a directory above the scanned one is read only this way. A link that leads nowhere (no target, a loop, a path through a file) is left out. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout), or the store's project lies above the git checkout the run started in or, above the scanned directory, is the home directory or above it; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the home directory or one above it, to a file outside what was read that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too.
898898

899899
**Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates:
900900

‎crates/socket-patch-cli/tests/common/pnpm_links.rs‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,49 @@ fn links_below(tree: &Path) -> Vec<(PathBuf, PathBuf)> {
4545
}
4646

4747
/// The entries of the virtual store `store` that a path which starts
48-
/// below `tree` and outside the store's entries leads into: each entry
49-
/// that a link outside the entries resolves into, each entry that a link
50-
/// inside one of those resolves into, and so on.
48+
/// below `tree`, or below what a link leads to outside it, and outside
49+
/// the store's entries leads into: each entry that a link outside the
50+
/// entries resolves into, each entry that a link inside one of those
51+
/// resolves into, and so on.
5152
pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet<String> {
5253
let tree = std::fs::canonicalize(tree).unwrap();
5354
let store = std::fs::canonicalize(store).unwrap();
54-
let links = links_below(&tree);
55+
// Node loads what a link leads to from where it really is: every
56+
// directory a link leads to outside the trees read so far is read as
57+
// well, and so is the `node_modules` of each directory above it. A
58+
// `node_modules` that is a link is one more link, and what it leads
59+
// to is read the same way. Nothing at the temp dir or above it is
60+
// read: the tests build below it.
61+
let stop = std::fs::canonicalize(std::env::temp_dir()).unwrap();
62+
let mut trees = vec![tree];
63+
let mut links = Vec::new();
64+
let mut next = 0;
65+
while next < trees.len() {
66+
let found = links_below(&trees[next]);
67+
next += 1;
68+
let mut targets: Vec<PathBuf> = found.iter().map(|(_, to)| to.clone()).collect();
69+
links.extend(found);
70+
while let Some(target) = targets.pop() {
71+
let read = trees.iter().any(|tree| target.starts_with(tree));
72+
if read || target.starts_with(&store) || !target.is_dir() || stop.starts_with(&target) {
73+
continue;
74+
}
75+
for above in target.ancestors().skip(1) {
76+
if stop.starts_with(above) {
77+
break;
78+
}
79+
let modules = above.join("node_modules");
80+
let Ok(real) = std::fs::canonicalize(&modules) else {
81+
continue;
82+
};
83+
if real != modules {
84+
links.push((modules, real.clone()));
85+
}
86+
targets.push(real);
87+
}
88+
trees.push(target);
89+
}
90+
}
5591
let mut reachable = BTreeSet::new();
5692
loop {
5793
let before = reachable.len();

‎crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3655,7 +3655,16 @@ fn write_route_workspace(proj: &Path, registry: &MockServer, modules_dir: Option
36553655
/// it attests with their status, and its stderr.
36563656
#[cfg(unix)]
36573657
fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, String) {
3658-
let (code, stdout, stderr) = run_socket(
3658+
route_vex_env(dir, server, &[])
3659+
}
3660+
3661+
/// [`route_vex`] with extra env.
3662+
fn route_vex_env(
3663+
dir: &Path,
3664+
server: &MockServer,
3665+
env: &[(String, String)],
3666+
) -> (i32, Vec<(String, String)>, String) {
3667+
let (code, stdout, stderr) = run_socket_env(
36593668
dir,
36603669
&[
36613670
"vex",
@@ -3670,6 +3679,7 @@ fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, St
36703679
"--patch-server-url",
36713680
&server.uri(),
36723681
],
3682+
env,
36733683
);
36743684
let statements = serde_json::from_str::<serde_json::Value>(&stdout)
36753685
.ok()
@@ -3911,6 +3921,78 @@ async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag:
39113921
attested.contains(&not_affected(leaf)),
39123922
"{tag}: without the links leaf is attested again: {attested:?}\n{stderr}"
39133923
);
3924+
3925+
// A link that leads out of the project is followed. A directory
3926+
// beside the project that links nothing of the store changes nothing;
3927+
// one whose `node_modules` links the upstream leaf, as a member that
3928+
// left the workspace keeps doing, refuses the patch. The test's own
3929+
// directory stands in for the home directory, so no `node_modules`
3930+
// that the machine keeps above it is read.
3931+
let home = [("HOME".to_string(), tmp.path().to_str().unwrap().to_string())];
3932+
let outside = tmp.path().join("shared");
3933+
std::fs::create_dir_all(outside.join("lib")).unwrap();
3934+
std::fs::create_dir_all(proj.join("tools")).unwrap();
3935+
std::os::unix::fs::symlink(outside.join("lib"), proj.join("tools/lib")).unwrap();
3936+
let (code, attested, stderr) = route_vex_env(&proj, &server, &home);
3937+
assert_eq!(
3938+
code, 0,
3939+
"{tag}: vex with a link out of the project:\n{stderr}"
3940+
);
3941+
assert!(
3942+
attested.contains(&not_affected(leaf)) && attested.contains(&not_affected(peer_user)),
3943+
"{tag}: a link to a directory that links nothing must change nothing: \
3944+
{attested:?}\n{stderr}"
3945+
);
3946+
std::fs::create_dir_all(outside.join("node_modules")).unwrap();
3947+
std::os::unix::fs::symlink(&old_leaf, outside.join("node_modules/leaf")).unwrap();
3948+
let reachable = pnpm_links::reachable_store_entries(&proj, &store);
3949+
assert!(
3950+
reachable.contains("leaf@1.0.0"),
3951+
"{tag}: the independent reading must follow the link out of the project: {reachable:?}"
3952+
);
3953+
let (code, attested, stderr) = route_vex_env(&proj, &server, &home);
3954+
assert_eq!(code, 0, "{tag}: vex with a stale member outside:\n{stderr}");
3955+
assert!(
3956+
!attested.contains(&not_affected(leaf))
3957+
&& attested.contains(&not_affected(peer_user))
3958+
&& stderr.contains("not_applied"),
3959+
"{tag}: a directory outside that links the upstream leaf must refuse its patch: \
3960+
{attested:?}\n{stderr}"
3961+
);
3962+
std::fs::remove_file(outside.join("node_modules/leaf")).unwrap();
3963+
let (code, attested, stderr) = route_vex_env(&proj, &server, &home);
3964+
assert_eq!(code, 0, "{tag}: vex once the stale link is gone:\n{stderr}");
3965+
assert!(
3966+
attested.contains(&not_affected(leaf)),
3967+
"{tag}: without the stale link leaf is attested again: {attested:?}\n{stderr}"
3968+
);
3969+
3970+
// A `node_modules` there that is a link itself is one more link: into
3971+
// the upstream entry's `node_modules`, it loads the upstream leaf.
3972+
std::fs::remove_dir(outside.join("node_modules")).unwrap();
3973+
std::os::unix::fs::symlink(old_leaf.parent().unwrap(), outside.join("node_modules")).unwrap();
3974+
let reachable = pnpm_links::reachable_store_entries(&proj, &store);
3975+
assert!(
3976+
reachable.contains("leaf@1.0.0"),
3977+
"{tag}: the independent reading must read a linked node_modules: {reachable:?}"
3978+
);
3979+
let (code, attested, stderr) = route_vex_env(&proj, &server, &home);
3980+
assert_eq!(
3981+
code, 0,
3982+
"{tag}: vex with a linked node_modules outside:\n{stderr}"
3983+
);
3984+
assert!(
3985+
!attested.contains(&not_affected(leaf)) && stderr.contains("not_applied"),
3986+
"{tag}: a node_modules outside that is a link into the upstream entry must refuse \
3987+
the patch: {attested:?}\n{stderr}"
3988+
);
3989+
std::fs::remove_file(outside.join("node_modules")).unwrap();
3990+
let (code, attested, stderr) = route_vex_env(&proj, &server, &home);
3991+
assert_eq!(code, 0, "{tag}: vex once that link is gone:\n{stderr}");
3992+
assert!(
3993+
attested.contains(&not_affected(leaf)),
3994+
"{tag}: without that link leaf is attested again: {attested:?}\n{stderr}"
3995+
);
39143996
}
39153997

39163998
#[cfg(unix)]

0 commit comments

Comments
 (0)