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 e088c638d..f97459091 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,17 @@ //! `--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. 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. @@ -61,15 +72,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; 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 +139,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 +402,63 @@ 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` 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"]); + 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 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 + // 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, 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 /// `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 +485,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. 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() { @@ -439,6 +528,10 @@ 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. + 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"]); cell.undone(&undo, "rolledBack", &before, &upstream.marker); @@ -456,10 +549,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 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(), @@ -470,7 +564,9 @@ fn hosted_npm_translate_lock() { ); } -/// The vendored flow of the module docs. +/// 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() { @@ -533,6 +629,10 @@ 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. + 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"]); cell.undone(&undo, "removed", &before, &upstream.marker); @@ -557,9 +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; `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, @@ -597,6 +699,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}")); } 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();