From 9a41046e5a9115ecc8684a597a9e01c4e42dcdcf Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 16:16:56 -0500 Subject: [PATCH 1/2] Record what an npm scan does after a Bazel build The two npm flows of the real-Bazel tests ran each command once. A pipeline runs it on every run, so both flows now run the command of their mode a second time, after the patched build, and ask `vex` for its document. That second run does not patch. On Bazel 9.3.2, 8.8.2 and 7.7.2, in hosted and in vendored mode: - `scan --mode --yes --json` exits 0 with status `success`, skips the package as `user_patch_conflict` and reports `scannedPackages: 0`. - `vex --output ` exits 1 (`no_applicable_patches`, the package omitted as `vex_npm_patched_dependency`) and writes no document. - No file of the checkout changes. The first run of either mode writes a `pnpm-workspace.yaml` with `packages: ['.']`. From then on the inspection of the project's own patches (`UserPatchIndex`, patch/user_patches.rs) walks that pattern, and for a pattern that names the root it lists the root's children. There it meets `bazel-`, the link Bazel keeps to its execution root. The checkout's `package.json` shows up again behind it, the walk does not follow links, and it records the link as a workspace member that "cannot be inspected safely", which protects every npm package. In a checkout without Bazel's links the second hosted scan reports the patch applied again, the second vendored scan reports `already_vendored`, and `vex` writes its document. This commit holds the tests to what the commands do today, so the fix in the next commit shows as a changed expectation. The step asks Bazel where the checkout is (`bazel info workspace`, which must succeed) and asserts that its four links are there: it cannot pass on a checkout without them. It asks for the `vex` document beside the workspace copy, inside the scratch root of the cell, so it writes nothing into the checkout or into the machine's temp directory. The fixture's package is scoped, and `socket-patch` spells its purl in two ways: `pkg:npm/@socketsecurity/...` in the `user_patch_conflict` event of either scan and in the `vex` event of the hosted flow, `pkg:npm/%40socketsecurity/...` in the `vex` event of the vendored flow and in the events of the first scans. The step compares purls through a helper that reads both as the one package, so it holds no event to a spelling. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/npm.rs | 110 ++++++++++++++++-- 1 file changed, 100 insertions(+), 10 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index e088c638d..e248eeebb 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -30,6 +30,15 @@ //! `--lockfile_mode=error` build passes. Hosted: Bazel fetched the //! tarball from the stand-in patch host. Vendored: the scan did, and //! Bazel read the committed file without a request to the stand-in. +//! Then the command of the mode runs a second time, as it does on every +//! run of a pipeline, and `vex` is asked for its document. Bazel has built +//! in the checkout by now and keeps its `bazel-*` links there, and the +//! first run left a `pnpm-workspace.yaml` that lists the root as its one +//! workspace package. Both commands take the link to Bazel's execution +//! root, where the checkout's `package.json` shows up again, for a +//! workspace member they cannot inspect: the scan exits 0 with status +//! `success` and skips the package as `user_patch_conflict`, and `vex` +//! exits 1 and writes no document. No file changes. //! - (d) The undo (`rollback --yes`, or `vendor --revert`): every file of //! the checkout is the one of before, byte for byte, and the build prints //! the unpatched marker again. @@ -61,15 +70,18 @@ //! that URL to the stand-in ([`route_registry`]), as a user behind a registry //! mirror has it. +use std::path::PathBuf; use std::time::Instant; use base64::Engine as _; use serde_json::{json, Value}; use sha2::{Digest, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; +use socket_patch_core::utils::purl::canonical_purl; +use crate::envelope::{event_triples, find_event}; use crate::harness::{ - changed, fixture_path, rewrite, Cell, Fixture, Ran, Run, StandIn, Tree, CONSUMER, + changed, fixture_path, rewrite, Cell, Fixture, Ran, Run, StandIn, Tree, CONSUMER, NOTHING, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -125,6 +137,22 @@ fn overriding_workspace(copy: &str) -> String { format!("packages:\n - '.'\noverrides:\n '{NAME}@{VERSION}': file:{copy}\n") } +/// The links Bazel keeps at the top of a checkout it has built in, beside +/// the one to its execution root, which is named for the checkout's +/// directory. +const BAZEL_LINKS: [&str; 3] = ["bazel-bin", "bazel-out", "bazel-testlogs"]; + +/// What a command reported: the events of its `envelope`, as +/// `event_triples` reads them, each purl in its canonical spelling. +/// `socket-patch` writes the `@` of an npm scope out in some of its events +/// and as `%40` in others. Both name the one package, so a test compares +/// events through this and holds none to either spelling. +fn reported(envelope: &Value) -> Vec<(String, String, String)> { + let triples = event_triples(envelope).into_iter(); + let canonical = triples.map(|(purl, action, code)| (canonical_purl(&purl), action, code)); + canonical.collect() +} + /// The package with `index_js` as its entry file, as a registry tarball. /// Every sum a test holds a build to is computed from the bytes it serves, /// so nothing depends on the exact bytes the archive crates emit. @@ -372,6 +400,54 @@ fn second_machine( (twin, other) } +/// The second half of step (c), in the checkout of `cell` that Bazel has +/// built in and that holds the files of `patched`: beside Bazel's links, +/// `scan --mode --yes` skips the package as `user_patch_conflict`, +/// for the link to the execution root, and scans none; `vex` fails with one +/// event, which omits the package, and writes no document; and no file of +/// the checkout changes. +fn runs_again(cell: &Cell, standin: &StandIn, mode: &str, patched: &Tree) { + let test = &cell.test; + // Bazel says where the checkout is, and its links are there. + let info = cell.bazel("info", &["workspace"]); + assert!(info.ok(), "{test}: {}", info.dump()); + let checkout = PathBuf::from(info.stdout().trim()); + let named = checkout.file_name().expect("the checkout's directory"); + let root_link = format!("bazel-{}", named.to_string_lossy()); + for link in BAZEL_LINKS.into_iter().chain([root_link.as_str()]) { + let link = checkout.join(link); + assert!(link.is_symlink(), "{test}: no link {}", link.display()); + } + let one = |action: &str, code: &str| [(canonical_purl(PURL), action.into(), code.into())]; + + let scan = socket_patch(cell, standin, &["scan", "--mode", mode, "--yes"]); + let said = &scan.dump; + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + let conflict = "user_patch_conflict"; + let skipped = one("skipped", conflict); + assert_eq!(reported(&scan.envelope), skipped, "{test}: {said}"); + let reason = find_event(&scan.envelope, "skipped", Some(conflict))["reason"].as_str(); + let link = "/bazel-ws (linked workspace cannot be inspected safely)"; + assert!(reason.is_some_and(|r| r.contains(link)), "{test}: {said}"); + assert_eq!(scan.envelope["scannedPackages"], 0, "{test}: {said}"); + + // The document goes beside the checkout, into the scratch root of the + // cell, where nothing has that name: it is no file of the checkout, and + // none of the machine's shared temp directory. + let document = checkout.parent().expect("a scratch root").join("vex.json"); + assert!(!document.exists(), "{test}: {}", document.display()); + let output = document.to_string_lossy(); + let vex = socket_patch(cell, standin, &["vex", "--output", &output]); + let said = &vex.dump; + assert_eq!(vex.code, 1, "{test}: {said}"); + let omitted = one("skipped", "vex_npm_patched_dependency"); + assert_eq!(reported(&vex.envelope), omitted, "{test}: {said}"); + assert!(!document.exists(), "{test}: {said}"); + + assert_eq!(changed(patched, &cell.tree()), NOTHING, "{test}"); +} + /// Step (e): the build of `twin` fails because Bazel finds the sha512 of /// `found` where the lock pins that of `pinned`, and the registry is not /// asked for the upstream tarball instead. Gives the build and the line it @@ -398,7 +474,9 @@ fn refuses(twin: &Cell, other: &StandIn, found: &[u8], pinned: &[u8]) -> (Run, S (build, refusal) } -/// The hosted flow of the module docs. +/// The hosted flow of the module docs. Today its second scan, beside the +/// links of the Bazel that built in the checkout, skips the package as +/// `user_patch_conflict`, and `vex` writes no document. #[test] #[ignore = "real Bazel; run with --ignored"] fn hosted_npm_translate_lock() { @@ -439,6 +517,9 @@ fn hosted_npm_translate_lock() { "{test}: the patched build did not fetch the tarball from the stand-in patch host" ); + // The same command and `vex`, now that Bazel has built in the checkout. + runs_again(&cell, &standin, "hosted", &pinned); + // (d) The undo: every file is the one of before, and so is the build. let undo = socket_patch(&cell, &standin, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, &upstream.marker); @@ -456,10 +537,11 @@ fn hosted_npm_translate_lock() { ); println!( - "{test}: Bazel {release} built {:?} from {origin}{} after `scan --mode hosted`; `rollback` \ - restored all {} files and the {:?} build; other bytes at the patch host failed a second \ - machine's build ({refusal}); the stand-in answered {} requests for the upstream tarball \ - and {} for the patched one; {:?}", + "{test}: Bazel {release} built {:?} from {origin}{} after `scan --mode hosted`; beside \ + Bazel's links a second scan skipped the package as user_patch_conflict and `vex` wrote \ + no document; `rollback` restored all {} files and the {:?} build; other bytes at the \ + patch host failed a second machine's build ({refusal}); the stand-in answered {} \ + requests for the upstream tarball and {} for the patched one; {:?}", patch.package.marker, patch.route, before.len(), @@ -470,7 +552,9 @@ fn hosted_npm_translate_lock() { ); } -/// The vendored flow of the module docs. +/// The vendored flow of the module docs. Today its second scan, beside the +/// links of the Bazel that built in the checkout, skips the package as +/// `user_patch_conflict`, and `vex` writes no document. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_npm_translate_lock() { @@ -533,6 +617,9 @@ fn vendored_npm_translate_lock() { cell.builds_patched(&vendored, &patch.package.marker); assert_eq!(standin.requests(), requests, "{test}: Bazel asked a host"); + // The same command and `vex`, now that Bazel has built in the checkout. + runs_again(&cell, &standin, "vendored", &vendored); + // (d) The undo: every file is the one of before, and so is the build. let undo = socket_patch(&cell, &standin, &["vendor", "--revert"]); cell.undone(&undo, "removed", &before, &upstream.marker); @@ -557,9 +644,11 @@ fn vendored_npm_translate_lock() { println!( "{test}: Bazel {release} built {:?} from {copy} after `scan --mode vendored`, with no \ - request to the stand-in; `vendor --revert` restored all {} files and the {:?} build; \ - other bytes in the committed tarball failed a second machine's build ({refusal}); the \ - stand-in answered {} requests for the upstream tarball and {} for the patched one; {:?}", + request to the stand-in; beside Bazel's links a second scan skipped the package as \ + user_patch_conflict and `vex` wrote no document; `vendor --revert` restored all {} \ + files and the {:?} build; other bytes in the committed tarball failed a second \ + machine's build ({refusal}); the stand-in answered {} requests for the upstream tarball \ + and {} for the patched one; {:?}", patch.package.marker, before.len(), upstream.marker, @@ -597,6 +686,7 @@ fn a_test_pins_the_one_entry_of_the_fixture_lock() { assert_eq!(manifest["version"], VERSION); let bare = NAME.strip_prefix("@socketsecurity/").expect("the scope"); assert_eq!(PURL, format!("pkg:npm/%40socketsecurity/{bare}@{VERSION}")); + assert_eq!(canonical_purl(PURL), format!("pkg:npm/{NAME}@{VERSION}")); assert_eq!(TGZ, format!("{bare}-{VERSION}.tgz")); assert_eq!(UPSTREAM_TGZ, format!("/{REGISTRY}/{NAME}/-/{TGZ}")); } From 8dfd6ead32ddde5bb806bf43f19c89749ac37697 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 16:16:57 -0500 Subject: [PATCH 2/2] Take the root alone for a workspace pattern that names the root After a Bazel build, the next `scan --mode hosted` or `scan --mode vendored` of an npm project skipped every npm package as `user_patch_conflict`, with exit 0 and status `success`, and `vex` exited 1 without a document. The previous commit holds the tests to that, on Bazel 9.3.2, 8.8.2 and 7.7.2 with aspect_rules_js 3.6.0. Bazel is only where it showed. The first scan of either mode writes a `pnpm-workspace.yaml` with `packages: ['.']`. The inspection of the project's own patches (`UserPatchIndex::workspace_members`) walks each pattern to a depth it takes from the pattern's segments. `.` leaves no segment, but the depth was counted on the segments joined again, and an empty string split at `/` is one item. So for a pattern that names the root the walk listed the root's children, one level, as it does for `*`. No child can match an empty pattern, so no member ever came of that listing. What came of it: every link at the root that leads to a directory with a `package.json` was recorded as a workspace member that "cannot be inspected safely", and one such entry protects every npm package of the project. Bazel's `bazel-` is such a link (its execution root shows the checkout's files again). So is a Nix `result`, a `current -> releases/x`, or a link to the checkout of another package. The depth is now the number of segments after the literal prefix, counted on the segments themselves: none for `.`, and what it was for every pattern that has a segment. A pattern that names the root then has one member, the root, and nothing below the root is listed. That is what the package managers take for it. pnpm appends `/package.json` to each pattern, globs for those files from the workspace root, and adds `.` itself to every list (`findPackages` and `findWorkspacePackagesNoCheck`, which pnpm 11 names `findWorkspaceProjectsNoCheck`, read in the bundles of pnpm 8.15.9, 9.15.9, 10.34.5 and 11.27.0); npm globs for the folder `/` (`@npmcli/map-workspaces` 5.0.3). `.` finds the root and no other directory. What is still read. The root is read before any pattern is looked at: its `package.json`, `patches/` and every `--patch-dir` of its scripts, its `pnpm-workspace.yaml`, its locks, and the ancestors that hold a workspace file. The walk never took a member from the root's children for such a pattern, so the directories read are the ones read before; the unit tests hold the list of directories read in each case. A pattern with a segment of its own is walked exactly as before, beside a root pattern too: `*`, `packages/*`, `**` and a literal path record a link that is or leads to a member as they did. Two other entries could come from listing the root for such a pattern and no longer do: "cannot inspect workspace" when the root directory itself cannot be listed, and the limit of 16,384 entries for a root with that many directories and links. Neither stood for a member or a patch that went unread. The same holds for every spelling that leaves no segment: `./`, `''`, `./.`, `.//`, `packages/..`, and a `..` that names an ancestor alone (its children are not listed either; an ancestor outside the repository is refused as before). A `!` pattern never reached the walk. Both `pnpm-workspace.yaml` and the `workspaces` of a `package.json` go through this walk. There is no Bazel-specific code. Not covered: - A root-level wildcard (`packages: ['*']` or `['**']`) at a Bazel root. Bazel's links match such a pattern, so after a build a scan still skips every npm package as `user_patch_conflict`. A safe skip there has to look at where a link leads, which is a change of its own. - `list_patch_directory` follows a linked directory, so a project whose scripts run `patch-package --patch-dir .` at a Bazel root still lists Bazel's output tree through its links. Unit tests in `user_patches.rs`, with real links and no Bazel file. Each spelling of the root, in either file, yields no entry, reads the root alone and finds the root's patch; beside `packages/*` that pattern's link is recorded and the root's is not. The twin holds seven patterns with a segment to the directories and the links they give without this change. The in-memory view is held to the same. On real Bazel the two npm flows now expect of the second run what the commands report in a checkout without Bazel's links (measured on 9.3.2 with the walk as it was and a Bazel that makes no links): the hosted scan reports the patch applied again, the vendored scan reports `already_vendored`, `vex` exits 0 and its document names the package, no file changes and the build is still the patched one. bazel-npm.yml starts the npm legs on a pull request, as on a push to main, that changes `patch/user_patches.rs`. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-npm.yml | 10 +- .../tests/e2e_bazel_build/npm.rs | 93 ++++++----- .../src/patch/user_patches.rs | 155 +++++++++++++++++- 3 files changed, 213 insertions(+), 45 deletions(-) diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index ae9c89092..ec106bc7c 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -30,7 +30,13 @@ on: # vendor/npm_*, the lock inventory), the `pnpm-workspace.yaml` lookup, # the npm-family lock and config readers (vex/discover/npm.rs, # patch/redirect/npmrc.rs), the upstream restore of `rollback`, the - # crawler every `scan` starts, and the `package.json` reader. The + # crawler every `scan` starts, and the `package.json` reader. One file + # is here for what the flows assert, not for that build: + # patch/user_patches.rs, the inspection of the project's own patches. + # Its walk of the pnpm workspace decides what the second run of each + # flow reports, and no other test runs it beside Bazel's links. That + # file also holds the Composer, Cargo and Go parts of the gate, so a + # change to those starts the npm legs too. The # globs name that one crate, so no bench fixture is here, and nothing # another ecosystem's flow owns: a change to one ecosystem starts that # ecosystem's legs only. @@ -59,6 +65,7 @@ on: - 'crates/socket-patch-core/src/vex/discover/npm.rs' - 'crates/socket-patch-core/src/crawlers/npm_crawler.rs' - 'crates/socket-patch-core/src/formats/package_json.rs' + - 'crates/socket-patch-core/src/patch/user_patches.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -84,6 +91,7 @@ on: - 'crates/socket-patch-core/src/vex/discover/npm.rs' - 'crates/socket-patch-core/src/crawlers/npm_crawler.rs' - 'crates/socket-patch-core/src/formats/package_json.rs' + - 'crates/socket-patch-core/src/patch/user_patches.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/vendor/**' diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index e248eeebb..f97459091 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -34,11 +34,13 @@ //! run of a pipeline, and `vex` is asked for its document. Bazel has built //! in the checkout by now and keeps its `bazel-*` links there, and the //! first run left a `pnpm-workspace.yaml` that lists the root as its one -//! workspace package. Both commands take the link to Bazel's execution -//! root, where the checkout's `package.json` shows up again, for a -//! workspace member they cannot inspect: the scan exits 0 with status -//! `success` and skips the package as `user_patch_conflict`, and `vex` -//! exits 1 and writes no document. No file changes. +//! workspace package. That pattern names the root alone, so no link at +//! the root is taken for a workspace member, the one to Bazel's execution +//! root included, where the checkout's `package.json` shows up again: +//! both commands see the package as they do in a checkout without the +//! links. The hosted scan reports the patch applied again and the +//! vendored one reports it `already_vendored`, `vex` attests the package, +//! no file changes, and the build is still the patched one. //! - (d) The undo (`rollback --yes`, or `vendor --revert`): every file of //! the checkout is the one of before, byte for byte, and the build prints //! the unpatched marker again. @@ -79,7 +81,7 @@ use sha2::{Digest, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use socket_patch_core::utils::purl::canonical_purl; -use crate::envelope::{event_triples, find_event}; +use crate::envelope::event_triples; use crate::harness::{ changed, fixture_path, rewrite, Cell, Fixture, Ran, Run, StandIn, Tree, CONSUMER, NOTHING, }; @@ -401,12 +403,20 @@ fn second_machine( } /// The second half of step (c), in the checkout of `cell` that Bazel has -/// built in and that holds the files of `patched`: beside Bazel's links, -/// `scan --mode --yes` skips the package as `user_patch_conflict`, -/// for the link to the execution root, and scans none; `vex` fails with one -/// event, which omits the package, and writes no document; and no file of -/// the checkout changes. -fn runs_again(cell: &Cell, standin: &StandIn, mode: &str, patched: &Tree) { +/// built in and that holds the files of `patched`. Beside Bazel's links, +/// `scan --mode --yes` scans the package and reports the one event +/// `seen` for it (an action and an error code), which is what it reports in +/// a checkout without those links; `vex` attests the package in its +/// document; no file of the checkout changes; and the build still prints +/// `marker`. +fn runs_again( + cell: &Cell, + standin: &StandIn, + mode: &str, + seen: (&str, &str), + patched: &Tree, + marker: &str, +) { let test = &cell.test; // Bazel says where the checkout is, and its links are there. let info = cell.bazel("info", &["workspace"]); @@ -424,13 +434,9 @@ fn runs_again(cell: &Cell, standin: &StandIn, mode: &str, patched: &Tree) { let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); - let conflict = "user_patch_conflict"; - let skipped = one("skipped", conflict); - assert_eq!(reported(&scan.envelope), skipped, "{test}: {said}"); - let reason = find_event(&scan.envelope, "skipped", Some(conflict))["reason"].as_str(); - let link = "/bazel-ws (linked workspace cannot be inspected safely)"; - assert!(reason.is_some_and(|r| r.contains(link)), "{test}: {said}"); - assert_eq!(scan.envelope["scannedPackages"], 0, "{test}: {said}"); + let seen = one(seen.0, seen.1); + assert_eq!(reported(&scan.envelope), seen, "{test}: {said}"); + assert_eq!(scan.envelope["scannedPackages"], 1, "{test}: {said}"); // The document goes beside the checkout, into the scratch root of the // cell, where nothing has that name: it is no file of the checkout, and @@ -440,12 +446,17 @@ fn runs_again(cell: &Cell, standin: &StandIn, mode: &str, patched: &Tree) { let output = document.to_string_lossy(); let vex = socket_patch(cell, standin, &["vex", "--output", &output]); let said = &vex.dump; - assert_eq!(vex.code, 1, "{test}: {said}"); - let omitted = one("skipped", "vex_npm_patched_dependency"); - assert_eq!(reported(&vex.envelope), omitted, "{test}: {said}"); - assert!(!document.exists(), "{test}: {said}"); + assert_eq!(vex.code, 0, "{test}: {said}"); + let attested = one("verified", ""); + assert_eq!(reported(&vex.envelope), attested, "{test}: {said}"); + let written = std::fs::read_to_string(&document).unwrap_or_default(); + // With its closing quote, as the document writes `"@id": ""`: a + // longer version that only starts so is another package. + let names = written.contains(&format!("\"{PURL}\"")); + assert!(names, "{test}: {said}\n{written}"); assert_eq!(changed(patched, &cell.tree()), NOTHING, "{test}"); + cell.builds_patched(patched, marker); } /// Step (e): the build of `twin` fails because Bazel finds the sha512 of @@ -474,9 +485,9 @@ fn refuses(twin: &Cell, other: &StandIn, found: &[u8], pinned: &[u8]) -> (Run, S (build, refusal) } -/// The hosted flow of the module docs. Today its second scan, beside the -/// links of the Bazel that built in the checkout, skips the package as -/// `user_patch_conflict`, and `vex` writes no document. +/// The hosted flow of the module docs. Its second scan, beside the links of +/// the Bazel that built in the checkout, reports the patch applied again, +/// and `vex` writes a document that attests the package. #[test] #[ignore = "real Bazel; run with --ignored"] fn hosted_npm_translate_lock() { @@ -518,7 +529,8 @@ fn hosted_npm_translate_lock() { ); // The same command and `vex`, now that Bazel has built in the checkout. - runs_again(&cell, &standin, "hosted", &pinned); + let (seen, marker) = (("applied", ""), &patch.package.marker); + runs_again(&cell, &standin, "hosted", seen, &pinned, marker); // (d) The undo: every file is the one of before, and so is the build. let undo = socket_patch(&cell, &standin, &["rollback", "--yes"]); @@ -538,10 +550,10 @@ fn hosted_npm_translate_lock() { println!( "{test}: Bazel {release} built {:?} from {origin}{} after `scan --mode hosted`; beside \ - Bazel's links a second scan skipped the package as user_patch_conflict and `vex` wrote \ - no document; `rollback` restored all {} files and the {:?} build; other bytes at the \ - patch host failed a second machine's build ({refusal}); the stand-in answered {} \ - requests for the upstream tarball and {} for the patched one; {:?}", + Bazel's links a second scan reported the patch applied again, `vex` attested the \ + package and the build stayed patched; `rollback` restored all {} files and the {:?} \ + build; other bytes at the patch host failed a second machine's build ({refusal}); the \ + stand-in answered {} requests for the upstream tarball and {} for the patched one; {:?}", patch.package.marker, patch.route, before.len(), @@ -552,9 +564,9 @@ fn hosted_npm_translate_lock() { ); } -/// The vendored flow of the module docs. Today its second scan, beside the -/// links of the Bazel that built in the checkout, skips the package as -/// `user_patch_conflict`, and `vex` writes no document. +/// The vendored flow of the module docs. Its second scan, beside the links +/// of the Bazel that built in the checkout, reports the package +/// `already_vendored`, and `vex` writes a document that attests it. #[test] #[ignore = "real Bazel; run with --ignored"] fn vendored_npm_translate_lock() { @@ -618,7 +630,8 @@ fn vendored_npm_translate_lock() { assert_eq!(standin.requests(), requests, "{test}: Bazel asked a host"); // The same command and `vex`, now that Bazel has built in the checkout. - runs_again(&cell, &standin, "vendored", &vendored); + let (seen, marker) = (("skipped", "already_vendored"), &patch.package.marker); + runs_again(&cell, &standin, "vendored", seen, &vendored, marker); // (d) The undo: every file is the one of before, and so is the build. let undo = socket_patch(&cell, &standin, &["vendor", "--revert"]); @@ -644,11 +657,11 @@ fn vendored_npm_translate_lock() { println!( "{test}: Bazel {release} built {:?} from {copy} after `scan --mode vendored`, with no \ - request to the stand-in; beside Bazel's links a second scan skipped the package as \ - user_patch_conflict and `vex` wrote no document; `vendor --revert` restored all {} \ - files and the {:?} build; other bytes in the committed tarball failed a second \ - machine's build ({refusal}); the stand-in answered {} requests for the upstream tarball \ - and {} for the patched one; {:?}", + request to the stand-in; beside Bazel's links a second scan reported the package \ + already_vendored, `vex` attested it and the build stayed patched; `vendor --revert` \ + restored all {} files and the {:?} build; other bytes in the committed tarball failed \ + a second machine's build ({refusal}); the stand-in answered {} requests for the \ + upstream tarball and {} for the patched one; {:?}", patch.package.marker, before.len(), upstream.marker, diff --git a/crates/socket-patch-core/src/patch/user_patches.rs b/crates/socket-patch-core/src/patch/user_patches.rs index 9ac012054..f981d270e 100644 --- a/crates/socket-patch-core/src/patch/user_patches.rs +++ b/crates/socket-patch-core/src/patch/user_patches.rs @@ -625,10 +625,12 @@ impl UserPatchIndex { let max_depth = if pattern.contains("**") { 32 } else { - pattern - .split('/') - .count() - .saturating_sub(prefix.components().count()) + // One level for each segment after the literal prefix. A pattern + // with no segment left (`.`, `./`) names its base alone, as a + // literal path does: a package manager takes that one directory + // for it, so nothing below the base is listed. (Split again at + // `/`, the empty pattern would count as one segment.) + segments.len().saturating_sub(prefix.components().count()) }; let skipped = |name: &str| WALK_SKIP.contains(&name); let mut out = Vec::new(); @@ -1767,6 +1769,151 @@ mod tests { assert!(!index.conflicts("pkg:npm/child@1.0.0").is_empty()); } + /// A project, in `proj` of a new directory, that lists `patterns` as its + /// workspace packages: in `pnpm-workspace.yaml`, or in the `workspaces` + /// of its `package.json`. It is its own git repository, so the walk + /// reads nothing above it. Three links lead to a directory outside it + /// that holds a `package.json`: `result` at the root, `packages/linked` + /// beside the member `packages/real`, and `packages/real/deep` inside + /// that member. The root holds a patch-package patch. + #[cfg(unix)] + fn linked_project(patterns: &[&str], in_manifest: bool) -> tempfile::TempDir { + let tmp = tempfile::tempdir().unwrap(); + let (root, out) = (tmp.path().join("proj"), tmp.path().join("out")); + let patterns = serde_json::json!(patterns); + write(&out, "package.json", "{}"); + write(&root, ".git/HEAD", "ref: refs/heads/main\n"); + if in_manifest { + let manifest = serde_json::json!({ "workspaces": patterns }); + write(&root, "package.json", &manifest.to_string()); + } else { + write(&root, "package.json", "{}"); + let workspace = format!("packages: {patterns}\n"); + write(&root, "pnpm-workspace.yaml", &workspace); + } + write(&root, "patches/mine+1.0.0.patch", "diff"); + write(&root, "packages/real/package.json", "{}"); + write(&root, "other/package.json", "{}"); + for link in ["result", "packages/linked", "packages/real/deep"] { + std::os::unix::fs::symlink(&out, root.join(link)).unwrap(); + } + tmp + } + + /// Holds what the walk does in a [`linked_project`] of `patterns`, + /// listed in either file, through the consent gate (which names a + /// source by its full path) and through the view the hosted engine and + /// `vex` read. It reads the root and the directories `members` (both + /// lists are sorted, with a space between entries) and no other; it + /// finds the root's own patch; and `links`, and nothing else, protect + /// an npm package no patch names, each as a workspace member that + /// cannot be inspected. + #[cfg(unix)] + async fn walks(patterns: &[&str], members: &str, links: &str) { + let why = "(linked workspace cannot be inspected safely)"; + for in_manifest in [false, true] { + let said = format!("{patterns:?} in_manifest={in_manifest}"); + let tmp = linked_project(patterns, in_manifest); + let root = tmp.path().join("proj"); + let disk = ProjectView::Disk(&root); + let scope = ReadScope::Workspace; + let gate = UserPatchIndex::walk(&disk, Some(&root), Scope::Gate, scope).await; + let view = UserPatchIndex::walk(&disk, None, Scope::NpmFamily, scope).await; + for ((index, dirs), base) in [(gate, root.as_path()), (view, Path::new(""))] { + let dirs: Vec<&Path> = dirs.iter().map(|dir| dir.as_path()).collect(); + let read = [""].into_iter().chain(members.split_whitespace()); + assert_eq!(dirs, read.map(Path::new).collect::>(), "{said}"); + let shown = |rel: &str| base.join(rel).display().to_string(); + let named = links + .split_whitespace() + .map(|l| format!("{} {why}", shown(l))); + let unknown = index.conflicts("pkg:npm/other@1.0.0"); + assert_eq!(unknown, named.collect::>(), "{said}"); + let mine = index.conflicts("pkg:npm/mine@1.0.0"); + let patch = shown("patches/mine+1.0.0.patch"); + assert!(mine.contains(&patch), "{said}: {mine:?}"); + } + } + } + + /// A pattern that names the workspace root alone has one member, the + /// root, which the walk reads before it looks at any pattern. pnpm + /// globs for the file `/package.json` and npm for the folder + /// `/`, so `.` finds the root and no other directory: nothing + /// below the root is a member, and a link there is none either, + /// wherever it leads. So the root's children are not listed, in any + /// spelling of the root. Beside a pattern with a segment of its own, + /// that pattern's link is still recorded and the root's is not. (A `!` + /// pattern never reaches the walk, so `!.` alone lists nothing under + /// any rule.) + #[cfg(unix)] + #[tokio::test] + async fn a_pattern_that_names_the_root_takes_the_root_alone() { + let spellings = [".", "./", "", "./.", ".//", "packages/..", "!."]; + for root in spellings { + walks(&[root], "", "").await; + } + walks(&[".", "!packages/*"], "", "").await; + walks(&[".", "packages/*"], "packages/real", "packages/linked").await; + } + + /// The twin of the test above: a pattern with a segment of its own is + /// walked to the depth of its segments and no deeper, as it was before + /// the root was told apart, and a link there that is or leads to a + /// member is recorded. `*` lists the root's children; `packages/*` + /// those of `packages` and nothing inside a member; a literal path its + /// one directory; `**` every directory. + #[cfg(unix)] + #[tokio::test] + async fn a_pattern_with_a_segment_still_records_its_linked_members() { + let every_link = "packages/linked packages/real/deep result"; + // The pattern, the members read, the links recorded. + let cases = [ + ("*", "other", "result"), + ("packages/*", "packages/real", "packages/linked"), + ("packages/real/*", "", "packages/real/deep"), + ("packages/real", "packages/real", ""), + ("result", "", "result"), + ("packages/linked", "", "packages/linked"), + ("**", "other packages/real", every_link), + ]; + for (pattern, members, links) in cases { + walks(&[pattern], members, links).await; + } + } + + /// An in-memory project, where a link leads nowhere: a pattern that + /// names the root records none, and a pattern that names a link + /// records that link. + #[tokio::test] + async fn an_in_memory_root_pattern_takes_the_root_alone() { + use crate::vendor::lock_inventory::{MemoryEntry, MemoryProject}; + + let recorded = ["result (linked workspace cannot be inspected safely)"]; + let cases: [(&str, &[&str]); 4] = [ + ("['.']", &[]), + ("['./']", &[]), + ("['result']", &recorded), + ("['.', 'result']", &recorded), + ]; + for (patterns, links) in cases { + let mut memory = MemoryProject::new(); + let workspace = format!("packages: {patterns}\n"); + memory.insert("pnpm-workspace.yaml", MemoryEntry::Text(workspace.into())); + memory.insert("package.json", MemoryEntry::Text("{}".into())); + memory.insert("patches/mine+1.0.0.patch", MemoryEntry::Text("diff".into())); + memory.insert("result", MemoryEntry::Symlink); + let index = UserPatchIndex::npm_family_in(&ProjectView::Memory(&memory), &[]).await; + assert_eq!(index.conflicts("pkg:npm/other@1.0.0"), links, "{patterns}"); + let mine = index.conflicts("pkg:npm/mine@1.0.0"); + // A source is a path, which Windows writes with `\`. + let found = mine + .iter() + .any(|source| source.replace('\\', "/") == "patches/mine+1.0.0.patch"); + assert!(found, "{patterns}: {mine:?}"); + } + } + #[tokio::test] async fn composer_covers_external_locked_and_dependency_provided_patches() { let tmp = tempfile::tempdir().unwrap();