diff --git a/.github/workflows/bazel-go.yml b/.github/workflows/bazel-go.yml index e0e9afd8b..b189b3f12 100644 --- a/.github/workflows/bazel-go.yml +++ b/.github/workflows/bazel-go.yml @@ -23,12 +23,17 @@ on: # What a pull request run covers: the Go flow and its fixture, the # harness and the workflows that run it, the Bazel installer and its # pins, the Go files the flow runs through, as go-compatibility.yml - # lists them, and what socket-patch does only in a Bazel workspace - # (`bazel/`). Nothing another ecosystem's flow owns is here, so a change - # to one ecosystem starts that ecosystem's legs only. + # lists them, what socket-patch does only in a Bazel workspace + # (`bazel/`), and the VEX code: `vex/` of the core and the files of the + # `vex` command. Every flow holds the exact document socket-patch writes + # about its patched build, so a change to how a document is built or + # worded starts the legs of every ecosystem. Nothing else that another + # ecosystem's flow owns is here, so any other change to one ecosystem + # starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, - # hosted/, commands/), the shared test helpers and the toolchain files. + # hosted/, the rest of commands/), the shared test helpers and the + # toolchain files. # A change there gets its run on the push to main (when the file is in # the list below) or in the nightly run, not on the pull request: that # is the price of not running every ecosystem's legs on every shared @@ -45,6 +50,8 @@ on: - 'crates/*/src/**/*golang*/**' - 'crates/socket-patch-core/src/vendor/go*.rs' - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -65,6 +72,8 @@ on: - 'crates/*/src/**/*golang*/**' - 'crates/socket-patch-core/src/vendor/go*.rs' - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index ec106bc7c..699a19c2d 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -36,18 +36,21 @@ on: # 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. + # change to those starts the npm legs too. The `*pnpm*` globs name that + # one crate, so no bench fixture is here. Last, the VEX code: `vex/` of + # the core and the files of the `vex` command. Every flow holds the + # exact document socket-patch writes about its patched build, so a + # change to how a document is built or worded starts the legs of every + # ecosystem. Nothing else that another ecosystem's flow owns is here: + # any other change to one ecosystem starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, - # the rest of vendor/, hosted/, commands/), the shared test helpers and - # the toolchain files. A change there gets its run on the push to main - # (when the file is in the list below) or in the nightly run, not on the - # pull request: that is the price of not running every ecosystem's legs - # on every shared change. On demand, workflow_dispatch runs the legs on - # any branch. + # the rest of vendor/, hosted/, the rest of commands/), the shared test + # helpers and the toolchain files. A change there gets its run on the + # push to main (when the file is in the list below) or in the nightly + # run, not on the pull request: that is the price of not running every + # ecosystem's legs on every shared change. On demand, workflow_dispatch + # runs the legs on any branch. paths: - '.github/workflows/bazel-npm.yml' - '.github/workflows/bazel-compatibility.yml' @@ -66,6 +69,8 @@ on: - '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-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -92,6 +97,8 @@ on: - '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-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.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/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index bbacdb4ed..6299fc1c3 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -32,12 +32,16 @@ on: # `*python*` pattern would also match the benchmark fixtures, the rest # of vendored mode and the files of the lock-file package managers # (pdm, pipenv, poetry, uv), where this flow does no more than find - # that the project is not theirs. Nothing another ecosystem's flow owns - # is here, so a change to one ecosystem starts that ecosystem's legs - # only. Three PyPI helpers that those files call, and that are no other - # project manager's own, are listed with them: the finder of a - # project's Python lock files, the spelling of a version in a wheel's - # file name, and the hosted scan's check of an installed wheel. + # that the project is not theirs. Three PyPI helpers that those files + # call, and that are no other project manager's own, are listed with + # them: the finder of a project's Python lock files, the spelling of a + # version in a wheel's file name, and the hosted scan's check of an + # installed wheel. Last, the VEX code: `vex/` of the core and the files + # of the `vex` command. Every flow holds the exact document socket-patch + # writes about its patched build, so a change to how a document is built + # or worded starts the legs of every ecosystem. Nothing else that + # another ecosystem's flow owns is here, so any other change to one + # ecosystem starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, # the rest of hosted/ and of commands/), the shared test helpers and the @@ -69,6 +73,8 @@ on: - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -100,6 +106,8 @@ on: - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index b11dcde9c..07183b368 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -30,8 +30,12 @@ on: # (formats/gem), lock discovery, the lock inventory, the Ruby crawler # (it says which lock Bundler loads), the upstream restore of # `rollback`, and the stale-install guard that both commands end with. - # Nothing another ecosystem's flow owns is here, so a change to one - # ecosystem starts that ecosystem's legs only. + # Last, the VEX code: `vex/` of the core and the files of the `vex` + # command. Every flow holds the exact document socket-patch writes about + # its patched build, so a change to how a document is built or worded + # starts the legs of every ecosystem. Nothing else that another + # ecosystem's flow owns is here, so any other change to one ecosystem + # starts that ecosystem's legs only. # # What it does not cover: shared engine code. The other half of the # hosted rewrite is there (`rewrite_gem` and its planner in @@ -60,6 +64,8 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -82,6 +88,8 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/patch/redirect/**' diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs index ba452a93b..5901b009f 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs @@ -29,7 +29,9 @@ //! of its own. //! //! The marker is read from what Bazel built, and the patched one holds an -//! id made for the run, so no cache of an earlier run can supply it. +//! id made for the run, so no cache of an earlier run can supply it. Each +//! flow asserts the VEX document of its patch as `main.rs` says; agent mode +//! also has its `apply` write one. //! //! One loopback server stands in for four hosts, by route prefix: the //! Socket API, `proxy.golang.org` (the upstream module), `patch.socket.dev` @@ -58,7 +60,8 @@ use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::envelope::find_event; use crate::harness::{ - cell_without_bazel, changed, fixture_path, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, + Tree, CONSUMER, NOTHING, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -80,6 +83,9 @@ const FIXTURE: Fixture = Fixture { const MODULE: &str = "example.com/upstream"; const VERSION: &str = "v1.0.0"; const PURL: &str = "pkg:golang/example.com/upstream@v1.0.0"; +/// The product `vex` reads from the fixture's own `go.mod`, which records +/// a module and no version. +const PRODUCT: &str = "pkg:golang/example.com/consumer"; /// Its two files. The fixture's `go.sum` holds the `h1:` of these bytes. const GO_MOD: &[u8] = b"module example.com/upstream\n\ngo 1.21\n"; const UPSTREAM_LIB: &[u8] = b"package upstream\n\nfunc Greeting() string { return \"PRISTINE\" }\n"; @@ -304,7 +310,10 @@ fn hosted_go_deps() { // (b) The one command of hosted mode. It rewrites those two files and // no other: the one `replace` line, and the two sums of the Socket // module in place of the upstream module's. - let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &uuid, How::Hosted); + let in_run = cell.document("in-run"); + let scan = socket_patch(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let said = &scan.dump; let pinned = cell.pinned_by(&scan, PURL, &uuid, &before, &["go.mod", "go.sum"]); let text = |rel: &str| String::from_utf8(pinned[rel].clone()).expect("a text file"); @@ -315,6 +324,10 @@ fn hosted_go_deps() { let mut sums: Vec<&str> = go_sum.lines().collect(); sums.sort_unstable(); assert_eq!(sums, socket.go_sum(), "{test}: go.sum:\n{go_sum}"); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before anything has fetched the Socket module. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(socket_patch, &claim, true); assert_eq!(standin.asked(&socket_zip), 0, "{test}: {said}"); // (c) The same build, no step in between: patched, from the patch @@ -330,10 +343,21 @@ fn hosted_go_deps() { upstream_fetches, "{test}: the patched build fetched the upstream module" ); - - // (d) The undo: every file is the one of before, and so is the build. + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + cell.stands_alone(socket_patch, &claim, true); + cell.stands_alone(socket_patch, &claim, false); + // Without a product, as a user types it: the same document for the + // module of the checkout's own `go.mod`. + cell.detects_product(socket_patch, Some(PRODUCT)); + + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, UNPATCHED); + cell.attests_nothing(socket_patch, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(socket_patch, &hosted, &before, &pinned, &claim); // (e) A second machine with the rewritten files, and a patch host that // serves other bytes at the pinned URL: still a module zip `go` @@ -437,6 +461,14 @@ impl Kept { } } + /// What a VEX document says of a patch of the mode. + fn how(self) -> How { + match self { + Kept::Vendored => How::Vendored, + Kept::Agent => How::Agent, + } + } + /// The command of the mode. fn scan(self) -> [&'static str; 4] { let mode = match self { @@ -647,11 +679,17 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { // (b) The command of the mode: the copy, the one `replace` line, and // the line that keeps Bazel and gazelle out of the copies. - let scan = with.run(&cell, &mode.scan()); + let claim = Claim::new(PURL, &with.uuid, mode.how()); + let run = |cell: &Cell, args: &[&str]| with.ran(cell, args); + let in_run = cell.document("in-run"); + let scan = with.run(&cell, &[&mode.scan()[..], &with_vex(&in_run)].concat()); let event = find_event(&scan.envelope, "applied", None); assert_eq!(event["purl"], PURL, "{test}: {}", scan.dump); + cell.wrote_in_run(&scan, &in_run, &claim); if mode == Kept::Agent { - with.run(&cell, &["apply"]); + let again = cell.document("apply"); + let apply = with.run(&cell, &[&["apply"][..], &with_vex(&again)].concat()); + cell.wrote_in_run(&apply, &again, &claim); } let pinned = cell.tree(); let wrote = changed(&before, &pinned); @@ -667,9 +705,15 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { let replace = format!("replace {MODULE} {VERSION} => ./{copy_dir}"); let replaces = go_mod.lines().filter(|line| line.trim() == replace).count(); assert_eq!(replaces, 1, "{test}: go.mod:\n{go_mod}"); + cell.stands_alone(run, &claim, true); - // (c) The next build is patched, from the copy. + // (c) The next build is patched, from the copy, and `vex` says so; with + // `--no-verify` it says that it checked no file, and without a product + // it says the same for the module of the checkout's own `go.mod`. cell.builds_patched(&pinned, &patched); + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + cell.detects_product(run, Some(PRODUCT)); // (d) The user's next step: gazelle writes nothing into the copy, the // build stays patched, and no package of the checkout is under @@ -682,13 +726,20 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { let all = cell.bazel("build", &["//..."]); assert!(all.ok(), "{test}: {}", all.dump()); - // (e) The undo. An agent rollback keeps its emptied manifest. - let (undo, counted, left): (&[&str], &str, &[&str]) = match mode { - Kept::Vendored => (&["vendor", "--revert", "--yes"], "removed", &[]), + // (e) The undo. An agent rollback keeps its emptied manifest, which + // `vex` then finds empty, where the other undo leaves it none to find. + let (undo, counted, left, nothing): (&[&str], &str, &[&str], (i32, &str)) = match mode { + Kept::Vendored => ( + &["vendor", "--revert", "--yes"], + "removed", + &[], + (2, "manifest_not_found"), + ), Kept::Agent => ( &["rollback", "--yes"], "rolledBack", &[".socket/manifest.json"], + (1, "no_patches"), ), }; let undo = with.run(&cell, undo); @@ -702,6 +753,9 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { ); cell.builds(UNPATCHED); assert_eq!(changed(&before, &cell.tree()), left, "{test}"); + cell.attests_nothing(run, nothing.0, nothing.1); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &mode.scan(), &before, &pinned, &claim); let next = if ships_build { "`bazel build //...` passed" @@ -1529,9 +1583,10 @@ fn a_manifest_in_another_project_brings_the_file_of_both_projects_in_line() { } } -/// Without a Bazel: the fixture's directories are those of its table, and -/// its `go.sum` pins the module the test serves, which holds the `h1:` -/// arithmetic here to sums that `go` computed. +/// Without a Bazel: the fixture's directories are those of its table, its +/// `go.sum` pins the module the test serves, which holds the `h1:` +/// arithmetic here to sums that `go` computed, and its `go.mod` names the +/// module of [`PRODUCT`]. #[test] fn the_fixture_pins_the_upstream_module_the_test_serves() { FIXTURE.check(); @@ -1539,4 +1594,8 @@ fn the_fixture_pins_the_upstream_module_the_test_serves() { let go_sum = std::fs::read_to_string(&path).expect("the fixture's go.sum"); let lines: Vec<&str> = go_sum.lines().collect(); assert_eq!(lines, upstream().go_sum(), "{}", path.display()); + let go_mod = std::fs::read_to_string(path.with_file_name("go.mod")).expect("go.mod"); + let module = PRODUCT.strip_prefix("pkg:golang/").expect("a Go module"); + let line = format!("module {module}"); + assert!(go_mod.lines().any(|named| named == line), "{go_mod}"); } diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index 7ac2c500f..19204f18d 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -10,12 +10,16 @@ use std::ffi::{OsStr, OsString}; use std::ops::Range; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; +use std::sync::OnceLock; use serde_json::{json, Value}; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; -use crate::envelope::event_for; +use socket_patch_core::utils::purl::normalize_purl; +use socket_patch_core::vex::NOT_VERIFIED_SUFFIX; + +use crate::envelope::{codes_in, event_for, events}; use crate::fs_tree; use crate::hosted_memory_common::hermetic::{self, Extra}; use crate::hosted_memory_common::{mount_api, read_tree, Patch, ORG}; @@ -139,6 +143,103 @@ pub type Tree = BTreeMap>; /// What [`changed`] gives for two equal trees. pub const NOTHING: [&str; 0] = []; +/// The product the forms of `vex` are told, so that the documents of every +/// flow name one, whatever its fixture lets `socket-patch` detect: the PyPI +/// and the RubyGems fixture have no project file. One run per flow goes +/// without it ([`Cell::detects_product`]). +const PRODUCT: &str = "pkg:generic/socket-fixture@0.0.0"; + +/// The advisory of every patch record a flow is served: the one of the +/// shared API stand-in, and of the records a flow writes itself. +const ADVISORY: &str = "GHSA-test-aaaa-bbbb"; + +/// The mode a flow patched its package in, which a document says after the +/// patch id. +#[derive(Clone, Copy)] +pub enum How { + Hosted, + Vendored, + Agent, +} + +impl How { + fn words(self) -> &'static str { + match self { + How::Hosted => " (redirected)", + How::Vendored => " (vendored)", + How::Agent => "", + } + } +} + +/// What a document has to say: the package `purl` is not affected, through +/// the patch `uuid` of this run. The id is new for every run, so no +/// document of an earlier run says it. +pub struct Claim<'a> { + pub purl: &'a str, + pub uuid: &'a str, + pub how: How, +} + +impl<'a> Claim<'a> { + pub fn new(purl: &'a str, uuid: &'a str, how: How) -> Claim<'a> { + Claim { purl, uuid, how } + } +} + +/// `path` as an argument of `socket-patch`. +fn argument(path: &Path) -> &str { + path.to_str().expect("a UTF-8 path") +} + +/// The stand-alone `vex` that writes its document to `path`. +fn vex(path: &Path) -> [&str; 5] { + ["vex", "--output", argument(path), "--product", PRODUCT] +} + +/// What the document at `path` holds. +fn document_at(test: &str, path: &Path) -> (String, Value) { + let text = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("{test}: no document {}: {e}", path.display())); + let document = + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{test}: no JSON ({e}):\n{text}")); + (text, document) +} + +/// `document` without what each run and each form writes for itself: the +/// id of the document, its times and those of its statements, and the mark +/// of `vex --no-verify` at the end of an impact statement. What is left is +/// what a document says and the strings it says it with: the product, the +/// package, the advisory and its aliases, the status, the justification +/// and the patch. +fn wording(mut document: Value) -> Value { + fn without(of: &mut Value, fields: &[&str]) { + let Some(object) = of.as_object_mut() else { + return; + }; + for field in fields { + object.remove(*field); + } + } + without(&mut document, &["@id", "timestamp", "last_updated"]); + let statements = document["statements"].as_array_mut(); + for statement in statements.into_iter().flatten() { + without(statement, &["timestamp", "last_updated"]); + let Some(impact) = statement["impact_statement"].as_str() else { + continue; + }; + let unmarked = impact.strip_suffix(NOT_VERIFIED_SUFFIX).unwrap_or(impact); + statement["impact_statement"] = unmarked.to_string().into(); + } + document +} + +/// What a `scan` or an `apply` is given to write the document of its own +/// run to `path`. +pub fn with_vex(path: &Path) -> [&str; 4] { + ["--vex", argument(path), "--vex-product", PRODUCT] +} + /// `name`'s value when it is set and non-empty. fn var(name: &str) -> Option { std::env::var_os(name).filter(|value| !value.is_empty()) @@ -258,6 +359,28 @@ pub fn fixture_path(rel: &str) -> PathBuf { .join(rel) } +/// The marker file of a vendored copy, in the directory of its patch. +const MARKER: &str = "/socket-patch.vendor.json"; + +/// `tree` with every [`MARKER`] as its JSON value without `vendoredAt`, +/// the one field that holds a time: two runs that vendor the same patch +/// of the same package write markers that are equal in this, and a marker +/// that names another package, patch or advisory is not. A marker that is +/// no JSON object stays as it is. +fn undated(tree: &Tree) -> Tree { + let mut tree = tree.clone(); + for (file, bytes) in &mut tree { + if !file.ends_with(MARKER) { + continue; + } + if let Ok(Value::Object(mut fields)) = serde_json::from_slice(bytes) { + fields.remove("vendoredAt"); + *bytes = Value::Object(fields).to_string().into_bytes(); + } + } + tree +} + /// The names under which `before` and `after` differ. pub fn changed(before: &Tree, after: &Tree) -> Vec { let names = before.keys().chain(after.keys()); @@ -301,6 +424,9 @@ struct Scratch { /// The downloader config, which only [`Cell::route_downloads`] writes. /// Beside the workspace copy, so it is no file of the checkout. downloads: PathBuf, + /// The VEX documents of a flow ([`Cell::document`]), beside the + /// workspace copy for the same reason. + documents: PathBuf, /// Removed on drop, after [`Scratch::drop`] made it removable. dir: tempfile::TempDir, } @@ -330,6 +456,7 @@ impl Scratch { repository_cache: made(repository_cache.unwrap_or_else(|| root.join("cache"))), contents_cache: made(root.join("contents")), downloads: root.join("downloader.cfg"), + documents: made(root.join("vex")), dir, } } @@ -644,6 +771,9 @@ pub struct Cell { socket_bin: Option, /// The rules of the downloader config, once a flow has asked for one. downloads: Option>, + /// The [`wording`] of the first document [`Cell::attests`] read in + /// this checkout, which every later one is held to. + wording: OnceLock, // Dropped after `Cell::drop` has stopped the server. scratch: Scratch, } @@ -700,6 +830,7 @@ impl Cell { numbers, socket_bin, downloads: None, + wording: OnceLock::new(), scratch, }) } @@ -725,23 +856,33 @@ impl Cell { if let Err(why) = self.shutdown() { panic!("{}: {why}", self.test); } - let mut twin = Cell { + self.unbuilt(&self.tree()) + } + + /// A checkout that no Bazel has built in: `files` in a workspace copy + /// of its own, which has no output base and none of Bazel's `bazel-*` + /// links, with the settings of this cell. Nothing but `socket-patch` + /// runs in it unless the caller builds there ([`Cell::twin`]), so this + /// cell's server keeps running. + pub fn unbuilt(&self, files: &Tree) -> Cell { + let mut copy = Cell { test: self.test.clone(), repo_env: self.repo_env.clone(), bazel: self.bazel.clone(), numbers: self.numbers, socket_bin: self.socket_bin.clone(), downloads: None, + wording: OnceLock::new(), scratch: Scratch::new(Some(self.scratch.repository_cache.clone())), }; - for (rel, bytes) in self.tree() { - twin.write(&rel, bytes); + for (rel, bytes) in files { + copy.write(rel, bytes); } - std::fs::create_dir(twin.scratch.workspace.join(".git")).expect("create .git"); + std::fs::create_dir(copy.scratch.workspace.join(".git")).expect("create .git"); if let Some(rules) = &self.downloads { - twin.route_downloads(rules); + copy.route_downloads(rules); } - twin + copy } /// Send the downloads of Bazel's own downloader where `rules` say: the @@ -962,6 +1103,182 @@ impl Cell { [out.stdout, out.stderr].map(|stream| String::from_utf8_lossy(&stream).into_owned()) } + /// Where a flow has `socket-patch` write the VEX document `name`: + /// beside the workspace copy, so it is no file of the checkout, and no + /// comparison of the checkout's files sees it. + pub fn document(&self, name: &str) -> PathBuf { + self.scratch.documents.join(format!("{name}.vex.json")) + } + + /// The document at `path` says `claim` and nothing else: one statement, + /// `not_affected` for the one advisory, with the package as the one + /// subcomponent of the one product and the patch of this run in its + /// impact statement, which ends with `; not verified on disk` exactly + /// when the run did not check the files (`verified` is false). And it + /// says so in the words of every other document read in this checkout: + /// the forms spell the product, the package, the advisory and the + /// status alike, and differ in nothing but what [`wording`] leaves out. + fn attests(&self, path: &Path, claim: &Claim, verified: bool) { + let test = &self.test; + let (text, document) = document_at(test, path); + let context = "https://openvex.dev/ns/v0.2.0"; + assert_eq!(document["@context"], context, "{test}: {text}"); + let statements = document["statements"].as_array(); + let Some([statement]) = statements.map(Vec::as_slice) else { + panic!("{test}: not one statement:\n{text}"); + }; + assert_eq!(statement["status"], "not_affected", "{test}: {text}"); + let justification = "inline_mitigations_already_exist"; + assert_eq!(statement["justification"], justification, "{test}: {text}"); + let advisory = &statement["vulnerability"]["name"]; + assert_eq!(*advisory, ADVISORY, "{test}: {text}"); + // The package is named as its record names it: with `%40` or with + // `@` for the scope of an npm name. + let named = statement["products"][0]["subcomponents"][0]["@id"].as_str(); + let named = named.unwrap_or_default(); + let purl = normalize_purl(claim.purl); + assert_eq!(normalize_purl(named), purl, "{test}: {text}"); + let products = json!([{ "@id": PRODUCT, "subcomponents": [{ "@id": named }] }]); + assert_eq!(statement["products"], products, "{test}: {text}"); + let (uuid, how) = (claim.uuid, claim.how.words()); + let mut impact = format!("Patched via Socket patch {uuid}{how}"); + if !verified { + impact += NOT_VERIFIED_SUFFIX; + } + assert_eq!(statement["impact_statement"], impact, "{test}: {text}"); + let said = wording(document); + let first = self.wording.get_or_init(|| said.clone()); + assert_eq!( + said, *first, + "{test}: not the words of the first document of this checkout:\n{text}" + ); + } + + /// The stand-alone `vex` of this checkout, through `run`, the flow's way + /// to run `socket-patch` in a cell. It attests `claim` and nothing + /// else, in its envelope and in the document it writes, which is not + /// the one of an earlier call. `verified` is false for + /// `vex --no-verify`, which says in a warning, and in the document, + /// that it checked no file. + pub fn stands_alone(&self, run: impl Fn(&Cell, &[&str]) -> Ran, claim: &Claim, verified: bool) { + let path = self.document("stand-alone"); + let _ = std::fs::remove_file(&path); + let unchecked: &[&str] = if verified { &[] } else { &["--no-verify"] }; + let ran = run(self, &[&vex(&path), unchecked].concat()); + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "success", "{test}: {said}"); + let [event] = events(&ran.envelope) else { + panic!("{test}: not one event: {said}"); + }; + assert_eq!(event["action"], "verified", "{test}: {said}"); + let purl = normalize_purl(event["purl"].as_str().unwrap_or_default()); + assert_eq!(purl, normalize_purl(claim.purl), "{test}: {said}"); + let details = &event["details"]; + assert_eq!(details["status"], "not_affected", "{test}: {said}"); + assert_eq!(details["vulnerability"], ADVISORY, "{test}: {said}"); + let warned: &[&str] = if verified { &[] } else { &["vex_not_verified"] }; + let warnings = codes_in(&ran.envelope["warnings"]); + assert_eq!(warnings, warned, "{test}: {said}"); + self.attests(&path, claim, verified); + } + + /// `vex --output ` as a user types it, with no `--product`, + /// through `run`, in this checkout that Bazel has built in: beside the + /// project's own files are Bazel's links, and behind them those files + /// again. `product` is what `vex` reads from the project file of the + /// checkout: it writes the document every other form wrote here, for + /// that product, and warns of nothing. With `None` the checkout has no + /// file `vex` reads a product from: it exits 2 with + /// `product_undetected` and writes no document. + pub fn detects_product(&self, run: impl Fn(&Cell, &[&str]) -> Ran, product: Option<&str>) { + let path = self.document("no-product"); + let ran = run(self, &["vex", "--output", argument(&path)]); + let (test, said) = (&self.test, &ran.dump); + let Some(product) = product else { + assert_eq!(ran.code, 2, "{test}: {said}"); + let error = &ran.envelope["error"]["code"]; + assert_eq!(*error, "product_undetected", "{test}: {said}"); + assert!(!path.exists(), "{test}: a document is left: {said}"); + return; + }; + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!( + codes_in(&ran.envelope["warnings"]), + NOTHING, + "{test}: {said}" + ); + let (text, document) = document_at(test, &path); + let mut named = self.wording.get().cloned().expect("a document here"); + named["statements"][0]["products"][0]["@id"] = product.into(); + assert_eq!(wording(document), named, "{test}: {said}\n{text}"); + } + + /// For a finished command that was given [`with_vex`] for `path`: it + /// passed, and wrote the document of its own run, which attests + /// `claim` and nothing else. A hosted scan says of its document that + /// no file was hashed for it: the lock names the patch, and the bytes + /// come with the next build. + pub fn wrote_in_run(&self, ran: &Ran, path: &Path, claim: &Claim) { + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + let vex = &ran.envelope["vex"]; + assert_eq!(vex["statements"], 1, "{test}: {said}"); + assert_eq!(vex["format"], "openvex-0.2.0", "{test}: {said}"); + assert_eq!(vex["path"], argument(path), "{test}: {said}"); + let warned: &[&str] = match claim.how { + How::Hosted => &["vex_hosted_unverified"], + How::Vendored | How::Agent => &[], + }; + assert_eq!(codes_in(&vex["warnings"]), warned, "{test}: {said}"); + self.attests(path, claim, true); + } + + /// The same two documents from a checkout that no Bazel has built in: + /// one with the files `before`, where `command`, the command of the + /// mode, applies the patch and writes the document of its run, and the + /// stand-alone `vex` writes its own, both in the words of this + /// checkout's documents. The command leaves the files `patched`, those + /// the patched build started from, so both checkouts attest the same + /// files. One field of one file is left out: `vendoredAt`, the time of + /// its run in the marker of a vendored copy. + pub fn attests_unbuilt( + &self, + run: impl Fn(&Cell, &[&str]) -> Ran, + command: &[&str], + before: &Tree, + patched: &Tree, + claim: &Claim, + ) { + let fresh = self.unbuilt(before); + let in_run = fresh.document("in-run"); + let ran = run(&fresh, &[command, &with_vex(&in_run)].concat()); + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{test}: {said}"); + fresh.wrote_in_run(&ran, &in_run, claim); + let differ = changed(&undated(patched), &undated(&fresh.tree())); + assert_eq!(differ, NOTHING, "{test}: {said}"); + fresh.stands_alone(run, claim, true); + let (here, there) = (self.wording.get(), fresh.wording.get()); + assert_eq!(there, here, "{test}: the two checkouts word it apart"); + } + + /// The stand-alone `vex` of a checkout that holds no patch any more, + /// through `run`: it exits `code` with the error `error` and leaves no + /// document, and says that it removed the one [`Cell::stands_alone`] + /// left. + pub fn attests_nothing(&self, run: impl Fn(&Cell, &[&str]) -> Ran, code: i32, error: &str) { + let path = self.document("stand-alone"); + let ran = run(self, &vex(&path)); + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, code, "{test}: {said}"); + assert_eq!(ran.envelope["error"]["code"], error, "{test}: {said}"); + assert!(!path.exists(), "{test}: a document is left: {said}"); + let warned = codes_in(&ran.envelope["warnings"]); + let removed = warned.iter().any(|code| code == "vex_stale_doc_removed"); + assert!(removed, "{test}: {said}"); + } + /// `bazel shutdown`, when the pid file of a server is there. No command /// options: the startup options are what address the server. fn shutdown(&self) -> Result<(), String> { @@ -1038,6 +1355,7 @@ pub fn cell_without_bazel(release: &str) -> Cell { numbers: numbers(release).expect("a release"), socket_bin: None, downloads: None, + wording: OnceLock::new(), scratch: Scratch::new(None), } } @@ -1085,6 +1403,67 @@ fn a_downloader_config_is_named_by_the_option_of_the_release() { } } +/// Without a Bazel: a document is no file of the checkout it is about, nor +/// of a checkout made from it, which has documents of its own. +#[test] +fn a_document_is_no_file_of_the_checkout() { + let cell = cell_without_bazel("9.3.2"); + cell.write("MODULE.bazel", ""); + let fresh = cell.unbuilt(&cell.tree()); + assert_eq!(changed(&cell.tree(), &fresh.tree()), NOTHING); + let documents = [cell.document("one"), fresh.document("one")]; + assert_ne!(documents[0], documents[1]); + for document in &documents { + assert!(document.parent().is_some_and(Path::is_dir), "{document:?}"); + for copy in [&cell, &fresh] { + assert!(!document.starts_with(©.scratch.workspace)); + } + } +} + +/// Without a Bazel: two documents are held to each other in every string +/// but the id, the times and the mark of `--no-verify`, so the two +/// spellings of an npm scope are two wordings; and two trees in every +/// byte but the `vendoredAt` of a marker. +#[test] +fn documents_and_markers_are_compared_but_for_their_ids_and_times() { + let (escaped, plain) = ("pkg:npm/%40scope/name@1.0.0", "pkg:npm/@scope/name@1.0.0"); + let document = |n: u32, package: &str, impact: &str| { + let time = format!("2026-01-0{n}T00:00:00Z"); + wording(json!({ + "@id": format!("urn:uuid:{n}"), + "timestamp": time, + "statements": [{ + "timestamp": time, + "products": [{ "@id": PRODUCT, "subcomponents": [{ "@id": package }] }], + "impact_statement": impact, + }], + })) + }; + let patched = "Patched via Socket patch one (vendored)"; + let first = document(1, escaped, patched); + let unchecked = format!("{patched}{NOT_VERIFIED_SUFFIX}"); + assert_eq!(document(2, escaped, &unchecked), first); + assert_ne!(document(1, plain, patched), first); + assert_ne!(document(1, escaped, "Patched via Socket patch two"), first); + + let tree = |file: &str, purl: &str, n: u32| { + let marker = json!({ "purl": purl, "vendoredAt": format!("2026-01-0{n}T00:00:00Z") }); + undated(&Tree::from([( + file.to_string(), + marker.to_string().into_bytes(), + )])) + }; + let marker = format!(".socket/vendor/npm/one{MARKER}"); + let first = tree(&marker, escaped, 1); + assert_eq!(changed(&first, &tree(&marker, escaped, 2)), NOTHING); + assert_eq!(changed(&first, &tree(&marker, plain, 1)), [marker.as_str()]); + // No other file is read for a time. + let ledger = ".socket/vendor/state.json"; + let other = changed(&tree(ledger, escaped, 1), &tree(ledger, escaped, 2)); + assert_eq!(other, [ledger]); +} + /// Set in the copy of this test binary that the next test starts, which /// then plays the shell of a developer. const PLAYS_THE_SHELL: &str = "SOCKET_PATCH_BAZEL_E2E_PLAYS_THE_SHELL"; diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs index bd9f102b7..c4bcc1ff7 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs @@ -31,6 +31,23 @@ //! `SOCKET_PATCH_BAZEL_E2E_REQUIRED=1` (CI) it fails instead. `harness.rs` //! lists the other variables. //! +//! Every flow whose build is patched also holds `socket-patch` to the VEX +//! document it writes about that build. The command of the mode writes one +//! for its own run (`--vex`), in the checkout Bazel has built in; `vex` +//! writes one before the patched build and after it, and one with +//! `--no-verify`; after the undo `vex` writes none and removes the last; +//! and the command and `vex` write the same two in a checkout with the +//! same files that no Bazel has built in. Each document is one statement: +//! the package under test is `not_affected`, through the patch of this +//! run. The documents of a flow are also held to each other: they differ +//! in their id, their times and the mark of `--no-verify`, and in no other +//! string. Every form is told one product; `vex` without one, as a user +//! types it, runs once after the patched build, where it names the project +//! of the checkout's own `package.json` or `go.mod`, or writes no document +//! where the fixture has no such file. Nothing in `socket-patch` reads a +//! Bazel file for it, so these tests say for which workspaces the document +//! and the build agree. +//! //! A flow is one `#[ignore]`d test in its ecosystem's module, and its //! fixture is one directory of files that every release builds beside one //! `MODULE.bazel` per era of rulesets; the fixture's table in the test code 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 f97459091..c590d55ca 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -39,8 +39,9 @@ //! 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. +//! vendored one reports it `already_vendored`, each writes the VEX +//! document of its run, `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. @@ -50,6 +51,8 @@ //! or they replace the committed file (vendored). The build fails on the //! checksum and does not take the registry's tarball in its place. //! +//! Both flows assert the VEX document of their patch as `main.rs` says. +//! //! A marker is read from what Bazel built. Bazel's downloader keeps every //! file it fetches in the repository cache, under its checksum, and hands it //! out again without a request; the tests of a leg share that cache, and CI @@ -83,7 +86,8 @@ 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, NOTHING, + changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, Run, StandIn, Tree, + CONSUMER, NOTHING, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -109,6 +113,9 @@ const VERSION: &str = "1.0.0"; /// Socket API's purl of a scoped package. `scan` takes either spelling and /// names a patch in its events as the API did. const PURL: &str = "pkg:npm/%40socketsecurity/bazel-fixture-upstream@1.0.0"; +/// The product `vex` reads from the fixture's own `package.json`: its name +/// and its version. +const PRODUCT: &str = "pkg:npm/socket-fixture@0.0.0"; /// The file name of its tarball on the registry and on the patch host: the /// name without its scope. const TGZ: &str = "bazel-fixture-upstream-1.0.0.tgz"; @@ -406,15 +413,17 @@ fn second_machine( /// 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`. +/// a checkout without those links; the document of that run, and those of +/// `vex` and of `vex --no-verify`, attest `claim`; `vex` without a product +/// names the fixture's own; 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, + claim: &Claim, marker: &str, ) { let test = &cell.test; @@ -430,30 +439,26 @@ fn runs_again( } let one = |action: &str, code: &str| [(canonical_purl(PURL), action.into(), code.into())]; - let scan = socket_patch(cell, standin, &["scan", "--mode", mode, "--yes"]); + let again = cell.document("again"); + let scan = ["scan", "--mode", mode, "--yes"]; + let scan = socket_patch(cell, standin, &[&scan[..], &with_vex(&again)].concat()); 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}"); + cell.wrote_in_run(&scan, &again, claim); + + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, args); + cell.stands_alone(run, claim, true); + cell.stands_alone(run, claim, false); + // Without a product, as a user types it: the same document for the + // project of the checkout's own `package.json`, which Bazel's links + // show a second time. + cell.detects_product(run, Some(PRODUCT)); assert_eq!(changed(patched, &cell.tree()), NOTHING, "{test}"); cell.builds_patched(patched, marker); @@ -507,7 +512,11 @@ fn hosted_npm_translate_lock() { // (b) The one command of hosted mode. It rewrites those two files and // no other: the entry of the package names the patched tarball, by its // sum and by its URL on the patch host. - let scan = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &patch.uuid, How::Hosted); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let written = [LOCK, "pnpm-workspace.yaml"]; let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); let lock = text(&pinned, LOCK); @@ -519,6 +528,10 @@ fn hosted_npm_translate_lock() { assert!(lock.contains(&entry), "{test}: {LOCK}:\n{lock}"); let workspace = text(&pinned, "pnpm-workspace.yaml"); assert_eq!(workspace, TRUSTING_WORKSPACE, "{test}"); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before the patched build. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); // (c) The same build, no step in between: patched, from the patch host. let patched_fetches = standin.asked(&patch.route); @@ -530,11 +543,15 @@ fn hosted_npm_translate_lock() { // 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); + runs_again(&cell, &standin, "hosted", seen, &pinned, &claim, marker); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &standin, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, &upstream.marker); + cell.attests_nothing(run, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &hosted, &before, &pinned, &claim); // (e) A second machine, a second patch, and a patch host that serves // other bytes at the URL the lock pins: still a tarball of the package, @@ -583,7 +600,11 @@ fn vendored_npm_translate_lock() { let before = builds_upstream(&cell, &standin, &upstream); // (b) The one command of vendored mode. - let scan = socket_patch(&cell, &standin, &["scan", "--mode", "vendored", "--yes"]); + let vendoring = ["scan", "--mode", "vendored", "--yes"]; + let claim = Claim::new(PURL, &patch.uuid, How::Vendored); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&vendoring[..], &with_vex(&in_run)].concat()); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); @@ -622,6 +643,10 @@ fn vendored_npm_translate_lock() { assert_eq!(*overridden, format!("file:{copy}"), "{test}: {manifest:#}"); let workspace = text(&vendored, "pnpm-workspace.yaml"); assert_eq!(workspace, overriding_workspace(©), "{test}"); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before the patched build. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); // (c) The same build, no step in between: patched, from the committed // file. Bazel asks the stand-in for nothing. @@ -631,11 +656,15 @@ fn vendored_npm_translate_lock() { // 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); + runs_again(&cell, &standin, "vendored", seen, &vendored, &claim, marker); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &standin, &["vendor", "--revert"]); cell.undone(&undo, "removed", &before, &upstream.marker); + cell.attests_nothing(run, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &vendoring, &before, &vendored, &claim); // (e) A second machine and a second patch, vendored there, and then // other bytes in the committed file: still a tarball of the package, @@ -675,9 +704,10 @@ fn vendored_npm_translate_lock() { /// fixture's directories and the legs of its workflow are those of its /// table; the fixture's lock holds the one entry a test pins, with the /// placeholder and no URL, and pinning changes nothing else; the fixture -/// depends on the package at the version of that entry; two runs serve two -/// upstream tarballs; and the names written out above are those of the one -/// package, under the organisation's scope. +/// depends on the package at the version of that entry and has the name +/// and the version of [`PRODUCT`]; two runs serve two upstream tarballs; and +/// the names written out above are those of the one package, under the +/// organisation's scope. #[test] fn a_test_pins_the_one_entry_of_the_fixture_lock() { FIXTURE.check(); @@ -694,6 +724,8 @@ fn a_test_pins_the_one_entry_of_the_fixture_lock() { let fixture: Value = serde_json::from_str(&read("package.json")).expect("package.json"); assert_eq!(fixture["dependencies"][NAME], VERSION); + let named = [&fixture["name"], &fixture["version"]].map(|field| field.as_str().expect("text")); + assert_eq!(PRODUCT, format!("pkg:npm/{}@{}", named[0], named[1])); let manifest: Value = serde_json::from_str(MANIFEST).expect("the package's package.json"); assert_eq!(manifest["name"], NAME); assert_eq!(manifest["version"], VERSION); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index b88838988..5d48ad304 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -39,7 +39,8 @@ //! grant pins: after the same `scan`, the build fails on the sha256. //! //! The marker is read from what Bazel built, and the patched one holds an -//! id made for the run, so no cache of an earlier run can supply it. +//! id made for the run, so no cache of an earlier run can supply it. The +//! flow asserts the VEX document of its patch as `main.rs` says. //! //! One loopback server stands in for four hosts. The Socket API and the //! patch host answer at their own paths; `pypi.org` (the project pages of @@ -81,7 +82,8 @@ use base64::Engine as _; use serde_json::{json, Value}; use crate::harness::{ - changed, fixture_path, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, + changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, Tree, + CONSUMER, NOTHING, }; use crate::hosted_memory_common::Patch; @@ -397,7 +399,11 @@ fn hosted_pip_parse() { // (b) The one command of hosted mode. It rewrites that file and no // other: the pin of the dependency as it was, and the package as a // direct reference to the patched wheel with its sha256. - let scan = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &uuid, How::Hosted); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let said = &scan.dump; let pinned = cell.pinned_by(&scan, PURL, &uuid, &before, &[REQUIREMENTS]); let direct = format!("{NAME} @ {origin}{patched_route}"); @@ -410,6 +416,10 @@ fn hosted_pip_parse() { ), "{test}" ); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before anything has fetched the patched wheel. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); assert_eq!(standin.asked(&patched_route), 0, "{test}: {said}"); let index_requests = standin.asked(&page); // The scan left Bazel's lock as it was, so a frozen lock fails here @@ -435,6 +445,13 @@ fn hosted_pip_parse() { // From here on the checkout stands: the next build changes no file, // and that lock holds when Bazel may not update it. cell.builds_patched(&built, &marker); + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); + // Without a product, as a user types it, `vex` writes none: the + // checkout has no file it reads a product from. + cell.detects_product(run, None); // (d) The undo: `requirements.txt` is the one of before at once, and // the lock is still the one of the patched build, so a frozen lock @@ -461,6 +478,10 @@ fn hosted_pip_parse() { standin.asked(&page) > index_requests, "{test}: the build after the undo did not ask the index about {NAME}" ); + // `vex` has no document for the checkout of before. + cell.attests_nothing(run, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &hosted, &before, &pinned, &claim); // (e) A second machine. Bazel keeps a download that has a checksum in // the repository cache, which the two machines share, so this one gets diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index bdb225970..1e1eb046a 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -24,6 +24,8 @@ //! patch registry that serves other bytes fails the build, and the //! upstream gem is not fetched in its place. //! +//! The flow asserts the VEX document of its patch as `main.rs` says. +//! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The //! fixture's lock therefore holds no sha256 of a gem: it has a placeholder @@ -66,7 +68,9 @@ use std::time::Instant; use serde_json::json; use sha2::{Digest, Sha256}; -use crate::harness::{fixture_path, rewrite, Cell, Fixture, StandIn, CONSUMER}; +use crate::harness::{ + fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, StandIn, CONSUMER, +}; use crate::hosted_memory_common::Patch; /// The sha256 of `bytes` in lowercase hex, as a `Gemfile.lock` and the gem @@ -288,7 +292,10 @@ fn hosted_bundle_fetch() { // no other: the declaration gains the patch registry as its source, and // the lock resolves the gem from it, in a section of its own, with the // sha256 of the patched gem. - let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &uuid, How::Hosted); + let in_run = cell.document("in-run"); + let scan = socket_patch(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let said = &scan.dump; let pinned = cell.pinned_by(&scan, PURL, &uuid, &before, &["Gemfile", "Gemfile.lock"]); let text = |rel: &str| String::from_utf8(pinned[rel].clone()).expect("a text file"); @@ -306,6 +313,10 @@ fn hosted_bundle_fetch() { !lock.contains(&sum(&upstream_gem)), "{test}: Gemfile.lock:\n{lock}" ); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before anything has fetched the patched gem. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(socket_patch, &claim, true); assert_eq!(standin.asked(&patched_route), 0, "{test}: {said}"); // (c) The same build, no step in between: patched, from the patch @@ -321,10 +332,21 @@ fn hosted_bundle_fetch() { upstream_fetches, "{test}: the patched build fetched the upstream gem" ); + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + cell.stands_alone(socket_patch, &claim, true); + cell.stands_alone(socket_patch, &claim, false); + // Without a product, as a user types it, `vex` writes none: the + // checkout has no file it reads a product from. + cell.detects_product(socket_patch, None); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, &unpatched); + cell.attests_nothing(socket_patch, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(socket_patch, &hosted, &before, &pinned, &claim); // (e) A second machine with the rewritten files, and a patch registry // that serves other bytes at the pinned URL: still a gem RubyGems diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs new file mode 100644 index 000000000..69072290b --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs @@ -0,0 +1,213 @@ +//! `vex` for a project that Bazel does not build, in a checkout where Bazel +//! builds something else. +//! +//! `web/` is a plain pnpm project. The root of its checkout is a Bazel +//! workspace that builds Java and nothing of `web/`: its one hub is +//! `maven.install` of rules_jvm_external in a `MODULE.bazel`, or +//! `maven_install` in a `WORKSPACE`, and no Bazel file names the project's +//! lock. So what `socket-patch` patched there is what the project's own +//! package manager installs, as in a checkout without Bazel, and `vex` must +//! say what it says there: the exit code, both streams and the document of +//! each form are those of that checkout, byte for byte (but for the path of +//! the checkout and the time; each form is told the id of its document). +//! +//! These two tests are the fixed point for every change to what `vex` says +//! in a Bazel workspace. A change that makes one of them fail, or that +//! needs an edit to this file, has changed the answer for a project Bazel +//! does not build. A change that makes `vex` read a Bazel file adds a test +//! of its own for the case it touches. + +use std::path::{Path, PathBuf}; + +use crate::vex_e2e_common; +use vex_e2e_common::*; + +const PURL: &str = "pkg:npm/left-pad@1.3.0"; +const UUID: &str = "6d2f8b1c-4e7a-4c3d-9b5e-0a1f2e3d4c5b"; +const VULNS: &[(&str, &[&str])] = &[("GHSA-bzl-besd-0001", &["CVE-2026-6161"])]; +/// The entry file of the package, before the patch and with it. +const UPSTREAM: &str = "module.exports = (s) => s;\n"; +const PATCHED: &str = "/* patched */\nmodule.exports = (s) => s;\n"; +/// The sum of a tarball, as a lock spells it. +const INTEGRITY: &str = "sha512-UEFUQ0hFRHBhdGNoZWRQQVRDSEVEcGF0Y2hlZA=="; +/// The id every form is told to give its document (`--doc-id`, and +/// `--vex-doc-id` for `apply`), where `vex` would make a new one per run. +const DOCUMENT: &str = "urn:uuid:0b6c7d2e-5a41-4f38-8e9d-1c2b3a4f5e6d"; + +/// A root `MODULE.bazel` whose one hub is Maven's, and the package of the +/// root that it builds. +const JAVA_MODULE: &str = r#"module(name = "shop", version = "0.0.0") + +bazel_dep(name = "rules_jvm_external", version = "6.7") + +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install(artifacts = ["com.google.guava:guava:33.4.0-jre"]) +use_repo(maven, "maven") +"#; +const JAVA_BUILD: &str = r#"java_library( + name = "server", + srcs = glob(["server/**/*.java"]), + deps = ["@maven//:com_google_guava_guava"], +) +"#; + +/// A root `WORKSPACE` whose one hub is Maven's. +const JAVA_WORKSPACE: &str = r#"workspace(name = "shop") + +load("@rules_jvm_external//:defs.bzl", "maven_install") + +maven_install( + artifacts = ["com.google.guava:guava:33.4.0-jre"], + repositories = ["https://repo1.maven.org/maven2"], +) +"#; + +/// What is at the root of each checkout, and its files: no Bazel, then the +/// two workspaces that build Java. +const AROUND: [(&str, &[(&str, &str)]); 3] = [ + ("no Bazel", &[]), + ( + "a Java MODULE.bazel", + &[("MODULE.bazel", JAVA_MODULE), ("BUILD.bazel", JAVA_BUILD)], + ), + ("a Java WORKSPACE", &[("WORKSPACE", JAVA_WORKSPACE)]), +]; + +/// The files of the pnpm project: its `package.json`, and a lock as pnpm 9 +/// and later write it, which holds `resolution` for the one package. +fn project(resolution: &str) -> Vec<(String, String)> { + let package = r#"{"name": "web", "version": "1.0.0", "dependencies": {"left-pad": "1.3.0"}}"#; + let lock = format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\nimporters:\n\n .:\n dependencies:\n \ + left-pad:\n specifier: 1.3.0\n version: 1.3.0\n\npackages:\n\n \ + left-pad@1.3.0:\n resolution: {{{resolution}}}\n\nsnapshots:\n\n \ + left-pad@1.3.0: {{}}\n" + ); + let files = [ + ("package.json", package.to_string()), + ("pnpm-lock.yaml", lock), + ]; + files.map(|(rel, text)| (rel.to_string(), text)).to_vec() +} + +/// What a run said: its exit code, its stdout, its stderr and its +/// document, with what differs from one checkout and one run to the next +/// in fixed words: the path of the checkout and the time. +fn settled(out: &VexOutcome, checkout: &Path) -> (Option, String, String, String) { + let document = std::fs::read_to_string(&out.output).unwrap_or_default(); + // The path as the test names it and as the system resolves it, each as + // plain text and as a JSON string spells it. + let resolved = checkout.canonicalize().expect("the checkout"); + let mut paths = Vec::new(); + for path in [resolved.as_path(), checkout] { + let plain = path.to_string_lossy().into_owned(); + let quoted = serde_json::to_string(&plain).expect("a JSON string"); + paths.extend([quoted[1..quoted.len() - 1].to_string(), plain]); + } + let time = regex::Regex::new(r#""timestamp": "[^"]*""#).expect("a time"); + let fixed = |text: &str| { + let text = paths.iter().fold(text.to_string(), |text, path| { + text.replace(path.as_str(), "") + }); + time.replace_all(&text, r#""timestamp": """#) + .into_owned() + }; + let streams = [&out.stdout, &out.stderr, &document].map(|text| fixed(text)); + let [stdout, stderr, document] = streams; + (out.code, stdout, stderr, document) +} + +/// `vex` as JSON and as a person reads it, and `apply --vex`, each as `run` +/// says, in a checkout with the project's `files` in `web/` and each set of +/// Bazel files at its root. Without Bazel a form attests the package +/// through the patch, as `marker` says; beside each workspace it says what +/// it said there. +fn says_the_same_beside_bazel(files: &[(String, String)], run: VexRun, marker: Marker) { + let told = |run: VexRun, option: &str| run.arg(option).arg(DOCUMENT); + let person = VexRun { + human: true, + ..run.clone() + }; + let forms = [ + told(run.clone(), "--doc-id"), + told(person, "--doc-id"), + told(run.via(VexVia::Apply), "--vex-doc-id"), + ]; + let mut without_bazel = Vec::new(); + for (around, bazel) in AROUND { + let root = tempfile::tempdir().expect("a temp root"); + let web = root.path().join("web"); + let write = |path: PathBuf, text: &str| { + std::fs::create_dir_all(path.parent().expect("a file path")).expect("a directory"); + std::fs::write(path, text).expect("a file of the checkout"); + }; + write(root.path().join(".git/HEAD"), "ref: refs/heads/main\n"); + for (rel, text) in bazel { + write(root.path().join(rel), text); + } + for (rel, text) in files { + write(web.join(rel), text); + } + for (n, form) in forms.iter().enumerate() { + // Each form writes the same path: the document compared is its own. + let _ = std::fs::remove_file(web.join(DEFAULT_OUTPUT)); + let out = run_vex(&binary(), &web, form); + let said = settled(&out, root.path()); + if bazel.is_empty() { + assert_eq!(out.code, Some(0), "form {n}: {out}"); + assert_attested(out.doc(), PURL, UUID, marker, VULNS); + without_bazel.push(said); + } else { + assert_eq!(said, without_bazel[n], "{around}, form {n}: {out}"); + } + } + } +} + +/// Hosted mode: the lock names the patched tarball on the patch host, and +/// the record comes from the API. +#[test] +fn a_hosted_pin_beside_a_java_bazel_build_attests_as_without_bazel() { + let files = [("package/index.js", &*git_sha256(PATCHED.as_bytes()))]; + let api = PatchApi::start(vec![(UUID.into(), patch_view(UUID, PURL, &files, VULNS))]); + let pin = format!( + "integrity: {INTEGRITY}, tarball: \ + https://patch.socket.dev/patch/npm/left-pad/1.3.0/{HOSTED_TOKEN}/{UUID}/left-pad-1.3.0.tgz" + ); + says_the_same_beside_bazel(&project(&pin), VexRun::online(&api), Marker::Redirected); +} + +/// Agent mode: the installed copy holds the patch, which the manifest +/// records with its blob, and the run is offline. +#[test] +fn an_installed_patch_beside_a_java_bazel_build_attests_as_without_bazel() { + let (ghsa, cves) = VULNS[0]; + let patched = git_sha256(PATCHED.as_bytes()); + let manifest = serde_json::json!({ "patches": { PURL: { + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "package/index.js": { + "beforeHash": git_sha256(UPSTREAM.as_bytes()), + "afterHash": patched, + }}, + "vulnerabilities": { ghsa: { + "cves": cves, "summary": "s", "severity": "high", "description": "d", + }}, + "description": "a patch", + "license": "MIT", + "tier": "free", + }}}); + let mut files = project(&format!("integrity: {INTEGRITY}")); + let installed = r#"{"name": "left-pad", "version": "1.3.0"}"#; + files.extend([ + ( + "node_modules/left-pad/package.json".into(), + installed.into(), + ), + ("node_modules/left-pad/index.js".into(), PATCHED.into()), + (format!(".socket/blobs/{patched}"), PATCHED.into()), + (".socket/manifest.json".into(), manifest.to_string()), + ]); + says_the_same_beside_bazel(&files, VexRun::offline(), Marker::Applied); +} diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs index 39d72efa2..20ae25a43 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs @@ -35,6 +35,7 @@ mod vex_pdm_hatch_common; #[path = "../vex_pipenv_pip_common/mod.rs"] mod vex_pipenv_pip_common; +mod bazel_beside; mod bun; mod cargo; mod common_selftest; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index f4a1b214b..26c359fe5 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2659,6 +2659,41 @@ installed tree leaves the gem with its patched sources and no finished extension Patch runs again: `apply` puts the previous build back and completes the rebuild, and `rollback` restores the original sources and build. +## Bazel workspaces: VEX + +`vex` and `--vex` read what socket-patch wrote and what the project's own package manager +installed. They read no `MODULE.bazel`, `WORKSPACE` or BUILD file, so in a Bazel workspace a +document says what was patched, and that is what Bazel builds only where Bazel builds from +the files socket-patch rewrote. The two are tested to agree on real Bazel 9.3.2, 8.8.2 and +7.7.2 for four shapes, all under Bzlmod: Go through gazelle's +`go_deps.from_file(go_mod = "//:go.mod")` with +`go_deps.config(check_direct_dependencies = "error")` and the module required directly in +`go.mod` (hosted, vendored and agent mode), npm through +aspect_rules_js's `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` (hosted and +vendored), PyPI through rules_python's `pip.parse(requirements_lock = "//:requirements.txt")` +(hosted), and RubyGems through rules_ruby's +`ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted). There +the build prints the patched package, and the document of the run (`--vex`), of `vex` and of +`vex --no-verify` is one `not_affected` statement that names the package and the patch; the +first two are the same in a checkout with the same files that Bazel has not built in, and +after the undo `vex` writes no document. For PyPI on Bazel 8.5 and later a hosted scan leaves +`MODULE.bazel.lock` stale, so the document is there before a frozen build passes: a build with +`--lockfile_mode=error` fails until a build that may update the lock has run, and the updated +lock has to be committed. + +In every other Bazel shape nothing checks the document against the build, and in these it was +measured to be wrong (`not_affected` while Bazel builds the unpatched package, or while the +build is broken): agent mode beside rules_js, which builds from the lock and never reads the +patched `node_modules`; Go under a `go_repository` rule of a `WORKSPACE`, in hosted and +vendored mode; Go under `go_deps` when another Bazel module of the build requires a higher +version of the patched module, because gazelle then builds that version and drops the +replacement; a +`pip.parse` or `pip_parse` that takes the requirements of the build's platform from another +file than the one socket-patch rewrote; vendored mode for PyPI. Do not publish a document for +an artifact that Bazel built outside those four shapes. A project that Bazel does not build is +not concerned: beside a Bazel workspace whose files name none of its locks, `vex` says what it +says without Bazel. + ## Supported platforms Prebuilt binaries are published for: